问:
save state of togglebutton android
Can anyone tell me why this doesn't work please? I am trying to save the state of the togglebutton, but everytime I close the app and start again, it goes back to off. I want the state to be remembered, so when someone adds something to their favourites, to remember it as being added to favourite.

private String state = "State";

```<code>public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.recipe_menu, menu);
    toggleButton = (ToggleButton) findViewById(R.id.myToggleButton);
    toggleButton.setChecked(readState());
    toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked)
                // The toggle is enabled
                toggleButton.setBackgroundDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_favorite_black_24dp));
            else
                // The toggle is disabled
                toggleButton.setBackgroundDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_favorite_border_black_24dp));

            saveState(isChecked);
        }
    });
    return super.onCreateOptionsMenu(menu);
}

private void saveState(boolean isFavourite) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    sharedPreferences.edit().putBoolean(state, isFavourite).apply();
}
private boolean readState() {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    return sharedPreferences.getBoolean(state, true);
}
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    toggleButton = (ToggleButton) findViewById(R.id.myToggleButton);
    toggleButton.setBackgroundDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_favorite_border_black_24dp));
    toggleButton.setChecked(readState());
}
</code>```

答:
You are changing the state of your togglebutton twice.
So, these lines are not necessary. Delete the below lines.

```<code>SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
toggleButton.setChecked(sharedPreferences.getBoolean("toggleButton", true));
</code>```

Hope this helps..

Title: save state of togglebutton android

Body:
Can anyone tell me why this doesn't work please? I am trying to save the state of the togglebutton, but everytime I close the app and start again, it goes back to off. I want the state to be remembered, so when someone adds something to their favourites, to remember it as being added to favourite.

private String state = "State";

public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.recipe_menu, menu);
    toggleButton = (ToggleButton) findViewById(R.id.myToggleButton);
    toggleButton.setChecked(readState());
    toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked)
                // The toggle is enabled
                toggleButton.setBackgroundDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_favorite_black_24dp));
            else
                // The toggle is disabled
                toggleButton.setBackgroundDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_favorite_border_black_24dp));

            saveState(isChecked);
        }
    });
    return super.onCreateOptionsMenu(menu);
}

private void saveState(boolean isFavourite) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    sharedPreferences.edit().putBoolean(state, isFavourite).apply();
}
private boolean readState() {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    return sharedPreferences.getBoolean(state, true);
}
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    toggleButton = (ToggleButton) findViewById(R.id.myToggleButton);
    toggleButton.setBackgroundDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_favorite_border_black_24dp));
    toggleButton.setChecked(readState());
}

Body:
You are changing the state of your togglebutton twice.
So, these lines are not necessary. Delete the below lines.

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
toggleButton.setChecked(sharedPreferences.getBoolean("toggleButton", true));

Hope this helps..


来源: stackexchange

问:
Django x-www-form-urlencoded request
I'm trying to do the following request with django :

I tried the following code but it doesn't work :

```<code>data = {'username': admin,
        'password': 123,
        'grant_type': 'password',
        'client_id': 'xxxx',
        'client_secret': 'xxxx'}
headers = {'content-type': 'application/x-www-form-urlencoded'}
r = requests.post(url, data=data, headers=headers)
</code>```

Thanks for your help !

答:
It is form-encoded by default.

Typically, you want to send some form-encoded data — much like an HTML
  form. To do this, simply pass a dictionary to the data argument. Your
  dictionary of data will automatically be form-encoded when the request
  is made.

```<code>>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.post("http://httpbin.org/post", data=payload)
>>> print r.text
{
  "origin": "179.13.100.4",
  "files": {},
  "form": {
    "key2": "value2",
    "key1": "value1"
  },
  "url": "http://httpbin.org/post",
  "args": {},
  "headers": {
    "Content-Length": "23",
    "Accept-Encoding": "identity, deflate, compress, gzip",
    "Accept": "*/*",
    "User-Agent": "python-requests/0.8.0",
    "Host": "127.0.0.1:7077",
    "Content-Type": "application/x-www-form-urlencoded"
  },
  "data": ""
}
</code>```

http://docs.python-requests.org/en/v0.10.7/user/quickstart/#make-a-post-request

ContentLicense: CC BY-SA 3.0

Title: Django x-www-form-urlencoded request

Body:
I'm trying to do the following request with django :

I tried the following code but it doesn't work :

data = {'username': admin,
        'password': 123,
        'grant_type': 'password',
        'client_id': 'xxxx',
        'client_secret': 'xxxx'}
headers = {'content-type': 'application/x-www-form-urlencoded'}
r = requests.post(url, data=data, headers=headers)

Thanks for your help !

Body:
It is form-encoded by default.

Typically, you want to send some form-encoded data — much like an HTML
  form. To do this, simply pass a dictionary to the data argument. Your
  dictionary of data will automatically be form-encoded when the request
  is made.

>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.post("http://httpbin.org/post", data=payload)
>>> print r.text
{
  "origin": "179.13.100.4",
  "files": {},
  "form": {
    "key2": "value2",
    "key1": "value1"
  },
  "url": "http://httpbin.org/post",
  "args": {},
  "headers": {
    "Content-Length": "23",
    "Accept-Encoding": "identity, deflate, compress, gzip",
    "Accept": "*/*",
    "User-Agent": "python-requests/0.8.0",
    "Host": "127.0.0.1:7077",
    "Content-Type": "application/x-www-form-urlencoded"
  },
  "data": ""
}

http://docs.python-requests.org/en/v0.10.7/user/quickstart/#make-a-post-request


问:
Verify empty field Selenium C#
I am trying to check if a text field is empty and I can't convert bool to string.
I am trying this:

```<code>var firstName = driver.FindElement(By.Id("name_3_firstname"));
if (firstName.Equals(" ")) {
                Console.WriteLine("This field can not be empty");
            }
</code>```

Also, how can I check if certain number field is exactly 20 digits?
Can you help me do this?

Thank you in advance!

答:
If it's string, then you can use string.Empty or "", because " " contains a space, therefore it's not empty.

For those 20 digits, you can use a bit of a workaround field.ToString().Length == 20 or you can repetitively divide it by 10 until the resulting value is 0, but I'd say the workaround might be easier to use.

This is more of a general C# answer. I'm not exactly sure how well it's gonna work in Selenium, but I've checked and string.Empty and ToString() appear to exist there.

Title: Verify empty field Selenium C#

Body:
I am trying to check if a text field is empty and I can't convert bool to string.
I am trying this:

var firstName = driver.FindElement(By.Id("name_3_firstname"));
if (firstName.Equals(" ")) {
                Console.WriteLine("This field can not be empty");
            }

Also, how can I check if certain number field is exactly 20 digits?
Can you help me do this?

Thank you in advance!


问:
What's the difference between function and function() in C#?
For example,
    Thread t = new Thread(function);
Why not
    Thread t = new Thread(function());
Thank you.

答:
Before I answer, I have a very important question, Why Thread in current version of .Net, use Task and Parallel APIs, which are much cleaner and better abstracted alternatives. For understanding its fine, but not for usage anymore

Following is the source code of Thread class, check the constructor with only ThreadStart delegate, pasting underneath:

```<code> [System.Security.SecuritySafeCritical]  // auto-generated
        public Thread(ThreadStart start) {
            if (start == null) {
                throw new ArgumentNullException("start");
            }
            Contract.EndContractBlock();
            SetStartHelper((Delegate)start,0);  //0 will setup Thread with default stackSize
        }
</code>```

Following is the source code for ThreadStart delegate

```<code>[System.Runtime.InteropServices.ComVisible(true)]
    public delegate void ThreadStart();
</code>```

So Thread class just needs a Delegate, with void return and no input, which is what function points to in Thread t = new Thread(function), actually this is a short form, called method grouping, otherwise full fledged form would be creating a ThreadStart object, assigning it a function which maps to its signature. Following are the other options:

() => Function() // Lambda Syntax, use directly in Thread constructor

ThreadStart ts = new ThreadStart(Function) // variable ts can be used in the Thread constructor

Body:
Before I answer, I have a very important question, Why Thread in current version of .Net, use Task and Parallel APIs, which are much cleaner and better abstracted alternatives. For understanding its fine, but not for usage anymore

Following is the source code of Thread class, check the constructor with only ThreadStart delegate, pasting underneath:

 [System.Security.SecuritySafeCritical]  // auto-generated
        public Thread(ThreadStart start) {
            if (start == null) {
                throw new ArgumentNullException("start");
            }
            Contract.EndContractBlock();
            SetStartHelper((Delegate)start,0);  //0 will setup Thread with default stackSize
        }

Following is the source code for ThreadStart delegate

[System.Runtime.InteropServices.ComVisible(true)]
    public delegate void ThreadStart();

So Thread class just needs a Delegate, with void return and no input, which is what function points to in Thread t = new Thread(function), actually this is a short form, called method grouping, otherwise full fledged form would be creating a ThreadStart object, assigning it a function which maps to its signature. Following are the other options:

() => Function() // Lambda Syntax, use directly in Thread constructor

ThreadStart ts = new ThreadStart(Function) // variable ts can be used in the Thread constructor


问:
after used AJAX/GET cannot continue with jq function like .click

i have code with AJAX/GET and after code reload data from php file i
  have another block code using jquery now my problem its why after
  reload data from mysql/php server while the page all the date reloaded
  i can't using function from another script "functionToClick.js". this
  file with 700 lines and work beutiful wehn i using file without AJAX
  just normal PHP code. evry one some idee why its like so?

```<code><head>
    <title>Page Title</title>

    <script src="https://code.jquery.com/jquery-3.1.1.js"></script>
    <script src="style.js" type="text/javascript"></script>

    <link rel="stylesheet" type="text/css" href="styleTable.css">

</head>

<body>
    <div id="contant"></div>
    <h1></h1>
    <div id="div_sum"></div>
    <div id="div_list_value"></div>
    <div id="div_list_choice"></div>
    <div id="div_singels"></div>
    <div id="div_singels_value"></div>
    <p></p>

        <script type="text/javascript">

        $(document).ready(function() {
            $.ajax({    //create an ajax request to load_page.php
            type: "GET",
            url: "getBets.php",
            dataType: "html",   //expect html to be returned
                success: function(response){
                    $("#contant").html(response);
                    /*here i need put my all SCRIPT
                      from another js file than its work
                      but its lang code ineed include here
                      how does i can this*/

                }
            });
        });

        </script>
    <script src="functionToClick.js" type="text/javascript"></script>
</body>
</code>```

