问:
Is declaring the same variable multiple times a good practice
Here is my javascript code:

```<code>(function(){
"use strict";
document.addEventListener("DOMContentLoaded",animations); /*on content loaded */

function animations() {

/*start of animation for the toggle navigation button in smaller view ports*/
(function () {

    var button = document.getElementById('nav-icon');
    button.addEventListener('click', function(){
        if (this.classList.contains('active')===true) {
            this.classList.remove('active');
        }
        else {
            this.classList.add('active');
        }
    })

})();  /*End of the toggle navigation animation*/

/*Start of  scrolling side navigation for smaller view ports*/

(function(){

        var button = document.getElementById('nav-icon');
        var body = document.querySelector('body');
        button.addEventListener('click', function(){
        if (this.classList.contains('active')===true) {
            body.classList.add('active-nav');
        }
        else {
            body.classList.remove('active-nav');
        }

    });

    })(); /*End of scrolling side navigation*/

(function () {
        // body...
        var media = window.matchMedia("(min-width: 992px)");
        var body = document.querySelector('body');
        var button = document.getElementById('nav-icon');
        window.addEventListener('resize',function(){

            if (media.matches) {

                    body.classList.remove('active-nav');

                    if (button.classList.contains('active')===true) {

                        button.classList.remove('active');
                    }

                }

        });

    })();

};

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

As you can see I have declared variables that have exactly the same value multiple times in my code, but they are in different functions. each iife is a seperate animation and has a different functionality although they might share  common elements. However, I wanted to know if this was a good practice. Should I declare common variables in the main function so they might be in the execution context of all the sub functions? Also, please highlight anything that doesnot look good or is not a good practice. Thank you

答:
Variables last for only the scope they're defined in. So, even if you have variables that get the same value from your DOM, they will only be in memory as long as they're in scope (in this case, as long as your function is executing). <br>
Don't worry about it. </p>

Body:
Here is my javascript code:

(function(){
"use strict";
document.addEventListener("DOMContentLoaded",animations); /*on content loaded */

function animations() {

/*start of animation for the toggle navigation button in smaller view ports*/
(function () {

    var button = document.getElementById('nav-icon');
    button.addEventListener('click', function(){
        if (this.classList.contains('active')===true) {
            this.classList.remove('active');
        }
        else {
            this.classList.add('active');
        }
    })

})();  /*End of the toggle navigation animation*/

/*Start of  scrolling side navigation for smaller view ports*/

(function(){

        var button = document.getElementById('nav-icon');
        var body = document.querySelector('body');
        button.addEventListener('click', function(){
        if (this.classList.contains('active')===true) {
            body.classList.add('active-nav');
        }
        else {
            body.classList.remove('active-nav');
        }

    });

    })(); /*End of scrolling side navigation*/

(function () {
        // body...
        var media = window.matchMedia("(min-width: 992px)");
        var body = document.querySelector('body');
        var button = document.getElementById('nav-icon');
        window.addEventListener('resize',function(){

            if (media.matches) {

                    body.classList.remove('active-nav');

                    if (button.classList.contains('active')===true) {

                        button.classList.remove('active');
                    }

                }

        });

    })();

};

})();

As you can see I have declared variables that have exactly the same value multiple times in my code, but they are in different functions. each iife is a seperate animation and has a different functionality although they might share  common elements. However, I wanted to know if this was a good practice. Should I declare common variables in the main function so they might be in the execution context of all the sub functions? Also, please highlight anything that doesnot look good or is not a good practice. Thank you

Body:
Variables last for only the scope they're defined in. So, even if you have variables that get the same value from your DOM, they will only be in memory as long as they're in scope (in this case, as long as your function is executing).

Don't worry about it.


来源: stackexchange

问:
Select SQL by group
I try to select with calculate by group but I get this error:

Msg 8120, Level 16, State 1, Line 1
  Column 'dbo.LN0617.RATE' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Can someone help me?

```<code>SELECT
    NT4                AS nt,
    LN0617.OFFCR       AS OfficeCode,
    ln0617.RATE * 100  AS LaiSuat,
    SUM( ln0617.CBAL ) AS SoDu,
    ln0617.RATE * 100 * sum( ln0617.CBAL ) AS LS1
FROM
    [dbo].[SIL_CM]
    JOIN [dbo].[LN0617] ON
    (
        ln0617.ACCTNO = SIL_CM.TK
        AND
        ln0617.CBAL <> 0
        AND
        SIL_CM.TKTYPE='L'
    )
GROUP BY
    sil_cm.NT4,
    LN0617.OFFCR,
    ln0617.RATE * 100
ORDER BY
    LN0617.OFFCR,
    ln0617.RATE * 100
</code>```

答:
I believe you only need to refer to the column for grouping as * 100 is constant</p>

```<code>SELECT
      NT4                                               AS nt
    , LN0617.OFFCR                                      AS OfficeCode
    , ln0617.RATE * 100                                 AS LaiSuat
    , SUM(ln0617.CBAL)                                  AS SoDu
    , SUM(ln0617.CBAL * ln0617.RATE) / SUM(ln0617.cbal) AS LS1
FROM [dbo].[SIL_CM] SIL_CM
JOIN [dbo].[LN0617] LN0617 ON ln0617.ACCTNO = SIL_CM.TK
WHERE ln0617.CBAL <> 0
      AND SIL_CM.TKTYPE = 'L'
GROUP BY
      sil_cm.NT4
    , LN0617.OFFCR
    , ln0617.RATE
ORDER BY
      LN0617.OFFCR
    , ln0617.RAT
</code>```

ContentLicense: CC BY-SA 3.0

Title: Select SQL by group

Body:
I try to select with calculate by group but I get this error:

Msg 8120, Level 16, State 1, Line 1
  Column 'dbo.LN0617.RATE' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Can someone help me?

SELECT
    NT4                AS nt,
    LN0617.OFFCR       AS OfficeCode,
    ln0617.RATE * 100  AS LaiSuat,
    SUM( ln0617.CBAL ) AS SoDu,
    ln0617.RATE * 100 * sum( ln0617.CBAL ) AS LS1
FROM
    [dbo].[SIL_CM]
    JOIN [dbo].[LN0617] ON
    (
        ln0617.ACCTNO = SIL_CM.TK
        AND
        ln0617.CBAL <> 0
        AND
        SIL_CM.TKTYPE='L'
    )
GROUP BY
    sil_cm.NT4,
    LN0617.OFFCR,
    ln0617.RATE * 100
ORDER BY
    LN0617.OFFCR,
    ln0617.RATE * 100

Body:
I believe you only need to refer to the column for grouping as * 100 is constant

SELECT
      NT4                                               AS nt
    , LN0617.OFFCR                                      AS OfficeCode
    , ln0617.RATE * 100                                 AS LaiSuat
    , SUM(ln0617.CBAL)                                  AS SoDu
    , SUM(ln0617.CBAL * ln0617.RATE) / SUM(ln0617.cbal) AS LS1
FROM [dbo].[SIL_CM] SIL_CM
JOIN [dbo].[LN0617] LN0617 ON ln0617.ACCTNO = SIL_CM.TK
WHERE ln0617.CBAL <> 0
      AND SIL_CM.TKTYPE = 'L'
GROUP BY
      sil_cm.NT4
    , LN0617.OFFCR
    , ln0617.RATE
ORDER BY
      LN0617.OFFCR
    , ln0617.RAT


问:
How to Get Uploaded Files' tmp_name in a Form?
I am creating a form where users can upload at most 4 pictures and change the uploaded pictures. Pictures are uploaded to the folder upload/.

If any picture already exists in the folder, the form will show the existing picture so that the user can check whether to change the picture or not.

HTML & PHP codes are as below:

     <form name="upload_form" action="upload.php">

         <?php
         if( file_exists("upload/pic0.jpg")){
           echo "";
         }
         ?>
         <input type="file" name="picture[]" id="picture" />
         <button onclick="removeBlock()">Remove</button>

         <?php
         if( file_exists("upload/pic1.jpg")){
           echo "";
         }
         ?>
        <input type="file" name="picture[]" id="picture" />
        <button onclick="removeBlock()">Remove</button>

        <?php
         if( file_exists("upload/pic2.jpg")){
           echo "";
         }
         ?>
        <input type="file" name="picture[]" id="picture" />
        <button onclick="removeBlock()">Remove</button>

        <?php
         if( file_exists("upload/pic3.jpg")){
           echo "";
         }
         ?>
        <input type="file" name="picture[]" id="picture" />
        <button onclick="removeBlock()">Remove</button>

      <input type="submit" />

      <button onclick="addBlock()">Upload More</button>

    </form>```
</div>
</div>
</p>

```<?php  //upload.php
for ($i = 0; $i < count($_FILES["picture"]["name"]); $i++) {
  move_uploaded_file($_FILES["picture"]["tmp_name"][$i], "upload/pic".$i
}
?>
```

If users don't want the old picture, they can click <input type="file"> to upload a new picture;

If they still want the old one, how can I let <input type="file"> get the existing picture's tmp_name so that the upload.php can upload the picture?

Thank you very much !

答:
Just ignore the move_uploaded_file() when no uploaded files

```<code>for ($i = 0; $i < count($_FILES["picture"]["name"]); $i++) {
  if ($_FILES["picture"]['size'] > 0 && $_FILES['picture']['error'] == 0) {
      // upload file when there are uploaded file
      move_uploaded_file($_FILES['picture']['tmp_name'][$i], 'upload/pic' . $i);
  }
}
</code>```

Body:
I am creating a form where users can upload at most 4 pictures and change the uploaded pictures. Pictures are uploaded to the folder upload/.

If any picture already exists in the folder, the form will show the existing picture so that the user can check whether to change the picture or not.

HTML & PHP codes are as below:

     <form name="upload_form" action="upload.php">

         <?php
         if( file_exists("upload/pic0.jpg")){
           echo "";
         }
         ?>
         <input type="file" name="picture[]" id="picture" />
         <button onclick="removeBlock()">Remove</button>

         <?php
         if( file_exists("upload/pic1.jpg")){
           echo "";
         }
         ?>
        <input type="file" name="picture[]" id="picture" />
        <button onclick="removeBlock()">Remove</button>

        <?php
         if( file_exists("upload/pic2.jpg")){
           echo "";
         }
         ?>
        <input type="file" name="picture[]" id="picture" />
        <button onclick="removeBlock()">Remove</button>

        <?php
         if( file_exists("upload/pic3.jpg")){
           echo "";
         }
         ?>
        <input type="file" name="picture[]" id="picture" />
        <button onclick="removeBlock()">Remove</button>

      <input type="submit" />

      <button onclick="addBlock()">Upload More</button>

    </form>

