答:
```<code>        conn.Open();
        SqlCommand com = new SqlCommand("update lend set date_back=convert(datetime2, getdate(), 102) where client_name ='" + comboBox1.Text + "'", conn);
        SqlDataAdapter da = new SqlDataAdapter("Declare @startdate smalldatetime declare @enddate smalldatetime set @startdate = (select date_lended from dbo.lend where client_name = '" + comboBox1.Text + "') set @enddate = (select date_back from dbo.lend where client_name = '" + comboBox1.Text + "') SELECT DATEDIFF(DAY, @startdate+2, @enddate)as timepassedd", conn);
        DataSet ds = new DataSet();
        da.Fill(ds);
        if(ds.Tables.Count == 1)
        {
            if(ds.Tables[0].Rows.Count > 0)
            {
                foreach(DataRow dr in ds.Tables[0].Rows)
                {
                    if(dr.ItemArray.Length > 0)
                    {
                        if(dr["timepassedd"] != DBNull.Value)
                        {
                            int date;
                            date = Convert.ToInt32(Dr["timepassedd"]);
                            if (date > 0)
                            {
                                com = new SqlCommand("delete lend where client_name ='" + comboBox1.Text + "'" +
                                    "UPDATE book_list set book_stock = book_stock  1 WHERE book_name ='" + comboBox1.Text + "'", conn);
                                com.ExecuteNonQuery();
                                MessageBox.Show("You Returned the book " + date + " Days Late!" +
                                    "please pay the fee to the front desk");
                                UserPanel u = new UserPanel();
                                u.Show();
                                this.Hide();
                            }
                            else if (date <= 0)
                            {
                                com = new SqlCommand("delete lend where client_name ='" + comboBox1.Text + "'" +
                                    "UPDATE book_list set book_stock = book_stock  1 WHERE book_name ='" + comboBox1.Text + "'", conn);
                                com.ExecuteNonQuery();
                                MessageBox.Show("You Returned the book " + date + " Days Late!" +
                                    "please pay the fee to the front desk");
                                UserPanel u = new UserPanel();
                                u.Show();
                                this.Hide();
                            }
                        }
                    }
                }
            }
        }
        conn.Close();
</code>```

You should check for DBNull value, if the column is null-able in the database a DBNull.Value will be returned instead! So you should check this column for such a value before dealing with it

Also, you shouldn't accept values from the user input and directly injecting them into the SQL query! ADO.Net. Has something called Sql Parameters it can be found in the property Parameters in the SqlCommand class. You should use this property to add values from user as parameters to the query

For Example, client name can be added like this:

```<code>    com.Parameters.Add(new SqlParameter("client_name", comboBox1.Text));
</code>```

Now you tell the Sql Command that the value is actually presented in the SqlParameters collection like this:

```<code>SqlCommand com = new SqlCommand("update lend set date_back=convert(datetime2, getdate(), 102) where client_name ='@client_name'", conn);
</code>```

Take a look at this question Why do we always prefer using parameters in the SQL statements?

This is a MSDN reference for the Parameters property

Title: c# fetching database into SQL Server datatable

Body:
        conn.Open();
        SqlCommand com = new SqlCommand("update lend set date_back=convert(datetime2, getdate(), 102) where client_name ='" + comboBox1.Text + "'", conn);
        SqlDataAdapter da = new SqlDataAdapter("Declare @startdate smalldatetime declare @enddate smalldatetime set @startdate = (select date_lended from dbo.lend where client_name = '" + comboBox1.Text + "') set @enddate = (select date_back from dbo.lend where client_name = '" + comboBox1.Text + "') SELECT DATEDIFF(DAY, @startdate+2, @enddate)as timepassedd", conn);
        DataSet ds = new DataSet();
        da.Fill(ds);
        if(ds.Tables.Count == 1)
        {
            if(ds.Tables[0].Rows.Count > 0)
            {
                foreach(DataRow dr in ds.Tables[0].Rows)
                {
                    if(dr.ItemArray.Length > 0)
                    {
                        if(dr["timepassedd"] != DBNull.Value)
                        {
                            int date;
                            date = Convert.ToInt32(Dr["timepassedd"]);
                            if (date > 0)
                            {
                                com = new SqlCommand("delete lend where client_name ='" + comboBox1.Text + "'" +
                                    "UPDATE book_list set book_stock = book_stock  1 WHERE book_name ='" + comboBox1.Text + "'", conn);
                                com.ExecuteNonQuery();
                                MessageBox.Show("You Returned the book " + date + " Days Late!" +
                                    "please pay the fee to the front desk");
                                UserPanel u = new UserPanel();
                                u.Show();
                                this.Hide();
                            }
                            else if (date <= 0)
                            {
                                com = new SqlCommand("delete lend where client_name ='" + comboBox1.Text + "'" +
                                    "UPDATE book_list set book_stock = book_stock  1 WHERE book_name ='" + comboBox1.Text + "'", conn);
                                com.ExecuteNonQuery();
                                MessageBox.Show("You Returned the book " + date + " Days Late!" +
                                    "please pay the fee to the front desk");
                                UserPanel u = new UserPanel();
                                u.Show();
                                this.Hide();
                            }
                        }
                    }
                }
            }
        }
        conn.Close();

You should check for DBNull value, if the column is null-able in the database a DBNull.Value will be returned instead! So you should check this column for such a value before dealing with it

Also, you shouldn't accept values from the user input and directly injecting them into the SQL query! ADO.Net. Has something called Sql Parameters it can be found in the property Parameters in the SqlCommand class. You should use this property to add values from user as parameters to the query

For Example, client name can be added like this:

    com.Parameters.Add(new SqlParameter("client_name", comboBox1.Text));

Now you tell the Sql Command that the value is actually presented in the SqlParameters collection like this:

SqlCommand com = new SqlCommand("update lend set date_back=convert(datetime2, getdate(), 102) where client_name ='@client_name'", conn);

Take a look at this question Why do we always prefer using parameters in the SQL statements?

This is a MSDN reference for the Parameters property


来源: stackexchange

问:
How to revolve an object around another object (C++ and Ogre3D)?
I am currently making a solar system in Ogre3D. The other planets revolve around the sun perfectly but when I try to revolve the moon around the earth, it revolves at a certain point NEAR earth, not around earth, which makes it intersect with the earth at times.

This is the code for creating the planet's distance from the origin (0,0,0)

```<code>    Vector3 location = Vector3::ZERO;
    float distance = revolverDistance;
    location.x = distance; location.z = distance; location.y = 0;
    planet->setPosition(location.x, location.y, location.z);
</code>```

And this is the code for the revolution

```<code>Degree planetRevolution = Degree(revolution * evt.timeSinceLastFrame);
    Vector3 location = Vector3::ZERO;
    location.x = revolver->getPosition().x - revolve->getPosition().x;
    location.z = revolver->getPosition().z - revolve->getPosition().z;
    float oldX = location.x;
    float oldZ = location.z;
    float newX = (oldX*Math::Cos(planetRevolution)) + (oldZ*Math::Sin(planetRevolution));
    float newZ = (oldX*-Math::Sin(planetRevolution)) + (oldZ*Math::Cos(planetRevolution));
    mPlanet->setPosition(newX, mPlanet->getPosition().y, newZ);
</code>```

Revolve = A planet (ex. earth)

Revolver = Another planet that is revolving around another planet (ex. moon)

For variables, I have sunDistance = 0, earthDistance = 150, and moonDistance = 155, all in which are floats.*

I have tried setting float distance = revolveDistance + revolverDistance, and changing the distance of the moon to 5 but the point of which it revolves just moved slightly further away.

Thank you in advance!

REMINDER (Thank you to one of the people who answered for reminding me):
I am not allowed to use the scene hierarchy.

答:
Your question is an excellent example what the scene graph hierarchy is good for :)

Set up an Ogre scene node at the sun's center point.

Attach the sun entity to the sun node

Place another scene node at the sun's position. This will be the planet's pivot node, around which it revolves.

Make the pivot node a child of the sun node.

Place a scene node at the planet's start position

Attach planet entity

make the planet node a child of the pivot node

Create another pivot scene node at the planet position and make it child of the planet's center node.

Create a scene node at the moon's position, attach moon entity to it and make it child at the moon pivot node.

Now Ogre will do everything for you without fiddling around with hardcoded positions. You will just have to rotate the pivot nodes, no need for setting positions anymore.

ContentLicense: CC BY-SA 3.0

Body:
I am currently making a solar system in Ogre3D. The other planets revolve around the sun perfectly but when I try to revolve the moon around the earth, it revolves at a certain point NEAR earth, not around earth, which makes it intersect with the earth at times.

This is the code for creating the planet's distance from the origin (0,0,0)

    Vector3 location = Vector3::ZERO;
    float distance = revolverDistance;
    location.x = distance; location.z = distance; location.y = 0;
    planet->setPosition(location.x, location.y, location.z);

And this is the code for the revolution

Degree planetRevolution = Degree(revolution * evt.timeSinceLastFrame);
    Vector3 location = Vector3::ZERO;
    location.x = revolver->getPosition().x - revolve->getPosition().x;
    location.z = revolver->getPosition().z - revolve->getPosition().z;
    float oldX = location.x;
    float oldZ = location.z;
    float newX = (oldX*Math::Cos(planetRevolution)) + (oldZ*Math::Sin(planetRevolution));
    float newZ = (oldX*-Math::Sin(planetRevolution)) + (oldZ*Math::Cos(planetRevolution));
    mPlanet->setPosition(newX, mPlanet->getPosition().y, newZ);

Revolve = A planet (ex. earth)

Revolver = Another planet that is revolving around another planet (ex. moon)

For variables, I have sunDistance = 0, earthDistance = 150, and moonDistance = 155, all in which are floats.*

I have tried setting float distance = revolveDistance + revolverDistance, and changing the distance of the moon to 5 but the point of which it revolves just moved slightly further away.

Thank you in advance!

REMINDER (Thank you to one of the people who answered for reminding me):
I am not allowed to use the scene hierarchy.