```<code>$( document ).ready(function (){

    var total = 1;
    var value_team = [];
    var sum_value = [];
    var list_value = [];
    var singels = [];
    var singelsvalue = [];
    //var test = 2;

    $("td").on("click", function more()
    {
        var $this = $(this);
        var choice = $this.attr("choice");
        var value = $this.attr("value");
        var index =

    singels.indexOf($(this).attr("choice"));
    var a = $this.attr("a");
    var b = $this.attr("b");
    var c = $this.attr("c");
    var d = $this.attr("d");
    var e = $this.attr("e");
    var f = $this.attr("f");
    var g = $this.attr("g");
    var h = $this.attr("h");
    var i = $this.attr("i");
    var z = $this.attr("z");
    var idBet = $this.attr("idBet");
    var chaekA =

$this.next("td").attr("a");
var chaekB = $this.next("td").attr("b");
var chaekC = $this.next("td").attr("c");
var chaekAprev = $this.prev("td").attr("a");
var chaekBprev = $this.prev("td").attr("b");
var chaekCprev = $this.prev("td").attr("c");
var firstKidsa = $(this).parent().find("td:first").attr("a");
var lastKidsa = $(this).parent().find("td:last").attr("a");
var firstKidsb = $(this).parent().find("td:first").attr("b");
var lastKidsb = $(this).parent().find("td:last").attr("b");
var firstKidsc = $(this).parent().find("td:first").attr("c");
var lastKidsc = $(this).parent().find("td:last").attr("c");
var div_sum = $("#div_sum");
var div_list_value = $("#div_list_value");
var div_list_choice = $("#div_list_choice");
var div_singels = $("#div_singels");
var div_singels_value = $("#div_singels_value");

        });
</code>```

答:
```<code>        $(document).ready(function() {
            $.ajax({    //create an ajax request to load_page.php
            type: "GET",
            url: "getBets.php",
            dataType: "html",   //expect html to be returned
                success: function(response){
                    $("#contant").html(response);
                    //alert(response);
            $( ".with" ).click(function(){
                    $( this ).toggleClass( "with_click" );
                    //$( this ).siblings("th").removeClass( "with_click" );
            });
                                     $( document ).ready(function ()
                                        {

                                            var total = 1;
                                            var value_team = [];
                                            var sum_value = [];
                                            var list_value = [];
                                            var singels = [];
                                            var singelsvalue = [];
                                            //var test = 2;

                                                $("td").on("click", function more()
                                                {
                                                    var $this = $(this);
                                                    var choice = $this.attr("choice");
                                                    var value = $this.attr("value");
                                                    var index = singels.indexOf($(this).attr("choice"));
                                                    var a = $this.attr("a");
                                                    var b = $this.attr("b");
                                                    var c = $this.attr("c");
                                                    var d = $this.attr("d");
                                                    var e = $this.attr("e");
                                                    var f = $this.attr("f");
                                                    var g = $this.attr("g");
                                                    var h = $this.attr("h");
                                                    var i = $this.attr("i");
                                                    var z = $this.attr("z");
                                                    var idBet = $this.attr("idBet");
                                                    var chaekA = $this.next("td").attr("a");
                                                    var chaekB = $this.next("td").attr("b");
                                                    var chaekC = $this.next("td").attr("c");
                                                    var chaekAprev = $this.prev("td").attr("a");
                                                    var chaekBprev = $this.prev("td").attr("b");
                                                    var chaekCprev = $this.prev("td").attr("c");

                                                    var firstKidsa = $(this).parent().find("td:first").attr("a");
                                                    var lastKidsa = $(this).parent().find("td:last").attr("a");
                                                    var firstKidsb = $(this).parent().find("td:first").attr("b");
                                                    var lastKidsb = $(this).parent().find("td:last").attr("b");
                                                    var firstKidsc = $(this).parent().find("td:first").attr("c");
                                                    var lastKidsc = $(this).parent().find("td:last").attr("c");

                                                    var div_sum = $("#div_sum");
                                                    var div_list_value = $("#div_list_value");
                                                    var div_list_choice = $("#div_list_choice");
                                                    var div_singels = $("#div_singels");
                                                    var div_singels_value = $("#div_singels_value");

                                    ///////////////////////////////////////////// D
            /* number 1*/       if(z==1&&a==0&&d==0&&e==0&&f==0)
                                {
                                    sum_value.push(value);
                                    list_value.push(value);
                                    value_team.push(choice);
                                    singels.push(choice);
                                    singelsvalue.push(value);

                                    total *= value;

                                    div_sum.text("Total = " + total.toFixed(2));
                                    div_list_value.html("Selected value = " + list_value.join(", "));
                                    div_list_choice.html("Selected choice = " + value_team.join(", "));
                                    div_singels.html("singels = " + singels.join(", "));
                                    div_singels_value.html("singels_value = " + singelsvalue.join(", "));

                                    $this.attr("a","1");
                                    $this.attr("d","1");
                                    $this.siblings("td").attr("d","1");
                                    console.log("number 1 in D");

                                }
            /* number 2*/       if(z=="x"&&b==0&&d==1)
                                {

                                    singels.push(choice);
                                    singelsvalue.push(value);

                                    div_sum.text("Total = " + total.toFixed(2));
                                    div_list_value.html("Selected value = " + list_value.join(", "));
                                    div_list_choice.html("Selected choice = " + value_team.join(", "));
                                    div_singels.html("singels = " + singels.join(", "));
                                    div_singels_value.html("singels_value = " + singelsvalue.join(", "));

                                    $this.attr("b","1");
                                    console.log("number 2 in D");

                                }
            /* number 3*/       if(z==2&&c==0&&d==1)
                                {

                                    singels.push(choice);
                                    singelsvalue.push(value);

                                    div_sum.text("Total = " + total.toFixed(2));
                                    div_list_value.html("Selected value = " + list_value.join(", "));
                                    div_list_choice.html("Selected choice = " + value_team.join(", "));
                                    div_singels.html("singels = " + singels.join(", "));
                                    div_singels_value.html("singels_value = " + singelsvalue.join(", "));

                                    $this.attr("c","1");
                                    console.log("number 3 in D");

                                }
            /* number 4*/       if(z==2&&c==1&&d==1)
                                {

                                    singels.splice(singels.indexOf($this.attr("choice")), 1);
                                    singelsvalue.splice(singelsvalue.indexOf($this.attr("value")), 1);

                                    div_sum.text("Total = " + total.toFixed(2));
                                    div_list_value.html("Selected value = " + list_value.join(", "));
                                    div_list_choice.html("Selected choice = " + value_team.join(", "));
                                    div_singels.html("singels = " + singels.join(", "));
                                    div_singels_value.html("singels_value = " + singelsvalue.join(", "));

                                    $this.attr("c","0");
                                    console.log("number 4 in D");

                                }
            /* number 5*/       if(z=="x"&&b==1&&d==1)
                                {

                                    singels.splice(singels.indexOf($this.attr("choice")), 1);
                                    singelsvalue.splice(singelsvalue.indexOf($this.attr("value")), 1);

                                    div_sum.text("Total = " + total.toFixed(2));
                                    div_list_value.html("Selected value = " + list_value.join(", "));
                                    div_list_choice.html("Selected choice = " + value_team.join(", "));
                                    div_singels.html("singels = " + singels.join(", "));
                                    div_singels_value.html("singels_value = " + singelsvalue.join(", "));

                                    $this.attr("b","0");
                                    console.log("number 5 in D");

                                }
            /* number 6*/       if(z==1&&a==1&&d==1)
                                {

                                    if (singels.length >= 1)
                                    {
                                    list_value.shift(list_value.indexOf(+$(this).attr("value")), 1);
                                    value_team.shift(value_team.indexOf(+$(this).attr("choice")), 1);
                                    singels.shift(singels.indexOf($this.attr("choice")), 1);
                                    singelsvalue.shift(singelsvalue.indexOf($this.attr("value")), 1);
                                    console.log("yes" + singels.length)
                                    }
                                    total /= $(this).attr("value");
                                    if (singels.length < 1)
                                    {
                                    list_value.pop(list_value.indexOf(+$(this).attr("value")), 1);
                                    value_team.pop(value_team.indexOf(+$(this).attr("choice")), 1);
                                    singels.pop(singels.indexOf($this.attr("choice")), 1);
                                    singelsvalue.pop(singelsvalue.indexOf($this.attr("value")), 1);
                                    console.log("yes 2")
                                    }

                                    div_sum.text("Total = " + total.toFixed(2));
                                    div_list_value.html("Selected value = " + list_value.join(", "));
                                    div_list_choice.html("Selected choice = " + value_team.join(", "));
                                    div_singels.html("singels = " + singels.join(", "));
                                    div_singels_value.html("singels_value = " + singelsvalue.join(", "));

                                    $this.attr("a","0");
                                    $this.attr("d","0");
                                    $this.siblings("td").attr("d","0");
                                    console.log("number 6 in D");

                                }
            /////////////////////////////////////////////D sptziel*****************
            /* number 7*/       if(z==1&&a==1&&d==1&&e==0&&chaekB==1&&lastKidsc==0)
                                {

                                    list_value.splice(list_value.indexOf(+$(this).attr("value")), 1);
                                    value_team.splice(value_team.indexOf(+$(this).attr("choice")), 1);
                                    singels.splice(singels.indexOf($this.attr("choice")), 1);
                                    singelsvalue.splice(singelsvalue.indexOf($this.attr("value")), 1);

                                //  total /= sum_value.splice(sum_value.indexOf(+$(this).attr("value")), 1);

                                    sum_value.push($this.next("td").attr("value"));
                                    list_value.push($this.next("td").attr("value"));
                                    value_team.push($this.next("td").attr("choice"));
                                    singels.push($this.next("td").attr("choice"));
                                    singelsvalue.push($this.next("td").attr("value"));

                                    total *= $this.next("td").attr("value");

                                    div_sum.text("Total = " + total.toFixed(2));
                                    div_list_value.html("Selected value = " + list_value.join(", "));
                                    div_list_choice.html("Selected choice = " + value_team.join(", "));
                                    div_singels.html("singels = " + singels.join(", "));
                                    div_singels_value.html("singels_value = " + singelsvalue.join(", "));

                                    $this.attr("a","0");
                                    $this.attr("d","0");
                                    $this.attr("e","1");
                                    $this.siblings("td").attr("d","0");
                                    $this.siblings("td").attr("e","1");
                                    console.log("number 7 in D sptziel");
                                }
            /* number 8*/       if(z==1&&a==1&&d==1&&e==0&&chaekB==0&&lastKidsc==1)
                                {

                                    list_value.splice(list_value.indexOf(+$(this).attr("value")), 1);
                                    value_team.splice(value_team.indexOf(+$(this).attr("choice")), 1);
                                    singels.splice(singels.indexOf($this.attr("choice")), 1);
                                    singelsvalue.splice(singelsvalue.indexOf($this.attr("value")), 1);

                                //  total /= sum_value.splice(sum_value.indexOf(+$(this).attr("value")), 1);

                                    sum_value.push($(this).parent().find("td:last").attr("value"));
                                    list_value.push($(this).parent().find("td:last").attr("value"));
                                    value_team.push($(this).parent().find("td:last").attr("choice"));
                                    singels.push($(this).parent().find("td:last").attr("choice"));
                                    singelsvalue.push($(this).parent().find("td:last").attr("value"));

                                    total *= $(this).parent().find("td:last").attr("value");

                                    div_sum.text("Total = " + total.toFixed(2));
                                    div_list_value.html("Selected value = " + list_value.join(", "));
                                    div_list_choice.html("Selected choice = " + value_team.join(", "));
                                    div_singels.html("singels = " + singels.join(", "));
                                    div_singels_value.html("singels_value = " + singelsvalue.join(", "));

                                    $this.attr("a","0");
                                    $this.attr("d","0");
                                    $this.attr("f","1");
                                    $this.siblings("td").attr("d","0");
                                    $this.siblings("td").attr("f","1");
                                    console.log("number 8 in D sptziel");

                                }
            /* number 9*/       if(z==1&&a==1&&d==1&&e==0&&chaekB==1&&lastKidsc==1)
                                {
                                    list_value.splice(list_value.indexOf(+$(this).attr("value")), 1);
                                    value_team.splice(value_team.indexOf(+$(this).attr("choice")), 1);
                                    singels.splice(singels.indexOf($this.attr("choice")), 1);
                                    singelsvalue.splice(singelsvalue.indexOf($this.attr("value")), 1);

                                //  total /= $(this).attr("value");

                                    sum_value.push($(this).parent().find("td:last").attr("value"));
                                    list_value.push($this.next("td").attr("value"));
                                    value_team.push($this.next("td").attr("choice"));
                                    singels.push($(this).parent().find("td:last").attr("choice"));
                                    singelsvalue.push($(this).parent().find("td:last").attr("value"));

                                    total *= $this.next("td").attr("value");

                                    div_sum.text("Total = " + total.toFixed(2));
                                    div_list_value.html("Selected value = " + list_value.join(", "));
                                    div_list_choice.html("Selected choice = " + value_team.join(", "));
                                    div_singels.html("singels = " + singels.join(", "));
                                    div_singels_value.html("singels_value = " + singelsvalue.join(", "));

                                    $this.attr("a","0");
                                    $this.attr("d","0");
                                    $this.attr("e","1");
                                    $this.siblings("td").attr("d","0");
                                    $this.siblings("td").attr("e","1");
                                    console.log("number 9 in D sptziel");

                                }
            /* number 10*/      if(z==2&&a==0&&e==1&&d==0&&chaekB==1&&firstKidsa==0)
                                {
                                    list_value.splice(list_value.indexOf(+$(this).attr("value")), 1);
                                    value_team.splice(value_team.indexOf(+$(this).attr("choice")), 1);
                                    singels.splice(singels.indexOf($this.attr("choice")), 1);
                                    singelsvalue.splice(singelsvalue.indexOf($this.attr("value")), 1);

                                //  total /= sum_value.splice(sum_value.indexOf(+$(this).attr("value")), 1);

                                /*  sum_value.push($(this).parent().find("td:last").attr("value"));
                                    list_value.push($this.prev("td").attr("value"));
                                    value_team.push($this.prev("td").attr("choice"));
                                    singels.push($(this).parent().find("td:last").attr("choice"));
                                    singelsvalue.push($(this).parent().find("td:last").attr("value"));
                                */

                                    total *= $this.prev("td").attr("value");

                                    div_sum.text("Total = " + total.toFixed(2));
                                    div_list_value.html("Selected value = " + list_value.join(", "));
                                    div_list_choice.html("Selected choice = " + value_team.join(", "));
                                    div_singels.html("singels = " + singels.join(", "));
                                    div_singels_value.html("singels_value = " + singelsvalue.join(", "));

                                    $this.attr("c","0");
                                    console.log("number 10 in D sptziel");

                                }

            /* number 27*/      if(z==2&&c==1&&f==1&&d==0&&firstKidsa==0&&chaekBprev==1)
                                {

                                    list_value.splice(list_value.indexOf(+$(this).attr("value")), 1);
                                    value_team.splice(value_team.indexOf(+$(this).attr("choice")), 1);
                                    singels.splice(singels.indexOf($this.attr("choice")), 1);
                                    singelsvalue.splice(singelsvalue.indexOf($this.attr("value")), 1);

                                    total /= sum_value.splice(sum_value.indexOf(+$(this).attr("value")), 1);

                                    sum_value.push($this.prev("td").attr("value"));
                                    list_value.push($this.prev("td").attr("value"));
                                    value_team.push($this.prev("td").attr("choice"));
                                //  singels.push($this.prev("td").attr("choice"));
                                //  singelsvalue.push($this.prev("td").attr("value"));

                                    total *= $this.prev("td").attr("value");

                                    div_sum.text("Total = " + total.toFixed(2));
                                    div_list_value.html("Selected value = " + list_value.join(", "));
                                    div_list_choice.html("Selected choice = " + value_team.join(", "));
                                    div_singels.html("singels = " + singels.join(", "));
                                    div_singels_value.html("singels_value = " + singelsvalue.join(", "));

                                    $this.attr("c","0");
                                    $this.attr("f","0");
                                    $this.attr("e","1");
                                    $this.siblings("td").attr("f","0");
                                    $this.siblings("td").attr("e","1");
                                    console.log("number 27 in F sptziel");
                                }
            /* number 28*/      if(z==2&&c==1&&f==1&&d==0&&firstKidsa==1&&chaekBprev==1)
                                {

                                    list_value.splice(list_value.indexOf(+$(this).attr("value")), 1);
                                    value_team.splice(value_team.indexOf(+$(this).attr("choice")), 1);
                                    singels.splice(singels.indexOf($this.attr("choice")), 1);
                                    singelsvalue.splice(singelsvalue.indexOf($this.attr("value")), 1);

                                    total /= sum_value.splice(sum_value.indexOf(+$(this).attr("value")), 1);

                                    sum_value.push($this.prev("td").attr("value"));
                                    list_value.push($this.prev("td").attr("value"));
                                    value_team.push($this.prev("td").attr("choice"));

                                }

                                           });

                                    });
                                }

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

Body:
i have code with AJAX/GET and after code reload data from php file i
  have another block code using jquery now my problem its why after
  reload data from mysql/php server while the page all the date reloaded
  i can't using function from another script "functionToClick.js". this
  file with 700 lines and work beutiful wehn i using file without AJAX
  just normal PHP code. evry one some idee why its like so?

    <title>Page Title</title>

    <link rel="stylesheet" type="text/css" href="styleTable.css">

$( document ).ready(function (){

    var total = 1;
    var value_team = [];
    var sum_value = [];
    var list_value = [];
    var singels = [];
    var singelsvalue = [];
    //var test = 2;

    $("td").on("click", function more()
    {
        var $this = $(this);
        var choice = $this.attr("choice");
        var value = $this.attr("value");
        var index =

    singels.indexOf($(this).attr("choice"));
    var a = $this.attr("a");
    var b = $this.attr("b");
    var c = $this.attr("c");
    var d = $this.attr("d");
    var e = $this.attr("e");
    var f = $this.attr("f");
    var g = $this.attr("g");
    var h = $this.attr("h");
    var i = $this.attr("i");
    var z = $this.attr("z");
    var idBet = $this.attr("idBet");
    var chaekA =

$this.next("td").attr("a");
var chaekB = $this.next("td").attr("b");
var chaekC = $this.next("td").attr("c");
var chaekAprev = $this.prev("td").attr("a");
var chaekBprev = $this.prev("td").attr("b");
var chaekCprev = $this.prev("td").attr("c");
var firstKidsa = $(this).parent().find("td:first").attr("a");
var lastKidsa = $(this).parent().find("td:last").attr("a");
var firstKidsb = $(this).parent().find("td:first").attr("b");
var lastKidsb = $(this).parent().find("td:last").attr("b");
var firstKidsc = $(this).parent().find("td:first").attr("c");
var lastKidsc = $(this).parent().find("td:last").attr("c");
var div_sum = $("#div_sum");
var div_list_value = $("#div_list_value");
var div_list_choice = $("#div_list_choice");
var div_singels = $("#div_singels");
var div_singels_value = $("#div_singels_value");

        });


问:
How can I print out a single string from two sets of data?
I just started learning Python this week by working on a personal project. The goal of the script I'm working on is to essentially scrape the user's ID and comment from a given news article URL and put them together.

So far it looks like this:

```<code>from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