<?php  //upload.php
for ($i = 0; $i < count($_FILES["picture"]["name"]); $i++) {
  move_uploaded_file($_FILES["picture"]["tmp_name"][$i], "upload/pic".$i
}
?>

If users don't want the old picture, they can click <input type="file"> to upload a new picture;

If they still want the old one, how can I let <input type="file"> get the existing picture's tmp_name so that the upload.php can upload the picture?

Thank you very much !

Body:
Just ignore the move_uploaded_file() when no uploaded files

for ($i = 0; $i < count($_FILES["picture"]["name"]); $i++) {
  if ($_FILES["picture"]['size'] > 0 && $_FILES['picture']['error'] == 0) {
      // upload file when there are uploaded file
      move_uploaded_file($_FILES['picture']['tmp_name'][$i], 'upload/pic' . $i);
  }
}


问:
all strings of length k that can be formed from a set of n characters
This question has been asked for other languages but I'm looking for the most idiomatic way to find all strings of length k that can be formed from a set of n characters in R

Example input and output:

```<code>input <- c('a', 'b')

output <- c('aa', 'ab', 'ba', 'bb')
</code>```

答:
Adapting AK88's answer, outer can be used for arbitrary values of k, although it's not necessarily the most efficient solution:

```<code>input <- c('a', 'b')
k = 5
perms = input
for (i in 2:k) {
    perms = outer(perms, input, paste, sep="")
}
result = as.vector(perms)
</code>```

Body:
This question has been asked for other languages but I'm looking for the most idiomatic way to find all strings of length k that can be formed from a set of n characters in R

Example input and output:

input <- c('a', 'b')

output <- c('aa', 'ab', 'ba', 'bb')

Body:
Adapting AK88's answer, outer can be used for arbitrary values of k, although it's not necessarily the most efficient solution:

input <- c('a', 'b')
k = 5
perms = input
for (i in 2:k) {
    perms = outer(perms, input, paste, sep="")
}
result = as.vector(perms)


问:
Rolling and cumulative standard deviation in a Python dataframe
Is there a vectorized operation to calculate the cumulative and rolling standard deviation (SD) of a Python DataFrame?

For example, I want to add a column 'c' which calculates the cumulative SD based on column 'a', i.e. in index 0, it shows NaN due to 1 data point, and in index 1, it calculates SD based on 2 data points, and so on.

The same question goes to rolling SD too. Is there an efficient way to calculate without iterating through df.itertuples()?

```<code>import numpy as np
import pandas as pd

def main():
    np.random.seed(123)
    df = pd.DataFrame(np.random.randn(10, 2), columns=['a', 'b'])
    print(df)

if __name__ == '__main__':
    main()
</code>```

Body:
Is there a vectorized operation to calculate the cumulative and rolling standard deviation (SD) of a Python DataFrame?

For example, I want to add a column 'c' which calculates the cumulative SD based on column 'a', i.e. in index 0, it shows NaN due to 1 data point, and in index 1, it calculates SD based on 2 data points, and so on.

The same question goes to rolling SD too. Is there an efficient way to calculate without iterating through df.itertuples()?

import numpy as np
import pandas as pd

def main():
    np.random.seed(123)
    df = pd.DataFrame(np.random.randn(10, 2), columns=['a', 'b'])
    print(df)

if __name__ == '__main__':
    main()

Body:
For cumulative SD base on columna 'a', let's use rolling with a windows size the length of the dataframe and min_periods = 2:

df['a'].rolling(len(df),min_periods=2).std()

Output:

          a         b         c
0 -1.085631  0.997345       NaN
1  0.282978 -1.506295  0.967753
2 -0.578600  1.651437  0.691916
3 -2.426679 -0.428913  1.133892
4  1.265936 -0.866740  1.395750
5 -0.678886 -0.094709  1.250335
6  1.491390 -0.638902  1.374933
7 -0.443982 -0.434351  1.274843
8  2.205930  2.186786  1.450563
9  1.004054  0.386186  1.403721

And for rolling SD based on two values at a time:

df['c'] = df['a'].rolling(2).std()

Output:

          a         b         c
0 -1.085631  0.997345       NaN
1  0.282978 -1.506295  0.967753
2 -0.578600  1.651437  0.609228
3 -2.426679 -0.428913  1.306789
4  1.265936 -0.866740  2.611073
5 -0.678886 -0.094709  1.375197
6  1.491390 -0.638902  1.534617
7 -0.443982 -0.434351  1.368514
8  2.205930  2.186786  1.873771
9  1.004054  0.386186  0.849855


问:
Page readable by file_get_contents but not cURL
I'm creating an API endpoint in PHP, and have a page that outputs JSON, let's call it example.com/stats. When a user tries to return the data, it's only successful when they use file_get_contents(), when users try to reach it using cURL they receive a NULL response. How should I be serving JSON data in PHP so that it's compatible with both file_get_contents and curl?

More info below.

SOURCE for /stats

```<code>header('Content-type: application/json');
echo '{"status":"error", "message":"invalid operation"}';
</code>```

When I try to read this page from another server via file_get_contents() everything works fine.

```<code>function fgc($receive_url){
$fgc = json_decode(file_get_contents($receive_url), true);
return $fgc;
}

$out = fgc("https://example.com/stats");
var_dump($out);

//returns: array(2) { ["status"]=> string(5) "error" ["message"]=> string(17) "invalid operation" }
</code>```

When I try doing the same thing but with cURL I get NULL.

```<code>function curlit($receive_url){
$ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, $receive_url);
$ccc = curl_exec($ch);
$json = json_decode($ccc, true);
return $json;
}

$out = curlit("https://example.com/stats");
var_dump($out);
</code>```

Please note other sites that display JSON work fine with my cURL function, it's specifically the data I'm serving from example.com/stats that fails when using cURL. I thought using the header application/json would be enough to allow this data to be reachable via cURL. Any ideas what could be wrong on the serving side? Why would file get contents work but not curl? Maybe cURL is displaying a result before the page is done loading? I tried removing the application/json header but that made no difference.

答:
Answer added for reference:

After debuging with OP, he found out that example.com was issuing a 301 redirect.

Solution is to make cURL follow the redirect by adding the following option:

```<code>curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
</code>```

Body:
I'm creating an API endpoint in PHP, and have a page that outputs JSON, let's call it example.com/stats. When a user tries to return the data, it's only successful when they use file_get_contents(), when users try to reach it using cURL they receive a NULL response. How should I be serving JSON data in PHP so that it's compatible with both file_get_contents and curl?

More info below.

SOURCE for /stats

header('Content-type: application/json');
echo '{"status":"error", "message":"invalid operation"}';

When I try to read this page from another server via file_get_contents() everything works fine.

function fgc($receive_url){
$fgc = json_decode(file_get_contents($receive_url), true);
return $fgc;
}

$out = fgc("https://example.com/stats");
var_dump($out);

//returns: array(2) { ["status"]=> string(5) "error" ["message"]=> string(17) "invalid operation" }

When I try doing the same thing but with cURL I get NULL.

function curlit($receive_url){
$ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, $receive_url);
$ccc = curl_exec($ch);
$json = json_decode($ccc, true);
return $json;
}

$out = curlit("https://example.com/stats");
var_dump($out);

Please note other sites that display JSON work fine with my cURL function, it's specifically the data I'm serving from example.com/stats that fails when using cURL. I thought using the header application/json would be enough to allow this data to be reachable via cURL. Any ideas what could be wrong on the serving side? Why would file get contents work but not curl? Maybe cURL is displaying a result before the page is done loading? I tried removing the application/json header but that made no difference.

Body:
Answer added for reference:

After debuging with OP, he found out that example.com was issuing a 301 redirect.

Solution is to make cURL follow the redirect by adding the following option:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);


问:
Laravel - change specific tr bgcolor in views using controller based on parameter
I'm trying to change the color of my table rows based on my parameter. here's my code:

AdminController.php

```<code>public function table_row(){

    if ($walk->is_paid && $walk->is_completed) {
        $highlightClass = 'bg-success';
    }
    elseif (empty($walk->is_paid) && $walk->is_completed) {
        $highlightClass = 'bg-warning';
    }
    elseif ($walk->is_cancelled) {
        $highlightClass = 'bg-danger';
    }
    return view('walks', compact('$highlightClass'));
}
</code>```

walks.blade.php

```<code><tr class="{{ $highlightClass }}">
</code>```

It didn't work.. :(

Here's the image of table in my views:

enter image description here

答:
This should be the way to send data to views. Remove the $ in compact method.

```<code>public function table_row(){
    $highlightClass = "";

    if ($walk->is_paid && $walk->is_completed) {
        $highlightClass = 'bg-success';
    }
    elseif (empty($walk->is_paid) && $walk->is_completed) {
        $highlightClass = 'bg-warning';
    }
    elseif ($walk->is_cancelled) {
        $highlightClass = 'bg-danger';
    }

    return view('walks', compact('highlightClass')); // not $highlightClass
}
</code>```

Ref: https://www.w3schools.com/php/func_array_compact.asp

```<code>// walks.blade.php

<tr class="{{$highlightClass or ''}}">
</code>```

Body:
I'm trying to change the color of my table rows based on my parameter. here's my code:

AdminController.php

public function table_row(){

    if ($walk->is_paid && $walk->is_completed) {
        $highlightClass = 'bg-success';
    }
    elseif (empty($walk->is_paid) && $walk->is_completed) {
        $highlightClass = 'bg-warning';
    }
    elseif ($walk->is_cancelled) {
        $highlightClass = 'bg-danger';
    }
    return view('walks', compact('$highlightClass'));
}

walks.blade.php

It didn't work.. :(

Here's the image of table in my views:

enter image description here

Body:
This should be the way to send data to views. Remove the $ in compact method.

public function table_row(){
    $highlightClass = "";

    if ($walk->is_paid && $walk->is_completed) {
        $highlightClass = 'bg-success';
    }
    elseif (empty($walk->is_paid) && $walk->is_completed) {
        $highlightClass = 'bg-warning';
    }
    elseif ($walk->is_cancelled) {
        $highlightClass = 'bg-danger';
    }

    return view('walks', compact('highlightClass')); // not $highlightClass
}

Ref: https://www.w3schools.com/php/func_array_compact.asp

// walks.blade.php

<tr class="{{$highlightClass or ''}}">


问:
How i can use the id in the textbox from a moda form to do query using php and mysql to fill out the value of other textbox
I had a form table and For the edit button, when i click the button the modal will come out.

The problem is how i can use the id in the textbox to do query using php and mysql to fill out the value of other textbox.

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script type="text/javascript">
//jquery funtion to sent id to Edit modal
$(document).ready(function() {
  $('#modalEditGroup').on('show.bs.modal', function(e) {
    var id = $(e.relatedTarget).data('id');
     $('#id').val(id);
  });
});
</script></code>```

<input type="button" id="edit-group" name="edit-group" class="btn btn-primary btn-xs" data-id="<?php echo $row['group_id'];?>" data-toggle="modal" data-target="#modalEditGroup" value="Edit">

              <button type="button" class="close"
                 data-dismiss="modal">
                     ×
                     Close
              </button>

                  Edit Group

              <form class="form-horizontal" role="form" method="POST" action="<?php echo $_SERVER['PHP_SELF'] ?>">

                  Id

                          <input type="text" class="form-control" id="id" name="id" class="id" />

                  Group Name

                       <input type="text" id="group_name_edit" required="required" class="form-control col-md-7 col-xs-12" value=""  name="group_name_edit">

                  Access Level

                   <input type="text" id="access_level_edit" required="required" class="form-control col-md-7 col-xs-12" value=""  name="access_level_edit">

                  Approve By

                   <input type="text" id="approve_by_edit" required="required" class="form-control col-md-7 col-xs-12" value=""  name="approve_by_edit">

                      <button class="btn btn-primary" type="reset">Reset</button>
                      <button type="submit" class="btn btn-success" id="submit" name="submit">Submit</button>

              </form>

```