问:
c# fetching database into SQL Server datatable
I have a problem with this code... I don't have the slightest clue for what is happening...

When I run this code in Visual Studio, I get an error saying:

System.InvalidCastException: 'Object cannot be cast from DBNull to other types.'

And here's the code:

```<code>conn.Open();

SqlCommand com = new SqlCommand("update lend set date_back=convert(datetime2, getdate(), 102) where client_name ='" + comboBox1.Text + "'", conn);

SqlDataAdapter da = new SqlDataAdapter("Declare @startdate smalldatetime declare @enddate smalldatetime set @startdate = (select date_lended from dbo.lend where client_name = '" + comboBox1.Text + "') set @enddate = (select date_back from dbo.lend where client_name = '" + comboBox1.Text + "') SELECT DATEDIFF(DAY, @startdate+2, @enddate)as timepassedd", conn);

DataTable dt = new DataTable();
da.Fill(dt);

foreach (DataRow DR in dt.Rows)
{
    int date;
    date = Convert.ToInt32(DR["timepassedd"]);

    if (date > 0)
    {
        com = new SqlCommand("DELETE lend WHERE client_name ='"+comboBox1.Text+"'" +
                             "UPDATE book_list set book_stock = book_stock  1 WHERE book_name ='" + comboBox1.Text + "'",conn);
        com.ExecuteNonQuery();

        MessageBox.Show("You Returned the book " + date + " Days Late!" +
                            "please pay the fee to the front desk");

        UserPanel u = new UserPanel();
        u.Show();

        this.Hide();
    }
    else if (date <= 0)
    {
        com = new SqlCommand("DELETE lend WHERE client_name ='" + comboBox1.Text + "'" +
                             "UPDATE book_list set book_stock = book_stock  1 WHERE book_name ='" + comboBox1.Text + "'", conn);
        com.ExecuteNonQuery();

        MessageBox.Show("You returned the book " + date + " Days Late!" +
                            "please pay the fee to the front desk");

        UserPanel u = new UserPanel();
        u.Show();

        this.Hide();
    }
}

conn.Close();
</code>```

Thanks in advance

答:
```<code>set @startdate = (select date_lended from dbo.lend where client_name = '" + comboBox1.Text + "')
set @enddate = (select date_back from dbo.lend where client_name = '" + comboBox1.Text + "')
</code>```

a) vulnerable to unexpected behaviour if comboBox1.Text was ever to contain ' characters

b) both will result in @startdate or @enddate being NULL if there are no records matching what's selected in the combobox, which then produces a NULL value for '@datepassedd', hence your error when trying to convert to an int.

c) you don't need to query the database twice, you can just do

```<code>select DATEDIFF(DAY, date_lended+2, date_back) as timepassedd FROM dbo.lend where client_name = @clientName
</code>```

(@clientName can then be added a as parameter)

In this case, there will be no rows returned if no records match the name. BTW there was never any need to use a DataTable and iterate through the records, as your query as it is now only ever returns a single row.

Body:
I have a problem with this code... I don't have the slightest clue for what is happening...

When I run this code in Visual Studio, I get an error saying:

System.InvalidCastException: 'Object cannot be cast from DBNull to other types.'

And here's the code:

conn.Open();

SqlCommand com = new SqlCommand("update lend set date_back=convert(datetime2, getdate(), 102) where client_name ='" + comboBox1.Text + "'", conn);

SqlDataAdapter da = new SqlDataAdapter("Declare @startdate smalldatetime declare @enddate smalldatetime set @startdate = (select date_lended from dbo.lend where client_name = '" + comboBox1.Text + "') set @enddate = (select date_back from dbo.lend where client_name = '" + comboBox1.Text + "') SELECT DATEDIFF(DAY, @startdate+2, @enddate)as timepassedd", conn);

DataTable dt = new DataTable();
da.Fill(dt);

foreach (DataRow DR in dt.Rows)
{
    int date;
    date = Convert.ToInt32(DR["timepassedd"]);

    if (date > 0)
    {
        com = new SqlCommand("DELETE lend WHERE client_name ='"+comboBox1.Text+"'" +
                             "UPDATE book_list set book_stock = book_stock  1 WHERE book_name ='" + comboBox1.Text + "'",conn);
        com.ExecuteNonQuery();

        MessageBox.Show("You Returned the book " + date + " Days Late!" +
                            "please pay the fee to the front desk");

        UserPanel u = new UserPanel();
        u.Show();

        this.Hide();
    }
    else if (date <= 0)
    {
        com = new SqlCommand("DELETE lend WHERE client_name ='" + comboBox1.Text + "'" +
                             "UPDATE book_list set book_stock = book_stock  1 WHERE book_name ='" + comboBox1.Text + "'", conn);
        com.ExecuteNonQuery();

        MessageBox.Show("You returned the book " + date + " Days Late!" +
                            "please pay the fee to the front desk");

        UserPanel u = new UserPanel();
        u.Show();

        this.Hide();
    }
}

conn.Close();

Thanks in advance

Body:
set @startdate = (select date_lended from dbo.lend where client_name = '" + comboBox1.Text + "')
set @enddate = (select date_back from dbo.lend where client_name = '" + comboBox1.Text + "')

a) vulnerable to unexpected behaviour if comboBox1.Text was ever to contain ' characters

b) both will result in @startdate or @enddate being NULL if there are no records matching what's selected in the combobox, which then produces a NULL value for '@datepassedd', hence your error when trying to convert to an int.

c) you don't need to query the database twice, you can just do

select DATEDIFF(DAY, date_lended+2, date_back) as timepassedd FROM dbo.lend where client_name = @clientName

(@clientName can then be added a as parameter)

In this case, there will be no rows returned if no records match the name. BTW there was never any need to use a DataTable and iterate through the records, as your query as it is now only ever returns a single row.


问:
Braintree PHP SDK cURL exception
I keep getting back a Braintree_Exception_SSLCertificate exception when I try to generate a client token using Braintree_ClientToken::generate(). I've got the SDK loaded and my PHP setup seems to meet the minimum requirements for the SDK.

The versions of PHP and cURL I'm running are:

PHP 5.5.3

cURL 7.32.0 with OpenSSL/1.0.1e. SSL is enabled in my cURL module.

I noticed Braintree is enforcing TLS 1.2 so I thought that might be the issue but I tried adding the following line to Http.php in the Braintree SDK:

```<code>curl_setopt($curl, CURLOPT_SSLVERSION, 6);
</code>```

This should set cURL to use TLS 1.2 but it didn't seem to help and I'm not sure how to verify that the setting even took effect.

I haven't managed to successfully place a request to Braintree's API yet so I'm worried this is something I'm doing wrong or maybe the version of cURL I'm using is no good. Is there anything I need to enable SSL that I've missed?

Thanks,
Brad.

答:
Okay, I have just climbed Himalaya. The solution above is not a solution at all. Here's what I did to solve this problem. For Centos 7 machine, yum update is sometimes useless. The only solution is to update OpenSSL and Curl manually.

There are 15 steps:

Download latest OpenSSL package.

```<code>wget https://www.openssl.org/source/openssl-1.0.2l.tar.gz
</code>```

Unzip

```<code>tar -xzvf openssl-1.0.2l.tar.gz
</code>```

Enter folder

```<code>cd openssl-1.0.2l
</code>```

Config

```<code>./config --shared
</code>```

Install

```<code>make && make install
</code>```

That's not the end of the journey, you have to update curl too. Download the latest version of curl.

```<code>wget https://curl.haxx.se/download/curl-7.55.1.tar.gz
</code>```

Unzip

```<code>tar -xzvf curl-7.55.1.tar.gz
</code>```

Enter folder

```<code>cd curl-7.55.1
</code>```

Set lib path

```<code>export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/ssl/lib
</code>```

Config

```<code>./configure --prefix=/usr/local/curl/ --without-nss --with-ssl=/usr/local/ssl/
</code>```

Install

```<code>make && make install
</code>```

Backup a bit

```<code>mv /usr/bin/curl /usr/bin/curl.bak
</code>```

Link it

```<code>ln -s /usr/local/curl/bin/curl /usr/bin/curl
</code>```

Finally, check your curl version by

```<code>curl --version
</code>```

If you did all these steps correctly, it shows

```<code>curl 7.55.1 (x86_64-pc-linux-gnu) libcurl/7.55.1 OpenSSL/1.0.2l
</code>```

Title: Braintree PHP SDK cURL exception

Body:
I keep getting back a Braintree_Exception_SSLCertificate exception when I try to generate a client token using Braintree_ClientToken::generate(). I've got the SDK loaded and my PHP setup seems to meet the minimum requirements for the SDK.

The versions of PHP and cURL I'm running are:

PHP 5.5.3

cURL 7.32.0 with OpenSSL/1.0.1e. SSL is enabled in my cURL module.

I noticed Braintree is enforcing TLS 1.2 so I thought that might be the issue but I tried adding the following line to Http.php in the Braintree SDK:

curl_setopt($curl, CURLOPT_SSLVERSION, 6);

This should set cURL to use TLS 1.2 but it didn't seem to help and I'm not sure how to verify that the setting even took effect.

I haven't managed to successfully place a request to Braintree's API yet so I'm worried this is something I'm doing wrong or maybe the version of cURL I'm using is no good. Is there anything I need to enable SSL that I've missed?

Thanks,
Brad.

Body:
Okay, I have just climbed Himalaya. The solution above is not a solution at all. Here's what I did to solve this problem. For Centos 7 machine, yum update is sometimes useless. The only solution is to update OpenSSL and Curl manually.

There are 15 steps:

Download latest OpenSSL package.

wget https://www.openssl.org/source/openssl-1.0.2l.tar.gz

Unzip

tar -xzvf openssl-1.0.2l.tar.gz

Enter folder

cd openssl-1.0.2l

Config

./config --shared

Install

make && make install

That's not the end of the journey, you have to update curl too. Download the latest version of curl.

wget https://curl.haxx.se/download/curl-7.55.1.tar.gz