articleurl = "http://news.nate.com/view/20170401n02609?mid=n1008"

articleid = articleurl[26:40]

print(articleid)

commentslink = "http://comm.news.nate.com/Comment/ArticleComment/list?artc_sq=" + articleid + "&prebest=0&order=O&mid=n1008&domain=&argList=0"
commentslink2 = "http://comm.news.nate.com/Comment/ArticleComment/list?artc_sq=" + articleid + "&order=O&cmtr_fl=0&prebest=0&clean_idx=&user_nm=&fold=&mid=n1008&domain=&argList=0&return_sq=&twitterAuth=N&connectAuth=N&page=2#comment"

print(commentslink)
print(commentslink2)

chrome_path = r"F:\Downloads\chromedriver_win32\chromedriver.exe"
driver = webdriver.Chrome(chrome_path)
driver.get(commentslink)

userlist = []
commentlist = []

usernames = (driver.find_elements_by_class_name("""nameui"""))
for userid in usernames:
    userlist += userid.text
    userlist.append(userid.text)
    print(userid.text)

comments = (driver.find_elements_by_class_name("""usertxt"""))
for comment in comments:
    commentlist += comment.text
    commentlist.append(comment.text)
    print(comment.text)
</code>```

However, the console spits out the complete list of user ID's followed by the complete list of comments. I would like the user's comment to follow right after the user's ID. Right now, the console gives me this:

```<code>(1) bong****
(2) yang****
(3) hide****
... (continues through rest of user ID list)
(1) 어려보이고 싶어하는 순간 나이 먹은거래...
(2) 예능안보내는 이유가 있었네
(3) 드럽게 재미없네
... (continues through rest of comment list)
</code>```

I've been trying to get it to look like this (numbers are for clarity):

```<code>(1) bong****: (1) 어려보이고 싶어하는 순간 나이 먹은거래...
</code>```

I've been trying to work this out but nothing I've done has worked. I am thinking the problem is with the way the variables or for loops are coded. Are there any ideas on how to fix this?

Any help would be appreciated, thanks!

答:
zip() function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.</p>

```<code>finalResult = list(zip(userlist, commentlist))
print(finalResult)
</code>```

Body:
I just started learning Python this week by working on a personal project. The goal of the script I'm working on is to essentially scrape the user's ID and comment from a given news article URL and put them together.

So far it looks like this:

from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

articleurl = "http://news.nate.com/view/20170401n02609?mid=n1008"

articleid = articleurl[26:40]

print(articleid)

commentslink = "http://comm.news.nate.com/Comment/ArticleComment/list?artc_sq=" + articleid + "&prebest=0&order=O&mid=n1008&domain=&argList=0"
commentslink2 = "http://comm.news.nate.com/Comment/ArticleComment/list?artc_sq=" + articleid + "&order=O&cmtr_fl=0&prebest=0&clean_idx=&user_nm=&fold=&mid=n1008&domain=&argList=0&return_sq=&twitterAuth=N&connectAuth=N&page=2#comment"

print(commentslink)
print(commentslink2)

chrome_path = r"F:\Downloads\chromedriver_win32\chromedriver.exe"
driver = webdriver.Chrome(chrome_path)
driver.get(commentslink)

userlist = []
commentlist = []

usernames = (driver.find_elements_by_class_name("""nameui"""))
for userid in usernames:
    userlist += userid.text
    userlist.append(userid.text)
    print(userid.text)

comments = (driver.find_elements_by_class_name("""usertxt"""))
for comment in comments:
    commentlist += comment.text
    commentlist.append(comment.text)
    print(comment.text)

However, the console spits out the complete list of user ID's followed by the complete list of comments. I would like the user's comment to follow right after the user's ID. Right now, the console gives me this:

(1) bong****
(2) yang****
(3) hide****
... (continues through rest of user ID list)
(1) 어려보이고 싶어하는 순간 나이 먹은거래...
(2) 예능안보내는 이유가 있었네
(3) 드럽게 재미없네
... (continues through rest of comment list)

I've been trying to get it to look like this (numbers are for clarity):

(1) bong****: (1) 어려보이고 싶어하는 순간 나이 먹은거래...

I've been trying to work this out but nothing I've done has worked. I am thinking the problem is with the way the variables or for loops are coded. Are there any ideas on how to fix this?

Any help would be appreciated, thanks!

Body:
zip() function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.

finalResult = list(zip(userlist, commentlist))
print(finalResult)


问:
Getting "x509: certificate signed by unknown authority" even with "--insecure-skip-tls-verify" option in Kubernetes
I have a private Docker image registry running on a Linux VM (10.78.0.228:5000) and a Kubernetes master running on a different VM running Centos Linux 7.

I used the below command to create a POD:

kubectl create --insecure-skip-tls-verify -f monitorms-rc.yml

I get this:

sample   monitorms-mmqhm    0/1    ImagePullBackOff   0  8m

and upon running:
kubectl describe pod monitorms-mmqhm --namespace=sample

Warning Failed Failed to pull image "10.78.0.228:5000/monitorms":
  Error response from daemon: {"message":"Get
  https://10.78.0.228:5000/v1/_ping: x509: certificate signed by unknown
  authority"}

Isn't Kubernetes supposed to ignore the server certificate for all operations during POD creation when the --insecure-skip-tls-verify is passed?

If not, how do I make it ignore the tls verification while pulling the docker image?

PS:

Kubernetes version :

Client Version: v1.5.2
Server Version: v1.5.2

I have raised this issue here: https://github.com/kubernetes/kubernetes/issues/43924

答:
The issue you're seeing is actually a docker issue. Using --insecure-skip-tls-verify is a valid arg to kubectl, but it only deals with the connecition between kubectl and the kubernetes API server. The error you're seeing is actually because the docker daemon cannot login to the private registry because the cert it's using in unsigned.

Have a look at the Docker insecure registry docs and this should solve your problem.

ContentLicense: CC BY-SA 4.0


问:
angularjs ui-router - How can I hide the submenu when a specific child-route was hit
I am working on an AngularJS / Ui-router example where I have the following:

A state news, with a sub-state music, when clicking on music the news active state is maintained because I have news.music (music a sub-state of news).

However, sports state is not a sub-state of news. How can I maintain news active state (blue background) when I click on sports?

I have seen many related posts but they are so old.

Here are snaps of the code:

```<code>app.config(function($stateProvider){
  $stateProvider.state('news', {
    url: '/news',
    templateUrl : 'news.html'
  })
});