答:
In the same way as setting id in #id field like,

```<code>$('#modalEditGroup').on('show.bs.modal', function(e) {
  var t=$(e.relatedTarget),
      id = t.data('id'),
      gname=t.data('gname'),
      alevel=t.data('alevel'),
      appby=t.data('appby');
     $('#id').val(id);
     $('#group_name_edit').val(gname);
     $('#access_level_edit').val(alevel);
     $('#approve_by_edit').val(appby);
});
</code>```

Add data-* in HTML like,

```<code><input type="button" id="edit-group" name="edit-group"
   class="btn btn-primary btn-xs"
   data-id="<?php echo $row['group_id'];?>"
   data-gname="<?php echo $row['group_name'];?>"
   data-alevel="<?php echo $row['access_level'];?>"
   data-appby="<?php echo $row['approve_by'];?>"
   data-toggle="modal" data-target="#modalEditGroup"
   value="Edit" />
</code>```

And add on submit event like,

```<code>$('#submit').on('click',fucntion(){
   $.ajax({
      url:'YOUR-URL-TO-SUBMIT-DATA',
      type:'post',
      data:{
          id:$('#id').val(),group_name:$('#group_name_edit').val(),
          access_level:$('#access_level_edit').val(),
          approve_by:$('#approve_by_edit').val()
      },
      success:function(data){
          // check for success and error messages
          // if success then hide modal box and alert('Success');
      }
   });
});
</code>```

Body:
I had a form table and For the edit button, when i click the button the modal will come out.

The problem is how i can use the id in the textbox to do query using php and mysql to fill out the value of other textbox.

<input type="button" id="edit-group" name="edit-group" class="btn btn-primary btn-xs" data-id="<?php echo $row['group_id'];?>" data-toggle="modal" data-target="#modalEditGroup" value="Edit">

              <button type="button" class="close"
                 data-dismiss="modal">
                     ×
                     Close
              </button>

                  Edit Group

              <form class="form-horizontal" role="form" method="POST" action="<?php echo $_SERVER['PHP_SELF'] ?>">

                  Id

                          <input type="text" class="form-control" id="id" name="id" class="id" />

                  Group Name

                       <input type="text" id="group_name_edit" required="required" class="form-control col-md-7 col-xs-12" value=""  name="group_name_edit">

                  Access Level

                   <input type="text" id="access_level_edit" required="required" class="form-control col-md-7 col-xs-12" value=""  name="access_level_edit">

                  Approve By

                   <input type="text" id="approve_by_edit" required="required" class="form-control col-md-7 col-xs-12" value=""  name="approve_by_edit">

                      <button class="btn btn-primary" type="reset">Reset</button>
                      <button type="submit" class="btn btn-success" id="submit" name="submit">Submit</button>

              </form>

Body:
In the same way as setting id in #id field like,

$('#modalEditGroup').on('show.bs.modal', function(e) {
  var t=$(e.relatedTarget),
      id = t.data('id'),
      gname=t.data('gname'),
      alevel=t.data('alevel'),
      appby=t.data('appby');
     $('#id').val(id);
     $('#group_name_edit').val(gname);
     $('#access_level_edit').val(alevel);
     $('#approve_by_edit').val(appby);
});

Add data-* in HTML like,

<input type="button" id="edit-group" name="edit-group"
   class="btn btn-primary btn-xs"
   data-id="<?php echo $row['group_id'];?>"
   data-gname="<?php echo $row['group_name'];?>"
   data-alevel="<?php echo $row['access_level'];?>"
   data-appby="<?php echo $row['approve_by'];?>"
   data-toggle="modal" data-target="#modalEditGroup"
   value="Edit" />

And add on submit event like,

$('#submit').on('click',fucntion(){
   $.ajax({
      url:'YOUR-URL-TO-SUBMIT-DATA',
      type:'post',
      data:{
          id:$('#id').val(),group_name:$('#group_name_edit').val(),
          access_level:$('#access_level_edit').val(),
          approve_by:$('#approve_by_edit').val()
      },
      success:function(data){
          // check for success and error messages
          // if success then hide modal box and alert('Success');
      }
   });
});


问:
Simple regex - ignoring certain characters
I'm trying to use the match method with an argument of a regex to select a valid phone number, by definition, any string with nine digits.

For example:

9347584987 is valid,

(456)322-3456 is valid,

(324)5688890 is valid.

But

(340)HelloWorld is NOT valid and

456748 is NOT valid.

So far, I'm able to use \d{9} to select the example string of 9 digit characters in a row, but I'm not sure how to specifically ignore any character, such as '-' or '(' or ')' in the middle of the sequence.

What kind of Regex could I use here?

Body:
"9347584987"      =~ /(?:\d.*){9}/ #=> 0
"(456)322-3456"   =~ /(?:\d.*){9}/ #=> 1
"(324)5688890"    =~ /(?:\d.*){9}/ #=> 1
"(340)HelloWorld" =~ /(?:\d.*){9}/ #=> nil
"456748"          =~ /(?:\d.*){9}/ #=> nil


问:
PHP big array performance?
I have a question regarding array's performance with huge amount of elements. I have this big array that currently has about 100 elements and I will keep adding to it in the future so it will get larger and larger with time. My question is, will there be a huge performance impact when this array gets to 500+ elements or more?</p>

```<code>  $pages=array(
  '<div class="article"><img src="image url here"></div>',
  '<div class="article"><img src="image url here"></div>',
  '<div class="article"><img src="image url here"></div>',
  '<div class="article"><img src="image url here"></div>',
  '<div class="article"><img src="image url here"></div>',
  '<div class="article"><img src="image url here"></div>',
  '<div class="article"><img src="image url here"></div>',
  '<div class="article"><img src="image url here"></div>');
  }
</code>```

答:
Theoretically, there is no limit on the sizes of arrays. In your case, I don't see any major performance impact. The only thing you need to worry about is if it would cause a memory issue based on the memory allocated to your script (as you say your array would grow). This can be changed in the 'memory_limit' in your php.ini configuration.

For a large array, performance also depends on the operations that you would perform once you have all the data in your large array. Operations like in_array would have to search the entire array in the worst case.

Title: PHP big array performance?

Body:
I have a question regarding array's performance with huge amount of elements. I have this big array that currently has about 100 elements and I will keep adding to it in the future so it will get larger and larger with time. My question is, will there be a huge performance impact when this array gets to 500+ elements or more?

  $pages=array(
  '

',
  '

',
  '

',
  '

',
  '

',
  '

',
  '

',
  '

');
  }