Unzip

tar -xzvf curl-7.55.1.tar.gz

Enter folder

cd curl-7.55.1

Set lib path

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/ssl/lib

Config

./configure --prefix=/usr/local/curl/ --without-nss --with-ssl=/usr/local/ssl/

Install

make && make install

Backup a bit

mv /usr/bin/curl /usr/bin/curl.bak

Link it

ln -s /usr/local/curl/bin/curl /usr/bin/curl

Finally, check your curl version by

curl --version

If you did all these steps correctly, it shows

curl 7.55.1 (x86_64-pc-linux-gnu) libcurl/7.55.1 OpenSSL/1.0.2l


问:
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

答:
Just add top, leading, trailing constraints to the custom view with respect to its superview.
Add the bottom constraint to the top another view that will lie below your custom view & is also a subview on your custom view's superview.

In your code the problem is with your bottom constraint as well. You are trying to add the constraint b/w the bottom of custom view & top of navigation bar.

```<code> let topConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0)

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

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

let bottomConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: anotherView, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0)
</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:
Just add top, leading, trailing constraints to the custom view with respect to its superview.
Add the bottom constraint to the top another view that will lie below your custom view & is also a subview on your custom view's superview.

In your code the problem is with your bottom constraint as well. You are trying to add the constraint b/w the bottom of custom view & top of navigation bar.

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

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

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

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


问:
How to stop showing a blank page when going to next fragment
For what I did is first to create a tapBar (Activity). Then under Activity, I have first, second and third fragments. I am trying to move to next fragment from first fragment but I get a blank page (since it is not blue color which I set in xml). Any suggestions?

Activity

```<code>public class TabBar extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tabbar);
        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
        SimpleFragmentPagerAdapter adapter = new SimpleFragmentPagerAdapter(this, getSupportFragmentManager());
        viewPager.setAdapter(adapter);
        TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
        tabLayout.setupWithViewPager(viewPager);
    }
}
</code>```

First fragment

```<code>public class First extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.first, null);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Fragment fragment = new Next();
                FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.hide(First.this);
                fragmentTransaction.show(fragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
            }
        });
    return rootView;
}
</code>```

Next Fragment

```<code>public class Next extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.next, container, false);
        return rootView;
    }
}
</code>```

Next Fragment XML

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/avoscloud_blue">
</RelativeLayout>
</code>```

答: tansaction.replace() this method work for new fragment if it will not work than make custom pager adapter and try again using it. and if you dont want to create pager adapter just add container layout in your xml and put fragment inside it and replace that fragment on button click</p>

Body:
For what I did is first to create a tapBar (Activity). Then under Activity, I have first, second and third fragments. I am trying to move to next fragment from first fragment but I get a blank page (since it is not blue color which I set in xml). Any suggestions?

Activity

public class TabBar extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tabbar);
        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
        SimpleFragmentPagerAdapter adapter = new SimpleFragmentPagerAdapter(this, getSupportFragmentManager());
        viewPager.setAdapter(adapter);
        TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
        tabLayout.setupWithViewPager(viewPager);
    }
}

First fragment

public class First extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.first, null);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Fragment fragment = new Next();
                FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.hide(First.this);
                fragmentTransaction.show(fragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
            }
        });
    return rootView;
}

Next Fragment

public class Next extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.next, container, false);
        return rootView;
    }
}

Next Fragment XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/avoscloud_blue">
</RelativeLayout>


问:
Generate a data series with several constraints
I would like to generate a set of 62 numbers ranging from 1 to 7 (integer only), and their mean has to be 4.65. On top of this, 28 of those numbers need to have a mean of 4.73 and 34 of them need to have a mean of 4.83.

I have been trying to work this out using excel solver, but what i got is a set of same number.  I turn to R and try to impose standard deviation.. but i'm not so sure how to generate that set of numbers with all these contraints..

```<code> x <- rnorm(28, m=4.73, sd=1)

 y <- rnorm(34, m=4.83, sd=1)

 z <- rnorm(62, m=4.65, sd=1)

 z[1:20]

 xtrunc <- x[x <=7]
</code>```

答:
I have created such a vector in x3. Translated in R, your question is:

"a set of 62 numbers"

```<code>> length(x3)
[1] 62
</code>```

"ranging from 1 to 7"

```<code>> range(x3)
[1] 4.431431 5.296670
</code>```

"their mean has to be 4.65".

```<code>> mean(x3)
[1] 4.650001
</code>```

"On top of this, 28 of those numbers need to have a mean of 4.73"

```<code>> mean(x3[1:28])
[1] 4.73
</code>```

"and 34 of them need to have a mean of 4.83."

```<code>> mean(x3[1:34])
[1] 4.830001
</code>```

x3 is:

```<code>> x3 = c(rep(4.73,28),rep(5.29667,6), rep(4.431431,28))
</code>```

Constructed by applying your constraints in the order of increasing vector length and computing the repeated value required to get the mean to the required value.

Body:
I would like to generate a set of 62 numbers ranging from 1 to 7 (integer only), and their mean has to be 4.65. On top of this, 28 of those numbers need to have a mean of 4.73 and 34 of them need to have a mean of 4.83.

I have been trying to work this out using excel solver, but what i got is a set of same number.  I turn to R and try to impose standard deviation.. but i'm not so sure how to generate that set of numbers with all these contraints..

 x <- rnorm(28, m=4.73, sd=1)

 y <- rnorm(34, m=4.83, sd=1)

 z <- rnorm(62, m=4.65, sd=1)

 z[1:20]

 xtrunc <- x[x <=7]

Body:
I have created such a vector in x3. Translated in R, your question is:

"a set of 62 numbers"

> length(x3)
[1] 62

"ranging from 1 to 7"

> range(x3)
[1] 4.431431 5.296670

"their mean has to be 4.65".

> mean(x3)
[1] 4.650001

"On top of this, 28 of those numbers need to have a mean of 4.73"

> mean(x3[1:28])
[1] 4.73

"and 34 of them need to have a mean of 4.83."

> mean(x3[1:34])
[1] 4.830001

x3 is:

> x3 = c(rep(4.73,28),rep(5.29667,6), rep(4.431431,28))

Constructed by applying your constraints in the order of increasing vector length and computing the repeated value required to get the mean to the required value.


问:
PhantomJs screenshot is not rendering correctly
We are developing a web scraper type thing, where the user enters a website's url and our web application generates a screenshot of the website. We use phantomjs's rendering for generating the screenshot in PNG format. Although it works like a charm for most cases, some websites are not rendered correctly. For example if you take the website http://dorevi.lt/ it shows like this in the browser:

However the screenshot rendered by phantom is as below:

You can see that it stretches the center table and breaks content in between. What I have tried so far is:

tried to put all sorts of delay, even upto 30 seconds, between page read and page render but no luck.

tried all solution from this answer where we wait for DOM content to be loaded (enternal stlysheets etc) , but again same output

Tried to add all possible parameters while executing the phanjomjs script, this is what my final command looks like:
phantomjs.exe --ignore-ssl-errors=true --load-images=true --ssl-protocol=any --debug=true --local-to-remote-url-access=true --web-security=false --disk-cache=false script.js

As you can see I have used all possible flags too but still the same output. Please help me on this, as we need to make sure we generate accurate screenshots of the webpages.

Info:
Phantomjs version used: 2.1
OS: CentOS for production, also testing on windows 7 with same output
Technolog: Application is used building PHP

Edit 1: Adding --debug=true output