app.config(function($stateProvider){
  $stateProvider.state('sports', {
    url: '/sports',
    templateUrl : 'sports.html'
  })
});

app.config(function($stateProvider){
  $stateProvider.state('news.music', {
    url: '/music',
    templateUrl : 'music.html'
  })
});
</code>```

index.html

```<code><ul class="nav nav-pills">
      <li role="presentation" ui-sref-active="active"><a ui-sref="news">News</a></li>
      <li role="presentation" ui-sref-active="active"><a ui-sref="about">About</a></li>
</ul>
<ui-view></ui-view>
</code>```

news.html

```<code><ul class="nav nav-tabs">
      <li role="presentation" ui-sref-active="active"><a ui-sref="sports">Sports</a></li>
      <li role="presentation" ui-sref-active="active"><a ui-sref="news.music">Music</a></li>
</ul>
<ui-view></ui-view>
</code>```

And a running plunker

答:
Well, while this is still a error in your application design you could do it with a controller by having news.sports as a child route of news like in this runnable plnkr demo. Your questions should be: "How can I hide the submenu when a specific child-route was hit".

View

```<code><ul class="nav nav-tabs" ng-controller="submenuController" ng-show="showSubMenu">
  <li role="presentation" ui-sref-active="active"><a ui-sref="news.sports">Sports</a></li>
  <li role="presentation" ui-sref-active="active"><a ui-sref="news.music">Music</a></li>
</ul>
<ui-view></ui-view>
</code>```

Controller

```<code>app.controller('submenuController', function ($scope, $rootScope, $state) {

  $scope.showSubMenu = true;

  $scope.$watch(function(){
      return $state.$current.name
  }, function(currentStateName){
     $scope.showSubMenu = currentStateName === 'news.sports' ? false : true;
  })
});
</code>```

Body:
I am working on an AngularJS / Ui-router example where I have the following:

A state news, with a sub-state music, when clicking on music the news active state is maintained because I have news.music (music a sub-state of news).

However, sports state is not a sub-state of news. How can I maintain news active state (blue background) when I click on sports?

I have seen many related posts but they are so old.

Here are snaps of the code:

app.config(function($stateProvider){
  $stateProvider.state('news', {
    url: '/news',
    templateUrl : 'news.html'
  })
});

app.config(function($stateProvider){
  $stateProvider.state('sports', {
    url: '/sports',
    templateUrl : 'sports.html'
  })
});

app.config(function($stateProvider){
  $stateProvider.state('news.music', {
    url: '/music',
    templateUrl : 'music.html'
  })
});

index.html

News

About

<ui-view></ui-view>

news.html

Sports

Music

<ui-view></ui-view>

And a running plunker

Body:
Well, while this is still a error in your application design you could do it with a controller by having news.sports as a child route of news like in this runnable plnkr demo. Your questions should be: "How can I hide the submenu when a specific child-route was hit".

View

<ul class="nav nav-tabs" ng-controller="submenuController" ng-show="showSubMenu">
  <li role="presentation" ui-sref-active="active"><a ui-sref="news.sports">Sports</a></li>
  <li role="presentation" ui-sref-active="active"><a ui-sref="news.music">Music</a></li>
</ul>
<ui-view></ui-view>

Controller

app.controller('submenuController', function ($scope, $rootScope, $state) {

  $scope.showSubMenu = true;

  $scope.$watch(function(){
      return $state.$current.name
  }, function(currentStateName){
     $scope.showSubMenu = currentStateName === 'news.sports' ? false : true;
  })
});


问:
Graphics programs in Codeblocks
I've tried running and going through everything I can find on the net to fix the issue but it just doesn't work.
So far I've done:

Downloaded Codeblocks 13.12 (as well as tried with 16.01) with mingw setup.

Added graphics.h and winbgi.h files to the include folder in Codeblocks, mingw.
Added libbgi.a to lib similarly.

Linked the library by going to Compiler Settings->linker settings.
also added the words on the right side:

-lbgi -lgdi32 -lcomdlg32 -luuid -loleaut32 -lole32

The program compiles just fine. I've fixed an error in the graphics.h file which had a double declaration of int right as well as explained in the stack overflow as well as other answers on how to run graphics in codeblocks.

Everytime I run a code, Codeblocks says program.exe has stopped working as soon as it encounters initgraph

答:
I have been through that as well.
Just do one thing. Download codeblocks ep from here.

Then do the same with this codeblocks ep. download winbgi.h...Everything just the same way you did with codeblocks!

Title: Graphics programs in Codeblocks


问:
umbraco datatypes and text value from code behind
I am trying to get the text value of a dropdown list from the API and I am seriously struggling.

This is what I have at the moment:

```<code>Document doc = new Document(Node.GetCurrent().Id);

doc.GetProperty("fieldPropertyName").Value;
</code>```

This returns a string representation of the id for the prevalue.

What I want is the text for that pre value.

Thanks in advance for the help.

答:
Please excuse this being in VB.

This is the language I happened to be developing in. (How I wish I could use C#)

```<code>Imports System.Runtime.CompilerServices
Imports umbraco.cms.businesslogic.web
Imports umbraco.cms.businesslogic.datatype

Module UmbracoExtensionHelper

    <Extension()>
    Public Function GetCustomPropertyValueFromPreValues(ByVal doc As Document, ByVal propertyName As String)
        Dim returnValue As String = ""
        Dim objProperty As umbraco.cms.businesslogic.property.Property = doc.getProperty(propertyName)

        If objProperty IsNot Nothing Then
            Dim objPreValues = PreValues.GetPreValues(objProperty.PropertyType.DataTypeDefinition.Id)
            If objPreValues IsNot Nothing Then

                ''run through the ids of the datatypes and the value of the property
                For Each entry As DictionaryEntry In objPreValues
                    Dim currentPreValue As PreValue = CType(entry.Value, PreValue)
                    If currentPreValue.Id.ToString().ToLower() = objProperty.Value.ToString().ToLower() Then
                        returnValue = currentPreValue.Value.ToLower()
                        Exit For
                    End If
                Next

            End If
        End If

        Return returnValue
    End Function

End Module
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am trying to get the text value of a dropdown list from the API and I am seriously struggling.