问:
IMAP Append for Office 365
I am trying to make something which involves syncing of emails across users in office 365. I am using Outlook's REST API but I cannot find any function similar to IMAP's Append in this API. (Please note I don't want to send. I want something similar to insert or push)

Also, from the response to this question, I found that Office 365 does not support OAuth Mechanism for IMAP. So I cannot use Outlook OAuth2.0 to connect to IMAP.

Is there any way to connect to office365 account with IMAP without a password or to push email using Outlook REST API?

答: Apparently, I figured it out later that there is no way to authorize outlook 365 accounts without username and password. Hence, to use IMAP.Append, one has to provide username and password.</p>

Title: IMAP Append for Office 365


问:
Operator overloading in c (not c++) is it possible?
This question arises from my need to "convert" std::string to char* form.

Preferably I would like to maintain as much code as possible and that includes plenty of "=" initialization/assignment operators.

standard c operators exist for the basic data types (int, char, float, pointers to, etc...).

Is it even possible to overload the assignment operator in c? I suppose that each data type as it's own operator so messing with one wouldn't mess with others.

Anyhow, this is just something that intrigued me as I can't find much references on how C operators are implemented.

Cheers

well, some examples are in order

```<code>std::string a_string;
a_string = "bla"
</code>```

or using standard C

```<code>char a_char_array[10];
strcpy(a_char_array,"bla");
</code>```

or

```<code>char *a_char_pointer = "bla";
</code>```

what I'm thinking about is a wa to replace these 3 use cases with a single one where I can (through a #define) switch between using char* or std::string.

I guess that everyone that really cares about performance vs coding speed has already thought about the implications of using std::string instead of char*. All of the advantages of using stl are usually often offseted (is this even a word!?) by lower performance (you can't always get what you want right??).

As I said, I have a large project and I want to see for myself what are the changes in using one method or the other.

My post title was purposely misleading as I didn't want this to become a char* vs string battle, but I guess I can't really explain what I want without some more details.

Cheers

答: If you see std::string in your code, and the compiler doesn't complain, then you have a C++, not C.</p>

ContentLicense: CC BY-SA 2.5

Body:
This question arises from my need to "convert" std::string to char* form.

Preferably I would like to maintain as much code as possible and that includes plenty of "=" initialization/assignment operators.

standard c operators exist for the basic data types (int, char, float, pointers to, etc...).

Is it even possible to overload the assignment operator in c? I suppose that each data type as it's own operator so messing with one wouldn't mess with others.

Anyhow, this is just something that intrigued me as I can't find much references on how C operators are implemented.

Cheers

well, some examples are in order

std::string a_string;
a_string = "bla"

or using standard C

char a_char_array[10];
strcpy(a_char_array,"bla");

or

char *a_char_pointer = "bla";

what I'm thinking about is a wa to replace these 3 use cases with a single one where I can (through a #define) switch between using char* or std::string.

I guess that everyone that really cares about performance vs coding speed has already thought about the implications of using std::string instead of char*. All of the advantages of using stl are usually often offseted (is this even a word!?) by lower performance (you can't always get what you want right??).

As I said, I have a large project and I want to see for myself what are the changes in using one method or the other.

My post title was purposely misleading as I didn't want this to become a char* vs string battle, but I guess I can't really explain what I want without some more details.

Cheers


问:
sending email using codeigniter email class
i have an error by trying to send an email using codeigniter email Class.

I have an error of :
Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()

How can i test to send email in codeigniter?. I am also using localhost. Is this problem only occurs when i use localhost?

Here is my code:

```<code>public function emailme() {
        $this->load->library('email');
        $message = $this->input->post('email_msg');
        $this->email->from('iamjohnx3303@yahoo.com', 'John');
        $this->email->to('iamjohnx3302@gmail.com');
        $this->email->subject('Email Test');
        $this->email->message($message);
        $this->email->send();
    }
</code>```

答:
Configuration in sendmail.ini

path   c:\xampp\sendmail\sendmail.ini

Configurations

```<code>[sendmail]

smtp_server=smtp.gmail.com
smtp_port=25
error_logfile=error.log
debug_logfile=debug.log
auth_username=myemail@gmail.com
auth_password=yourgmailpassword
force_sender=myemail@gmail.com
</code>```

in php.ini

pathc:\xampp\xampp\php\php.ini

```<code>[mail function]
sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"
</code>```

then

```<code>$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.googlemail.com',
'smtp_port' => 465,
'smtp_user' => 'xxx@gmail.com',// your mail name
'smtp_pass' => '*****',
'mailtype'  => 'html',
'charset'   => 'iso-8859-1'
 'wordwrap' => TRUE
);

$this->load->library('email', $config);
</code>```

Mail Settings in XAMPP(Important)

```<code>$this->email->from('mygmail@gmail.com', 'myname');//your mail address and name
$this->email->to('target@gmail.com'); //receiver mail

$this->email->subject('testing');
$this->email->message($message);

$this->email->send(); //sending mail
</code>```

Body:
i have an error by trying to send an email using codeigniter email Class.

I have an error of :
Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()

How can i test to send email in codeigniter?. I am also using localhost. Is this problem only occurs when i use localhost?

Here is my code:

public function emailme() {
        $this->load->library('email');
        $message = $this->input->post('email_msg');
        $this->email->from('iamjohnx3303@yahoo.com', 'John');
        $this->email->to('iamjohnx3302@gmail.com');
        $this->email->subject('Email Test');
        $this->email->message($message);
        $this->email->send();
    }

Body:
Configuration in sendmail.ini

path   c:\xampp\sendmail\sendmail.ini

Configurations

[sendmail]

smtp_server=smtp.gmail.com
smtp_port=25
error_logfile=error.log
debug_logfile=debug.log
auth_username=myemail@gmail.com
auth_password=yourgmailpassword
force_sender=myemail@gmail.com

in php.ini

pathc:\xampp\xampp\php\php.ini

[mail function]
sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"

then

$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.googlemail.com',
'smtp_port' => 465,
'smtp_user' => 'xxx@gmail.com',// your mail name
'smtp_pass' => '*****',
'mailtype'  => 'html',
'charset'   => 'iso-8859-1'
 'wordwrap' => TRUE
);

$this->load->library('email', $config);

Mail Settings in XAMPP(Important)

$this->email->from('mygmail@gmail.com', 'myname');//your mail address and name
$this->email->to('target@gmail.com'); //receiver mail

$this->email->subject('testing');
$this->email->message($message);

$this->email->send(); //sending mail


问:
Get the number of records from 2 columns where the time is overlapping
I am new to MS ACCESS and am having trouble trying to get the number of records from overlapping time ranges. This is an example of my data.

example of raw data

I am trying to do is to get the column number_of_records. For example, if there are 4 records added at 5.11, the number_of_records should become 8 as 4 records are added at 5.10.

example of raw data with no_of_records column

There is a mistake in my image above. I forgot to mention that for example, if the time hits 6:00, the number of records should not add on to the previous records and should start afresh.

Do any of you have any suggestions?

答:
Consider the correlated count subquery:</p>

```<code>SELECT t.time_column_1, t.time_column_2,
     (SELECT Count(*) FROM myTable sub
      WHERE sub.time_column_1 <= t.time_column_1
      AND sub.time_column_2 = t.time_column_2) AS number_of_records
FROM mytable t
ORDER BY t.time_column_2, t.time_column_1
</code>```

Body:
Consider the correlated count subquery:

SELECT t.time_column_1, t.time_column_2,
     (SELECT Count(*) FROM myTable sub
      WHERE sub.time_column_1 <= t.time_column_1
      AND sub.time_column_2 = t.time_column_2) AS number_of_records
FROM mytable t
ORDER BY t.time_column_2, t.time_column_1


问:
How To Prevent Multiple Socket.io Event Listeners
I need to be able to access req from my socket.io event listeners. So I did this:

Server

```<code>var express = require('express'),
    app = express(),

app.set('view engine', 'pug');

app.use(express.static(__dirname + '/public'));

client = require('socket.io').listen(8080).sockets;

app.get('/', function (req, res) {
    client.on('connection', function (socket) {
        console.log("Connection")
    });
    res.render('chat');
});

app.listen(config.server.port, function() {
    console.log("Listening on port " + config.server.port);
});
</code>```

Client:

```<code>try {
        var socket = io.connect('http://127.0.0.1:8080');

    } catch(e) {
        //Set status to warn user
        console.log(e);
    }
</code>```

The problem is that if you add socket.io event listeners inside of an express route handler multiple listeners are created on the socket. If you were to create the pug file and test this code you would notice the console logging "connection" once on first refresh twice on second and so on because each time the route is handled another event listener is being added. I could fix it by moving the listener outside of the route handler however I need to be able to access "req". Is there any solution to this that would allow me to access "req" and prevent excess listeners from being added?

答:
Unfortunately, the req object accessed in the socket.io connection event listener is the req when the event listener is declared, NOT the req when the event listener is executed. Thus, the expected behavior mentioned in the question (if my understanding is correct) is impossible.

Here is a simple experiment, for the code in question:

```<code>app.get('/', function (req, res) {
  client.on('connection', function (socket) {
    console.log("req.url: " + req.url)
  });
  res.render('chat');
});
</code>```

If browser is used to send 2 HTTP request: first GET /?q=42 and then GET /?q=88, the console.log result would be:

```<code>//first request
req.url: /?q=42

//second request
req.url: /?q=42
req.url: /?q=88
</code>```

For the second request, as connection event is listened twice, the event listener would be executed twice too. However, the execution result is different -- the event listener attached in the first HTTP request remember the req object value at that time.

If there is only one client, and no concurrent requests (a very restricted situation), there is a workaround -- save req as currentReq, and make event listener deal with currentReq:

```<code>var currentReq;
var isListened = false;

// write logic in middleware, so it can be used in all routes.
app.use(function(req, res, next) {
  currentReq = req;
  if (!isListened) {
    client.on('connection', function (socket) {
      console.log("req.url: " + currentReq.url)
    });
    isListened = true;
  }
  next();
});

app.get('/', function (req, res) {
  res.render('chat');
});
</code>```

Here is some thinking about why this is impossible.

The scenario in the question is:

Browser send HTTP GET request to Node.js

Node.js return HTML page to browser

Browser parse and render HTML page

Browser send WebSocket connection request to Node.js

Node.js establish WebSocket connection, and print log on console.

It is clear that when connection event happens (step 5), the HTTP req (step 1) has long gone. There is no way to restore initial HTTP request information in step 5, as WebSocket and HTTP are different connection, on different port.

Body:
I need to be able to access req from my socket.io event listeners. So I did this:

Server

var express = require('express'),
    app = express(),

app.set('view engine', 'pug');

app.use(express.static(__dirname + '/public'));

client = require('socket.io').listen(8080).sockets;

app.get('/', function (req, res) {
    client.on('connection', function (socket) {
        console.log("Connection")
    });
    res.render('chat');
});

app.listen(config.server.port, function() {
    console.log("Listening on port " + config.server.port);
});

Client:

try {
        var socket = io.connect('http://127.0.0.1:8080');

    } catch(e) {
        //Set status to warn user
        console.log(e);
    }

The problem is that if you add socket.io event listeners inside of an express route handler multiple listeners are created on the socket. If you were to create the pug file and test this code you would notice the console logging "connection" once on first refresh twice on second and so on because each time the route is handled another event listener is being added. I could fix it by moving the listener outside of the route handler however I need to be able to access "req". Is there any solution to this that would allow me to access "req" and prevent excess listeners from being added?

Body:
Unfortunately, the req object accessed in the socket.io connection event listener is the req when the event listener is declared, NOT the req when the event listener is executed. Thus, the expected behavior mentioned in the question (if my understanding is correct) is impossible.

Here is a simple experiment, for the code in question:

app.get('/', function (req, res) {
  client.on('connection', function (socket) {
    console.log("req.url: " + req.url)
  });
  res.render('chat');
});

If browser is used to send 2 HTTP request: first GET /?q=42 and then GET /?q=88, the console.log result would be:

//first request
req.url: /?q=42

//second request
req.url: /?q=42
req.url: /?q=88

For the second request, as connection event is listened twice, the event listener would be executed twice too. However, the execution result is different -- the event listener attached in the first HTTP request remember the req object value at that time.

If there is only one client, and no concurrent requests (a very restricted situation), there is a workaround -- save req as currentReq, and make event listener deal with currentReq:

var currentReq;
var isListened = false;

// write logic in middleware, so it can be used in all routes.
app.use(function(req, res, next) {
  currentReq = req;
  if (!isListened) {
    client.on('connection', function (socket) {
      console.log("req.url: " + currentReq.url)
    });
    isListened = true;
  }
  next();
});

app.get('/', function (req, res) {
  res.render('chat');
});

Here is some thinking about why this is impossible.

The scenario in the question is:

Browser send HTTP GET request to Node.js

Node.js return HTML page to browser

Browser parse and render HTML page

Browser send WebSocket connection request to Node.js

Node.js establish WebSocket connection, and print log on console.

It is clear that when connection event happens (step 5), the HTTP req (step 1) has long gone. There is no way to restore initial HTTP request information in step 5, as WebSocket and HTTP are different connection, on different port.


问:
How to extract nested json elements in mule flow without changing it to Object?
I have a requirement wherein I need to extract the value of a key from JSON input into the mule flow to check condition in choice flow control. My JSON is something like this and I want to extract "todelete". I do not want to change my JSON to Object. Please suggest.</p>

```<code>    [
        {
            "selectiontypeid" : 133,
            "internalrecipientstatusid" : 123,
            "createdby" : "Anu",
            "createddate" : "06/26/2017",
            "authorizedby" : "Anu",
            "authorizeddate" : "06/26/2017",
            "individualdata" :

             [
                        { "intexchangegroupname" : "abc", "employeename" : "abc", "todelete" : "Y"},
                        { "intexchangegroupname" : "abc", "employeename" : "abc", "todelete" : "N"},
                        { "intexchangegroupname" : "abc", "employeename" : "abc", "todelete" : "N"}
             ]

        }
    ]
</code>```

答:
I hope the following code will meet your requirements

payload.individualdata[0].*todelete

Body:
I have a requirement wherein I need to extract the value of a key from JSON input into the mule flow to check condition in choice flow control. My JSON is something like this and I want to extract "todelete". I do not want to change my JSON to Object. Please suggest.

    [
        {
            "selectiontypeid" : 133,
            "internalrecipientstatusid" : 123,
            "createdby" : "Anu",
            "createddate" : "06/26/2017",
            "authorizedby" : "Anu",
            "authorizeddate" : "06/26/2017",
            "individualdata" :

             [
                        { "intexchangegroupname" : "abc", "employeename" : "abc", "todelete" : "Y"},
                        { "intexchangegroupname" : "abc", "employeename" : "abc", "todelete" : "N"},
                        { "intexchangegroupname" : "abc", "employeename" : "abc", "todelete" : "N"}
             ]

        }
    ]


问:
Ionic 2 list not filtering
I am following this tutorial:
https://www.joshmorony.com/high-performance-list-filtering-in-ionic-2/

this is my search.html

```<code><ion-header>
    <ion-navbar>
        <ion-title>search</ion-title>
    </ion-navbar>
    <ion-toolbar primary >
        <ion-searchbar [(ngModel)]="searchTerm" [formControl]="searchControl" ></ion-searchbar>
    </ion-toolbar>
</ion-header>

<ion-content padding>
        <ion-list>
            <ion-item *ngFor="let item of items" >
                {{ item.name}}
            </ion-item>
        </ion-list>
</ion-content>
</code>```

and this is my search.js

```<code>mport { Component } from '@angular/core';
import { IonicPage, NavController, NavParams,ViewController } from 'ionic-angular';
import { DataListProvider } from '../../../providers/data-list/data-list';
import { KeysPipe } from '../../../providers/pipes/pipes';
import 'rxjs/add/operator/debounceTime';
import { FormControl } from '@angular/forms';

@IonicPage()
@Component({
    selector: 'page-country-list-modal',
    templateUrl: 'country-list-modal.html',
})
export class searchPage {

    items=[]
    items1=[]

    searchTerm: string = '';
    searchControl: FormControl;
    searching: any = false;

    constructor(public navCtrl: NavController, public navParams: NavParams,public viewCtrl: ViewController, public dataListProvider : DataListProvider) {
        this.searchControl = new FormControl();
    }

    ngOnInit() {
        console.log ('1234')
        this.items1=JSON.parse(localStorage.getItem("countryList"))

        for(let key in this.items1) {
            if (key == "")
            {

            }else{
                this.items.push({ 'name':  this.items1[key] });
            }
        }
    }

    ionViewDidLoad() {

        this.setFilteredItems();

        this.searchControl.valueChanges.debounceTime(700).subscribe(search => {

            this.setFilteredItems();

        });
    }

    setFilteredItems()
    {
        if (this.searchTerm) {

            return this.items.filter(item => {
                 return item.name.toLowerCase().indexOf(this.searchTerm.toLowerCase()) > -1;
            });
        } else {
            return this.items;
        }
    }

}
</code>```

But the issue its not sorting through the list at all. How do I fix this issue

My items looks like

[{"name":"Canada"},{"name":"Japan"}....]

答:
filter function just return the filtered array, not modify the original array. You need do like this:

```<code>filteredItems =[];
setFilteredItems()
    {
        if (this.searchTerm) {

            this.filteredItems = this.items.filter(item => {
                 return item.name.toLowerCase().indexOf(this.searchTerm.toLowerCase()) > -1;
            });
        } else {
            this.filteredItems = this.items;
        }
    }
</code>```

and use filteredItems to genarate item in template

Title: Ionic 2 list not filtering

Body:
I am following this tutorial:
https://www.joshmorony.com/high-performance-list-filtering-in-ionic-2/

this is my search.html

<ion-header>
    <ion-navbar>
        <ion-title>search</ion-title>
    </ion-navbar>
    <ion-toolbar primary >
        <ion-searchbar [(ngModel)]="searchTerm" [formControl]="searchControl" ></ion-searchbar>
    </ion-toolbar>
</ion-header>

<ion-content padding>
        <ion-list>
            <ion-item *ngFor="let item of items" >
                {{ item.name}}
            </ion-item>
        </ion-list>
</ion-content>

and this is my search.js

mport { Component } from '@angular/core';
import { IonicPage, NavController, NavParams,ViewController } from 'ionic-angular';
import { DataListProvider } from '../../../providers/data-list/data-list';
import { KeysPipe } from '../../../providers/pipes/pipes';
import 'rxjs/add/operator/debounceTime';
import { FormControl } from '@angular/forms';

@IonicPage()
@Component({
    selector: 'page-country-list-modal',
    templateUrl: 'country-list-modal.html',
})
export class searchPage {

    items=[]
    items1=[]

    searchTerm: string = '';
    searchControl: FormControl;
    searching: any = false;

    constructor(public navCtrl: NavController, public navParams: NavParams,public viewCtrl: ViewController, public dataListProvider : DataListProvider) {
        this.searchControl = new FormControl();
    }

    ngOnInit() {
        console.log ('1234')
        this.items1=JSON.parse(localStorage.getItem("countryList"))

        for(let key in this.items1) {
            if (key == "")
            {

            }else{
                this.items.push({ 'name':  this.items1[key] });
            }
        }
    }

    ionViewDidLoad() {

        this.setFilteredItems();

        this.searchControl.valueChanges.debounceTime(700).subscribe(search => {

            this.setFilteredItems();

        });
    }

    setFilteredItems()
    {
        if (this.searchTerm) {

            return this.items.filter(item => {
                 return item.name.toLowerCase().indexOf(this.searchTerm.toLowerCase()) > -1;
            });
        } else {
            return this.items;
        }
    }

}

But the issue its not sorting through the list at all. How do I fix this issue

My items looks like

[{"name":"Canada"},{"name":"Japan"}....]

Body:
filter function just return the filtered array, not modify the original array. You need do like this:

filteredItems =[];
setFilteredItems()
    {
        if (this.searchTerm) {

            this.filteredItems = this.items.filter(item => {
                 return item.name.toLowerCase().indexOf(this.searchTerm.toLowerCase()) > -1;
            });
        } else {
            this.filteredItems = this.items;
        }
    }

and use filteredItems to genarate item in template


问:
How can I compare arbitrary version numbers?
Does anyone have code to compare two version numbers in JavaScript? I just want simple version comparisons (e.g. "1.0" vs "1.5.6"), and it should work with numbers or strings. It can ignore trailing beta identifiers like "1.5.6b4", but can otherwise expect the strings to be well-formed. The function should return a signed integer like a normal cmp function.

```<code>function cmpVersion(a, b)
  return less than one if a < b
  return 0 if a == b
  return greater than one if a > b
</code>```

I have an answer, but will choose a better or more elegant solution over my own.

(I am using this to compare jQuery.browser.version numbers, but the answer will be more widely applicable)

答:
I've refactored mine down to be as concise as I can make it. It does not have the check for trailing zeroes but will work for build numbers of any length (e.g. major, major.minor, major.minor.build).

```<code>var cmpVersion = function(a, b) {
  let arrA = Array.from(a.split('.'), i => +i);
  let arrB = Array.from(b.split('.'), i => +i);

  for (let i = 0; i < (arrA.length >= arrB.length ? arrA.length : arrB.length); i++) {
    if (arrA[i] && !arrB[i] || arrA[i] > arrB[i]) return 'less than one';
    else if (!arrA[i] && arrB[i] || arrA[i] < arrB[i]) return 'greater than one';
  }
  return 0;
}
</code>```

Basically, first I created a new array out of each version string so that I can compare each digit individually. Then in the for loop, I choose the length of the longest version string (or the length of the first version string if they're of equal length).

The if statement checks to see if there is a digit in a but not in b or if the digit of a is greater than the digit of b for a corresponding placeholder, in which case it will return 'less than one'.

As well, the else statement checks to see if there is a digit in b but not in a or if the digit of b is greater than the digit of a for a corresponding place value, in which case it will return 'greater than one'.

The last return 0 statement is a catch-all, which our function will get to if the version strings are equal.

Body:
Does anyone have code to compare two version numbers in JavaScript? I just want simple version comparisons (e.g. "1.0" vs "1.5.6"), and it should work with numbers or strings. It can ignore trailing beta identifiers like "1.5.6b4", but can otherwise expect the strings to be well-formed. The function should return a signed integer like a normal cmp function.

function cmpVersion(a, b)
  return less than one if a  b

I have an answer, but will choose a better or more elegant solution over my own.

(I am using this to compare jQuery.browser.version numbers, but the answer will be more widely applicable)

Body:
I've refactored mine down to be as concise as I can make it. It does not have the check for trailing zeroes but will work for build numbers of any length (e.g. major, major.minor, major.minor.build).

var cmpVersion = function(a, b) {
  let arrA = Array.from(a.split('.'), i => +i);
  let arrB = Array.from(b.split('.'), i => +i);

  for (let i = 0; i < (arrA.length >= arrB.length ? arrA.length : arrB.length); i++) {
    if (arrA[i] && !arrB[i] || arrA[i] > arrB[i]) return 'less than one';
    else if (!arrA[i] && arrB[i] || arrA[i] < arrB[i]) return 'greater than one';
  }
  return 0;
}

Basically, first I created a new array out of each version string so that I can compare each digit individually. Then in the for loop, I choose the length of the longest version string (or the length of the first version string if they're of equal length).

The if statement checks to see if there is a digit in a but not in b or if the digit of a is greater than the digit of b for a corresponding placeholder, in which case it will return 'less than one'.

As well, the else statement checks to see if there is a digit in b but not in a or if the digit of b is greater than the digit of a for a corresponding place value, in which case it will return 'greater than one'.

The last return 0 statement is a catch-all, which our function will get to if the version strings are equal.


问:
Select rows where value changes
I have a table in an access db with columns for job description, project, date, and amount needed.  For each description, I want to select the first date entry for each job/project combo, as well as the rows where the amount changes.

So, if I have

```<code>Job        proj date     amt
Programmer 105  01-01-11 3
Programmer 105  01-02-11 3
Programmer 105  01-03-11 2
Programmer 105  01-04-11 2
Programmer 105  01-05-11 3
Programmer 110  01-03-11 1
Programmer 110  01-04-11 2
Programmer 110  01-05-11 3
Manager    105  01-01-11 1
Manager    105  01-02-11 2
Manager    105  01-03-11 2
Manager    105  01-04-11 2
Manager    105  01-05-11 2
</code>```

I want to select

```<code>Programmer 105  01-01-11 3
Programmer 105  01-03-11 2
Programmer 105  01-05-11 3
Programmer 110  01-03-11 1
Programmer 110  01-04-11 2
Programmer 110  01-05-11 3
Manager    105  01-01-11 1
Manager    105  01-02-11 2
</code>```

I have a table with the distinct job descriptions that can be used.

答:
The first entry will always have Null for nextamt:</p>

```<code>SELECT j.Job,
    j.proj,
    j.Date,
    j.amt,
    (SELECT TOP 1 amt
     FROM jobs q
     WHERE q.job=j.job AND q.proj=j.proj AND q.date<j.date
     ORDER BY [date] DESC) AS nextamt
FROM jobs AS j
WHERE ((SELECT TOP 1 amt
        FROM jobs q
        WHERE q.job=j.job AND q.proj=j.proj AND q.date<j.date
        ORDER BY [date] DESC)) <>[amt]
Or ((SELECT TOP 1 amt
     FROM jobs q
     WHERE q.job=j.job AND q.proj=j.proj AND q.date<j.date
     ORDER BY [date] DESC)) Is Null
</code>```

Title: Select rows where value changes

Body:
I have a table in an access db with columns for job description, project, date, and amount needed.  For each description, I want to select the first date entry for each job/project combo, as well as the rows where the amount changes.

So, if I have

Job        proj date     amt
Programmer 105  01-01-11 3
Programmer 105  01-02-11 3
Programmer 105  01-03-11 2
Programmer 105  01-04-11 2
Programmer 105  01-05-11 3
Programmer 110  01-03-11 1
Programmer 110  01-04-11 2
Programmer 110  01-05-11 3
Manager    105  01-01-11 1
Manager    105  01-02-11 2
Manager    105  01-03-11 2
Manager    105  01-04-11 2
Manager    105  01-05-11 2

I want to select

Programmer 105  01-01-11 3
Programmer 105  01-03-11 2
Programmer 105  01-05-11 3
Programmer 110  01-03-11 1
Programmer 110  01-04-11 2
Programmer 110  01-05-11 3
Manager    105  01-01-11 1
Manager    105  01-02-11 2

I have a table with the distinct job descriptions that can be used.

Body:
The first entry will always have Null for nextamt:

SELECT j.Job,
    j.proj,
    j.Date,
    j.amt,
    (SELECT TOP 1 amt
     FROM jobs q
     WHERE q.job=j.job AND q.proj=j.proj AND q.date<j.date
     ORDER BY [date] DESC) AS nextamt
FROM jobs AS j
WHERE ((SELECT TOP 1 amt
        FROM jobs q
        WHERE q.job=j.job AND q.proj=j.proj AND q.date<j.date
        ORDER BY [date] DESC)) <>[amt]
Or ((SELECT TOP 1 amt
     FROM jobs q
     WHERE q.job=j.job AND q.proj=j.proj AND q.date<j.date
     ORDER BY [date] DESC)) Is Null


问:
Refreshing the screen after entity update from Rest API is not showing latest data?
Steps to reproduce -

I have updated the entity data using CUBA REST API.

I clicked refresh button in browser, it did refresh but the data in entity viewer is still showing old one. So I closed the entity viewer and opened again - it reflects the new changes.

I think the refresh is not working for entity viewer if it is updated by REST API.
Is it a bug or any work around is there?

答:
A quick workaround is to add a refresh button to the UI. Please check below screenshots to add the refresh button. I think that serves the purpose.

When Creating the Generic UI, click on Show advanced properties.

Show Advanced Properties > Table Actions > refresh.

Now you can see Refresh button in the web UI, so the user can click refresh button rather than loading the page.


问:
How to center my buttons vertically?
I put a div around each button and I set them both to inline. They just want to stack as I keep trying to center them.

This is my HTML:

     body{
  background-color:black;
     }

    #light{
 margin-left:50%;
 margin-right:70%;
    }

    #dark{
 margin-left:50%;
 margin-right:50%;
 display:inline-block;
    }

    h3{
 color:white;
 font-family:Courier New;
 font-size:24px;
 margin-left:500px;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <!DOCTYPE html>
    <html>
    <head>
    <title>question reality.</title>
    <link rel="stylesheet" type="text/css" href="intro page.css">
    </head>

    <body>

    <h3>make your choice.</h3>

    <div id="light"><button>Light</button></div>
    <div id="dark"><button>Dark</button></div>

    </body>
    </html></code>```

This is a screencap of what this thing is doing:

答:
Place your buttons in  a main container div, 100% width, and change the margins of the buttons to auto. The parent div must be 100% width and the children, will center align if their margin is set to auto.
https://codepen.io/DannaB67/pen/KqRoJK</p>

```<code>   body{
     background-color:black;
     }
  .main{
    width:100%;}

  #light{
    margin:auto;
    display:inline-block;
    }

  #dark{
    margin:auto;
    display:inline-block;
    }

  h3{
    color:white;
    font-family:Courier New;
    font-size:24px;
    text-align: center;
    }

<body>

    <div align="center" class="main">

      <h3>make your choice.</h3>
      <div id="light"><button>Light</button></div>
      <div id="dark"><button>Dark</button></div>

   </div>

</body>
</code>```

Title: How to center my buttons vertically?

Body:
I put a div around each button and I set them both to inline. They just want to stack as I keep trying to center them.

This is my HTML:

     body{
  background-color:black;
     }

    #light{
 margin-left:50%;
 margin-right:70%;
    }

    #dark{
 margin-left:50%;
 margin-right:50%;
 display:inline-block;
    }

    h3{
 color:white;
 font-family:Courier New;
 font-size:24px;
 margin-left:500px;
    }

    <!DOCTYPE html>

    <title>question reality.</title>
    <link rel="stylesheet" type="text/css" href="intro page.css">

make your choice.

<button>Light</button>

<button>Dark</button>

This is a screencap of what this thing is doing:

Body:
Place your buttons in  a main container div, 100% width, and change the margins of the buttons to auto. The parent div must be 100% width and the children, will center align if their margin is set to auto.
https://codepen.io/DannaB67/pen/KqRoJK

   body{
     background-color:black;
     }
  .main{
    width:100%;}

  #light{
    margin:auto;
    display:inline-block;
    }

  #dark{
    margin:auto;
    display:inline-block;
    }

  h3{
    color:white;
    font-family:Courier New;
    font-size:24px;
    text-align: center;
    }

<body>

    <div align="center" class="main">

      <h3>make your choice.</h3>
      <div id="light"><button>Light</button></div>
      <div id="dark"><button>Dark</button></div>

   </div>

</body>


问:
Target .NET 4.5.2 in Azure Cloud Serice
I use Azure to host a cloud service, and I updated my code to target the .NET 4.5.2 Framework.  When I published it, things went kablooey:

The 'targetFramework' attribute in the  element of the Web.config file is used only to target version 4.0 and later of the .NET Framework (for example, ''). The 'targetFramework' attribute currently references a version that is later than the installed version of the .NET Framework. Specify a valid target version of the .NET Framework, or install the required version of the .NET Framework.

The yellow screen of death threw up here:

compilation strict="false" explicit="true" targetFramework="4.5.2"

So I'm confused here because I don't NEED to target 4.5.2 for any special features in my code, but 4.5 seems "old".  Am I using cloud services wrong here?  Is there a problem for me to continue using 4.5?  OR should I go through some steps to have 4.5.2 available when I publish my code?

答: In case it helps anyone. I had the same issue and my fix was to update the OS from Windows Server 2012 to the latest OS (Currently Windows Server 2016) for the cloud service which fixed the problem.</p>

Title: Target .NET 4.5.2 in Azure Cloud Serice


问:
PDOException error in the cakephp 3
Cake php 3 error

```<code>Error Start:

Error: SQLSTATE[42000]: Syntax error or access violation: 1227 Access denied; you need (at least one of) the SUPER privilege(s) for this operation

If you are using SQL keywords as table column names, you can enable identifier quoting for your database connection in config/app.php.
Error End:
</code>```

There is PDOException error when I move the site local to server. I enable the identifier quoting in the app.php file. But nothing happened.

答: I found a solutions for it. Firstly we have need to set true the identifire on in app.php or give the the grant permission to the user. For more detail check this blog. http://www.peakhints.com/pdo-exception-error-cakephp-3/</p>

Title: PDOException error in the cakephp 3

Body:
Cake php 3 error

Error Start:

Error: SQLSTATE[42000]: Syntax error or access violation: 1227 Access denied; you need (at least one of) the SUPER privilege(s) for this operation

If you are using SQL keywords as table column names, you can enable identifier quoting for your database connection in config/app.php.
Error End:

There is PDOException error when I move the site local to server. I enable the identifier quoting in the app.php file. But nothing happened.


问:
Inserting column range in vba
I have a report in which I have to insert a new column between the last and second to last columns. However, when I try to insert the the column, I get a type mismatch error.

```<code>Dim columnInsert As Range
Dim rangeAverage As Range

Set columnInsert = Range("X80:X95")
Set rangeAverage = Range("AA1")

Columns(columnInsert:rangeAverage).Insert Shift:=xlToRight
</code>```

The problem pointed out by the editor is this line:

Columns(columnInsert:rangeAverage).Insert Shift:=xlToRight

Basically all I want to do is insert 15 long blank column between AA1 and Z, but I keep running into problems.

答:
The range you entered in your .Insert statement is incorrect

Columns(columnInsert:rangeAverage) translates to Columns(Range("X80:X95"):Range("AA1"))

This will shift only the cells in the range specified:

```<code>columnInsert.Insert Shift:=xlToRight    'shifts only the cells from X80:X95 to right
rangeAverage.Insert Shift:=xlToRight    'shifts cell AA1 to right
</code>```

This will shift the entire column AA to the right

```<code>Columns(rangeAverage).Insert Shift:=xlToRight
Columns(rangeAverage.Column).Insert Shift:=xlToRight
</code>```

Any of the statements bellow insert a blank column between Column Z and AA:

```<code>Columns("AA:AA").Insert Shift:=xlToRight
Columns("AA").Insert Shift:=xlToRight
Columns(27).Insert Shift:=xlToRight         'column index
</code>```

You can also insert multiple columns:

```<code>Columns("Z:AA").Insert Shift:=xlToLeft
</code>```

This inserts 2 empty columns to between column Y and Z

ContentLicense: CC BY-SA 4.0

Title: Inserting column range in vba

Body:
I have a report in which I have to insert a new column between the last and second to last columns. However, when I try to insert the the column, I get a type mismatch error.

Dim columnInsert As Range
Dim rangeAverage As Range

Set columnInsert = Range("X80:X95")
Set rangeAverage = Range("AA1")

Columns(columnInsert:rangeAverage).Insert Shift:=xlToRight

The problem pointed out by the editor is this line:

Columns(columnInsert:rangeAverage).Insert Shift:=xlToRight

Basically all I want to do is insert 15 long blank column between AA1 and Z, but I keep running into problems.

Body:
The range you entered in your .Insert statement is incorrect

Columns(columnInsert:rangeAverage) translates to Columns(Range("X80:X95"):Range("AA1"))

This will shift only the cells in the range specified:

columnInsert.Insert Shift:=xlToRight    'shifts only the cells from X80:X95 to right
rangeAverage.Insert Shift:=xlToRight    'shifts cell AA1 to right

This will shift the entire column AA to the right

Columns(rangeAverage).Insert Shift:=xlToRight
Columns(rangeAverage.Column).Insert Shift:=xlToRight

Any of the statements bellow insert a blank column between Column Z and AA:

Columns("AA:AA").Insert Shift:=xlToRight
Columns("AA").Insert Shift:=xlToRight
Columns(27).Insert Shift:=xlToRight         'column index

You can also insert multiple columns:

Columns("Z:AA").Insert Shift:=xlToLeft

This inserts 2 empty columns to between column Y and Z


问:
grails plugin for eclipse and netbeans 6.1
Has anyone been successful in getting the grails plugin for eclipse to work? How about grails plugin with netbeans?</p>

答:
Well, here's a quick update.  The Eclipse plugin works, and has refactoring support.  But, for some reason I can't get it to recognize the Grails plugins in the Eclipse project.

It's starting to come along though.

OwnerDisplayName: Mak

LastEditorDisplayName: Hank Gay

OwnerDisplayName: hendrixski


问:
Android EditText background text
Is there a way to set the background text of an EditText? for instance, I have a login screen with 2 EditText views, one for username and one for password. I want the text "Username" and "Password" be written inside the EditText, and once the user touches those the text disappears but once user deleted his own entry, text re-appears.

Is there a property for that or should I implement this on my own with events and stuff?

答: Use hint property, or setHint method.</p>

Title: Android EditText background text

Body: Use hint property, or setHint method.


问:
Best way to implement ArrayList in Android Studio
i have 30 items in ArrayList and its implement in Spinner, i placed it in java file like this

```<code>ArrayList<String> listProblemSolving = new ArrayList<>();
    listProblemSolving.add("List1");
    listProblemSolving.add("List2");
    listProblemSolving.add("List3");
    listProblemSolving.add("List4");
    listProblemSolving.add("List5");
    listProblemSolving.add("List6");
    listProblemSolving.add("List7");
    ...
    ArrayAdapter<String> adapterProblemSolving = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_dropdown_item, listProblemSolving);