```<code>2017-12-09T15:31:40 [DEBUG] CookieJar - Created but will not store cookies (use
option '--cookies-file=<filename>' to enable persistent cookie storage)
2017-12-09T15:31:41 [DEBUG] Set  "http"  proxy to:  "" : 1080
2017-12-09T15:31:41 [DEBUG] Phantom - execute: Configuration
2017-12-09T15:31:41 [DEBUG]      0 objectName : ""
2017-12-09T15:31:41 [DEBUG]      1 cookiesFile : ""
2017-12-09T15:31:41 [DEBUG]      2 diskCacheEnabled : "true"
2017-12-09T15:31:41 [DEBUG]      3 maxDiskCacheSize : "-1"
2017-12-09T15:31:41 [DEBUG]      4 diskCachePath : ""
2017-12-09T15:31:41 [DEBUG]      5 ignoreSslErrors : "true"
2017-12-09T15:31:41 [DEBUG]      6 localUrlAccessEnabled : "true"
2017-12-09T15:31:41 [DEBUG]      7 localToRemoteUrlAccessEnabled : "true"
2017-12-09T15:31:41 [DEBUG]      8 outputEncoding : "UTF-8"
2017-12-09T15:31:41 [DEBUG]      9 proxyType : "http"
2017-12-09T15:31:41 [DEBUG]      10 proxy : ":1080"
2017-12-09T15:31:41 [DEBUG]      11 proxyAuth : ":"
2017-12-09T15:31:41 [DEBUG]      12 scriptEncoding : "UTF-8"
2017-12-09T15:31:41 [DEBUG]      13 webSecurityEnabled : "false"
2017-12-09T15:31:41 [DEBUG]      14 offlineStoragePath : ""
2017-12-09T15:31:41 [DEBUG]      15 localStoragePath : ""
2017-12-09T15:31:41 [DEBUG]      16 localStorageDefaultQuota : "-1"
2017-12-09T15:31:41 [DEBUG]      17 offlineStorageDefaultQuota : "-1"
2017-12-09T15:31:41 [DEBUG]      18 printDebugMessages : "true"
2017-12-09T15:31:41 [DEBUG]      19 javascriptCanOpenWindows : "true"
2017-12-09T15:31:41 [DEBUG]      20 javascriptCanCloseWindows : "true"
2017-12-09T15:31:41 [DEBUG]      21 sslProtocol : "any"
2017-12-09T15:31:41 [DEBUG]      22 sslCiphers : "ECDHE-ECDSA-AES128-GCM-SHA256:
ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA:ECD
HE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-RC4-SH
A:ECDHE-RSA-RC4-SHA:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA:DHE-RSA-AES256-SHA:AES
128-GCM-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:RC4-SHA:RC4-MD5"
2017-12-09T15:31:41 [DEBUG]      23 sslCertificatesPath : ""
2017-12-09T15:31:41 [DEBUG]      24 sslClientCertificateFile : ""
2017-12-09T15:31:41 [DEBUG]      25 sslClientKeyFile : ""
2017-12-09T15:31:41 [DEBUG]      26 sslClientKeyPassphrase : ""
2017-12-09T15:31:41 [DEBUG]      27 webdriver : ":"
2017-12-09T15:31:41 [DEBUG]      28 webdriverLogFile : ""
2017-12-09T15:31:41 [DEBUG]      29 webdriverLogLevel : "INFO"
2017-12-09T15:31:41 [DEBUG]      30 webdriverSeleniumGridHub : ""
2017-12-09T15:31:41 [DEBUG] Phantom - execute: Script & Arguments
2017-12-09T15:31:41 [DEBUG]      script: "script.js"
2017-12-09T15:31:41 [DEBUG] Phantom - execute: Starting normal mode
2017-12-09T15:31:41 [DEBUG] WebPage - setupFrame ""
2017-12-09T15:31:41 [DEBUG] FileSystem - _open: ":/modules/fs.js" QMap(("mode",
QVariant(QString, "r")))
2017-12-09T15:31:41 [DEBUG] FileSystem - _open: ":/modules/system.js" QMap(("mod
e", QVariant(QString, "r")))
2017-12-09T15:31:41 [DEBUG] FileSystem - _open: ":/modules/webpage.js" QMap(("mo
de", QVariant(QString, "r")))
2017-12-09T15:31:42 [DEBUG] WebPage - updateLoadingProgress: 10
2017-12-09T15:31:42 [DEBUG] CookieJar - Saved "CMSSESSID8694f4a4=kpca79mq05g4v0f
nh31uvkmu86; domain=dorevi.lt; path=/"
2017-12-09T15:31:42 [DEBUG] WebPage - updateLoadingProgress: 30
2017-12-09T15:31:42 [DEBUG] WebPage - updateLoadingProgress: 32
2017-12-09T15:31:42 [DEBUG] WebPage - updateLoadingProgress: 35
2017-12-09T15:31:42 [DEBUG] WebPage - updateLoadingProgress: 37
2017-12-09T15:31:42 [DEBUG] WebPage - updateLoadingProgress: 39
2017-12-09T15:31:42 [DEBUG] WebPage - updateLoadingProgress: 41
2017-12-09T15:31:42 [DEBUG] WebPage - updateLoadingProgress: 43
2017-12-09T15:31:42 [DEBUG] WebPage - setupFrame ""
2017-12-09T15:31:42 [DEBUG] WebPage - updateLoadingProgress: 46
2017-12-09T15:31:42 [DEBUG] WebPage - updateLoadingProgress: 48
2017-12-09T15:31:43 [DEBUG] WebPage - updateLoadingProgress: 52
2017-12-09T15:31:43 [DEBUG] WebPage - updateLoadingProgress: 55
2017-12-09T15:31:43 [DEBUG] WebPage - updateLoadingProgress: 58
2017-12-09T15:31:43 [DEBUG] WebPage - updateLoadingProgress: 60
2017-12-09T15:31:43 [DEBUG] WebPage - updateLoadingProgress: 63
2017-12-09T15:31:43 [DEBUG] WebPage - updateLoadingProgress: 67
2017-12-09T15:31:43 [DEBUG] WebPage - updateLoadingProgress: 69
2017-12-09T15:31:43 [DEBUG] WebPage - updateLoadingProgress: 71
2017-12-09T15:31:43 [DEBUG] WebPage - updateLoadingProgress: 74
2017-12-09T15:31:43 [DEBUG] WebPage - updateLoadingProgress: 76
2017-12-09T15:31:43 [DEBUG] WebPage - updateLoadingProgress: 78
2017-12-09T15:31:43 [DEBUG] WebPage - updateLoadingProgress: 81
2017-12-09T15:31:43 [DEBUG] WebPage - updateLoadingProgress: 83
2017-12-09T15:31:43 [DEBUG] WebPage - updateLoadingProgress: 85
2017-12-09T15:31:43 [DEBUG] WebPage - updateLoadingProgress: 87
2017-12-09T15:31:43 [DEBUG] WebPage - updateLoadingProgress: 100
2017-12-09T15:31:43 [DEBUG] CookieJar - Saved "CMSSESSID8694f4a4=kpca79mq05g4v0f
nh31uvkmu86; domain=dorevi.lt; path=/"
2017-12-09T15:31:43 [DEBUG] CookieJar - Saved "_ga=GA1.2.690650226.1512813703; e
xpires=Mon, 09-Dec-2019 10:01:43 GMT; domain=.dorevi.lt; path=/"
2017-12-09T15:31:43 [DEBUG] CookieJar - Saved "CMSSESSID8694f4a4=kpca79mq05g4v0f
nh31uvkmu86; domain=dorevi.lt; path=/"
2017-12-09T15:31:43 [DEBUG] CookieJar - Saved "_ga=GA1.2.690650226.1512813703; e
xpires=Mon, 09-Dec-2019 10:01:43 GMT; domain=.dorevi.lt; path=/"
2017-12-09T15:31:43 [DEBUG] CookieJar - Saved "_gid=GA1.2.860165508.1512813703;
expires=Sun, 10-Dec-2017 10:01:43 GMT; domain=.dorevi.lt; path=/"
2017-12-09T15:31:43 [DEBUG] CookieJar - Saved "CMSSESSID8694f4a4=kpca79mq05g4v0f
nh31uvkmu86; domain=dorevi.lt; path=/"
2017-12-09T15:31:43 [DEBUG] CookieJar - Saved "_ga=GA1.2.690650226.1512813703; e
xpires=Mon, 09-Dec-2019 10:01:43 GMT; domain=.dorevi.lt; path=/"
2017-12-09T15:31:43 [DEBUG] CookieJar - Saved "_gid=GA1.2.860165508.1512813703;
expires=Sun, 10-Dec-2017 10:01:43 GMT; domain=.dorevi.lt; path=/"
2017-12-09T15:31:43 [DEBUG] CookieJar - Saved "_gat=1; expires=Sat, 09-Dec-2017
10:02:43 GMT; domain=.dorevi.lt; path=/"
2017-12-09T15:31:43 [DEBUG] WebPage - setupFrame ""
2017-12-09T15:31:53 [DEBUG] WebPage - setupFrame ""
2017-12-09T15:31:53 [DEBUG] WebPage - updateLoadingProgress: 10
2017-12-09T15:31:53 [DEBUG] WebPage - setupFrame ""
2017-12-09T15:31:53 [DEBUG] WebPage - updateLoadingProgress: 100
2017-12-09T15:31:53 [DEBUG] WebPage - setupFrame ""
2017-12-09T15:31:53 [DEBUG] FileSystem - _open: ":/modules/fs.js" QMap(("mode",
QVariant(QString, "r")))
2017-12-09T15:31:53 [DEBUG] FileSystem - _open: ":/modules/system.js" QMap(("mod
e", QVariant(QString, "r")))
2017-12-09T15:31:53 [DEBUG] FileSystem - _open: ":/modules/webpage.js" QMap(("mo
de", QVariant(QString, "r")))
2017-12-09T15:31:53 [DEBUG] WebPage - updateLoadingProgress: 10
2017-12-09T15:31:53 [DEBUG] WebPage - setupFrame ""
2017-12-09T15:31:53 [DEBUG] FileSystem - _open: ":/modules/fs.js" QMap(("mode",
QVariant(QString, "r")))
2017-12-09T15:31:53 [DEBUG] FileSystem - _open: ":/modules/system.js" QMap(("mod
e", QVariant(QString, "r")))
2017-12-09T15:31:53 [DEBUG] FileSystem - _open: ":/modules/webpage.js" QMap(("mo
de", QVariant(QString, "r")))
2017-12-09T15:31:53 [DEBUG] WebPage - updateLoadingProgress: 100
2017-12-09T15:31:53 [DEBUG] CookieJar - Purged (session) "CMSSESSID8694f4a4=kpca
79mq05g4v0fnh31uvkmu86; domain=dorevi.lt; path=/"
2017-12-09T15:31:53 [DEBUG] CookieJar - Saved "_ga=GA1.2.690650226.1512813703; e
xpires=Mon, 09-Dec-2019 10:01:43 GMT; domain=.dorevi.lt; path=/"
2017-12-09T15:31:53 [DEBUG] CookieJar - Saved "_gid=GA1.2.860165508.1512813703;
expires=Sun, 10-Dec-2017 10:01:43 GMT; domain=.dorevi.lt; path=/"
2017-12-09T15:31:53 [DEBUG] CookieJar - Saved "_gat=1; expires=Sat, 09-Dec-2017
10:02:43 GMT; domain=.dorevi.lt; path=/"
</code>```

答:
PhantomJS 2.1.1 is unfortunately indeed is old and abandoned in favor of headless Chrome's puppeteer

Here's making screenshot in that:

```<code>'use strict';

const puppeteer = require('puppeteer');

(async() => {

const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://www.nytimes.com/');
await page.screenshot({path: 'full.png', fullPage: true});
await browser.close();

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

ContentLicense: CC BY-SA 4.0

Body:
We are developing a web scraper type thing, where the user enters a website's url and our web application generates a screenshot of the website. We use phantomjs's rendering for generating the screenshot in PNG format. Although it works like a charm for most cases, some websites are not rendered correctly. For example if you take the website http://dorevi.lt/ it shows like this in the browser:

However the screenshot rendered by phantom is as below:

You can see that it stretches the center table and breaks content in between. What I have tried so far is:

tried to put all sorts of delay, even upto 30 seconds, between page read and page render but no luck.

tried all solution from this answer where we wait for DOM content to be loaded (enternal stlysheets etc) , but again same output

Tried to add all possible parameters while executing the phanjomjs script, this is what my final command looks like:
phantomjs.exe --ignore-ssl-errors=true --load-images=true --ssl-protocol=any --debug=true --local-to-remote-url-access=true --web-security=false --disk-cache=false script.js

As you can see I have used all possible flags too but still the same output. Please help me on this, as we need to make sure we generate accurate screenshots of the webpages.

Info:
Phantomjs version used: 2.1
OS: CentOS for production, also testing on windows 7 with same output
Technolog: Application is used building PHP

Edit 1: Adding --debug=true output

2017-12-09T15:31:40 [DEBUG] CookieJar - Created but will not store cookies (use
option '--cookies-file=<filename>' to enable persistent cookie storage)
2017-12-09T15:31:41 [DEBUG] Set  "http"  proxy to:  "" : 1080
2017-12-09T15:31:41 [DEBUG] Phantom - execute: Configuration
2017-12-09T15:31:41 [DEBUG]      0 objectName : ""
2017-12-09T15:31:41 [DEBUG]      1 cookiesFile : ""
2017-12-09T15:31:41 [DEBUG]      2 diskCacheEnabled : "true"
2017-12-09T15:31:41 [DEBUG]      3 maxDiskCacheSize : "-1"
2017-12-09T15:31:41 [DEBUG]      4 diskCachePath : ""
2017-12-09T15:31:41 [DEBUG]      5 ignoreSslErrors : "true"
2017-12-09T15:31:41 [DEBUG]      6 localUrlAccessEnabled : "true"
2017-12-09T15:31:41 [DEBUG]      7 localToRemoteUrlAccessEnabled : "true"
2017-12-09T15:31:41 [DEBUG]      8 outputEncoding : "UTF-8"
2017-12-09T15:31:41 [DEBUG]      9 proxyType : "http"
2017-12-09T15:31:41 [DEBUG]      10 proxy : ":1080"
2017-12-09T15:31:41 [DEBUG]      11 proxyAuth : ":"
2017-12-09T15:31:41 [DEBUG]      12 scriptEncoding : "UTF-8"
2017-12-09T15:31:41 [DEBUG]      13 webSecurityEnabled : "false"
2017-12-09T15:31:41 [DEBUG]      14 offlineStoragePath : ""
2017-12-09T15:31:41 [DEBUG]      15 localStoragePath : ""
2017-12-09T15:31:41 [DEBUG]      16 localStorageDefaultQuota : "-1"
2017-12-09T15:31:41 [DEBUG]      17 offlineStorageDefaultQuota : "-1"
2017-12-09T15:31:41 [DEBUG]      18 printDebugMessages : "true"
2017-12-09T15:31:41 [DEBUG]      19 javascriptCanOpenWindows : "true"
2017-12-09T15:31:41 [DEBUG]      20 javascriptCanCloseWindows : "true"
2017-12-09T15:31:41 [DEBUG]      21 sslProtocol : "any"
2017-12-09T15:31:41 [DEBUG]      22 sslCiphers : "ECDHE-ECDSA-AES128-GCM-SHA256:
ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA:ECD
HE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-RC4-SH
A:ECDHE-RSA-RC4-SHA:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA:DHE-RSA-AES256-SHA:AES
128-GCM-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:RC4-SHA:RC4-MD5"
2017-12-09T15:31:41 [DEBUG]      23 sslCertificatesPath : ""
2017-12-09T15:31:41 [DEBUG]      24 sslClientCertificateFile : ""
2017-12-09T15:31:41 [DEBUG]      25 sslClientKeyFile : ""
2017-12-09T15:31:41 [DEBUG]      26 sslClientKeyPassphrase : ""
2017-12-09T15:31:41 [DEBUG]      27 webdriver : ":"
2017-12-09T15:31:41 [DEBUG]      28 webdriverLogFile : ""
2017-12-09T15:31:41 [DEBUG]      29 webdriverLogLevel : "INFO"
2017-12-09T15:31:41 [DEBUG]      30 webdriverSeleniumGridHub : ""
2017-12-09T15:31:41 [DEBUG] Phantom - execute: Script & Arguments
2017-12-09T15:31:41 [DEBUG]      script: "script.js"
2017-12-09T15:31:41 [DEBUG] Phantom - execute: Starting normal mode
2017-12-09T15:31:41 [DEBUG] WebPage - setupFrame ""
2017-12-09T15:31:41 [DEBUG] FileSystem - _open: ":/modules/fs.js" QMap(("mode",
QVariant(QString, "r")))
2017-12-09T15:31:41 [DEBUG] FileSystem - _open: ":/modules/system.js" QMap(("mod
e", QVariant(QString, "r")))
2017-12-09T15:31:41 [DEBUG] FileSystem - _open: ":/modules/webpage.js" QMap(("mo
de", QVariant(QString, "r")))
2017-12-09T15:31:42 [DEBUG] WebPage - updateLoadingProgress: 10
2017-12-09T15:31:42 [DEBUG] CookieJar - Saved "CMSSESSID8694f4a4=kpca79mq05g4v0f
nh31uvkmu86; domain=dorevi.lt; path=/"
2017-12-09T15:31:42 [DEBUG] WebPage - updateLoadingProgress: 30
2017-12-09T15:31:42 [DEBUG] WebPage - updateLoadingProgress: 32
2017-12-09T15:31:42 [DEBUG] WebPage - updateLoadingProgress: 35
2017-12-09T15:31:42 [DEBUG] WebPage - updateLoadingProgress: 37
2017-12-09T15:31:42 [DEBUG] WebPage - updateLoadingProgress: 39
2017-12-09T15:31:42 [DEBUG] WebPage - updateLoadingProgress: 41
2017-12-09T15:31:42 [DEBUG] WebPage - updateLoadingProgress: 43
2017-12-09T15:31:42 [DEBUG] WebPage - setupFrame ""
2017-12-09T15:31:42 [DEBUG] WebPage - updateLoadingProgress: 46
2017-12-09T15:31:42 [DEBUG] WebPage - updateLoadingProgress: 48
2017-12-09T15:31:43 [DEBUG] WebPage - updateLoadingProgress: 52
2017-12-09T15:31:43 [DEBUG] WebPage - updateLoadingProgress: 55
2017-12-09T15:31:43 [DEBUG] WebPage - updateLoadingProgress: 58
2017-12-09T15:31:43 [DEBUG] WebPage - updateLoadingProgress: 60
2017-12-09T15:31:43 [DEBUG] WebPage - updateLoadingProgress: 63
2017-12-09T15:31:43 [DEBUG] WebPage - updateLoadingProgress: 67
2017-12-09T15:31:43 [DEBUG] WebPage - updateLoadingProgress: 69
2017-12-09T15:31:43 [DEBUG] WebPage - updateLoadingProgress: 71
2017-12-09T15:31:43 [DEBUG] WebPage - updateLoadingProgress: 74
2017-12-09T15:31:43 [DEBUG] WebPage - updateLoadingProgress: 76
2017-12-09T15:31:43 [DEBUG] WebPage - updateLoadingProgress: 78
2017-12-09T15:31:43 [DEBUG] WebPage - updateLoadingProgress: 81
2017-12-09T15:31:43 [DEBUG] WebPage - updateLoadingProgress: 83
2017-12-09T15:31:43 [DEBUG] WebPage - updateLoadingProgress: 85
2017-12-09T15:31:43 [DEBUG] WebPage - updateLoadingProgress: 87
2017-12-09T15:31:43 [DEBUG] WebPage - updateLoadingProgress: 100
2017-12-09T15:31:43 [DEBUG] CookieJar - Saved "CMSSESSID8694f4a4=kpca79mq05g4v0f
nh31uvkmu86; domain=dorevi.lt; path=/"
2017-12-09T15:31:43 [DEBUG] CookieJar - Saved "_ga=GA1.2.690650226.1512813703; e
xpires=Mon, 09-Dec-2019 10:01:43 GMT; domain=.dorevi.lt; path=/"
2017-12-09T15:31:43 [DEBUG] CookieJar - Saved "CMSSESSID8694f4a4=kpca79mq05g4v0f
nh31uvkmu86; domain=dorevi.lt; path=/"
2017-12-09T15:31:43 [DEBUG] CookieJar - Saved "_ga=GA1.2.690650226.1512813703; e
xpires=Mon, 09-Dec-2019 10:01:43 GMT; domain=.dorevi.lt; path=/"
2017-12-09T15:31:43 [DEBUG] CookieJar - Saved "_gid=GA1.2.860165508.1512813703;
expires=Sun, 10-Dec-2017 10:01:43 GMT; domain=.dorevi.lt; path=/"
2017-12-09T15:31:43 [DEBUG] CookieJar - Saved "CMSSESSID8694f4a4=kpca79mq05g4v0f
nh31uvkmu86; domain=dorevi.lt; path=/"
2017-12-09T15:31:43 [DEBUG] CookieJar - Saved "_ga=GA1.2.690650226.1512813703; e
xpires=Mon, 09-Dec-2019 10:01:43 GMT; domain=.dorevi.lt; path=/"
2017-12-09T15:31:43 [DEBUG] CookieJar - Saved "_gid=GA1.2.860165508.1512813703;
expires=Sun, 10-Dec-2017 10:01:43 GMT; domain=.dorevi.lt; path=/"
2017-12-09T15:31:43 [DEBUG] CookieJar - Saved "_gat=1; expires=Sat, 09-Dec-2017
10:02:43 GMT; domain=.dorevi.lt; path=/"
2017-12-09T15:31:43 [DEBUG] WebPage - setupFrame ""
2017-12-09T15:31:53 [DEBUG] WebPage - setupFrame ""
2017-12-09T15:31:53 [DEBUG] WebPage - updateLoadingProgress: 10
2017-12-09T15:31:53 [DEBUG] WebPage - setupFrame ""
2017-12-09T15:31:53 [DEBUG] WebPage - updateLoadingProgress: 100
2017-12-09T15:31:53 [DEBUG] WebPage - setupFrame ""
2017-12-09T15:31:53 [DEBUG] FileSystem - _open: ":/modules/fs.js" QMap(("mode",
QVariant(QString, "r")))
2017-12-09T15:31:53 [DEBUG] FileSystem - _open: ":/modules/system.js" QMap(("mod
e", QVariant(QString, "r")))
2017-12-09T15:31:53 [DEBUG] FileSystem - _open: ":/modules/webpage.js" QMap(("mo
de", QVariant(QString, "r")))
2017-12-09T15:31:53 [DEBUG] WebPage - updateLoadingProgress: 10
2017-12-09T15:31:53 [DEBUG] WebPage - setupFrame ""
2017-12-09T15:31:53 [DEBUG] FileSystem - _open: ":/modules/fs.js" QMap(("mode",
QVariant(QString, "r")))
2017-12-09T15:31:53 [DEBUG] FileSystem - _open: ":/modules/system.js" QMap(("mod
e", QVariant(QString, "r")))
2017-12-09T15:31:53 [DEBUG] FileSystem - _open: ":/modules/webpage.js" QMap(("mo
de", QVariant(QString, "r")))
2017-12-09T15:31:53 [DEBUG] WebPage - updateLoadingProgress: 100
2017-12-09T15:31:53 [DEBUG] CookieJar - Purged (session) "CMSSESSID8694f4a4=kpca
79mq05g4v0fnh31uvkmu86; domain=dorevi.lt; path=/"
2017-12-09T15:31:53 [DEBUG] CookieJar - Saved "_ga=GA1.2.690650226.1512813703; e
xpires=Mon, 09-Dec-2019 10:01:43 GMT; domain=.dorevi.lt; path=/"
2017-12-09T15:31:53 [DEBUG] CookieJar - Saved "_gid=GA1.2.860165508.1512813703;
expires=Sun, 10-Dec-2017 10:01:43 GMT; domain=.dorevi.lt; path=/"
2017-12-09T15:31:53 [DEBUG] CookieJar - Saved "_gat=1; expires=Sat, 09-Dec-2017
10:02:43 GMT; domain=.dorevi.lt; path=/"

Body:
PhantomJS 2.1.1 is unfortunately indeed is old and abandoned in favor of headless Chrome's puppeteer

Here's making screenshot in that:

'use strict';

const puppeteer = require('puppeteer');

(async() => {

const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://www.nytimes.com/');
await page.screenshot({path: 'full.png', fullPage: true});
await browser.close();

})();


问:
Reuse ICE candidates during webrtc re-negotiation
This is regarding the delay in the webrtc call setup due to ICE negotiations. I am trying out an audio call after which I enable video. A new video stream is added to the existing Peer Connection and ICE candidates are gathered for both audio and video tracks. Re-negotiation starts. SDP in the RE-INVITE has new ICE candidates for audio and video tracks.

Why can't we use the ICE candidate for audio track which existed already during initial audio call? Why gather ICE candidates again?

答:
compare to this sample:
https://webrtc.github.io/samples/src/content/peerconnection/upgrade/

Do you get new candidates for sdpMLineIndex 0 (audio)? If you just get new ones for sdpMLineIndex 1 (video) and support BUNDLE, set the bundle policy to 'max-bundle' when constructing the peerconnection.


问:
Using AppleScript and JavaScript to click a button that has no id
I'm trying to use AppleScript to click a button that has no id:

```<code><div class="form-group">
    <button type="submit" class="btn btn-lg btn-success btn-block">Sign in</button>