This is what I have at the moment:

Document doc = new Document(Node.GetCurrent().Id);

doc.GetProperty("fieldPropertyName").Value;

This returns a string representation of the id for the prevalue.

What I want is the text for that pre value.

Thanks in advance for the help.

Body:
Please excuse this being in VB.

This is the language I happened to be developing in. (How I wish I could use C#)

Imports System.Runtime.CompilerServices
Imports umbraco.cms.businesslogic.web
Imports umbraco.cms.businesslogic.datatype

Module UmbracoExtensionHelper

    <Extension()>
    Public Function GetCustomPropertyValueFromPreValues(ByVal doc As Document, ByVal propertyName As String)
        Dim returnValue As String = ""
        Dim objProperty As umbraco.cms.businesslogic.property.Property = doc.getProperty(propertyName)

        If objProperty IsNot Nothing Then
            Dim objPreValues = PreValues.GetPreValues(objProperty.PropertyType.DataTypeDefinition.Id)
            If objPreValues IsNot Nothing Then

                ''run through the ids of the datatypes and the value of the property
                For Each entry As DictionaryEntry In objPreValues
                    Dim currentPreValue As PreValue = CType(entry.Value, PreValue)
                    If currentPreValue.Id.ToString().ToLower() = objProperty.Value.ToString().ToLower() Then
                        returnValue = currentPreValue.Value.ToLower()
                        Exit For
                    End If
                Next

            End If
        End If

        Return returnValue
    End Function

End Module


问:
C# String Array to Double
Looking for some assistance. I'm sure its really easy, but I just cannot seem to get my head around it.

First, here's my code so far:

```<code>        //Prompts user to enter numbers
    Console.Write("Enter a line of comma-seperated temperatures: ");
    string temps = Console.ReadLine();
    //Splits commas, seperating numbers into array
    string[] numsInString = temps.Split(',');
    int temps1 = numsInString.Length;
    int[] temps2 = new int[temps1];
    for (int i = 0; i < numsInString.Length; i++)
    {
        temps2[i] = int.Parse(numsInString[i]);
    }

    Console.WriteLine("Minimum temp: " + temps2.Min());
    Console.WriteLine("Average temp: " + temps2.Average());
</code>```

So, it prompts the user to enter a temperature i.e "5" separated by commas, "5,6,7,8". My trouble is that I cannot have temperatures in the decimal range such as "5.4,5.7,6.3,6.8". I've figured out that I need to convert the string to double, but I'm not entirely sure on how to do that.

Thanks

答:
You want to change the type of your array to double[] and then change your parsing to parse double instead of int:

```<code>double[] temps2 = new double[temps1];

for (int i = 0; i < numsInString.Length; i++)
{
    temps2[i] = double.Parse(numsInString[i]);
}
</code>```

As a bit of an aside, you can also use LINQ to express this more declaratively:

```<code>double[] temps2 = temps.Split(',')
    .Select(double.Parse)
    .ToArray();
</code>```

Title: C# String Array to Double

Body:
Looking for some assistance. I'm sure its really easy, but I just cannot seem to get my head around it.

First, here's my code so far:

        //Prompts user to enter numbers
    Console.Write("Enter a line of comma-seperated temperatures: ");
    string temps = Console.ReadLine();
    //Splits commas, seperating numbers into array
    string[] numsInString = temps.Split(',');
    int temps1 = numsInString.Length;
    int[] temps2 = new int[temps1];
    for (int i = 0; i < numsInString.Length; i++)
    {
        temps2[i] = int.Parse(numsInString[i]);
    }

    Console.WriteLine("Minimum temp: " + temps2.Min());
    Console.WriteLine("Average temp: " + temps2.Average());

So, it prompts the user to enter a temperature i.e "5" separated by commas, "5,6,7,8". My trouble is that I cannot have temperatures in the decimal range such as "5.4,5.7,6.3,6.8". I've figured out that I need to convert the string to double, but I'm not entirely sure on how to do that.

Thanks

Body:
You want to change the type of your array to double[] and then change your parsing to parse double instead of int:

double[] temps2 = new double[temps1];

for (int i = 0; i < numsInString.Length; i++)
{
    temps2[i] = double.Parse(numsInString[i]);
}

As a bit of an aside, you can also use LINQ to express this more declaratively:

double[] temps2 = temps.Split(',')
    .Select(double.Parse)
    .ToArray();


问:
javascript return reference to array item
I have a array like this:

```<code>users = [{id:1, name:'name1'},{id:2, name:'name2'}]
</code>```

How could I get a reference to the item {id:2, name:'name2'}, so I can change it is name property, like:

```<code>user = get_item(users, 'id', 2);
user.name = "user2 name changed";
</code>```

console.log(users) will have the result:

```<code>[{id:1, name:'name1'},{id:2, name:'user2 name changed'}]
</code>```

I tried to use Array.filter() function, but it returns a new array instead of a reference to the original array. which I can not use to mutate the original array.

Any idea?

答:
You can use findIndex(), for example:</p>

```<code>var users = [{id:1, name:'name1'},{id:2, name:'name2'}]
var idx = users.findIndex(item => item.id === 2);
var u = users[idx]; // the reference of user2
u.name = "name changed."; // same as `users[idx].name = "name changed.";`
</code>```

Body:
I have a array like this:

users = [{id:1, name:'name1'},{id:2, name:'name2'}]

How could I get a reference to the item {id:2, name:'name2'}, so I can change it is name property, like:

user = get_item(users, 'id', 2);
user.name = "user2 name changed";

console.log(users) will have the result:

[{id:1, name:'name1'},{id:2, name:'user2 name changed'}]

I tried to use Array.filter() function, but it returns a new array instead of a reference to the original array. which I can not use to mutate the original array.

Any idea?

Body:
You can use findIndex(), for example:

var users = [{id:1, name:'name1'},{id:2, name:'name2'}]
var idx = users.findIndex(item => item.id === 2);
var u = users[idx]; // the reference of user2
u.name = "name changed."; // same as `users[idx].name = "name changed.";`


问:
Segue after new user creation using firebase not being performed -Swift
I am having issues with two segues however, since I used the same logic in the implementation of each of these segues I'm going to go ahead and condense everything into one question. Basically, I am trying to initialize a segue after performing createUser function with firebase and after performing login function also handled by Firebase, however, when the SignUp and Login buttons are clicked there seems to be no response to the segue being called. Below is the code for each of the @IBActions

```<code> @IBAction func signUpComplete(_ sender: Any) {
    FIRAuth.auth()?.createUser(withEmail: signUpEmailField.text!, password: signUpPasswordField.text!, completion: { (user: FIRUser?, error) in
        if self.signUpEmailField.text == "" || self.signUpPasswordField.text == "" {
                let alert = UIAlertController(title: "Oops!", message: "A valid E-mail and Password are Required", preferredStyle: UIAlertControllerStyle.alert)
                alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil))
                    self.present(alert, animated: true, completion: nil)

        if FIRAuthErrorCode.errorCodeEmailAlreadyInUse != nil {

            let emailExists = UIAlertController(title: "Oops!", message: "A user with this E-Mail already exists!", preferredStyle: UIAlertControllerStyle.alert)
            emailExists.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil))
            self.present(emailExists, animated: true, completion: nil)

            }

        else {

            DispatchQueue.main.async () {
                self.performSegue(withIdentifier: "signUpSucceededSegue", sender: self)
            }
            }

            }
        })
}
</code>```

and

```<code>@IBAction func loginButton(_ sender: Any) {

    FIRAuth.auth()?.signIn(withEmail: emailLoginField.text!, password: passwordLoginField.text!, completion: { (user: FIRUser?, error) in
            if self.emailLoginField.text == "" || self.passwordLoginField.text == ""{

                let alert = UIAlertController(title: "Alert", message: "E-Mail is Required", preferredStyle: UIAlertControllerStyle.alert)
                alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil))
                self.present(alert, animated: true, completion: nil)

            if FIRAuthErrorCode.errorCodeUserNotFound != nil {

                let invalidLogin = UIAlertController(title: "Alert", message: "E-Mail/Password Incorrect", preferredStyle: UIAlertControllerStyle.alert)
                invalidLogin.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil))
                self.present(invalidLogin, animated: true, completion: nil)

            }

        else{

                DispatchQueue.main.async () {

                    self.performSegue(withIdentifier: "loginSucceededSegue", sender: self)

                }

            }

        }
    })
</code>```

are there any glaring logical errors at first glance or is there a better way to implement a segue into these functions?

答:
Embed a Navigation Controller to the very first view of your storyboard

Then Try using this code:-

```<code>@IBAction func signUpComplete(_ sender: Any) {

if self.signUpEmailField.text == "" || self.signUpPasswordField.text == "" {

    let alert = UIAlertController(title: "Oops!", message: "A valid E-mail and Password are Required", preferredStyle: UIAlertControllerStyle.alert)
    alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil))
    self.present(alert, animated: true, completion: nil)

}else{

    FIRAuth.auth()?.createUser(withEmail: self.signUpEmailField!.text, password: self.signUpPasswordField!.text, completion: { (user, err) in

        if let ErrorCode = FIRAuthErrorCode(rawValue: err!._code){

            switch ErrorCode {

            case .errorCodeEmailAlreadyInUse : let emailExists = UIAlertController(title: "Oops!", message: "A user with this E-Mail already exists!", preferredStyle: UIAlertControllerStyle.alert)
                                               emailExists.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil))
                                               self.present(emailExists, animated: true, completion: nil)

                                               break

            default                      :  break

            }

        }else{

            let nextView = self.navigationController!.storyboard!.instantiateViewController(withIdentifier: "signUpSucceededSegue")
            self.navigationController!.pushViewController(nextView, animated: true)

        }
    })
  }
}
</code>```

Then alter your other code-block in the similar fashion.

Body:
I am having issues with two segues however, since I used the same logic in the implementation of each of these segues I'm going to go ahead and condense everything into one question. Basically, I am trying to initialize a segue after performing createUser function with firebase and after performing login function also handled by Firebase, however, when the SignUp and Login buttons are clicked there seems to be no response to the segue being called. Below is the code for each of the @IBActions

 @IBAction func signUpComplete(_ sender: Any) {
    FIRAuth.auth()?.createUser(withEmail: signUpEmailField.text!, password: signUpPasswordField.text!, completion: { (user: FIRUser?, error) in
        if self.signUpEmailField.text == "" || self.signUpPasswordField.text == "" {
                let alert = UIAlertController(title: "Oops!", message: "A valid E-mail and Password are Required", preferredStyle: UIAlertControllerStyle.alert)
                alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil))
                    self.present(alert, animated: true, completion: nil)

        if FIRAuthErrorCode.errorCodeEmailAlreadyInUse != nil {

            let emailExists = UIAlertController(title: "Oops!", message: "A user with this E-Mail already exists!", preferredStyle: UIAlertControllerStyle.alert)
            emailExists.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil))
            self.present(emailExists, animated: true, completion: nil)

            }

        else {

            DispatchQueue.main.async () {
                self.performSegue(withIdentifier: "signUpSucceededSegue", sender: self)
            }
            }

            }
        })
}