</code>```

and i implement in spinner like this

```<code>sp.setAdapter(adapterProblemSolving);
</code>```

The question is, can i store the list item in strings file?
And is there any simply way if i want to give different action to item list, for example i try this one

```<code>    sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
             if (position == 1)
                // do something

             if (position == 2)
                // do something

             ...
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });
</code>```

Thank you and sorry i you found this as dupplicate question.

答:
You can create a string-array in your strings.xml file and use that in your Adapter.

Here is the example:

```<code><resources>
   <string-array name="numbers">
      <item>1</item>
      <item>2</item>
      <item>3</item>
      <item>4</item>
   </string-array>
</resources>
</code>```

In your activity, you can use it like the following code:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    String[] numbers = getResources().getStringArray(R.array.numbers);
    Spinner spinner = (Spinner) findViewById(R.id.spinner);
    ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
      android.R.layout.simple_spinner_dropdown_item, numbers);
    spinner.setAdapter(adapter);
}
</code>```

Body:
i have 30 items in ArrayList and its implement in Spinner, i placed it in java file like this

ArrayList<String> listProblemSolving = new ArrayList<>();
    listProblemSolving.add("List1");
    listProblemSolving.add("List2");
    listProblemSolving.add("List3");
    listProblemSolving.add("List4");
    listProblemSolving.add("List5");
    listProblemSolving.add("List6");
    listProblemSolving.add("List7");
    ...
    ArrayAdapter<String> adapterProblemSolving = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_dropdown_item, listProblemSolving);