</div>
</code>```

The Sign in button on this site: https://intakeq.com/signin

Using this AppleScript code:

```<code>do JavaScript "document.getElementsByClassName('form-group')[0].firstElementChild.click()"
</code>```

答:
You are missing a few things for your question, but here's an answer that works in Safari:

```<code>tell application "Safari"
 --activate
 --(you can use with or without activate)
 do JavaScript "document.forms[0][7].click();" in document 1
 --7 is 'sign in' button
 --1 is email field;
 --2 is password field;
end tell
</code>```

Perhaps it's not the best way to do this, but I've tested this and it works. And I've given you extra info about the email and password fields.

Body:
I'm trying to use AppleScript to click a button that has no id:

    <button type="submit" class="btn btn-lg btn-success btn-block">Sign in</button>

The Sign in button on this site: https://intakeq.com/signin

Using this AppleScript code:

do JavaScript "document.getElementsByClassName('form-group')[0].firstElementChild.click()"

Body:
You are missing a few things for your question, but here's an answer that works in Safari:

tell application "Safari"
 --activate
 --(you can use with or without activate)
 do JavaScript "document.forms[0][7].click();" in document 1
 --7 is 'sign in' button
 --1 is email field;
 --2 is password field;
end tell

Perhaps it's not the best way to do this, but I've tested this and it works. And I've given you extra info about the email and password fields.


问:
Working with CordovaEmailComposer
I am new on Angular and Ionic Framework and want to incorporate the cordova email composer plugin. But failed to complete this. Here is my all code.

I did install the CLI :

```<code>ionic cordova plugin add https://github.com/katzer/cordova-plugin-email-composer.git
</code>```

Index.html

```<code>    <script src="lib/ionic/js/ionic.bundle.js"></script>
    <script src="cordova.js"></script>
    <script src="js/openfb.js"></script>
    <script src="js/ngopenfb.js"></script>
    <script src="js/ngCordovaOauth.js"></script>
    <script src="settings.js"></script>
    <script src="js/angular-translate.min.js"></script>
    <script src="translate.js"></script>
    <script src="js/app.js"></script>
    <script src="js/services.js"></script>
    <script src="js/controllers.js"></script>
    <script src="js/directives.js"></script>
    <script src="js/ngStorage.js"></script>
    <script src="js/ionic-close-popup.js"></script>
    <script src="js/angular-base64.js"></script>
</code>```

App.JS

```<code>angular.module('starter', ['ionic', 'starter.services', 'starter.controllers', 'starter.translate', 'ngStorage', 'ionic.closePopup', 'ab-base64', 'ngOpenFB', 'ngCordovaOauth','starter.directive'])
</code>```

Controller:

```<code>.controller('EmailController', function($scope) {
    $scope.sendEmail=function(EmailAddr){
        var email =
            {
                to: 'abcd@gmail.com',
                subject: 'Test Message',
                body: 'This is a test message',
                isHtml: true
            };
        $cordovaEmailComposer.isAvailable().then(function() {
            $cordovaEmailComposer.open(email).then(null, function () {
            // user cancelled email
            });
        }, function () {
            // not available
        });
    };
})
</code>```

HTML:

```<code><div class="list theme-forms" ng-controller="EmailController">
<button class="button button-block button-positive" ng-click="sendEmail()">SEND</button>
</div>
</code>```

When clicked on SEND Button, following error displayed on chrome console and email is not sent -

```<code>ionic.bundle.js:150 ReferenceError: $cordovaEmailComposer is not defined
    at b.$scope.sendEmail (controllers.js:746)
    at fn (eval at compile (ionic.bundle.js:260), <anonymous>:4:218)
    at ionic.bundle.js:472
    at b.$eval (ionic.bundle.js:176)
    at b.$apply (ionic.bundle.js:177)
    at HTMLButtonElement.<anonymous> (ionic.bundle.js:472)
    at Pf (ionic.bundle.js:70)
    at HTMLButtonElement.d (ionic.bundle.js:70)
    at n (ionic.bundle.js:22)
    at t (ionic.bundle.js:22)
</code>```

Could you help to give a hint what I have missed here?

EDIT 1

Now I've added following js file on index.html

```<code>js/ng-cordova.min.js
js/email_composer.js // form Plugin files
</code>```

and getting error console -

```<code>require is not defined
</code>```

When Click on SEND Button -

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

答:
```<code>try to use this plugin:-
http://ngcordova.com/docs/plugins/emailComposer/

module.controller('ThisCtrl', function($cordovaEmailComposer) {

 $cordovaEmailComposer.isAvailable().then(function() {
   // is available
 }, function () {
   // not available
 });

  var email = {
    to: 'max@mustermann.de',
    cc: 'erika@mustermann.de',
    bcc: ['john@doe.com', 'jane@doe.com'],
    attachments: [
      'file://img/logo.png',
      'res://icon.png',
      'base64:icon.png//iVBORw0KGgoAAAANSUhEUg...',
      'file://README.pdf'
    ],
    subject: 'Cordova Icons',
    body: 'How are you? Nice greetings from Leipzig',
    isHtml: true
  };

 $cordovaEmailComposer.open(email).then(null, function () {
   // user cancelled email
 });
});
</code>```

Title: Working with CordovaEmailComposer

Body:
I am new on Angular and Ionic Framework and want to incorporate the cordova email composer plugin. But failed to complete this. Here is my all code.

I did install the CLI :

ionic cordova plugin add https://github.com/katzer/cordova-plugin-email-composer.git

Index.html

App.JS

angular.module('starter', ['ionic', 'starter.services', 'starter.controllers', 'starter.translate', 'ngStorage', 'ionic.closePopup', 'ab-base64', 'ngOpenFB', 'ngCordovaOauth','starter.directive'])

Controller:

.controller('EmailController', function($scope) {
    $scope.sendEmail=function(EmailAddr){
        var email =
            {
                to: 'abcd@gmail.com',
                subject: 'Test Message',
                body: 'This is a test message',
                isHtml: true
            };
        $cordovaEmailComposer.isAvailable().then(function() {
            $cordovaEmailComposer.open(email).then(null, function () {
            // user cancelled email
            });
        }, function () {
            // not available
        });
    };
})

HTML:

<button class="button button-block button-positive" ng-click="sendEmail()">SEND</button>

When clicked on SEND Button, following error displayed on chrome console and email is not sent -

ionic.bundle.js:150 ReferenceError: $cordovaEmailComposer is not defined
    at b.$scope.sendEmail (controllers.js:746)
    at fn (eval at compile (ionic.bundle.js:260), <anonymous>:4:218)
    at ionic.bundle.js:472
    at b.$eval (ionic.bundle.js:176)
    at b.$apply (ionic.bundle.js:177)
    at HTMLButtonElement.<anonymous> (ionic.bundle.js:472)
    at Pf (ionic.bundle.js:70)
    at HTMLButtonElement.d (ionic.bundle.js:70)
    at n (ionic.bundle.js:22)
    at t (ionic.bundle.js:22)

Could you help to give a hint what I have missed here?

EDIT 1

Now I've added following js file on index.html

js/ng-cordova.min.js
js/email_composer.js // form Plugin files

and getting error console -

require is not defined

When Click on SEND Button -

TypeError: Cannot read property 'isAvailable' of undefined


问:
App does not close after calling finish() in android
I am working on an app in which I have one dialog and when I click on the exit button I want to close the app but sometimes app won't finish and return back to my first activity. I do not understand what to do with this.

Code for the same

```<code>    AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext());
        alertDialog.setMessage(context.getResources().getString(R.string.app_close_dialog_msg));
        alertDialog.setPositiveButton(R.string.app_close_dialog_msg_yes, new OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dismiss();
                ((Activity) context).finish();
                //((Activity) context). moveTaskToBack(true);
                System.exit(0);
                android.os.Process.killProcess(android.os.Process.myPid());

            }
        });