and

@IBAction func loginButton(_ sender: Any) {

    FIRAuth.auth()?.signIn(withEmail: emailLoginField.text!, password: passwordLoginField.text!, completion: { (user: FIRUser?, error) in
            if self.emailLoginField.text == "" || self.passwordLoginField.text == ""{

                let alert = UIAlertController(title: "Alert", message: "E-Mail is Required", preferredStyle: UIAlertControllerStyle.alert)
                alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil))
                self.present(alert, animated: true, completion: nil)

            if FIRAuthErrorCode.errorCodeUserNotFound != nil {

                let invalidLogin = UIAlertController(title: "Alert", message: "E-Mail/Password Incorrect", preferredStyle: UIAlertControllerStyle.alert)
                invalidLogin.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil))
                self.present(invalidLogin, animated: true, completion: nil)

            }

        else{

                DispatchQueue.main.async () {

                    self.performSegue(withIdentifier: "loginSucceededSegue", sender: self)

                }

            }

        }
    })

are there any glaring logical errors at first glance or is there a better way to implement a segue into these functions?

Body:
Embed a Navigation Controller to the very first view of your storyboard

Then Try using this code:-

@IBAction func signUpComplete(_ sender: Any) {

if self.signUpEmailField.text == "" || self.signUpPasswordField.text == "" {

    let alert = UIAlertController(title: "Oops!", message: "A valid E-mail and Password are Required", preferredStyle: UIAlertControllerStyle.alert)
    alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil))
    self.present(alert, animated: true, completion: nil)

}else{

    FIRAuth.auth()?.createUser(withEmail: self.signUpEmailField!.text, password: self.signUpPasswordField!.text, completion: { (user, err) in

        if let ErrorCode = FIRAuthErrorCode(rawValue: err!._code){

            switch ErrorCode {

            case .errorCodeEmailAlreadyInUse : let emailExists = UIAlertController(title: "Oops!", message: "A user with this E-Mail already exists!", preferredStyle: UIAlertControllerStyle.alert)
                                               emailExists.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil))
                                               self.present(emailExists, animated: true, completion: nil)

                                               break

            default                      :  break

            }

        }else{

            let nextView = self.navigationController!.storyboard!.instantiateViewController(withIdentifier: "signUpSucceededSegue")
            self.navigationController!.pushViewController(nextView, animated: true)

        }
    })
  }
}

Then alter your other code-block in the similar fashion.


问:
Excel VBA - How to select a dynamic range of cells for a chart series collection?
Im trying to define a chart series collection that goes from a determined cell to the end of data (down and right).

I used the following code to set up the labels of the axis:

```<code>oGrafico.Chart.SeriesCollection(nNoSerie).XValues = oPestana.Range(oPestana.Cells(46,14), oPestana.Cells(46,43))
</code>```

I tried to use a similar approach for the data series with assignation of the ranges to the code, but the error "Application-defined or Object-defined error" pops up:

```<code>oGrafico.Chart.SeriesCollection(nNoSerie).Values = oPestana.Range(oPestana.Cells(47,14).End(xlToRight),oPestana.Cells(46,47).End(xlDown))
</code>```

I've also tried with "oPestana.Range" instead of "oPestana.Cells" but i think i'm missing something. Is there any way to set up the data series in a similar way?

答:
Does this work for you?</p>

```<code>oGrafico.Chart.SeriesCollection(nNoSerie).Values = oPestana.Cells(47, 14).End(xlToRight).Resize(oPestana.Range(oPestana.Cells(46, 47), oPestana.Cells(46, 47).End(xlDown)).Cells.Count - 1, 1)
</code>```

Body:
Im trying to define a chart series collection that goes from a determined cell to the end of data (down and right).

I used the following code to set up the labels of the axis:

oGrafico.Chart.SeriesCollection(nNoSerie).XValues = oPestana.Range(oPestana.Cells(46,14), oPestana.Cells(46,43))

I tried to use a similar approach for the data series with assignation of the ranges to the code, but the error "Application-defined or Object-defined error" pops up:

oGrafico.Chart.SeriesCollection(nNoSerie).Values = oPestana.Range(oPestana.Cells(47,14).End(xlToRight),oPestana.Cells(46,47).End(xlDown))

I've also tried with "oPestana.Range" instead of "oPestana.Cells" but i think i'm missing something. Is there any way to set up the data series in a similar way?

Body:
Does this work for you?

oGrafico.Chart.SeriesCollection(nNoSerie).Values = oPestana.Cells(47, 14).End(xlToRight).Resize(oPestana.Range(oPestana.Cells(46, 47), oPestana.Cells(46, 47).End(xlDown)).Cells.Count - 1, 1)


问:
Explicitly choose which template overload should be used
Can we chose which function template overload should be used in this case?

```<code>struct X { };

struct A { A(X){} };
struct B { B(X){} };

template<class T>
void fun(T, A) { }

template<class T>
void fun(T, B) { }

int main() {
    /* explicitly choose overload */ fun(1, X());
}
</code>```

Error:

```<code>error: call of overloaded 'fun(int, X)' is ambiguous
     /* explicitly choose overload */ fun(1, X());
                                                ^
    candidate: void fun(T, A) [with T = int]
 void fun(T, A) { }
      ^~~
    candidate: void fun(T, B) [with T = int]
 void fun(T, B) { }
      ^~~
</code>```

For normal function it looks like this:

```<code>void fun(A){}
void fun(B){}

int main() {
    ((void(*)(A))(fun))(X());
}
</code>```

Is it possible?

答:
A low-tech solution to this problem would be to add one extra level of indirection. Add a function like funA, whose sole purpose is to give an explicit name to the first version of fun:

```<code>struct X { };

struct A { A(X){} };
struct B { B(X){} };

template<class T>
void fun(T, A) { }

template<class T>
void fun(T, B) { }

template <class T>
void funA(T t, A a) { fun(t, a); }

int main() {
    /* explicitly choose overload */ funA(1, X());
}
</code>```

However, I wonder why you cannot just change the argument to A(X()). You will have to change the calling code anyway, so what's the problem?

Body:
Can we chose which function template overload should be used in this case?

struct X { };

struct A { A(X){} };
struct B { B(X){} };

template<class T>
void fun(T, A) { }

template<class T>
void fun(T, B) { }

int main() {
    /* explicitly choose overload */ fun(1, X());
}

Error:

error: call of overloaded 'fun(int, X)' is ambiguous
     /* explicitly choose overload */ fun(1, X());
                                                ^
    candidate: void fun(T, A) [with T = int]
 void fun(T, A) { }
      ^~~
    candidate: void fun(T, B) [with T = int]
 void fun(T, B) { }
      ^~~

For normal function it looks like this:

void fun(A){}
void fun(B){}

int main() {
    ((void(*)(A))(fun))(X());
}

Is it possible?

Body:
A low-tech solution to this problem would be to add one extra level of indirection. Add a function like funA, whose sole purpose is to give an explicit name to the first version of fun:

struct X { };

struct A { A(X){} };
struct B { B(X){} };

template<class T>
void fun(T, A) { }

template<class T>
void fun(T, B) { }

template <class T>
void funA(T t, A a) { fun(t, a); }

int main() {
    /* explicitly choose overload */ funA(1, X());
}

However, I wonder why you cannot just change the argument to A(X()). You will have to change the calling code anyway, so what's the problem?


问:
Calculate distance using google map given a latitude and longitude
I am developing a desktop application and I have two point (latitude, longitude). How can I get the distance between these two points? I have looked at the API and most of them are javascript or web based. I am not developing a web page. How can I do this in java?

I want a road distance, not a straight distance

答: A quick Google gave me this: http://www.postalcodeworld.com/samples/distance.java.html Looks like this is a pretty good implementation of what you need using the Haversine Formula I think.</p>


问:
Query was empty error while inserting data in mysql through php usning html form
//This is my php code. i am trying to store data in a table using php and mysql using post method in html form tag but it shows an error that query is empty. i have just started to learn php so might be a dumb one but plz help me with it</p>

```<code><?php

   define('DB_NAME', 'db1');
   define('DB_USER', 'root');
   define('DB_PASSWORD', '');
   define('DB_HOST', 'localhost');

     $link= mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
       if(!$link){
       die('Could not connect:'. mysql_error());
       }
     $db_selected=mysql_select_db(DB_NAME,$link);
       if(!$db_selected){
       die('Cant use' .DB_NAME. ';'. mysql_error());
       }

     $value1="";
     $value2="";
     $value3="";
     $value4="";
     $value5="";
     $value6="";
     $value7="";
     $value8="";
     $value9="";
     $value10="";
     $value11="";
     $value12="";
     $value13="";
     $value14="";
     $value15="";
     $value16="";
     $value17="";
     $value18="";
     $value19="";
     $value20="";
     $value21="";
     $value22="";

     if(isset($_POST['submit'])){
     $value1=$_POST['Full Name'];
     $value2=$_POST['Fathers Name'];
     $value3=$_POST['Mothers Name'];
     $value4=$_POST['DOB'];
     $value5=$_POST['Gender'];
     $value6=$_POST['Marital Status'];
     $value7=$_POST['Husbands Name'];
     $value8=$_POST['Category'];
     $value9=$_POST['Sub-Category'];
     $value10=$_POST['Nationality'];
     $value11=$_POST['Religion'];
     $value12=$_POST['Address'];
     $value13=$_POST['Mobile no'];
     $value14=$_POST['Email-ID'];
     $value15=$_POST['Exam passed'];
     $value16=$_POST['Board'];
     $value17=$_POST['Passing Year'];
     $value18=$_POST['Percentage12'];
     $value19=$_POST['Migcir'];
     $value20=$_POST['ProofDOB'];
     $value21=$_POST['Marksheet'];
     $value22=$_POST['GapCertificate'];
      }
    $sql= mysql_query ("INSERT INTO cslist(Full Name, Fathers Name, Mothers          Name,DOB,Gender,Marital Status,Husbands Name,Category,Sub-Category,Nationality,Religion,Address,Mobile no,Email-ID,Exam passed, Board,Passing Year,Percentage12,Migcir,ProofDOB,Marksheet,GapCertificate) VALUES (
    '$value1','$value2','$value3','$value4','$value5','$value6','$value7','$value8','$value9','$value10','$value11','$value12','$value13','$value14','$value15','$value16','$value17','$value18','$value19','$value20','$value21','$value22')");

    $res=mysql_query($sql) or die ("Error: ". mysql_error(). " with query ".     $sql);
    mysql_close();

    ?>
</code>```