and i implement in spinner like this

sp.setAdapter(adapterProblemSolving);

The question is, can i store the list item in strings file?
And is there any simply way if i want to give different action to item list, for example i try this one

    sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
             if (position == 1)
                // do something

             if (position == 2)
                // do something

             ...
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

Thank you and sorry i you found this as dupplicate question.

Body:
You can create a string-array in your strings.xml file and use that in your Adapter.

Here is the example:

<resources>
   <string-array name="numbers">
      <item>1</item>
      <item>2</item>
      <item>3</item>
      <item>4</item>
   </string-array>
</resources>

In your activity, you can use it like the following code:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    String[] numbers = getResources().getStringArray(R.array.numbers);
    Spinner spinner = (Spinner) findViewById(R.id.spinner);
    ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
      android.R.layout.simple_spinner_dropdown_item, numbers);
    spinner.setAdapter(adapter);
}


问:
Ajax & Session Variables? Worksafe Filter (selective image hiding)
I'm building a photography portfolio. Some of my images have nudity, so I want to hide those by default until the user clicks a "Toggle Worksafe Mode" button.

I can do it with a standard form post (and sessions), but that causes "confirm form resubmission" errors when the user backs or reloads. I'm trying to figure out an AJAX post instead to avoid that.

UPDATE: This is the working code. Please note that this does NOT work with the "slim" jQuery distro; that's one of the main reasons I was having trouble.