</code>```

答: Try calling ActivityCompat.finishAffinity(activity); if your minSdk >= 16, this should close all the activities for your app

Body:
I am working on an app in which I have one dialog and when I click on the exit button I want to close the app but sometimes app won't finish and return back to my first activity. I do not understand what to do with this.

Code for the same

    AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext());
        alertDialog.setMessage(context.getResources().getString(R.string.app_close_dialog_msg));
        alertDialog.setPositiveButton(R.string.app_close_dialog_msg_yes, new OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dismiss();
                ((Activity) context).finish();
                //((Activity) context). moveTaskToBack(true);
                System.exit(0);
                android.os.Process.killProcess(android.os.Process.myPid());

            }
        });


问:
How do you save to WebArchive webView editable content?
I am trying to create a WebArchive from a WebView.  I have it working, but I have found a problem when I try and work with edited content.  This is what I am currently doing:

```<code>[webView setEditable:YES];
WebDataSource *dataSource = [[webView mainFrame] dataSource];

WebArchive *archive = [[WebArchive alloc]
        initWithMainResource:[dataSource mainResource]
        subresources:nil
        subframeArchives:nil];

[[archive data] writeToFile:destinationPath atomically:YES];
[[webView mainFrame]
 loadRequest:[NSURLRequest
     requestWithURL:
     [NSURL fileURLWithPath:destinationPath]
     ]];
</code>```

Any edits I make to the content in the WebView do not get stored in the WebArchive.  Do I need to commit my changes back to the original file in order for this to work?  I would like it to save based on the content that is in the WebView.  Any help would be appreciated. Thanks!

答:
After digging for awhile, I was able to figure out the answer to my own question.  Here is how I did it:

```<code>WebResource *dataSource = [[[[webView mainFrame] DOMDocument] webArchive] mainResource];

WebArchive *archive = [[WebArchive alloc]
       initWithMainResource:dataSource
       subresources:nil
       subframeArchives:nil];

[[archive data] writeToFile:@"output.webarchive" atomically:YES];
</code>```

Hope that helps someone.

ContentLicense: CC BY-SA 2.5

Body:
I am trying to create a WebArchive from a WebView.  I have it working, but I have found a problem when I try and work with edited content.  This is what I am currently doing:

[webView setEditable:YES];
WebDataSource *dataSource = [[webView mainFrame] dataSource];

WebArchive *archive = [[WebArchive alloc]
        initWithMainResource:[dataSource mainResource]
        subresources:nil
        subframeArchives:nil];

[[archive data] writeToFile:destinationPath atomically:YES];
[[webView mainFrame]
 loadRequest:[NSURLRequest
     requestWithURL:
     [NSURL fileURLWithPath:destinationPath]
     ]];

Any edits I make to the content in the WebView do not get stored in the WebArchive.  Do I need to commit my changes back to the original file in order for this to work?  I would like it to save based on the content that is in the WebView.  Any help would be appreciated. Thanks!

Body:
After digging for awhile, I was able to figure out the answer to my own question.  Here is how I did it:

WebResource *dataSource = [[[[webView mainFrame] DOMDocument] webArchive] mainResource];

WebArchive *archive = [[WebArchive alloc]
       initWithMainResource:dataSource
       subresources:nil
       subframeArchives:nil];

[[archive data] writeToFile:@"output.webarchive" atomically:YES];

Hope that helps someone.


问:
TypeError: inner() got multiple values for keyword argument 'ax'
I tried to run the below code:

Code:

```<code>df1=pd.read_excel('F:/MRCS_New_struture/2. EHM_Vanna/2015 Reports/Statistic_Env.xlsx', sheetname='Daitom (2)', header=0, index_col='Year')

CaAB=df1.iloc[:5,17:34]; print CaAB

a=[2007, 2008, 2011, 2013, 2015]
b=[100,200,300,500,22.33]

fig, ax=plt.subplots(2,1)

plt.plot(a, b, 'go-', label='line 1', linewidth=2, ax=ax)
plt.xticks(a, map(str,a))
CaAB.plot(kind='bar', ax=ax)
</code>```

And, it generated error (TypeError: inner() got multiple values for keyword argument 'ax'). What's wrong to my code?

答:
ax is not a valid argument for plt.plot(). The reason is that plt.plot() will call the plot method of the current active axes, same as plt.gca().plot(). Hence the axes is already given by the instance itself. Supplying it again as keyword argument does not make any sense and eventually produces the error.

Solution: Don't use ax as argument to plt.plot(). Instead,

call plt.plot(...) to plot to the current axes. Set the current axes with plt.sca(), or

directly call the plot() method of the axes. ax.plot(...)

Mind that in the example from the question, ax is not an axes. If this is confusing, name it differently,

```<code>fig, ax_arr = plt.subplots(2,1)

ax_arr[0].plot(a, b, 'go-', label='line 1', linewidth=2)
ax_arr[0].set_xticks(a)
ax_arr[0].set_xticklabels(list(map(str,a)))

df.plot(kind='bar', ax=ax_arr[1])
</code>```

Body:
I tried to run the below code:

Code:

df1=pd.read_excel('F:/MRCS_New_struture/2. EHM_Vanna/2015 Reports/Statistic_Env.xlsx', sheetname='Daitom (2)', header=0, index_col='Year')

CaAB=df1.iloc[:5,17:34]; print CaAB

a=[2007, 2008, 2011, 2013, 2015]
b=[100,200,300,500,22.33]

fig, ax=plt.subplots(2,1)

plt.plot(a, b, 'go-', label='line 1', linewidth=2, ax=ax)
plt.xticks(a, map(str,a))
CaAB.plot(kind='bar', ax=ax)

And, it generated error (TypeError: inner() got multiple values for keyword argument 'ax'). What's wrong to my code?

Body:
ax is not a valid argument for plt.plot(). The reason is that plt.plot() will call the plot method of the current active axes, same as plt.gca().plot(). Hence the axes is already given by the instance itself. Supplying it again as keyword argument does not make any sense and eventually produces the error.

Solution: Don't use ax as argument to plt.plot(). Instead,

call plt.plot(...) to plot to the current axes. Set the current axes with plt.sca(), or

directly call the plot() method of the axes. ax.plot(...)

Mind that in the example from the question, ax is not an axes. If this is confusing, name it differently,

fig, ax_arr = plt.subplots(2,1)

ax_arr[0].plot(a, b, 'go-', label='line 1', linewidth=2)
ax_arr[0].set_xticks(a)
ax_arr[0].set_xticklabels(list(map(str,a)))

df.plot(kind='bar', ax=ax_arr[1])


问:
How to opimize user defined python functions handling millions of rows?
I'm using python 3.6.
My Python code is retrieving data from a database, and processing the data and saving the result in csv format. After processing, I'm getting around 80 million rows.

One field of the processed data is a value of a dictionary, and that field contains multiple value against the key; so during processing, that field's values are stored in a data frame column in list format.

I need to replace that value with the corresponding dictionary key. So I wrote the following function for converting the value to a dictionary key:

```<code>def keysWithValue(aDict, target):
    return sorted(key for key, value in aDict.items() if target == value)
</code>```

I'm feeling that if I will use a for loop for those 80 million records and call this function on each of them, it will take lots of time. Can you please suggest me some alternative Python approach instead of modifying it directly in my database that will save my code running time?

答:
You can make a reverse lookup dictionary for that field:

```<code>from collections import defaultdict

def makeInverseLookupDict(aDict):
    reverseDict = defaultdict(list)
    for key, value in aDict.iteritems():
        reverseDict[value].append(key)

    return reverseDict