答:
The problem is here:

```<code>(Full Name, Fathers Name, Mothers          Name,DOB,Gender,Marital Status,Husbands Name,Category,Sub-Category,Nationality,Religion,Address,Mobile no,Email-ID,Exam passed, Board,Passing Year,Percentage12,Migcir,ProofDOB,Marksheet,GapCertificate)
</code>```

your column names are having space in them, some are in small case and some are in capital case. This is a very bad DB structure.

Either change the column names by making all columns small case and use _ underscore instead of space or enclosed your column names with ' single quotes

Body:
//This is my php code. i am trying to store data in a table using php and mysql using post method in html form tag but it shows an error that query is empty. i have just started to learn php so might be a dumb one but plz help me with it

<?php

   define('DB_NAME', 'db1');
   define('DB_USER', 'root');
   define('DB_PASSWORD', '');
   define('DB_HOST', 'localhost');

     $link= mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
       if(!$link){
       die('Could not connect:'. mysql_error());
       }
     $db_selected=mysql_select_db(DB_NAME,$link);
       if(!$db_selected){
       die('Cant use' .DB_NAME. ';'. mysql_error());
       }

     $value1="";
     $value2="";
     $value3="";
     $value4="";
     $value5="";
     $value6="";
     $value7="";
     $value8="";
     $value9="";
     $value10="";
     $value11="";
     $value12="";
     $value13="";
     $value14="";
     $value15="";
     $value16="";
     $value17="";
     $value18="";
     $value19="";
     $value20="";
     $value21="";
     $value22="";

     if(isset($_POST['submit'])){
     $value1=$_POST['Full Name'];
     $value2=$_POST['Fathers Name'];
     $value3=$_POST['Mothers Name'];
     $value4=$_POST['DOB'];
     $value5=$_POST['Gender'];
     $value6=$_POST['Marital Status'];
     $value7=$_POST['Husbands Name'];
     $value8=$_POST['Category'];
     $value9=$_POST['Sub-Category'];
     $value10=$_POST['Nationality'];
     $value11=$_POST['Religion'];
     $value12=$_POST['Address'];
     $value13=$_POST['Mobile no'];
     $value14=$_POST['Email-ID'];
     $value15=$_POST['Exam passed'];
     $value16=$_POST['Board'];
     $value17=$_POST['Passing Year'];
     $value18=$_POST['Percentage12'];
     $value19=$_POST['Migcir'];
     $value20=$_POST['ProofDOB'];
     $value21=$_POST['Marksheet'];
     $value22=$_POST['GapCertificate'];
      }
    $sql= mysql_query ("INSERT INTO cslist(Full Name, Fathers Name, Mothers          Name,DOB,Gender,Marital Status,Husbands Name,Category,Sub-Category,Nationality,Religion,Address,Mobile no,Email-ID,Exam passed, Board,Passing Year,Percentage12,Migcir,ProofDOB,Marksheet,GapCertificate) VALUES (
    '$value1','$value2','$value3','$value4','$value5','$value6','$value7','$value8','$value9','$value10','$value11','$value12','$value13','$value14','$value15','$value16','$value17','$value18','$value19','$value20','$value21','$value22')");

    $res=mysql_query($sql) or die ("Error: ". mysql_error(). " with query ".     $sql);
    mysql_close();

    ?>

Body:
The problem is here:

(Full Name, Fathers Name, Mothers          Name,DOB,Gender,Marital Status,Husbands Name,Category,Sub-Category,Nationality,Religion,Address,Mobile no,Email-ID,Exam passed, Board,Passing Year,Percentage12,Migcir,ProofDOB,Marksheet,GapCertificate)

your column names are having space in them, some are in small case and some are in capital case. This is a very bad DB structure.

Either change the column names by making all columns small case and use _ underscore instead of space or enclosed your column names with ' single quotes


问:
Loop through JSON with VBScript
I need to parse the JSON returned from an API in VBScript. I have the code that sends the request to the API and gets the response (this code can be provided). I only need the code that parses through the records of the JSON returned by the API and make it available. I need to know the content of each field from the JSON, and when each record starts and ends, so that each record can be stored in a database (database store code not needed).

The JSON model schema is like so:

{
  "name": string
  "id": int
  "birth": date
}
```

<p>If you have your own JSON parsing library, it can be useful. I am using this (it can be provided).</p>

<p>The code I have so far is like this:</p>

<pre class="lang-vb prettyprint-override"><code>Set objHTTP = Server.CreateObject("MSXML2.ServerXMLHTTP")
objHTTP.open "GET", "http://localhost/website/api.asp", False
'Some headers:
objHTTP.setRequestHeader "CustomerAccountId", "{my_account_id}"
objHTTP.setRequestHeader "CustomerId", "{my_customer_id}"
objHTTP.setRequestHeader "DeveloperToken", "{my_API_access_Key}"
objHTTP.setRequestHeader "Password", "{my_password}"
objHTTP.setRequestHeader "UserName", "{my_user_name}"
objHTTP.send ""

'Error treatment:
If objHTTP.Status >= 400 And objHTTP.Status <= 599 Then
   Response.write "Error Occurred : " & objHTTP.status & " - " & objHTTP.statusText
   Response.end
Else
   Response.write "Success : " & objHTTP.status & " - " & objHTTP.ResponseText
   Response.end
End If

str = objHTTP.responseText
Set o = json.Decode(str)
'I need the rest of the code here!
</code>```

答:
It seems you are using Classic ASP. That means you can easily run JScript instead of VBScript.

And that means you can use a proper JSON parser and easy syntax to access the resulting object.

```<code><script runat="server" language="JScript" src="json2.js">
<script runat="server" language="JScript">

function httpGet(url) {
  var objHTTP = Server.CreateObject("MSXML2.ServerXMLHTTP");
  objHTTP.open("GET", url, false);

  objHTTP.setRequestHeader("CustomerAccountId", "{my_account_id}");
  objHTTP.setRequestHeader("CustomerId", "{my_customer_id}");
  objHTTP.setRequestHeader("DeveloperToken", "{my_API_access_Key}");
  objHTTP.setRequestHeader("Password", "{my_password}");
  objHTTP.setRequestHeader("UserName", "{my_user_name}");
  objHTTP.send();

  // Error treatment
  if (objHTTP.Status >= 400 && objHTTP.Status <= 599) {
    Response.write("Error Occurred : " + objHTTP.status + " - " + objHTTP.statusText);
     Response.end();
  }
  return objHTTP;
}

var xhr = httpGet("http://localhost/website/api.asp");
var data = JSON.parse(xhr.responseText);

// read about how to access objects and arrays in JS
</script>
</code>```

You can even mix VBScript and Javascript on the same page.

```<code><script runat="server" language="VBScript">
Function HttpGet(url)
    Set objHTTP = Server.CreateObject("MSXML2.ServerXMLHTTP")

    With objHTTP
        .open "GET", url, False

        'Some headers:
        .setRequestHeader "CustomerAccountId", "{my_account_id}"
        .setRequestHeader "CustomerId", "{my_customer_id}"
        .setRequestHeader "DeveloperToken", "{my_API_access_Key}"
        .setRequestHeader "Password", "{my_password}"
        .setRequestHeader "UserName", "{my_user_name}"
        .send ""

        'Error treatment:
        If .Status >= 400 And .Status <= 599 Then
           Response.write "Error Occurred : " & .status & " - " & .statusText
           Response.end
        End If
    End With

    Set HttpGet = objHTTP
End Function
</script>

<script runat="server" language="JScript" src="json2.js">
<script runat="server" language="JScript">
var xhr = HttpGet("http://localhost/website/api.asp");
var data = JSON.parse(xhr.responseText);

// read about how to access objects and arrays in JS
</script>
</code>```

I am not showing how to work with objects in JS. For one thing, I don't know your object structure. For another, this is basic stuff you can read about absolutely everywhere.

Title: Loop through JSON with VBScript

Body:
I need to parse the JSON returned from an API in VBScript. I have the code that sends the request to the API and gets the response (this code can be provided). I only need the code that parses through the records of the JSON returned by the API and make it available. I need to know the content of each field from the JSON, and when each record starts and ends, so that each record can be stored in a database (database store code not needed).

The JSON model schema is like so:

{
  "name": string
  "id": int
  "birth": date
}

If you have your own JSON parsing library, it can be useful. I am using this (it can be provided).

The code I have so far is like this:

Set objHTTP = Server.CreateObject("MSXML2.ServerXMLHTTP")
objHTTP.open "GET", "http://localhost/website/api.asp", False
'Some headers:
objHTTP.setRequestHeader "CustomerAccountId", "{my_account_id}"
objHTTP.setRequestHeader "CustomerId", "{my_customer_id}"
objHTTP.setRequestHeader "DeveloperToken", "{my_API_access_Key}"
objHTTP.setRequestHeader "Password", "{my_password}"
objHTTP.setRequestHeader "UserName", "{my_user_name}"
objHTTP.send ""

'Error treatment:
If objHTTP.Status >= 400 And objHTTP.Status <= 599 Then
   Response.write "Error Occurred : " & objHTTP.status & " - " & objHTTP.statusText
   Response.end
Else
   Response.write "Success : " & objHTTP.status & " - " & objHTTP.ResponseText
   Response.end
End If

str = objHTTP.responseText
Set o = json.Decode(str)
'I need the rest of the code here!

Body:
It seems you are using Classic ASP. That means you can easily run JScript instead of VBScript.

And that means you can use a proper JSON parser and easy syntax to access the resulting object.

<script runat="server" language="JScript" src="json2.js">
<script runat="server" language="JScript">

function httpGet(url) {
  var objHTTP = Server.CreateObject("MSXML2.ServerXMLHTTP");
  objHTTP.open("GET", url, false);

  objHTTP.setRequestHeader("CustomerAccountId", "{my_account_id}");
  objHTTP.setRequestHeader("CustomerId", "{my_customer_id}");
  objHTTP.setRequestHeader("DeveloperToken", "{my_API_access_Key}");
  objHTTP.setRequestHeader("Password", "{my_password}");
  objHTTP.setRequestHeader("UserName", "{my_user_name}");
  objHTTP.send();

  // Error treatment
  if (objHTTP.Status >= 400 && objHTTP.Status <= 599) {
    Response.write("Error Occurred : " + objHTTP.status + " - " + objHTTP.statusText);
     Response.end();
  }
  return objHTTP;
}