Image Index Page:

```<code><?php
    session_start();
    if (!isset($_SESSION['Worksafe_Mode'] {
        $_SESSION['Worksafe_Mode'] = 1;
    }
?>
<!-- other page content -->
<script src="scripts/jquery-3.2.1.min.js"></script>
<!-- other page content -->
<button type="button" id="Worksafe_Button" name="Worksafe_Button">
    Toggle Worksafe Mode
</button>
<script>
    $('#Worksafe_Button').click(function() {
        $.post("worksafe_mode_toggle.php")
            .done(function(data) {
                window.location.href = window.location.href;
        });
    });
</script>
<!-- other page content -->
<?php
$Connection = Connect();
$query = mysqli_query($Connection, 'SELECT uri, name, nsfw FROM images ORDER BY uri');

while($row = mysqli_fetch_assoc($image)) {
    if ($_SESSION['Worksafe_Mode'] == 1 && $row['nsfw'] == 1) {
        echo 'If you are over 18, toggle Worksafe Mode to view this image';
    }
    else {
        echo '<img alt="'.$row['title'].'" src="../'.$row['uri'].'/s.jpg" srcset="../'.$row['uri'].'/m.jpg 2x">';
    }
}
?>
</code>```

worksafe_mode_script:

```<code>session_start();
if (isset($_SESSION['Worksafe_Mode'])) {
    if ($_SESSION['Worksafe_Mode'] == 1) {
        $_SESSION['Worksafe_Mode'] = 0;
    }
    else {
        $_SESSION['Worksafe_Mode'] = 1;
    }
}
</code>```

答:
there are a couple of ways to do this and it related to how you hide or load you images.

1. simple method

if you don't care about the user's age, and just need to toggle, then you can do it with just a js variable, a cookie, and two version of link. with this, you don't hide images, but loads them. the filtering is done in the server, where you can use database query or a simple folder separation. for example:

```<code>var nsfw = read_cookie('nsfw', false); // not an actual js function, search for how to read cookie in js --- read cookie value, default to false

function loadImage(nsfw){
    if (nsfw){
        $.get('nsfw-image-list-url', function(resp){
            // the url should return a json with list of image urls
            var list = resp;  // jQuery automatically parse json with the right MIME
            list.forEach(function(val){
                // insert image to page
                $('#container').append('<img src="' + val + '/>');
            });
        });
    } else {
        $.get('sfw-image-list-url', function(resp){
            // the url should return a json with list of image urls
            var list = resp;  // jQuery automatically parse json with the right MIME
            list.forEach(function(val){
                // insert image to page
                $('#container').append('<img src="' + val + '/>');
            });
        });
    }
}
</code>```

and in you button click event:

```<code>nsfw = !nsfw;
// clear the image first if needed
$('#container').empty();
loadImage(nsfw);
</code>```

2. another simple method, but not as simple as the #1

you can also do it with only one link that returns a list of images with the type of it, such as nsfw or other things.

note: this method still uses cookie

for example the returned list is like this:

```<code>[
    {"url": "some-image-1.jpg", "nsfw": "true"},
    {"url": "some-image-2.jpg", "nsfw": "false"},
    {"url": "some-image-3.jpg", "nsfw": "true"},
    {"url": "some-image-4.jpg", "nsfw": "false"},
    {"url": "some-image-5.jpg", "nsfw": "false"},
    {"url": "some-image-6.jpg", "nsfw": "true"}
]
</code>```

then you just render it when the conditions are met.

```<code>function renderImage(nsfw){
    $.get('image-list-url', function(resp){
        list.forEach(function(val, key){
            if (nsfw || !val.nsfw){
                $('#container').append('<img src="' + val.url + '/>');
            }
        });
    });
}
</code>```

and many other methods that are too long to explain, such as using Angular, React, or Vue

still uses cookie for between reloads or backs, and does not regard user's age.

as for the session based approach, you only need that if you need to verify your users age

that is if you have a membership functionality with DOB (date of birth) data in your site, if so, you can use @KScandrett 's answer

Body:
I'm building a photography portfolio. Some of my images have nudity, so I want to hide those by default until the user clicks a "Toggle Worksafe Mode" button.

I can do it with a standard form post (and sessions), but that causes "confirm form resubmission" errors when the user backs or reloads. I'm trying to figure out an AJAX post instead to avoid that.

UPDATE: This is the working code. Please note that this does NOT work with the "slim" jQuery distro; that's one of the main reasons I was having trouble.

Image Index Page:

<?php
    session_start();
    if (!isset($_SESSION['Worksafe_Mode'] {
        $_SESSION['Worksafe_Mode'] = 1;
    }
?>

<button type="button" id="Worksafe_Button" name="Worksafe_Button">
    Toggle Worksafe Mode
</button>

<?php
$Connection = Connect();
$query = mysqli_query($Connection, 'SELECT uri, name, nsfw FROM images ORDER BY uri');

while($row = mysqli_fetch_assoc($image)) {
    if ($_SESSION['Worksafe_Mode'] == 1 && $row['nsfw'] == 1) {
        echo 'If you are over 18, toggle Worksafe Mode to view this image';
    }
    else {
        echo '';
    }
}
?>

worksafe_mode_script:

session_start();
if (isset($_SESSION['Worksafe_Mode'])) {
    if ($_SESSION['Worksafe_Mode'] == 1) {
        $_SESSION['Worksafe_Mode'] = 0;
    }
    else {
        $_SESSION['Worksafe_Mode'] = 1;
    }
}

Body:
there are a couple of ways to do this and it related to how you hide or load you images.

1. simple method

if you don't care about the user's age, and just need to toggle, then you can do it with just a js variable, a cookie, and two version of link. with this, you don't hide images, but loads them. the filtering is done in the server, where you can use database query or a simple folder separation. for example:

var nsfw = read_cookie('nsfw', false); // not an actual js function, search for how to read cookie in js --- read cookie value, default to false

function loadImage(nsfw){
    if (nsfw){
        $.get('nsfw-image-list-url', function(resp){
            // the url should return a json with list of image urls
            var list = resp;  // jQuery automatically parse json with the right MIME
            list.forEach(function(val){
                // insert image to page
                $('#container').append('<img src="' + val + '/>');
            });
        });
    } else {
        $.get('sfw-image-list-url', function(resp){
            // the url should return a json with list of image urls
            var list = resp;  // jQuery automatically parse json with the right MIME
            list.forEach(function(val){
                // insert image to page
                $('#container').append('<img src="' + val + '/>');
            });
        });
    }
}

and in you button click event:

nsfw = !nsfw;
// clear the image first if needed
$('#container').empty();
loadImage(nsfw);

2. another simple method, but not as simple as the #1

you can also do it with only one link that returns a list of images with the type of it, such as nsfw or other things.

note: this method still uses cookie

for example the returned list is like this:

[
    {"url": "some-image-1.jpg", "nsfw": "true"},
    {"url": "some-image-2.jpg", "nsfw": "false"},
    {"url": "some-image-3.jpg", "nsfw": "true"},
    {"url": "some-image-4.jpg", "nsfw": "false"},
    {"url": "some-image-5.jpg", "nsfw": "false"},
    {"url": "some-image-6.jpg", "nsfw": "true"}
]

then you just render it when the conditions are met.

function renderImage(nsfw){
    $.get('image-list-url', function(resp){
        list.forEach(function(val, key){
            if (nsfw || !val.nsfw){
                $('#container').append('<img src="' + val.url + '/>');
            }
        });
    });
}

and many other methods that are too long to explain, such as using Angular, React, or Vue

still uses cookie for between reloads or backs, and does not regard user's age.

as for the session based approach, you only need that if you need to verify your users age

that is if you have a membership functionality with DOB (date of birth) data in your site, if so, you can use @KScandrett 's answer


答:
You can try two things

Use following styling and remove unnecessary margin-right

```<code>button {
   margin-top : __px;
}
</code>```

Use position relative

```<code>button {
   position: relative;
   top:20%;
}
</code>```

This will solve your problem

OR you can also try first answer at Vertically centering button using css

Let me know if you require any further help

Title: How to center my buttons vertically?

Body:
You can try two things

Use following styling and remove unnecessary margin-right

button {
   margin-top : __px;
}

Use position relative

button {
   position: relative;
   top:20%;
}

This will solve your problem

OR you can also try first answer at Vertically centering button using css

Let me know if you require any further help


问:
LEFT OUTER JOIN in LINQ
How to perform left outer join in C# LINQ to objects without using join-on-equals-into clauses? Is there any way to do that with where clause?
Correct problem:
For inner join is easy and I have a solution like this

```<code>List<JoinPair> innerFinal = (from l in lefts from r in rights where l.Key == r.Key
                             select new JoinPair { LeftId = l.Id, RightId = r.Id})
</code>```

but for left outer join I need a solution. Mine is something like this but it's not working

```<code>List< JoinPair> leftFinal = (from l in lefts from r in rights
                             select new JoinPair {
                                            LeftId = l.Id,
                                            RightId = ((l.Key==r.Key) ? r.Id : 0
                                        })
</code>```

where JoinPair is a class:

```<code>public class JoinPair { long leftId; long rightId; }
</code>```

答:
This is the general form (as already provided in other answers)

```<code>var c =
    from a in alpha
    join b in beta on b.field1 equals a.field1 into b_temp
    from b_value in b_temp.DefaultIfEmpty()
    select new { Alpha = a, Beta = b_value };
</code>```

However here's an explanation that I hope will clarify what this actually means!

```<code>join b in beta on b.field1 equals a.field1 into b_temp
</code>```

essentially creates a separate result set b_temp that effectively includes null 'rows' for entries on the right hand side (entries in 'b').

Then the next line:

```<code>from b_value in b_temp.DefaultIfEmpty()
</code>```

..iterates over that result set, setting the default null value for the 'row' on the right hand side, and setting the result of the right hand side row join to the value of 'b_value' (i.e. the value that's on the right hand side,if there's a matching record, or 'null' if there isn't).

Now, if the right hand side is the result of a separate LINQ query, it will consist of anonymous types, which can only either be 'something' or 'null'. If it's an enumerable however (e.g. a List - where MyObjectB is a class with 2 fields), then it's possible to be specific about what default 'null' values are used for its properties:

```<code>var c =
    from a in alpha
    join b in beta on b.field1 equals a.field1 into b_temp
    from b_value in b_temp.DefaultIfEmpty( new MyObjectB { Field1 = String.Empty, Field2 = (DateTime?) null })
    select new { Alpha = a, Beta_field1 = b_value.Field1, Beta_field2 = b_value.Field2 };
</code>```

This ensures that 'b' itself isn't null (but its properties can be null, using the default null values that you've specified), and this allows you to check properties of b_value without getting a null reference exception for b_value. Note that for a nullable DateTime, a type of (DateTime?) i.e. 'nullable DateTime' must be specified as the 'Type' of the null in the specification for the 'DefaultIfEmpty' (this will also apply to types that are not 'natively' nullable e.g double, float).

You can perform multiple left outer joins by simply chaining the above syntax.

Title: LEFT OUTER JOIN in LINQ

Body:
How to perform left outer join in C# LINQ to objects without using join-on-equals-into clauses? Is there any way to do that with where clause?
Correct problem:
For inner join is easy and I have a solution like this

List<JoinPair> innerFinal = (from l in lefts from r in rights where l.Key == r.Key
                             select new JoinPair { LeftId = l.Id, RightId = r.Id})

but for left outer join I need a solution. Mine is something like this but it's not working

List< JoinPair> leftFinal = (from l in lefts from r in rights
                             select new JoinPair {
                                            LeftId = l.Id,
                                            RightId = ((l.Key==r.Key) ? r.Id : 0
                                        })

where JoinPair is a class:

public class JoinPair { long leftId; long rightId; }

Body:
This is the general form (as already provided in other answers)

var c =
    from a in alpha
    join b in beta on b.field1 equals a.field1 into b_temp
    from b_value in b_temp.DefaultIfEmpty()
    select new { Alpha = a, Beta = b_value };

However here's an explanation that I hope will clarify what this actually means!

join b in beta on b.field1 equals a.field1 into b_temp

essentially creates a separate result set b_temp that effectively includes null 'rows' for entries on the right hand side (entries in 'b').

Then the next line:

from b_value in b_temp.DefaultIfEmpty()

..iterates over that result set, setting the default null value for the 'row' on the right hand side, and setting the result of the right hand side row join to the value of 'b_value' (i.e. the value that's on the right hand side,if there's a matching record, or 'null' if there isn't).

Now, if the right hand side is the result of a separate LINQ query, it will consist of anonymous types, which can only either be 'something' or 'null'. If it's an enumerable however (e.g. a List - where MyObjectB is a class with 2 fields), then it's possible to be specific about what default 'null' values are used for its properties:

var c =
    from a in alpha
    join b in beta on b.field1 equals a.field1 into b_temp
    from b_value in b_temp.DefaultIfEmpty( new MyObjectB { Field1 = String.Empty, Field2 = (DateTime?) null })
    select new { Alpha = a, Beta_field1 = b_value.Field1, Beta_field2 = b_value.Field2 };

This ensures that 'b' itself isn't null (but its properties can be null, using the default null values that you've specified), and this allows you to check properties of b_value without getting a null reference exception for b_value. Note that for a nullable DateTime, a type of (DateTime?) i.e. 'nullable DateTime' must be specified as the 'Type' of the null in the specification for the 'DefaultIfEmpty' (this will also apply to types that are not 'natively' nullable e.g double, float).

You can perform multiple left outer joins by simply chaining the above syntax.


问:
What is the cleanest way to ssh and run multiple commands in Bash?
I already have an ssh agent set up, and I can run commands on an external server in Bash script doing stuff like:

```<code>ssh blah_server "ls; pwd;"
</code>```

Now, what I'd really like to do is run a lot of long commands on an external server. Enclosing all of these in between quotation marks would be quite ugly, and I'd really rather avoid ssh'ing multiple times just to avoid this.

So, is there a way I can do this in one go enclosed in parentheses or something? I'm looking for something along the lines of:

```<code>ssh blah_server (
   ls some_folder;
   ./someaction.sh;
   pwd;
)
</code>```

Basically, I'll be happy with any solution as long as it's clean.

Edit

To clarify, I'm talking about this being part of a larger bash script. Other people might need to deal with the script down the line, so I'd like to keep it clean. I don't want to have a bash script with one line that looks like:

```<code>ssh blah_server "ls some_folder; ./someaction.sh 'some params'; pwd; ./some_other_action 'other params';"
</code>```

because it is extremely ugly and difficult to read.

答:
The posted answers using multiline strings and multiple bash scripts did not work for me.

Long multiline strings are hard to maintain.

Separate bash scripts do not maintain local variables.

Here is a functional way to ssh and run multiple commands while keeping local context.

```<code>LOCAL_VARIABLE=test

run_remote() {
    echo "$LOCAL_VARIABLE"
    ls some_folder;
    ./someaction.sh 'some params'
    ./some_other_action 'other params'
}

ssh otherhost "$(set); run_remote"
</code>```

Body:
I already have an ssh agent set up, and I can run commands on an external server in Bash script doing stuff like:

ssh blah_server "ls; pwd;"

Now, what I'd really like to do is run a lot of long commands on an external server. Enclosing all of these in between quotation marks would be quite ugly, and I'd really rather avoid ssh'ing multiple times just to avoid this.

So, is there a way I can do this in one go enclosed in parentheses or something? I'm looking for something along the lines of:

ssh blah_server (
   ls some_folder;
   ./someaction.sh;
   pwd;
)

Basically, I'll be happy with any solution as long as it's clean.

Edit

To clarify, I'm talking about this being part of a larger bash script. Other people might need to deal with the script down the line, so I'd like to keep it clean. I don't want to have a bash script with one line that looks like:

ssh blah_server "ls some_folder; ./someaction.sh 'some params'; pwd; ./some_other_action 'other params';"

because it is extremely ugly and difficult to read.

Body:
The posted answers using multiline strings and multiple bash scripts did not work for me.

Long multiline strings are hard to maintain.

Separate bash scripts do not maintain local variables.

Here is a functional way to ssh and run multiple commands while keeping local context.

LOCAL_VARIABLE=test

run_remote() {
    echo "$LOCAL_VARIABLE"
    ls some_folder;
    ./someaction.sh 'some params'
    ./some_other_action 'other params'
}

ssh otherhost "$(set); run_remote"


问:
What does it mean when Mockito's "when" has multiple 'thenReturn' calls?
Here is a code snippet extracted from a mockito unit test I'm working on:

```<code>        Mockito.when(clientResource.getJobStatus(JOB_ID))
            .thenReturn(createJobStatus(JOB_ID, com.test.models.JobStatus.State.IDLE))
            .thenReturn(createJobStatus(JOB_ID, com.test.models.JobStatus.State.STARTING))
            .thenReturn(createJobStatus(JOB_ID, com.test.models.JobStatus.State.RUNNING));
</code>```

What does it mean when a Mockito.when(...) has multiple thenReturn(...)'s chained after it?

答:
It means that it will return those values or answers in the order they were declared.

The first call to getJobStatus() will return createJobStatus(JOB_ID, com.test.models.JobStatus.State.IDLE)

The second call will return createJobStatus(JOB_ID, com.test.models.JobStatus.State.STARTING)

And so on...

You can see that in this method the answers are being polled from a queue.

Body:
Here is a code snippet extracted from a mockito unit test I'm working on:

        Mockito.when(clientResource.getJobStatus(JOB_ID))
            .thenReturn(createJobStatus(JOB_ID, com.test.models.JobStatus.State.IDLE))
            .thenReturn(createJobStatus(JOB_ID, com.test.models.JobStatus.State.STARTING))
            .thenReturn(createJobStatus(JOB_ID, com.test.models.JobStatus.State.RUNNING));

What does it mean when a Mockito.when(...) has multiple thenReturn(...)'s chained after it?