</code>```

Finding the keys with the given value is now O(1). This will take up as much space as the original dict, but will be instantaneous.

Body:
I'm using python 3.6.
My Python code is retrieving data from a database, and processing the data and saving the result in csv format. After processing, I'm getting around 80 million rows.

One field of the processed data is a value of a dictionary, and that field contains multiple value against the key; so during processing, that field's values are stored in a data frame column in list format.

I need to replace that value with the corresponding dictionary key. So I wrote the following function for converting the value to a dictionary key:

def keysWithValue(aDict, target):
    return sorted(key for key, value in aDict.items() if target == value)

I'm feeling that if I will use a for loop for those 80 million records and call this function on each of them, it will take lots of time. Can you please suggest me some alternative Python approach instead of modifying it directly in my database that will save my code running time?

Body:
You can make a reverse lookup dictionary for that field:

from collections import defaultdict

def makeInverseLookupDict(aDict):
    reverseDict = defaultdict(list)
    for key, value in aDict.iteritems():
        reverseDict[value].append(key)

    return reverseDict

Finding the keys with the given value is now O(1). This will take up as much space as the original dict, but will be instantaneous.


问:
How to implement parallelism with a recursive method?
I have a tree structure, for that I am using this class:

```<code>class Node
{
    long IdNode;
    List<Node> Childs;
    string path;
    Data data;
}
</code>```

The path is the IdNode spearated by ".", so the path of a Node is "IdParent.IdNode" and so on. So to set the path of a node I need the path of the parent.

I have this method:

```<code>public setPath(Node paramParentNode)
{
    this.path = paramParentNode.Path + "." + this.IDNode;

    foreach(Node iteratorNode in this.Childs)
    {
        iteratorNode.setPath(this);
    }
}
</code>```

This is a secuential version. But I was  thinking how to implement this in parallel, something like that:

```<code>public setPathMt(Node paramParentNode)
{
    this.path = paramParentNode.Path + "." + this.IDNode;

    Parallel.Foreach(this.Childs,
     (iteratorNode) =>
      {
          iteratorNode.SetPathMt(this);
      }
     );
}
</code>```

But I don't know if this a correct way, because I don't know how to wait the recursive call of the method, I mean, how I know when the recursive methods are finished.

Which would it be the best way to implement the multithread recursive method of that?

Thanks.

答:
Your method should be like

```<code>public SetPath(Node paramParentNode)
{
    paramParentNode.Path = paramParentNode.Path + "." + this.IDNode;

    foreach(Node iteratorNode in paramParentNode.Childs)
    {
        SetPath(iteratorNode);
    }
}
</code>```

and Parallel method like this

```<code>public SetPathMt(Node paramParentNode)
{
    paramParentNode.Path = paramParentNode.Path + "." + this.IDNode;

    Parallel.Foreach(paramParentNode.Childs,
     new ParallelOptions { MaxDegreeOfParallelism = 32 },
     (iteratorNode) =>
      {
          SetPathMt(iteratorNode);
      }
     );
}
</code>```

You were not using the node passed in the method at all. When you use this it means the instance of that class, which would remain same in all recursive methods. The only thing changing would be the parameter passes in the method.

new ParallelOptions { MaxDegreeOfParallelism = 32 } is to restrict the number of concurrent operations(threads) used by this Parallel operation to 32 (can be a number you want) or -1 (All available threads).

Body:
I have a tree structure, for that I am using this class:

class Node
{
    long IdNode;
    List<Node> Childs;
    string path;
    Data data;
}

The path is the IdNode spearated by ".", so the path of a Node is "IdParent.IdNode" and so on. So to set the path of a node I need the path of the parent.

I have this method:

public setPath(Node paramParentNode)
{
    this.path = paramParentNode.Path + "." + this.IDNode;

    foreach(Node iteratorNode in this.Childs)
    {
        iteratorNode.setPath(this);
    }
}

This is a secuential version. But I was  thinking how to implement this in parallel, something like that:

public setPathMt(Node paramParentNode)
{
    this.path = paramParentNode.Path + "." + this.IDNode;

    Parallel.Foreach(this.Childs,
     (iteratorNode) =>
      {
          iteratorNode.SetPathMt(this);
      }
     );
}

But I don't know if this a correct way, because I don't know how to wait the recursive call of the method, I mean, how I know when the recursive methods are finished.

Which would it be the best way to implement the multithread recursive method of that?

Thanks.

Body:
Your method should be like

public SetPath(Node paramParentNode)
{
    paramParentNode.Path = paramParentNode.Path + "." + this.IDNode;

    foreach(Node iteratorNode in paramParentNode.Childs)
    {
        SetPath(iteratorNode);
    }
}

and Parallel method like this

public SetPathMt(Node paramParentNode)
{
    paramParentNode.Path = paramParentNode.Path + "." + this.IDNode;

    Parallel.Foreach(paramParentNode.Childs,
     new ParallelOptions { MaxDegreeOfParallelism = 32 },
     (iteratorNode) =>
      {
          SetPathMt(iteratorNode);
      }
     );
}

You were not using the node passed in the method at all. When you use this it means the instance of that class, which would remain same in all recursive methods. The only thing changing would be the parameter passes in the method.

new ParallelOptions { MaxDegreeOfParallelism = 32 } is to restrict the number of concurrent operations(threads) used by this Parallel operation to 32 (can be a number you want) or -1 (All available threads).


问:
Error in JDBC query
```<code>sql  = "select milk_rate from special_milk_rate
        where code_producer_id=? and effective_from <= ?
        and effective_till >= ?"
</code>```

I am getting error in this query when in my JDBC code

Exception:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? and effective_from <= ? and effective_till >= ?' at line 1

But when I run it in MySQL command prompt with some values it runs fine there.

答: You have to use prepared statements instead of "normal" statements to have the question marks replaced by parameters.</p>

Title: Error in JDBC query

Body:
sql  = "select milk_rate from special_milk_rate
        where code_producer_id=? and effective_from <= ?
        and effective_till >= ?"

I am getting error in this query when in my JDBC code

Exception:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? and effective_from <= ? and effective_till >= ?' at line 1

But when I run it in MySQL command prompt with some values it runs fine there.


问:
How to load an image url to an imageview wherein the image view design declared inside a thread?
```<code>@SuppressWarnings({ "rawtypes" })
        public void addAttendance(ArrayList<Properties> attendanceusers) {
            //tl.removeView(tr);
            tl.removeAllViews();
            //addHeaderAttendance();
            ctr=0;
            for (Iterator i = attendanceusers.iterator(); i.hasNext();) {

                Properties p = (Properties) i.next();

                property_list.add(p);
                /** Create a TableRow dynamically **/
                tr = new TableRow(this);

                picurl=p.getPic();
                profile = new ImageView(this);

                profile.setPadding(20,50,20,50);
              /*  URL newurl = new URL(picurl);
                bmp = BitmapFactory.decodeStream(newurl.openConnection().getInputStream());
                profile.setImageBitmap(bmp);*/
                try {

                      Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(picurl).getContent());
                      profile.setImageBitmap(bitmap);
                    } catch (MalformedURLException e) {
                      e.printStackTrace();
                    } catch (IOException e) {
                      e.printStackTrace();
                    }

                profile.setOnClickListener(this);

                //myButton.setPadding(5, 5, 5, 5);
                Ll = new LinearLayout(this);

                params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
                        LayoutParams.WRAP_CONTENT);
                params.setMargins(0, 0, 0, 0);

                Ll.setPadding(0, 0, 20, 0);
                Ll.addView(profile,params);
                tr.addView((View)Ll);

                 // Add the TableRow to the TableLayout
                tl.addView(tr, new TableLayout.LayoutParams(
                        LayoutParams.FILL_PARENT,
                        LayoutParams.WRAP_CONTENT));
            }
        }
</code>```

My code for populating my image is not working because my main method is working on a thread. Can you suggest a code that i can put on the a method ? This post is not a duplicate of any other posts here on stack.
I tried this code on my other class which is working, however it will blink and blink if the main method(which im using is a thread):

```<code>new AsyncTask<Void, Void, Void>() {
                    @Override
                    protected Void doInBackground(Void... params) {
                        try {
                            InputStream in = new URL(picurl).openStream();
                            bmp = BitmapFactory.decodeStream(in);
                        } catch (Exception e) {
                           // log error
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void result) {
                        if (bmp != null)
                            profile.setImageBitmap(bmp);
                    }

               }.execute();
</code>```

However if i put it inside the first code that i pasted. The ui will constantly blink because it is a thread that is inside a thread. My image to is too large i cant resize it properly can you help me? i will promise to give a check and a plus for those who can help me, and for those who efforted i will also give a point

答:
I think you do not need use threads or somethink like this.

Just add to your project Picasso or Glide

This libraries support images loading from resources, memory or outside links from web. This will solve the problems with blink and it is a good solution for caching and safe content load.

Body:
@SuppressWarnings({ "rawtypes" })
        public void addAttendance(ArrayList<Properties> attendanceusers) {
            //tl.removeView(tr);
            tl.removeAllViews();
            //addHeaderAttendance();
            ctr=0;
            for (Iterator i = attendanceusers.iterator(); i.hasNext();) {

                Properties p = (Properties) i.next();

                property_list.add(p);
                /** Create a TableRow dynamically **/
                tr = new TableRow(this);

                picurl=p.getPic();
                profile = new ImageView(this);

                profile.setPadding(20,50,20,50);
              /*  URL newurl = new URL(picurl);
                bmp = BitmapFactory.decodeStream(newurl.openConnection().getInputStream());
                profile.setImageBitmap(bmp);*/
                try {

                      Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(picurl).getContent());
                      profile.setImageBitmap(bitmap);
                    } catch (MalformedURLException e) {
                      e.printStackTrace();
                    } catch (IOException e) {
                      e.printStackTrace();
                    }

                profile.setOnClickListener(this);

                //myButton.setPadding(5, 5, 5, 5);
                Ll = new LinearLayout(this);

                params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
                        LayoutParams.WRAP_CONTENT);
                params.setMargins(0, 0, 0, 0);

                Ll.setPadding(0, 0, 20, 0);
                Ll.addView(profile,params);
                tr.addView((View)Ll);

                 // Add the TableRow to the TableLayout
                tl.addView(tr, new TableLayout.LayoutParams(
                        LayoutParams.FILL_PARENT,
                        LayoutParams.WRAP_CONTENT));
            }
        }

My code for populating my image is not working because my main method is working on a thread. Can you suggest a code that i can put on the a method ? This post is not a duplicate of any other posts here on stack.
I tried this code on my other class which is working, however it will blink and blink if the main method(which im using is a thread):

new AsyncTask<Void, Void, Void>() {
                    @Override
                    protected Void doInBackground(Void... params) {
                        try {
                            InputStream in = new URL(picurl).openStream();
                            bmp = BitmapFactory.decodeStream(in);
                        } catch (Exception e) {
                           // log error
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void result) {
                        if (bmp != null)
                            profile.setImageBitmap(bmp);
                    }

               }.execute();

However if i put it inside the first code that i pasted. The ui will constantly blink because it is a thread that is inside a thread. My image to is too large i cant resize it properly can you help me? i will promise to give a check and a plus for those who can help me, and for those who efforted i will also give a point