var xhr = httpGet("http://localhost/website/api.asp");
var data = JSON.parse(xhr.responseText);

// read about how to access objects and arrays in JS
</script>

You can even mix VBScript and Javascript on the same page.

<script runat="server" language="VBScript">
Function HttpGet(url)
    Set objHTTP = Server.CreateObject("MSXML2.ServerXMLHTTP")

    With objHTTP
        .open "GET", url, False

        'Some headers:
        .setRequestHeader "CustomerAccountId", "{my_account_id}"
        .setRequestHeader "CustomerId", "{my_customer_id}"
        .setRequestHeader "DeveloperToken", "{my_API_access_Key}"
        .setRequestHeader "Password", "{my_password}"
        .setRequestHeader "UserName", "{my_user_name}"
        .send ""

        'Error treatment:
        If .Status >= 400 And .Status <= 599 Then
           Response.write "Error Occurred : " & .status & " - " & .statusText
           Response.end
        End If
    End With

    Set HttpGet = objHTTP
End Function
</script>

<script runat="server" language="JScript" src="json2.js">
<script runat="server" language="JScript">
var xhr = HttpGet("http://localhost/website/api.asp");
var data = JSON.parse(xhr.responseText);

// read about how to access objects and arrays in JS
</script>

I am not showing how to work with objects in JS. For one thing, I don't know your object structure. For another, this is basic stuff you can read about absolutely everywhere.


问:
extracting a word (of variable length) ending with 동 from a string in R
I have a data frame in R with one column containing an address in Korean. I need to extract one of the words (a word ending with 동), if it's there (it's possible that it's missing) and create a new column named "dong" that will contain this word. So my data is shown in column "address" and desired output is shown in column "dong" shown below.

```<code>address <- c("대전광역시 서구 탄방동 홈플러스","대전광역시 동구 효동 주민센터","대전광역시 대덕구 오정동 한남마트","대전광역시 동구 자양동 87-3번지 성동경로당","대전광역시 유성구 용계로 128")
dong <- c("탄방동","효동","오정동","자양동",NA)
data <- data.frame(address,dong, stringsAsFactors = FALSE)
</code>```

I've tried using grep but it's not giving me exactly what I need.

```<code>grep(".+동\\s",data$address,value=T)
</code>```

I think I have 2 issues: 1) I'm not sure how to write a proper regular expression to identify the word I need and 2) I'm not sure why grep returns the whole string rather than the word. I would appreciate any suggestions.

答:
A regex to extract Korean whole words ending with a specific letter is

```<code>\b\w*동\b
</code>```

See the regex demo.

Details:

\b- leading word boundary

\w* - 0+ word chars

동 - ending letter

\b - trailing word boundary

See the R demo:

```<code>address <- c("대전광역시 서구 탄방동 홈플러스","대전광역시 동구 효동 주민센터","대전광역시 대덕구 오정동 한남마트","대전광역시 동구 자양동 87-3번지 성동경로당","대전광역시 유성구 용계로 128")
## matches <- regmatches(address, gregexpr("\\b\\w*동\\b", address, perl=TRUE ))
matches <- regmatches(address, gregexpr("\\b\\w*동\\b", address ))
dong <- unlist(lapply(matches, function(x) if (length(x) == 0) NA else x))
data <- data.frame(address,dong, stringsAsFactors = FALSE)
</code>```

Output:

```<code>                                     address   dong
1            대전광역시 서구 탄방동 홈플러스 탄방동
2              대전광역시 동구 효동 주민센터   효동
3          대전광역시 대덕구 오정동 한남마트 오정동
4 대전광역시 동구 자양동 87-3번지 성동경로당 자양동
5               대전광역시 유성구 용계로 128   <NA>
</code>```

Note that dong <- unlist(lapply(matches, function(x) if (length(x) == 0) NA else x)) line is necessary to add NA to those rows where no match was found.

Body:
I have a data frame in R with one column containing an address in Korean. I need to extract one of the words (a word ending with 동), if it's there (it's possible that it's missing) and create a new column named "dong" that will contain this word. So my data is shown in column "address" and desired output is shown in column "dong" shown below.

address <- c("대전광역시 서구 탄방동 홈플러스","대전광역시 동구 효동 주민센터","대전광역시 대덕구 오정동 한남마트","대전광역시 동구 자양동 87-3번지 성동경로당","대전광역시 유성구 용계로 128")
dong <- c("탄방동","효동","오정동","자양동",NA)
data <- data.frame(address,dong, stringsAsFactors = FALSE)

I've tried using grep but it's not giving me exactly what I need.

grep(".+동\\s",data$address,value=T)

I think I have 2 issues: 1) I'm not sure how to write a proper regular expression to identify the word I need and 2) I'm not sure why grep returns the whole string rather than the word. I would appreciate any suggestions.

Body:
A regex to extract Korean whole words ending with a specific letter is

\b\w*동\b

See the regex demo.

Details:

\b- leading word boundary

\w* - 0+ word chars

동 - ending letter

\b - trailing word boundary

See the R demo:

address <- c("대전광역시 서구 탄방동 홈플러스","대전광역시 동구 효동 주민센터","대전광역시 대덕구 오정동 한남마트","대전광역시 동구 자양동 87-3번지 성동경로당","대전광역시 유성구 용계로 128")
## matches <- regmatches(address, gregexpr("\\b\\w*동\\b", address, perl=TRUE ))
matches <- regmatches(address, gregexpr("\\b\\w*동\\b", address ))
dong <- unlist(lapply(matches, function(x) if (length(x) == 0) NA else x))
data <- data.frame(address,dong, stringsAsFactors = FALSE)

Output:

                                     address   dong
1            대전광역시 서구 탄방동 홈플러스 탄방동
2              대전광역시 동구 효동 주민센터   효동
3          대전광역시 대덕구 오정동 한남마트 오정동
4 대전광역시 동구 자양동 87-3번지 성동경로당 자양동
5               대전광역시 유성구 용계로 128   <NA>

Note that dong <- unlist(lapply(matches, function(x) if (length(x) == 0) NA else x)) line is necessary to add NA to those rows where no match was found.


问:
Sending data with Publish channel in maximo
When you "export" data with the external system and publist channel in maximo, is it possible that the response you send will be in JSON? Because I can only get it in XML.</p>

答: how about using an XSLT that coverts xml to json. </p>


问:
My date in being transformed to UTC?
I got this function below which helps me to change a date format from one to another:

```<code>def change_time_format(self, date_string, input_format, output_format):

    if date_string == None:
        return None

    try:
        date = datetime.datetime.strptime(date_string, input_format)
        timestamp = calendar.timegm(date.timetuple())
        new_formatted_date = datetime.datetime.fromtimestamp(timestamp).strftime(output_format)
        return new_formatted_date
    except Exception as E:
        print E
        return None
</code>```

And when i'm calling it like this:

```<code>dtu.change_time_format('2017-01-01 12:34:56', '%Y-%m-%d %H:%M:%S', '%d%m%Y %H%M%S')
</code>```

I'm getting the input as:'01012017 153456' which is wrong and needs to be: '01012017 123456', there is a difference of 3 hours for some reason.

I can't find how to fix it, I searched for several ways over the web and I couldn't find nothing.

答:
From here: </p>

```<code>return datetime.datetime.strptime(date_string, input_format).strftime(output_format)
</code>```

Title: My date in being transformed to UTC?

Body:
I got this function below which helps me to change a date format from one to another:

def change_time_format(self, date_string, input_format, output_format):

    if date_string == None:
        return None

    try:
        date = datetime.datetime.strptime(date_string, input_format)
        timestamp = calendar.timegm(date.timetuple())
        new_formatted_date = datetime.datetime.fromtimestamp(timestamp).strftime(output_format)
        return new_formatted_date
    except Exception as E:
        print E
        return None

And when i'm calling it like this:

dtu.change_time_format('2017-01-01 12:34:56', '%Y-%m-%d %H:%M:%S', '%d%m%Y %H%M%S')

I'm getting the input as:'01012017 153456' which is wrong and needs to be: '01012017 123456', there is a difference of 3 hours for some reason.

I can't find how to fix it, I searched for several ways over the web and I couldn't find nothing.

Body:
From here:

return datetime.datetime.strptime(date_string, input_format).strftime(output_format)


问:
Angular 2 templates methods vs getters
I'm wondering if there is any benefit to do this:

```<code>  <div>{{getSomething()}}</div>

  export class MyComp {
    getSomething() { return ...}
  }
</code>```

Over this:

```<code> <div>{{getSomething}}</div>

 export class MyComp {
   get getSomething() { return ...}
 }
</code>```

Use methods vs getters to display calculated data.

答:
If you are a getter or a method doesn't matter from a technical point of view.

Some use the convention that a getter should behave similar to a field, and not do expensive computation, while a method should be used if the computation is more than some very basic things like for example building a full name from first- middle- and last name.

I think this is good practice to follow that distinction for Angular, because for view binding expensive calculation should be avoided because the method or getter can be called very often.
In such a case it's better to store the result in a field and bind to the field instead.

Very important in view binding is, that the method or getter doesn't return different values on subsequent calls when no dependencies were modified (like return {};, which would be treated as new object instance and cause an error like ExpressionChangedAfterItHasBeenCheckedError).

Title: Angular 2 templates methods vs getters

Body:
I'm wondering if there is any benefit to do this:

{{getSomething()}}

  export class MyComp {
    getSomething() { return ...}
  }

Over this:

{{getSomething}}

 export class MyComp {
   get getSomething() { return ...}
 }

Use methods vs getters to display calculated data.


问:
How to vertically stack (and wrap) a list of block elements with css
I have a ul / li list of which the li elements should stack vertically, and wrap after a certain number (either nth child or preferably parent height), like this:

```<code>1  4
2  5
3  6
</code>```

How could this be done? (preferably without fixed pixel size and absolute positioning)

答:
What you are looking for is column-count property.
Wrap the ul by a div with a class: </p>

```<code><div class="wrapper">
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
  </ul>
</div>
.wrapper{
    column-count: 2;
    column-gap: 20px;//for spacing between
}
</code>```

Body:
I have a ul / li list of which the li elements should stack vertically, and wrap after a certain number (either nth child or preferably parent height), like this:

1  4
2  5
3  6

How could this be done? (preferably without fixed pixel size and absolute positioning)

Body:
What you are looking for is column-count property.
Wrap the ul by a div with a class:

<div class="wrapper">
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
  </ul>
</div>
.wrapper{
    column-count: 2;
    column-gap: 20px;//for spacing between
}