问:
AJAX multiple inputs not passing or sending data to PHP
I have been battling with this AJAX to pass data to PHP for SQL Insertion, it seems the data does not get passed to the PHP. I have three HTML input types, text, radio button and select. The radio is used for gender, select for the country of residence, and text for the country's dialcode concatenated with the user's mobilenumber. Javascript is used to automatically retrieve the dialcode once the user selects his/her country in the dropdown. These inputs are not being passed for SQL insertion.

I am still very much an amateur and a student. I included the code here: https://jsfiddle.net/406tb35r/1/

Code is as follows:

```<code><script type="text/javascript">
 (function($){
     $(document).ready( function(){

        $('#country').change( function(e){
             //on change event
            $('input[name="dialcode"]').val($(this).find('option:selected').data('co'));
        });

    }); //make sure all html is loaded before running
 })(jQuery);  //assign jQuery to the $

function validate(evt) {
  var theEvent = evt || window.event;
  var key = theEvent.keyCode || theEvent.which;
  key = String.fromCharCode( key );
  var regex = /[0-9]|\./;
  if( !regex.test(key) ) {
    theEvent.returnValue = false;
    if(theEvent.preventDefault) theEvent.preventDefault();
  }
}

</script>
<form action="" method="post" class="start_form" id="userDetails">

        <fieldset>
          <legend><b>Are you a</b></legend>
          <input type="radio" name="gender" class="gender" value="male">Male<br>
          <input type="radio" name="gender" class="gender" value="female">Female<br>
      </fieldset>
  <select id="country" name="country" class="country">
  <option data-co="" value="">Which country are from?</option>
  <option data-co="+27" value="ZA">South Africa</option>
  <option data-co="+376" value="AD">Andorra</option>
  <option data-co="+971" value="AE">United Arab Emirates</option>
  <option data-co="+93" value="AF">Afghanistan</option>
  </select>
  <?php
$countryArray = array(
  'AD'=>array('name'=>'ANDORRA','code'=>'376'),
  'AE'=>array('name'=>'UNITED ARAB EMIRATES','code'=>'971'),
  'AF'=>array('name'=>'AFGHANISTAN','code'=>'93'),
  'AG'=>array('name'=>'ANTIGUA AND BARBUDA','code'=>'1268'),
  );

function countrySelector($defaultCountry = "", $id = "", $name = "", $classes = ""){
    global $countryArray;

    $output = "<select id='".$id."' name='".$name."' class='".$classes."'>";

  foreach($countryArray as $code => $country){
    $countryName = ucwords(strtolower($country["name"]));
    $output .= "<option data-co='".$country["code"]."' value='".$code."' ".(($code==strtoupper($defaultCountry))?"selected":"").">".$code." - ".$countryName." (+".$country["code"].")</option>";
}

  $output .= "</select>";

  return $output;
}
?>
<input align="center" type="text" name="dialcode" class="dialcode" value="" autocomplete="off" placeholder="" mssg="" maxlength="6" readonly>
        <input type="text" name="mobile" class="mobile" value="" autocomplete="off" placeholder="What is your Mobile Number?" mssg="" maxlength="12">

        <input style="width:100%;" type="submit" name="s_submit" value="Next" id="userSubmit"><br/>
        <a href="">Skip</a>
      </form>

<script type="text/javascript">
jQuery(document).ready(function(){

  $('#userSubmit').click(function(e){
    e.preventDefault();
      var gender = $('.gender').val();
        var country = $('.country');
          var dialcode = $('.dialcode');
          var mobile = $('.mobile').val();
    $.ajax({
      type: 'POST',
      url: DIR+'/insert.php',
      data:
            gender: gender,
            country: country,
            dialcode: dialcode,
            mobile: mobile
      success:function(){
        $('.content').load(DIR+'/welcome.php');}
      }

    });

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

This is the PHP for passing above data to SQL:

```<code><?php
session_start();
//Connect to DB
  include_once 'connect.php';
   $session = $_SESSION['id'];
   $universal = new universal;
   $susername = $universal->GETsDetails($session, "username");

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

   $gender = preg_replace("#[<> ]#i", "", $_POST['gender']);
   $country = preg_replace("#[<> ]#i", "", $_POST['country']);
   $mobilenumber = preg_replace("#[^0-9]#i", "", $_POST['dialcode'] . $_POST['mobile']);

      if((!$username) == ""){
        return "Your details are not logged in or do not have an account with iamstein!";
      } else {
        $users = $this->db->prepare("UPDATE users SET gender = :gender, country = :country, mobilenumber = :mobilenumber, WHERE id = :id");
        $users->execute(array(":gender" => $gender, ":country" => $country, "mobilenumber" => $mobilenumber, ":id" => $session));

      }
 }?>
</code>```

答:
You need to properly warp the data key

```<code>data: {
            gender: gender,
            country: country,
            dialcode: dialcode,
            mobile: mobile},
</code>```

You weren't passing the right format for the data key.. Alternatively you can serialize the form, just to avoid this errors and mistakes.

```<code>data:$('#userDetails').serialize(),
</code>```

Body:
I have been battling with this AJAX to pass data to PHP for SQL Insertion, it seems the data does not get passed to the PHP. I have three HTML input types, text, radio button and select. The radio is used for gender, select for the country of residence, and text for the country's dialcode concatenated with the user's mobilenumber. Javascript is used to automatically retrieve the dialcode once the user selects his/her country in the dropdown. These inputs are not being passed for SQL insertion.

I am still very much an amateur and a student. I included the code here: https://jsfiddle.net/406tb35r/1/

Code is as follows:

<form action="" method="post" class="start_form" id="userDetails">

        <fieldset>
          <legend>Are you a</legend>
          <input type="radio" name="gender" class="gender" value="male">Male

          <input type="radio" name="gender" class="gender" value="female">Female

      </fieldset>
  <select id="country" name="country" class="country">
  <option data-co="" value="">Which country are from?</option>
  <option data-co="+27" value="ZA">South Africa</option>
  <option data-co="+376" value="AD">Andorra</option>
  <option data-co="+971" value="AE">United Arab Emirates</option>
  <option data-co="+93" value="AF">Afghanistan</option>
  </select>
  <?php
$countryArray = array(
  'AD'=>array('name'=>'ANDORRA','code'=>'376'),
  'AE'=>array('name'=>'UNITED ARAB EMIRATES','code'=>'971'),
  'AF'=>array('name'=>'AFGHANISTAN','code'=>'93'),
  'AG'=>array('name'=>'ANTIGUA AND BARBUDA','code'=>'1268'),
  );

function countrySelector($defaultCountry = "", $id = "", $name = "", $classes = ""){
    global $countryArray;

    $output = "<select id='".$id."' name='".$name."' class='".$classes."'>";

  foreach($countryArray as $code => $country){
    $countryName = ucwords(strtolower($country["name"]));
    $output .= "<option data-co='".$country["code"]."' value='".$code."' ".(($code==strtoupper($defaultCountry))?"selected":"").">".$code." - ".$countryName." (+".$country["code"].")</option>";
}

  $output .= "</select>";

  return $output;
}
?>
<input align="center" type="text" name="dialcode" class="dialcode" value="" autocomplete="off" placeholder="" mssg="" maxlength="6" readonly>
        <input type="text" name="mobile" class="mobile" value="" autocomplete="off" placeholder="What is your Mobile Number?" mssg="" maxlength="12">

        <input style="width:100%;" type="submit" name="s_submit" value="Next" id="userSubmit">

        Skip
      </form>

This is the PHP for passing above data to SQL:

<?php
session_start();
//Connect to DB
  include_once 'connect.php';
   $session = $_SESSION['id'];
   $universal = new universal;
   $susername = $universal->GETsDetails($session, "username");

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

   $gender = preg_replace("#[<> ]#i", "", $_POST['gender']);
   $country = preg_replace("#[<> ]#i", "", $_POST['country']);
   $mobilenumber = preg_replace("#[^0-9]#i", "", $_POST['dialcode'] . $_POST['mobile']);

      if((!$username) == ""){
        return "Your details are not logged in or do not have an account with iamstein!";
      } else {
        $users = $this->db->prepare("UPDATE users SET gender = :gender, country = :country, mobilenumber = :mobilenumber, WHERE id = :id");
        $users->execute(array(":gender" => $gender, ":country" => $country, "mobilenumber" => $mobilenumber, ":id" => $session));

      }
 }?>

Body:
You need to properly warp the data key

data: {
            gender: gender,
            country: country,
            dialcode: dialcode,
            mobile: mobile},

You weren't passing the right format for the data key.. Alternatively you can serialize the form, just to avoid this errors and mistakes.

data:$('#userDetails').serialize(),


来源: stackexchange

问:
Azure Functions Continuous Deployment Failing on Syncing Function Triggers Step
I have my continuous deployment configured to use Bitbucket and release on a push to master. This has been working perfectly up until today. Now even builds that have previously been successful are failing on the Syncing Function Triggers step...

The final step Deployment Successful. doesn't show up. I downloaded the deployment logs and noticed that there is an error on one of the calls to Kudu.

2017-11-14T19:06:37.6185924Z,Syncing 3 function triggers with payload size 485 bytes failed with System.Net.Http.HttpRequestException: Response status code does not indicate success: 500 (Internal Server Error).\r\n   at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()\r\n   at Kudu.Core.Helpers.PostDeploymentHelper.d__33.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at Kudu.Core.Helpers.PostDeploymentHelper.d__25.MoveNext(),808a1bcf-e2c6-4e71-a5ba-8ba6afbb5c10,0

I can only assume that Kudu updated their API and now something is breaking in azure the deployment configuration. Is there a way to see or edit the Kudu .deploy file to gain more insight?

答:
This was caused by an issue with the Azure Functions service. The issue has now been resolved, and everything should be working again.

Apologies for the downtime of that sync API.

ContentLicense: CC BY-SA 3.0


问:
Laravel DELETE method with request body
I've been trying to add a FormRequest with rules and message to my delete method, but the request is coming back empty and the rules are failing every time.

Is it possible to get the request data in a delete method?

Here's my request class:

```<code>use App\Http\Requests\Request;

class DeleteRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'staff_id' => ['required', 'exists:users,uid'],
            'reason' => ['required', 'string'],
        ];
    }

    /**
     * Get custom messages for validator errors.
     *
     * @return array
     */
    public function messages()
    {
        return [
            'staff_id.required' => staticText('errors.staff_id.required'),
            'staff_id.exists' => staticText('errors.staff_id.exists'),
            'reason.required' => staticText('errors.reason.required'),
            'reason.string' => staticText('errors.reason.string'),
        ];
    }
}
</code>```

And the controller:

```<code>/**
 * Handle the 'code' delete request.
 *
 * @param integer $id            The id of the code to fetch.
 * @param DeleteRequest $request The request to handle the data.
 * @return response
 */
public function deleteCode($id, DeleteRequest $request)
{
    dd($request->all());
}
</code>```

答:
Even though the HTTP/1.1 spec does not explicitly state that DELETE requests should not have an entity body, some implementations completely ignore the body which contains your data, e.g. some versions of Jetty and Tomcat. On the other hand, some clients do not support sending it as well.

Think of it as a GET request. Have you seen any with form data? DELETE requests are almost the same.

You can read a LOT on the subject. Start here:

RESTful Alternatives to DELETE Request Body

It seems like that you want to alter the state of the resource rather than destroying it. Soft-deleting is not deleting and thus requires either a PUT or a PATCH method which both support entity bodies. If soft-deleting is not the case, you're doing two operations through one call.

Title: Laravel DELETE method with request body

Body:
I've been trying to add a FormRequest with rules and message to my delete method, but the request is coming back empty and the rules are failing every time.

Is it possible to get the request data in a delete method?

Here's my request class:

use App\Http\Requests\Request;

class DeleteRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'staff_id' => ['required', 'exists:users,uid'],
            'reason' => ['required', 'string'],
        ];
    }

    /**
     * Get custom messages for validator errors.
     *
     * @return array
     */
    public function messages()
    {
        return [
            'staff_id.required' => staticText('errors.staff_id.required'),
            'staff_id.exists' => staticText('errors.staff_id.exists'),
            'reason.required' => staticText('errors.reason.required'),
            'reason.string' => staticText('errors.reason.string'),
        ];
    }
}

And the controller:

/**
 * Handle the 'code' delete request.
 *
 * @param integer $id            The id of the code to fetch.
 * @param DeleteRequest $request The request to handle the data.
 * @return response
 */
public function deleteCode($id, DeleteRequest $request)
{
    dd($request->all());
}

ContentLicense: CC BY-SA 4.0


问:
Added some word in the middle of existing text using jquery?
Here my code for example.

```<code><div class="modal-body">
  <p>Do you really want to delete  files ?</p>
</div>
</code>```

I would like to add a word Insert_your_file_here between word delete and word files and a word right now at the end of the text. I can handle the right now sentences, but not with Document1 word.

What i expect the result is just like this.

```<code><div class="modal-body">
      <p>Do you really want to delete Document1 file right now ?</p>
</div>
</code>```

WHat i have tried is use append but i dont know how to specific location of the word that would be added

```<code>$('.modal-body p').append('Document1');
$('.modal-body p').append('right now');
</code>```

答:
Instead of appending, you can set the entire text in jQuery:

```<code>var documentName = "Document1";
$('.modal-body p').text("Do you really want to delete " + documentName + " right now?");
</code>```

Then you can change the documentName variable to whatever you want.

Body:
Here my code for example.

Do you really want to delete  files ?

I would like to add a word Insert_your_file_here between word delete and word files and a word right now at the end of the text. I can handle the right now sentences, but not with Document1 word.

What i expect the result is just like this.

Do you really want to delete Document1 file right now ?

WHat i have tried is use append but i dont know how to specific location of the word that would be added

$('.modal-body p').append('Document1');
$('.modal-body p').append('right now');

Body:
Instead of appending, you can set the entire text in jQuery:

var documentName = "Document1";
$('.modal-body p').text("Do you really want to delete " + documentName + " right now?");

Then you can change the documentName variable to whatever you want.


问:
Trying to figure out how to show a larger image in pop up box when hovering over a thumbnail in javascript
I have been able to figure everything out so far except for this last part where I need to show a larger image when hovering over a thumbnail. I have scoured the internet and stack overflow for hours now and surprisingly have not been able to find such a scenario.
This is what I have so far for the javascript:

```<code>alert("Your script is working.");   //test

var findImages = document.querySelectorAll(".example");
alert(findImages.length);

function mouseOverFunction(){

}

function mouseOutFunction(){

}

for(i=0; i<findImages.length; i++){
  findImages[i].addEventListener("mouseover", mouseOverFunction);
  findImages[i].addEventListener("mouseout", mouseOutFunction);
  alert(findImages[i].src);   //test
}
alert("Your script finished");    //test
</code>```

The findImages[] has all 5 images in it that I need to enlarge upon hovering over the thumbnail with my mouse. Any help would be greatly appreciated.
Thanks

答:
This is not a good way to achieve this,

but just to fixed your code, you need to pass the argument.

findImages[i].addEventListener("mouseover", function(){
        mouseOverFunction(i)});

also :

```<code> findImages[i].src = "/your/img/url";
 findImages[i].style.display = "block";
</code>```

Body:
I have been able to figure everything out so far except for this last part where I need to show a larger image when hovering over a thumbnail. I have scoured the internet and stack overflow for hours now and surprisingly have not been able to find such a scenario.
This is what I have so far for the javascript:

alert("Your script is working.");   //test

var findImages = document.querySelectorAll(".example");
alert(findImages.length);

function mouseOverFunction(){

}

function mouseOutFunction(){

}

for(i=0; i<findImages.length; i++){
  findImages[i].addEventListener("mouseover", mouseOverFunction);
  findImages[i].addEventListener("mouseout", mouseOutFunction);
  alert(findImages[i].src);   //test
}
alert("Your script finished");    //test

The findImages[] has all 5 images in it that I need to enlarge upon hovering over the thumbnail with my mouse. Any help would be greatly appreciated.
Thanks

Body:
This is not a good way to achieve this,

but just to fixed your code, you need to pass the argument.

findImages[i].addEventListener("mouseover", function(){
        mouseOverFunction(i)});

also :

 findImages[i].src = "/your/img/url";
 findImages[i].style.display = "block";


问:
Printing dynamic lines in Python with "for line in file"
I'm writing a program where a user can enter a beginning year and an end year, and the program will print out the winners of a book award for all the years in between. Here is what I have so far:

```<code>ui = input("Enter a beginning year('q' or 'Q' to quit): ")
ui2 = input("Enter an ending year: ")
file = open("bookListFile.txt", "r")

def getBook(user, user2):
    yearsBetween = int(ui2) - int(ui)
    yearCount = 0
    for line in file:
        while user in line and user.isdigit() and yearCount < yearsBetween:
            print(line)
            yearCount += 1

    getBook(ui, ui2)
</code>```

The problem here is when I print the line, it prints the same line over and over. For example, when I enter 1985 as the beginning year and 2000 as the end year, it will print the same line 15 times instead of the years in between.

Can I get some help here? If possible, could you explain how you did it too?

答:
It looks like the while loop is getting caught up and from what I see I think this program would be better served by the range function. (for posterity Python’s range() Function Explained)

```<code>def get_book(user, user2):
    year_range = range(user, user2)
    #Instead of manually counting up through the numbers a list is automatically
    #created through range of the numbers. Starting at user, ending at user2 and auto
    # stepping up by 1.
    for line in file:
        for i in year_range:
            #Instead of using a while loop and a manual count the for loop auto
            #counts through the range
            if str(i) in line:
                print(line)
</code>```

If you have any other questions or comments please let me know.

Body:
I'm writing a program where a user can enter a beginning year and an end year, and the program will print out the winners of a book award for all the years in between. Here is what I have so far:

ui = input("Enter a beginning year('q' or 'Q' to quit): ")
ui2 = input("Enter an ending year: ")
file = open("bookListFile.txt", "r")

def getBook(user, user2):
    yearsBetween = int(ui2) - int(ui)
    yearCount = 0
    for line in file:
        while user in line and user.isdigit() and yearCount < yearsBetween:
            print(line)
            yearCount += 1

    getBook(ui, ui2)

The problem here is when I print the line, it prints the same line over and over. For example, when I enter 1985 as the beginning year and 2000 as the end year, it will print the same line 15 times instead of the years in between.

Can I get some help here? If possible, could you explain how you did it too?

Body:
It looks like the while loop is getting caught up and from what I see I think this program would be better served by the range function. (for posterity Python’s range() Function Explained)

def get_book(user, user2):
    year_range = range(user, user2)
    #Instead of manually counting up through the numbers a list is automatically
    #created through range of the numbers. Starting at user, ending at user2 and auto
    # stepping up by 1.
    for line in file:
        for i in year_range:
            #Instead of using a while loop and a manual count the for loop auto
            #counts through the range
            if str(i) in line:
                print(line)

If you have any other questions or comments please let me know.


问:
divs with vertical line
I need help about this image. How can I  set it up in css and in html thank you in advance if anyone will give time to help me.

答:
Obisidians answer is good....I'm going to tweak it slightly be removing an HTML element and using :before, keeping the background image, but treating the line a little differently

#container {
  width: 300px;
  height: 200px;
  background: url(http:/fillmurray.com/300/200);
  position:relative;
}

#container::before {
  position: absolute;
  left: calc(50% - 1px);
  width:2px;
  height: 100%;
  background-color:cyan;
  content: '';
}

#container > div
{
  background-color: rgba(255,255,255,0.5);
  padding: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <div>Some Content</div>
</div></code>```

This way you have more freedom of the child contents

Title: divs with vertical line

Body:
Obisidians answer is good....I'm going to tweak it slightly be removing an HTML element and using :before, keeping the background image, but treating the line a little differently

#container {
  width: 300px;
  height: 200px;
  background: url(http:/fillmurray.com/300/200);
  position:relative;
}

#container::before {
  position: absolute;
  left: calc(50% - 1px);
  width:2px;
  height: 100%;
  background-color:cyan;
  content: '';
}

#container > div
{
  background-color: rgba(255,255,255,0.5);
  padding: 5px;
}

<div id="container">
  <div>Some Content</div>
</div>

This way you have more freedom of the child contents


问:
SQL Query & Grouping Row Data From Different Tables
I have the following query that works fine however I am trying to get a few of the rows consolidated if for example the first column (Name) is an exact match. I've tried delcaring a variable, using for XML, etc. but can't seem to get it working.

```<code>SELECT        MasterName.Last+ ', ' + MasterName.First+ ', '
              +MasterName.Middle AS NameCombined, MasterName.Type,
              JailIntake.Booking_Status, JailIntake.Intake_Date,
              JailIntake.Agency, MasterDescriptors.DOB, JailCharge.Suffix_1,
              JailCharge.Charge_Literal, JailIntake.Incident_Nr,
              JailCharge.Bond_Amount, Pictures.UnitID, ct500.code,
              Pictures.IType

FROM          RMS.dbo.MasterName AS MasterName INNER JOIN
              RMS.dbo.MasterDescriptors AS MasterDescriptors ON
              MasterName.Suffix_1 = MasterDescriptors.Suffix_1 AND
              MasterName.Incident_Nr = MasterDescriptors.Incident_Nr AND
              MasterName.Agency = MasterDescriptors.Agency AND
              MasterName.Module_ID = MasterDescriptors.Module_ID INNER JOIN
              RMS.dbo.JailIntake AS JailIntake ON
              MasterDescriptors.Module_ID = JailIntake.Module_ID AND
              MasterDescriptors.Incident_Nr = JailIntake.Incident_Nr AND
              MasterDescriptors.Agency = JailIntake.Agency AND
              MasterDescriptors.Suffix_1 = JailIntake.Suffix_1 INNER JOIN
              RMS.dbo.JailCharge AS JailCharge ON JailIntake.Incident_Nr =
              JailCharge.Incident_Nr AND JailIntake.Agency =
              JailCharge.Agency AND JailIntake.Module_ID =
              JailCharge.Module_ID INNER JOIN
              IMAGES.dbo.Pictures ON JailIntake.Incident_Nr =
              JailCharge.Incident_Nr AND 'ABBV^' + JailIntake.Incident_Nr +
              '^^^^INT^IN^MNI^' = Pictures.UnitID INNER JOIN
              PIMSTABL.dbo.ct500 AS ct500 ON ct500.code =
              JailIntake.Inmate_Type
WHERE         (MasterName.Type = 'IN') AND (JailIntake.Booking_Status = 'IJ'
              OR JailIntake.Booking_Status = 'OF') AND
              (JailIntake.Agency = 'ABBV') AND (Pictures.IType = '1106')

ORDER BY      MasterName.Last
</code>```

I won't include all the columns it generates by the SELECT portion but the ones I'm concerned with show up like this:

```<code>NAME OF PERSON       CHARGENUMBER     CHARGEDESCRIPTION

Doe, Jane                001               TEXT
Doe, Jane                002               TEXT
Doe, Jane                003               TEXT
Johnson, John            001               TEXT
Johnson, John            002               TEXT
Thompson, Tommy          001               TEXT
Williams, Wendy          001               TEXT
Williams, Wendy          002               TEXT
</code>```

My ultimate goal is to have it look like:

```<code>NAME OF PERSON       CHARGENUMBER          CHARGEDESCRIPTION

Doe, Jane            001, 002, 003         TEXT, TEXT, TEXT
Johnson, John          001, 002                TEXT, TEXT
Thompson, Tommy          001                      TEXT
Williams, Wendy        001, 002                TEXT, TEXT
</code>```

答:
Try the following:

```<code>CREATE TABLE #Temp([NAME OF PERSON] VARCHAR(100),CHARGENUMBER VARCHAR(100), CHARGEDESCRIPTION VARCHAR(100))

INSERT INTO #Temp VALUES('Doe, Jane','001','TEXT')
INSERT INTO #Temp VALUES('Doe, Jane','002','TEXT')
INSERT INTO #Temp VALUES('Doe, Jane','003','TEXT')
INSERT INTO #Temp VALUES('Johnson, John','001','TEXT')
INSERT INTO #Temp VALUES('Johnson, John','002','TEXT')
INSERT INTO #Temp VALUES('Thompson, Tommy','001','TEXT')
INSERT INTO #Temp VALUES('Williams, Wendy','001','TEXT')
INSERT INTO #Temp VALUES('Williams, Wendy','002','TEXT')
</code>```

Then change the values into comma separated.

```<code>SELECT
    [NAME OF PERSON],
    STUFF((
        SELECT ', ' + t.CHARGENUMBER
        FROM #Temp t
        WHERE t.[NAME OF PERSON] = T1.[NAME OF PERSON]
        ORDER BY t.CHARGENUMBER
        FOR XMl PATH('')
    ),1,1,'') AS CHARGENUMBER
    ,STUFF((
        SELECT ', ' + t.CHARGEDESCRIPTION
        FROM #Temp t
        WHERE t.[NAME OF PERSON] = T1.[NAME OF PERSON]
        ORDER BY t.CHARGEDESCRIPTION
        FOR XMl PATH('')
    ),1,1,'') AS CHARGEDESCRIPTION
FROM #Temp T1
GROUP BY [NAME OF PERSON];
</code>```

Hope this helps you.

Body:
I have the following query that works fine however I am trying to get a few of the rows consolidated if for example the first column (Name) is an exact match. I've tried delcaring a variable, using for XML, etc. but can't seem to get it working.

SELECT        MasterName.Last+ ', ' + MasterName.First+ ', '
              +MasterName.Middle AS NameCombined, MasterName.Type,
              JailIntake.Booking_Status, JailIntake.Intake_Date,
              JailIntake.Agency, MasterDescriptors.DOB, JailCharge.Suffix_1,
              JailCharge.Charge_Literal, JailIntake.Incident_Nr,
              JailCharge.Bond_Amount, Pictures.UnitID, ct500.code,
              Pictures.IType

FROM          RMS.dbo.MasterName AS MasterName INNER JOIN
              RMS.dbo.MasterDescriptors AS MasterDescriptors ON
              MasterName.Suffix_1 = MasterDescriptors.Suffix_1 AND
              MasterName.Incident_Nr = MasterDescriptors.Incident_Nr AND
              MasterName.Agency = MasterDescriptors.Agency AND
              MasterName.Module_ID = MasterDescriptors.Module_ID INNER JOIN
              RMS.dbo.JailIntake AS JailIntake ON
              MasterDescriptors.Module_ID = JailIntake.Module_ID AND
              MasterDescriptors.Incident_Nr = JailIntake.Incident_Nr AND
              MasterDescriptors.Agency = JailIntake.Agency AND
              MasterDescriptors.Suffix_1 = JailIntake.Suffix_1 INNER JOIN
              RMS.dbo.JailCharge AS JailCharge ON JailIntake.Incident_Nr =
              JailCharge.Incident_Nr AND JailIntake.Agency =
              JailCharge.Agency AND JailIntake.Module_ID =
              JailCharge.Module_ID INNER JOIN
              IMAGES.dbo.Pictures ON JailIntake.Incident_Nr =
              JailCharge.Incident_Nr AND 'ABBV^' + JailIntake.Incident_Nr +
              '^^^^INT^IN^MNI^' = Pictures.UnitID INNER JOIN
              PIMSTABL.dbo.ct500 AS ct500 ON ct500.code =
              JailIntake.Inmate_Type
WHERE         (MasterName.Type = 'IN') AND (JailIntake.Booking_Status = 'IJ'
              OR JailIntake.Booking_Status = 'OF') AND
              (JailIntake.Agency = 'ABBV') AND (Pictures.IType = '1106')

ORDER BY      MasterName.Last

I won't include all the columns it generates by the SELECT portion but the ones I'm concerned with show up like this:

NAME OF PERSON       CHARGENUMBER     CHARGEDESCRIPTION

Doe, Jane                001               TEXT
Doe, Jane                002               TEXT
Doe, Jane                003               TEXT
Johnson, John            001               TEXT
Johnson, John            002               TEXT
Thompson, Tommy          001               TEXT
Williams, Wendy          001               TEXT
Williams, Wendy          002               TEXT

My ultimate goal is to have it look like:

NAME OF PERSON       CHARGENUMBER          CHARGEDESCRIPTION

Doe, Jane            001, 002, 003         TEXT, TEXT, TEXT
Johnson, John          001, 002                TEXT, TEXT
Thompson, Tommy          001                      TEXT
Williams, Wendy        001, 002                TEXT, TEXT

Body:
Try the following:

CREATE TABLE #Temp([NAME OF PERSON] VARCHAR(100),CHARGENUMBER VARCHAR(100), CHARGEDESCRIPTION VARCHAR(100))

INSERT INTO #Temp VALUES('Doe, Jane','001','TEXT')
INSERT INTO #Temp VALUES('Doe, Jane','002','TEXT')
INSERT INTO #Temp VALUES('Doe, Jane','003','TEXT')
INSERT INTO #Temp VALUES('Johnson, John','001','TEXT')
INSERT INTO #Temp VALUES('Johnson, John','002','TEXT')
INSERT INTO #Temp VALUES('Thompson, Tommy','001','TEXT')
INSERT INTO #Temp VALUES('Williams, Wendy','001','TEXT')
INSERT INTO #Temp VALUES('Williams, Wendy','002','TEXT')

Then change the values into comma separated.

SELECT
    [NAME OF PERSON],
    STUFF((
        SELECT ', ' + t.CHARGENUMBER
        FROM #Temp t
        WHERE t.[NAME OF PERSON] = T1.[NAME OF PERSON]
        ORDER BY t.CHARGENUMBER
        FOR XMl PATH('')
    ),1,1,'') AS CHARGENUMBER
    ,STUFF((
        SELECT ', ' + t.CHARGEDESCRIPTION
        FROM #Temp t
        WHERE t.[NAME OF PERSON] = T1.[NAME OF PERSON]
        ORDER BY t.CHARGEDESCRIPTION
        FOR XMl PATH('')
    ),1,1,'') AS CHARGEDESCRIPTION
FROM #Temp T1
GROUP BY [NAME OF PERSON];

Hope this helps you.


问:
Run time error '3706': Provider cannot be found -Visual Basic
I am trying to connect Visual Basic to MS Access using ADODB. But as I execute my code, it prompts: "Provider cannot be found.It may not be installed properly." But when I check on my directory I've got my "msjetoledb40.dll" installed.

Here is my code:

```<code>Dim conn As ADODB.Connection, rec As ADODB.Recordset

    Sub sample()

    Set conn = New ADODB.Connection

    conn.Open ("Provider=Microsoft.Jet.OLEDB 4.0;Data Source=C:\sample.mdb;Persist Security Info=false;")
End Sub
</code>```

答:
Confirming the version of your MS Office on which the script is running. If you have installed MS Office 2013 or later, you should revise the connection string from:

```<code>Provider=Microsoft.Jet.OLEDB 4.0;Data Source=C:\sample.mdb;Persist Security Info=false;
</code>```

to:

```<code>Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\sample.mdb;Persist Security Info=false;
</code>```

At least, this sovled my problem.

Body:
I am trying to connect Visual Basic to MS Access using ADODB. But as I execute my code, it prompts: "Provider cannot be found.It may not be installed properly." But when I check on my directory I've got my "msjetoledb40.dll" installed.

Here is my code:

Dim conn As ADODB.Connection, rec As ADODB.Recordset

    Sub sample()

    Set conn = New ADODB.Connection

    conn.Open ("Provider=Microsoft.Jet.OLEDB 4.0;Data Source=C:\sample.mdb;Persist Security Info=false;")
End Sub

Body:
Confirming the version of your MS Office on which the script is running. If you have installed MS Office 2013 or later, you should revise the connection string from:

Provider=Microsoft.Jet.OLEDB 4.0;Data Source=C:\sample.mdb;Persist Security Info=false;

to:

Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\sample.mdb;Persist Security Info=false;

At least, this sovled my problem.


问:
MySQL returning incorrect data?
Recently an issue came up in the Django community regarding testing of MySQL (using MyISAM).

Here's the django ticket: http://code.djangoproject.com/ticket/14661

One of the Django core developers came up with this test and many of us have been able to replicate it. Anyone have a guess as to what we are running into here? Is it simply a bug in MySQL or am I missing something?

Here's the test code and queries:

```<code>DROP TABLE IF EXISTS `testapp_tag`;
CREATE TABLE `testapp_tag` (
    `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
    `name` varchar(10) NOT NULL,
    `parent_id` integer
);
INSERT INTO `testapp_tag` (`name`, `parent_id`) VALUES ("t1", NULL);
INSERT INTO `testapp_tag` (`name`, `parent_id`) VALUES ("t2", 1);
INSERT INTO `testapp_tag` (`name`, `parent_id`) VALUES ("t3", 1);
INSERT INTO `testapp_tag` (`name`, `parent_id`) VALUES ("t4", 3);
INSERT INTO `testapp_tag` (`name`, `parent_id`) VALUES ("t5", 3);
SELECT `testapp_tag`.`id`, `testapp_tag`.`name`, `testapp_tag`.`parent_id` FROM `testapp_tag` WHERE NOT ((`testapp_tag`.`id` IN (SELECT U0.`id` FROM `testapp_tag` U0 LEFT OUTER JOIN `testapp_tag` U1 ON (U0.`id` = U1.`parent_id`) WHERE U1.`id` IS NULL) AND `testapp_tag`.`id` IS NOT NULL)) ORDER BY `testapp_tag`.`name` ASC;
SELECT `testapp_tag`.`id`, `testapp_tag`.`name`, `testapp_tag`.`parent_id` FROM `testapp_tag` WHERE NOT ((`testapp_tag`.`id` IN (SELECT U0.`id` FROM `testapp_tag` U0 LEFT OUTER JOIN `testapp_tag` U1 ON (U0.`id` = U1.`parent_id`) WHERE U1.`id` IS NULL) AND `testapp_tag`.`id` IS NOT NULL)) ORDER BY `testapp_tag`.`name` ASC;
</code>```

Here's the output:

```<code>mysql> SELECT `testapp_tag`.`id`, `testapp_tag`.`name`, `testapp_tag`.`parent_id` FROM `testapp_tag` WHERE NOT ((`testapp_tag` .`id` IN (SELECT U0.`id` FROM `testapp_tag` U0 LEFT OUTER JOIN `testapp_tag` U1 ON (U0.`id` = U1.`parent_id`) WHERE U1.`id` IS  NULL) AND `testapp_tag`.`id` IS NOT NULL)) ORDER BY `testapp_tag`.`name` ASC;
+----+------+-----------+
| id | name | parent_id |
+----+------+-----------+
|  1 | t1   |      NULL |
|  3 | t3   |         1 |
|  5 | t5   |         3 |
+----+------+-----------+
3 rows in set (0.00 sec)

mysql> SELECT `testapp_tag`.`id`, `testapp_tag`.`name`, `testapp_tag`.`parent_id` FROM `testapp_tag` WHERE NOT ((`testapp_tag` .`id` IN (SELECT U0.`id` FROM `testapp_tag` U0 LEFT OUTER JOIN `testapp_tag` U1 ON (U0.`id` = U1.`parent_id`) WHERE U1.`id` IS NULL) AND `testapp_tag`.`id` IS NOT NULL)) ORDER BY `testapp_tag`.`name` ASC;
+----+------+-----------+
| id | name | parent_id |
+----+------+-----------+
|  1 | t1   |      NULL |
|  3 | t3   |         1 |
+----+------+-----------+
2 rows in set (0.01 sec)
</code>```

答:
Seems very interesting, and looks like a bug in the MySql query optimizer.

If you run this instead of the plain selects:

```<code>EXPLAIN EXTENDED SELECT `testapp_tag`.`id`, ....;
SHOW WARNINGS;
EXPLAIN EXTENDED SELECT `testapp_tag`.`id`, ...;
SHOW WARNINGS;
</code>```

Then, comparing the output from the EXPLAIN EXTENDED warnings, You can see that the first time around, the optimizer adds to the select:

```<code>or (`test`.`testapp_tag`.`id` = 5)
</code>```

Also, note that removing the AND testapp_tag.id IS NOT NULL from the WHERE, which does nothing since the field is marked as NOT NULL, seems to take away the issue.

ContentLicense: CC BY-SA 2.5

Title: MySQL returning incorrect data?

Body:
Recently an issue came up in the Django community regarding testing of MySQL (using MyISAM).

Here's the django ticket: http://code.djangoproject.com/ticket/14661

One of the Django core developers came up with this test and many of us have been able to replicate it. Anyone have a guess as to what we are running into here? Is it simply a bug in MySQL or am I missing something?

Here's the test code and queries:

DROP TABLE IF EXISTS `testapp_tag`;
CREATE TABLE `testapp_tag` (
    `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
    `name` varchar(10) NOT NULL,
    `parent_id` integer
);
INSERT INTO `testapp_tag` (`name`, `parent_id`) VALUES ("t1", NULL);
INSERT INTO `testapp_tag` (`name`, `parent_id`) VALUES ("t2", 1);
INSERT INTO `testapp_tag` (`name`, `parent_id`) VALUES ("t3", 1);
INSERT INTO `testapp_tag` (`name`, `parent_id`) VALUES ("t4", 3);
INSERT INTO `testapp_tag` (`name`, `parent_id`) VALUES ("t5", 3);
SELECT `testapp_tag`.`id`, `testapp_tag`.`name`, `testapp_tag`.`parent_id` FROM `testapp_tag` WHERE NOT ((`testapp_tag`.`id` IN (SELECT U0.`id` FROM `testapp_tag` U0 LEFT OUTER JOIN `testapp_tag` U1 ON (U0.`id` = U1.`parent_id`) WHERE U1.`id` IS NULL) AND `testapp_tag`.`id` IS NOT NULL)) ORDER BY `testapp_tag`.`name` ASC;
SELECT `testapp_tag`.`id`, `testapp_tag`.`name`, `testapp_tag`.`parent_id` FROM `testapp_tag` WHERE NOT ((`testapp_tag`.`id` IN (SELECT U0.`id` FROM `testapp_tag` U0 LEFT OUTER JOIN `testapp_tag` U1 ON (U0.`id` = U1.`parent_id`) WHERE U1.`id` IS NULL) AND `testapp_tag`.`id` IS NOT NULL)) ORDER BY `testapp_tag`.`name` ASC;

Here's the output:

mysql> SELECT `testapp_tag`.`id`, `testapp_tag`.`name`, `testapp_tag`.`parent_id` FROM `testapp_tag` WHERE NOT ((`testapp_tag` .`id` IN (SELECT U0.`id` FROM `testapp_tag` U0 LEFT OUTER JOIN `testapp_tag` U1 ON (U0.`id` = U1.`parent_id`) WHERE U1.`id` IS  NULL) AND `testapp_tag`.`id` IS NOT NULL)) ORDER BY `testapp_tag`.`name` ASC;
+----+------+-----------+
| id | name | parent_id |
+----+------+-----------+
|  1 | t1   |      NULL |
|  3 | t3   |         1 |
|  5 | t5   |         3 |
+----+------+-----------+
3 rows in set (0.00 sec)

mysql> SELECT `testapp_tag`.`id`, `testapp_tag`.`name`, `testapp_tag`.`parent_id` FROM `testapp_tag` WHERE NOT ((`testapp_tag` .`id` IN (SELECT U0.`id` FROM `testapp_tag` U0 LEFT OUTER JOIN `testapp_tag` U1 ON (U0.`id` = U1.`parent_id`) WHERE U1.`id` IS NULL) AND `testapp_tag`.`id` IS NOT NULL)) ORDER BY `testapp_tag`.`name` ASC;
+----+------+-----------+
| id | name | parent_id |
+----+------+-----------+
|  1 | t1   |      NULL |
|  3 | t3   |         1 |
+----+------+-----------+
2 rows in set (0.01 sec)

Body:
Seems very interesting, and looks like a bug in the MySql query optimizer.

If you run this instead of the plain selects:

EXPLAIN EXTENDED SELECT `testapp_tag`.`id`, ....;
SHOW WARNINGS;
EXPLAIN EXTENDED SELECT `testapp_tag`.`id`, ...;
SHOW WARNINGS;

Then, comparing the output from the EXPLAIN EXTENDED warnings, You can see that the first time around, the optimizer adds to the select:

or (`test`.`testapp_tag`.`id` = 5)

Also, note that removing the AND testapp_tag.id IS NOT NULL from the WHERE, which does nothing since the field is marked as NOT NULL, seems to take away the issue.


问:
How do I access a private member from a subclass
Trying to print the username in the method printShortSummary in the MessagePost class. The username is private in the Post class. Doing this for educational purposes. Still getting error that the username is private in Post. </p>

```<code>import java.util.ArrayList;

/**
 * This class stores information about a news feed post in a
 * social network. Posts can be stored and displayed. This class
 * serves as a superclass for more specific post types.
 *
 * @author Michael Kölling and David J. Barnes
 * @version 0.2
 */
public class Post
{
    private String username;  // username of the post's author
    private long timestamp;
    private int likes;
    private ArrayList<String> comments;

    /**
     * Constructor for objects of class Post.
     *
     * @param author    The username of the author of this post.
     */
    public Post(String author)
    {
        username = author;
        timestamp = System.currentTimeMillis();
        likes = 0;
        comments = new ArrayList<>();
    }

    public void getUserName()
    {

      getUserName();

    }
    /**
     * Record one more 'Like' indication from a user.
     */
    public void like()
    {
        likes++;
    }

    /**
     * Record that a user has withdrawn his/her 'Like' vote.
     */
    public void unlike()
    {
        if (likes > 0) {
            likes--;
        }
    }

    /**
     * Add a comment to this post.
     *
     * @param text  The new comment to add.
     */
    public void addComment(String text)
    {
        comments.add(text);
    }

    /**
     * Return the time of creation of this post.
     *
     * @return The post's creation time, as a system time value.
     */
    public long getTimeStamp()
    {
        return timestamp;
    }

    /**
     * Display the details of this post.
     *
     * (Currently: Print to the text terminal. This is simulating display
     * in a web browser for now.)
     */
    public void display()
    {
        System.out.println(username);
        System.out.print(timeString(timestamp));

        if(likes > 0) {
            System.out.println("  -  " + likes + " people like this.");
        }
        else {
            System.out.println();
        }

        if(comments.isEmpty()) {
            System.out.println("   No comments.");
        }
        else {
            System.out.println("   " + comments.size() + " comment(s). Click here to view.");
        }
    }

    /**
     * Create a string describing a time point in the past in terms
     * relative to current time, such as "30 seconds ago" or "7 minutes ago".
     * Currently, only seconds and minutes are used for the string.
     *
     * @param time  The time value to convert (in system milliseconds)
     * @return      A relative time string for the given time
     */

    private String timeString(long time)
    {
        long current = System.currentTimeMillis();
        long pastMillis = current - time;      // time passed in milliseconds
        long seconds = pastMillis/1000;
        long minutes = seconds/60;
        if(minutes > 0) {
            return minutes + " minutes ago";
        }
        else {
            return seconds + " seconds ago";
        }
    }
}

import java.util.ArrayList;

/**
 * This class stores information about a post in a social network news feed.
 * The main part of the post consists of a (possibly multi-line)
 * text message. Other data, such as author and time, are also stored.
 *
 * @author Michael Kölling and David J. Barnes
 * @version 0.2
 */
public class MessagePost extends Post
{
    private String message;  // an arbitrarily long, multi-line message

    /**
     * Constructor for objects of class MessagePost.
     *
     * @param author    The username of the author of this post.
     * @param text      The text of this post.
     */
    public MessagePost(String author, String text)
    {
        super(author);
        message = text;
    }

    public static void printShortSummary()
    {
      Post.getUserName();
      System.out.print ("Message postfrom" + username);

    }

    /**
     * Return the text of this post.
     *
     * @return The post's message text.
     */
    public String getText()
    {
        return message;
    }
}
</code>```

答:
You should be calling getUserName() but obviously cannot because it returns void and causes a Stack Overflow exception if called:

```<code>public void getUserName()
{
  getUserName();
}
</code>```

This should be

```<code>public String getUserName()
{
    return userName;
}
</code>```

And then that's how you access the user name from the subclass.

After that you would modify this method to be:

```<code>public static void printShortSummary()
{
    //Post.getUserName();
    System.out.print ("Message postfrom" + getUserName());
}
</code>```

The portion where you have Post.getUserName(); doesn't make any sense, it's not a static method and can't be referenced in that manner.

Body:
Trying to print the username in the method printShortSummary in the MessagePost class. The username is private in the Post class. Doing this for educational purposes. Still getting error that the username is private in Post.

import java.util.ArrayList;

/**
 * This class stores information about a news feed post in a
 * social network. Posts can be stored and displayed. This class
 * serves as a superclass for more specific post types.
 *
 * @author Michael Kölling and David J. Barnes
 * @version 0.2
 */
public class Post
{
    private String username;  // username of the post's author
    private long timestamp;
    private int likes;
    private ArrayList<String> comments;

    /**
     * Constructor for objects of class Post.
     *
     * @param author    The username of the author of this post.
     */
    public Post(String author)
    {
        username = author;
        timestamp = System.currentTimeMillis();
        likes = 0;
        comments = new ArrayList<>();
    }

    public void getUserName()
    {

      getUserName();

    }
    /**
     * Record one more 'Like' indication from a user.
     */
    public void like()
    {
        likes++;
    }

    /**
     * Record that a user has withdrawn his/her 'Like' vote.
     */
    public void unlike()
    {
        if (likes > 0) {
            likes--;
        }
    }

    /**
     * Add a comment to this post.
     *
     * @param text  The new comment to add.
     */
    public void addComment(String text)
    {
        comments.add(text);
    }

    /**
     * Return the time of creation of this post.
     *
     * @return The post's creation time, as a system time value.
     */
    public long getTimeStamp()
    {
        return timestamp;
    }

    /**
     * Display the details of this post.
     *
     * (Currently: Print to the text terminal. This is simulating display
     * in a web browser for now.)
     */
    public void display()
    {
        System.out.println(username);
        System.out.print(timeString(timestamp));

        if(likes > 0) {
            System.out.println("  -  " + likes + " people like this.");
        }
        else {
            System.out.println();
        }

        if(comments.isEmpty()) {
            System.out.println("   No comments.");
        }
        else {
            System.out.println("   " + comments.size() + " comment(s). Click here to view.");
        }
    }

    /**
     * Create a string describing a time point in the past in terms
     * relative to current time, such as "30 seconds ago" or "7 minutes ago".
     * Currently, only seconds and minutes are used for the string.
     *
     * @param time  The time value to convert (in system milliseconds)
     * @return      A relative time string for the given time
     */

    private String timeString(long time)
    {
        long current = System.currentTimeMillis();
        long pastMillis = current - time;      // time passed in milliseconds
        long seconds = pastMillis/1000;
        long minutes = seconds/60;
        if(minutes > 0) {
            return minutes + " minutes ago";
        }
        else {
            return seconds + " seconds ago";
        }
    }
}

import java.util.ArrayList;

/**
 * This class stores information about a post in a social network news feed.
 * The main part of the post consists of a (possibly multi-line)
 * text message. Other data, such as author and time, are also stored.
 *
 * @author Michael Kölling and David J. Barnes
 * @version 0.2
 */
public class MessagePost extends Post
{
    private String message;  // an arbitrarily long, multi-line message

    /**
     * Constructor for objects of class MessagePost.
     *
     * @param author    The username of the author of this post.
     * @param text      The text of this post.
     */
    public MessagePost(String author, String text)
    {
        super(author);
        message = text;
    }

    public static void printShortSummary()
    {
      Post.getUserName();
      System.out.print ("Message postfrom" + username);

    }

    /**
     * Return the text of this post.
     *
     * @return The post's message text.
     */
    public String getText()
    {
        return message;
    }
}

Body:
You should be calling getUserName() but obviously cannot because it returns void and causes a Stack Overflow exception if called:

public void getUserName()
{
  getUserName();
}

This should be

public String getUserName()
{
    return userName;
}

And then that's how you access the user name from the subclass.

After that you would modify this method to be:

public static void printShortSummary()
{
    //Post.getUserName();
    System.out.print ("Message postfrom" + getUserName());
}

The portion where you have Post.getUserName(); doesn't make any sense, it's not a static method and can't be referenced in that manner.


问:
Pulling data from Netezza db to amazon S3
I am trying to pull the data from Netezza database and place the returned result in the S3.</p>

答:
You can stream Netezza nzsql output to Amazon S3 bucket using AWS CLI.
Combination of nzsql command and aws cli will upload Netezza stream data into Amazon S3.

```<code>$ nzsql -host 192.168.0.111 -u admin -pw password -db training -F ',' -A -t -c "select * from patient_1" | aws s3 cp - s3://bucket/upload/test.txt

$ aws s3 ls s3://testnetezzabucket/upload/
2017-11-14 09:08:31 0
2017-11-14 18:05:04 506 nz_data.txt
2017-11-14 17:57:32 42 test.txt
$
</code>```

Follow Export Netezza Data into Amazon S3 Bucket

Body:
You can stream Netezza nzsql output to Amazon S3 bucket using AWS CLI.
Combination of nzsql command and aws cli will upload Netezza stream data into Amazon S3.

$ nzsql -host 192.168.0.111 -u admin -pw password -db training -F ',' -A -t -c "select * from patient_1" | aws s3 cp - s3://bucket/upload/test.txt

$ aws s3 ls s3://testnetezzabucket/upload/
2017-11-14 09:08:31 0
2017-11-14 18:05:04 506 nz_data.txt
2017-11-14 17:57:32 42 test.txt
$

Follow Export Netezza Data into Amazon S3 Bucket


问:
$.ajax() in jQuery 3.1.1 with php bootstrap4
I have the following error: Uncaught TypeError: $.ajax is not a function  with this code:

```<code>$("#fomulariollamada").submit(function(event){
  // cancels the form submission
  event.preventDefault();
  submitForm();
});

function submitForm(){
  // Initiate Variables With Form Content
  var name = $("#NombrePersona").val();
  var tel = $("#NumeroTelefono").val();
  var email = $("#CorreoElectronico").val();

  $.ajax({
    type: "POST",
    url: "php/process.php",
    data: "name=" + name + "&email=" + email + "&tel=" + tel,
    success : function(text){
      if (text == "success"){
        formSuccess();
      }
    }
  });
}

function formSuccess(){
  $( "#msgSubmit" ).removeClass( "hidden-xl-down" );
}
</code>```

I am using jQuery v3.2.1. How can I solve that? I'm learning jQuery.

Thank you very much

答: Is it possible you are using the slim build of jQuery? The slim build does not include the $.ajax function.</p>

Body:
I have the following error: Uncaught TypeError: $.ajax is not a function  with this code:

$("#fomulariollamada").submit(function(event){
  // cancels the form submission
  event.preventDefault();
  submitForm();
});

function submitForm(){
  // Initiate Variables With Form Content
  var name = $("#NombrePersona").val();
  var tel = $("#NumeroTelefono").val();
  var email = $("#CorreoElectronico").val();

  $.ajax({
    type: "POST",
    url: "php/process.php",
    data: "name=" + name + "&email=" + email + "&tel=" + tel,
    success : function(text){
      if (text == "success"){
        formSuccess();
      }
    }
  });
}

function formSuccess(){
  $( "#msgSubmit" ).removeClass( "hidden-xl-down" );
}

I am using jQuery v3.2.1. How can I solve that? I'm learning jQuery.

Thank you very much


问:
Future Proof DALs
We are in the beginning of a really long development project with several sub projects. Basically each sub-project will take several months to develop. The code itself will be split up into several C# projects, but the physical database will be shared by all projects.

The problem is maintainability. If we add a column to a table, or split a table into two smaller tables, we'll have to go back and modify our C# DAL to support these changes. This is not acceptable, as we'll constantly be adapting the DB conform to the needs of the company as a whole, and not just the needs of a single program. Constantly changing old code would be a neverending task.

Our DB people suggested a different view. We do all our CRUD through stored procedures, and use Linq across several tables to perform our SELECT statements. Then if we restructure the DB several years from now, we can simply supply the same stored procs and views and not have to modify our older code.

The question we have, is what ORM should be used for something like this? EF seems a bit overkill (maybe it's not). Would something like SubSonic with it's T4 templating allow for a simpiler (and perhaps faster) DAL?

Or perhaps someone has an idea on how to make this entire process less painful? We'd rather not add another layer to our application, but neither do we want to go back and modify code everytime we make a db change.

Edit 1:
So when I said "I don't really want to add more layers". This is mostly because we already have several layers. We have Silverlight views, view-models, BLL objects (via CSLA) then we have the DAL, and finally the SQL tables themseleves.

答:
C# DAL... not just the needs of a single program.  The whole point of a C# DAL as a separate assembly is that it can be reused across any type of .NET application.  The main problem you'll encounter is that if the database changes, then the DAL must change (once), then all applications that depend on the DAL must be re-deployed with the new DAL.  You also have the problem that the DAL can't be used by non-.NET applications.

Ok, so how can you centralize the DAL so that you don't have to re-deploy it for every application?  Think SOA.  You can build a WCF service to contain the DAL (and probably BLL).  All your applications (if you use web services, even those that are not .NET) can use this service.  When the database changes, you update your WCF service and deploy once.  Just make sure you don't make any breaking changes!  Create a MyMethod2 if you need to add/change functionality.

Note: When you hear n-tier, it usually
  refers to three-tier, where each tier
  is separate software and usually on
  separate servers: presentation (UI),
  application (your BLL/DAL), data (your
  SQL database).  There is merit to this architecture.

We'd rather not add another layer to our application.  Ok, so three-tier may not be the best approach in your case.

neither do we want to go back and modify code everytime we make a db change  Then what your DBA people suggested is the only way.

However, consider this: is changing a stored procedure the same as modifying code?  It basically is the same thing.  SQL stored procedures are often not version-controlled or tested, but they should be.  SQL doesn't have the richness of a language like .NET.  WCF can easily be scaled in a web farm.  Once you factor these and other reasons, it may be worth going the three-tier/SOA approach.

It really depends on the size of your project, skills of staff, future growth, etc. and that is something only you can determine.

Title: Future Proof DALs


问:
get List of values exist more than once in array
I have to get a list of values that exist more than once in an array.
This is current code , but as you can see it's too complicated.

var arr = [1, 2, 3, 4, 2, 3];
var flag = {}
var exist2arr = [];

for(var i = 0; i < arr.length; i++){
  for(var j = 0 ; j < arr.length; j ++){
     if(i !=j && arr[i] == arr[j]){
       if(!flag[arr[i]])
         exist2arr.push(arr[i]);
       flag[arr[i]] = 1;
     }
  }
}
console.log(exist2arr);```

Is there any other way (simple code using javascript built-in function) to achieve this?  Any kind of help appreciate.

答:
var arr = [1, 2, 3, 4, 2, 3];

var o = arr.reduce((o, n) => {
  n in o ? o[n] += 1 : o[n] = 1;
  return o;
}, {});

var res = Object.keys(o).filter(k => o[k] > 1);

console.log(res);```

Body:
I have to get a list of values that exist more than once in an array.
This is current code , but as you can see it's too complicated.

var arr = [1, 2, 3, 4, 2, 3];
var flag = {}
var exist2arr = [];

for(var i = 0; i < arr.length; i++){
  for(var j = 0 ; j < arr.length; j ++){
     if(i !=j && arr[i] == arr[j]){
       if(!flag[arr[i]])
         exist2arr.push(arr[i]);
       flag[arr[i]] = 1;
     }
  }
}
console.log(exist2arr);

Is there any other way (simple code using javascript built-in function) to achieve this?  Any kind of help appreciate.


问:
Custom Sort By "%%" in mysql
I have a table like this:

```<code>|city_name|
 Shadyside
 Chalkyitsik
 Wyalusing
 Quartzsite
 Seaside
 Shawnee Mission
 Siberia
 Sibley
 Nicasio
 Lacassine
 Sicily Island
 Andalusia
 Sidell
 Sidney
 ...
 ..
 .
</code>```

And selected with the following queries:

```<code>SELECT city_name FROM my_table WHERE city_name LIKE '%si%'
</code>```

Instead of '%si%', anything can be put.

I want to sort by the words first started with 'si'.

And the output is like this:

```<code>|city_name|
 Siberia
 Sibley
 Sicily Island
 Sidell
 Sidney
 ... And the rest of the words that are '%si%'
</code>```

How should this sorting(ORDER BY) be done?

答:
You can use multiple keys in the order by and expressions too:

```<code>SELECT city_name
FROM my_table
WHERE city_name LIKE '%si%'
ORDER BY (city_name LIKE 'si%') DESC, city_name;
</code>```

MySQL treats boolean expressions as numbers in a numeric context, with "0" for false and "1" for true.  The DESC puts the matches (1 = true) first.

Title: Custom Sort By "%%" in mysql

Body:
I have a table like this:

|city_name|
 Shadyside
 Chalkyitsik
 Wyalusing
 Quartzsite
 Seaside
 Shawnee Mission
 Siberia
 Sibley
 Nicasio
 Lacassine
 Sicily Island
 Andalusia
 Sidell
 Sidney
 ...
 ..
 .

And selected with the following queries:

SELECT city_name FROM my_table WHERE city_name LIKE '%si%'

Instead of '%si%', anything can be put.

I want to sort by the words first started with 'si'.

And the output is like this:

|city_name|
 Siberia
 Sibley
 Sicily Island
 Sidell
 Sidney
 ... And the rest of the words that are '%si%'

How should this sorting(ORDER BY) be done?

Body:
You can use multiple keys in the order by and expressions too:

SELECT city_name
FROM my_table
WHERE city_name LIKE '%si%'
ORDER BY (city_name LIKE 'si%') DESC, city_name;

MySQL treats boolean expressions as numbers in a numeric context, with "0" for false and "1" for true.  The DESC puts the matches (1 = true) first.


问:
How to manage user inputs in a short time interval?
i would like to implement a way of managing a user sending many messages in a time interval (for example 3 seconds), so that the chatbot only responds to the last one.

Example of inputs (in a gap of 3 seconds):

-Hi
-Hi
-Hi
-Help
Result: The chatbot only responds to the Help message.

Thanks in advance.

答:
You can leverage Middleware feature to intercept every message, with which you can store every user's every message in cache, when your bot receive a new message, you can compaire with those info in cache, then dicide whether the flow needs to go forward.

Npde.js code snippet for quick test:

```<code>const moment = require('moment');
let lastMessage = null;
let lastMessageTime = null;
bot.use({
    receive: (session, next) => {
        let currentMessage = session
        if (currentMessage.text !== lastMessage) {
            lastMessage = currentMessage.text;
            lastMessageTime = currentMessage.timestamp;
            next();
        } else {
            if (moment(currentMessage.timestamp) - moment(lastMessageTime) >= 3000) {
                lastMessageTime = currentMessage.timestamp;
                next();
            }
        }
    }
})
</code>```

What needs you paying attention is that, in production env, you need to store the message with session/user id. E.G. Using session/user id as prefix of message and timesamp key in cache.

Please refer to https://learn.microsoft.com/en-us/bot-framework/dotnet/bot-builder-dotnet-middleware for how to intercept messages in C#,
and refer to https://learn.microsoft.com/en-us/bot-framework/nodejs/bot-builder-nodejs-intercept-messages for Node.js version.

Hope it helps.

Body:
You can leverage Middleware feature to intercept every message, with which you can store every user's every message in cache, when your bot receive a new message, you can compaire with those info in cache, then dicide whether the flow needs to go forward.

Npde.js code snippet for quick test:

const moment = require('moment');
let lastMessage = null;
let lastMessageTime = null;
bot.use({
    receive: (session, next) => {
        let currentMessage = session
        if (currentMessage.text !== lastMessage) {
            lastMessage = currentMessage.text;
            lastMessageTime = currentMessage.timestamp;
            next();
        } else {
            if (moment(currentMessage.timestamp) - moment(lastMessageTime) >= 3000) {
                lastMessageTime = currentMessage.timestamp;
                next();
            }
        }
    }
})

What needs you paying attention is that, in production env, you need to store the message with session/user id. E.G. Using session/user id as prefix of message and timesamp key in cache.

Please refer to https://learn.microsoft.com/en-us/bot-framework/dotnet/bot-builder-dotnet-middleware for how to intercept messages in C#,
and refer to https://learn.microsoft.com/en-us/bot-framework/nodejs/bot-builder-nodejs-intercept-messages for Node.js version.

Hope it helps.


问:
Any working example recording a (e.g. rtsp) stream to a local MP4 file with ffmpeg/libav?
I'm looking for a working and not-out-dated script how to record an e.g. rtsp input stream to a local file (mp4) with ffmpeg/libav. If you could point me to one or post one, many thanks in advance. I'm searching for many hours and I haven't got any experience with this topic.

A lot of examples, libs, etc. are outdated, but I want to use ffmpeg >= v3.3.

Any special things I have to consider (when compiling ffmpeg, or when saving local file to iOS device)?

答:
Ffmpeg syntax is very straight forward.

```<code>ffmpeg [global_options] {[input_file_options] -i input_url} ... {[output_file_options] output_url} ...
</code>```

So, if you don´t need to reencode or decode your RTPS video stream, you can simply  run:

```<code>ffmpeg -i rtsp://your_stream_url your_file_name.format
</code>```

Where format could be avi, mp4, flv or others, ffmpeg you automatic package your stream to the output file.

More information here.

https://www.ffmpeg.org/ffmpeg.html

Any special things I have to consider (when compiling ffmpeg, or when
  saving local file to iOS device)?

Do you need to compile ffmpeg for an specific reason? I belive libav is enable on the executable you could download from the site.

Body:
Ffmpeg syntax is very straight forward.

ffmpeg [global_options] {[input_file_options] -i input_url} ... {[output_file_options] output_url} ...

So, if you don´t need to reencode or decode your RTPS video stream, you can simply  run:

ffmpeg -i rtsp://your_stream_url your_file_name.format

Where format could be avi, mp4, flv or others, ffmpeg you automatic package your stream to the output file.

More information here.

https://www.ffmpeg.org/ffmpeg.html

Any special things I have to consider (when compiling ffmpeg, or when
  saving local file to iOS device)?

Do you need to compile ffmpeg for an specific reason? I belive libav is enable on the executable you could download from the site.


问:
How do I convert [Size]byte to string in Go?
I have a sized byte array that I got after doing md5.Sum().

```<code>data := []byte("testing")
var pass string
var b [16]byte
b = md5.Sum(data)
pass = string(b)
</code>```

I get the error:

cannot convert b (type [16]byte) to type string

答:
it can be solved by this

```<code>pass = fmt.Sprintf("%x", b)
</code>```

or

```<code>import "encoding/base64"
pass = base64.StdEncoding.EncodeToString(b[:])
</code>```

this will encoding it to base64 string

Body:
I have a sized byte array that I got after doing md5.Sum().

data := []byte("testing")
var pass string
var b [16]byte
b = md5.Sum(data)
pass = string(b)

I get the error:

cannot convert b (type [16]byte) to type string

Body:
it can be solved by this

pass = fmt.Sprintf("%x", b)

or

import "encoding/base64"
pass = base64.StdEncoding.EncodeToString(b[:])

this will encoding it to base64 string


问:
Replace Chars inside either side of string?
OK, I am just going to come straight out with it, I have no idea how to do this, I have tried as much as I can with no success.

To get the string on the left to look like the result on the right with ReGex, the string looks like this,

String---String == String-String

This what happens when the middle character is different from the surrounding two characters,

String=@=string-String == String@string-String

EDIT, this is also a possiblity,

String@@@String == String@String

Any push in the right direction is much appreciated.

答:
Well I was able to figure this out after a couple of days at it.

This issue here is that Regex is that it will match a string as a whole, so if I wanted the exclude a character from a match I could do so by using Regex to drop either the first or last character in the matched string. But unfortunately, you can't not capture a character inside the matched result.

So when I want to match a character either side of another one like below;

So from my understanding of RegEx it is impossible.

However, I was able to use look-around to match each character either side, but b/c it was not a single match, it had the undesired result of matching just single characters as well, such as below;

Code is,

```<code>var match = Regex.IsMatch(text, @"(?<=[a-zA-Z0-9])[=@\-_]|[=@\-_](?=[a-zA-Z0-9])");
</code>```

And the results were this below, which also matched just single characters which was not desired.

So a change of thinking to the approach (which I don't know why I did not do in the first place, apart from the fact that I was so focused on matching the character either side of the desired character, I could not see the forest for the trees). The approach was to match when two of the same characters came before Word Characters or Digits, so I used look-around again and came up with this;
Here is the code,

```<code>var match =  Regex.IsMatch(subjectString, @"[=@\-_]{2}(?=[a-zA-Z0-9])");
</code>```

Whit the result looking like this,

Which now was what I was looking for. But, that did not solve the issue as when the character or string in the middle was different to the characters either side, to which the above would fail.

So I came up with this, and the answer to my question in my case. It is not a complete match , but matches two different conditions to get the result I needed.

```<code>var match =  Regex.IsMatch(subjectString, @"(?<=[a-zA-Z0-9])[@\-=_](?=[@\-=_])|(?<=[@\-=_])[@\-=_](?=[a-zA-Z0-9])");
</code>```

And the results are this;

I don't really care what people thought of the question, but hopefully this answer will help someone tries to do a single match on a character either side of a string or character

Body:
Well I was able to figure this out after a couple of days at it.

This issue here is that Regex is that it will match a string as a whole, so if I wanted the exclude a character from a match I could do so by using Regex to drop either the first or last character in the matched string. But unfortunately, you can't not capture a character inside the matched result.

So when I want to match a character either side of another one like below;

So from my understanding of RegEx it is impossible.

However, I was able to use look-around to match each character either side, but b/c it was not a single match, it had the undesired result of matching just single characters as well, such as below;

Code is,

var match = Regex.IsMatch(text, @"(?<=[a-zA-Z0-9])[=@\-_]|[=@\-_](?=[a-zA-Z0-9])");

And the results were this below, which also matched just single characters which was not desired.

So a change of thinking to the approach (which I don't know why I did not do in the first place, apart from the fact that I was so focused on matching the character either side of the desired character, I could not see the forest for the trees). The approach was to match when two of the same characters came before Word Characters or Digits, so I used look-around again and came up with this;
Here is the code,

var match =  Regex.IsMatch(subjectString, @"[=@\-_]{2}(?=[a-zA-Z0-9])");

Whit the result looking like this,

Which now was what I was looking for. But, that did not solve the issue as when the character or string in the middle was different to the characters either side, to which the above would fail.

So I came up with this, and the answer to my question in my case. It is not a complete match , but matches two different conditions to get the result I needed.

var match =  Regex.IsMatch(subjectString, @"(?<=[a-zA-Z0-9])[@\-=_](?=[@\-=_])|(?<=[@\-=_])[@\-=_](?=[a-zA-Z0-9])");

And the results are this;

I don't really care what people thought of the question, but hopefully this answer will help someone tries to do a single match on a character either side of a string or character


问:
CATransaction Delay
How can I set the delay of my implicit animation in core animation? I'm surprised that there is no kCATransactionAnimationDelay.</p>

答: Since you're doing an implicit animation, would you be better off just using UIView-based animation? It easily allows delays, and unless I'm mistaken, gives you access to exactly the same functionality you find when using implicit Core Animations.</p>

Title: CATransaction Delay


问:
Is it better to use entity property vs assignments in http post controller?
So say we have an aspnet core2 controller that's returning HttpPost object from another app.
Im using Entity framework core and both ways work but I'm just curious into best practices and performance to know what to use?

```<code>[HttpPost]
        public Message Post([FromBody] Message message)
        {
            // my old code
            // var msg = new Message { Owner = message.Owner, Text = message.Text };
            //db.Messages.AddAsync(msg)

            var msgEntity = db.Messages.Add(message).Entity;
            db.Messages.AddAsync(message);
            db.SaveChangesAsync();

            return message;

        }
</code>```

Something strange happens when I use Entity as well it changed the auto incremented Id parameter {Id:1002} when before I added it the next consecutive Id was suppose to be {Id:11}

答:
You should never save anything from a request directly. There's your best practice. The previous code is superior for the sole reason that you're explicitly choosing what posted values are actually persisted, rather than just blindly saving anything a user decides to send directly to your database.

The even better approach is to actually use a view model to accept user input. For example:

```<code>public class MessageViewModel
{
    public int OwnerId { get; set; }

    [Required]
    public string Text { get; set; }
}
</code>```

Then, you accept this as a param, instead, and map it onto your entity:

```<code>public async Task<IActionResult> Post([FromBody]MessageViewModel model)
{
    if (ModelState.IsValid)
    {
        var message = new Message
        {
            Owner = db.Users.Find(model.OwnerId),
            Text = model.Text
        };
        db.Messages.Add(message);
        await db.SaveChangesAsync();

        return Ok(message);
    }

    return BadRequest(ModelState);
}
</code>```

There's a number of important changes I made in the above code:

Added a conditional to check if ModelState.IsValid is true before proceeding with the save. As you have it now, you're just blindly attempting to save whatever gets passed in, even if doing so will end up raising a database exception because required values are missing and such.

With this conditional, you now need to handle the scenario where there's an issue. More likely than not, you'll want to return some sort of error object, to help the client fix issues. It's common to actually just return ModelState, which will serialize its list of validation errors, but you might want to do other things as well.

Since this now require potentially returning two different object types, the action signature has been changed to return IActionResult. It's usually better to just use this return type all the time. It's a catch-all, basically, whereas a specific return like Message can easily outgrow its usefulness, requiring you to just go ahead and change it later. You should really only return specific types when there's absolutely no chance of failure of any sort, i.e. the response will always be 200 OK. However, scenarios where that's the case are few and far between.

The view model just accepts the owner's id, instead of a full (presumably ApplicationUser) object. The same problem with accepting a Message and saving it directly exists here too. A malicious user could fudge with the Owner object properties, allowing them to potentially change all sorts of things that shouldn't be changed. In general, you should always set out to allow the user to manipulate as little data as possible. Anything you expose, should be done on purpose, fully understanding the implications. Since, we're now only accepting an id, we then need to look up the user with that id, to set the Owner property on the entity. If you happened to have an explicit foreign key property, such as OwnerId on Message, you could just set that directly.

Changed AddAsync to just Add. According to the documentation, you should almost never use AddAsync. It only exists for a very specific purpose that you're unlikely to ever encounter. It is recommend to always use Add, unless you have a good reason otherwise.

Added await to the SaveChangesAsync call. Always await asynchronous operations unless the completion of the operation as no bearing on anything. Here that's definitely not the case. SaveChangesAsync can raise exceptions, exceptions that your application will need to handle. Not awaiting it, basically just swallows these and lets the code happily continue as if there was no issue. Although that may sound like a positive, it is definitely not. There's also other issues that can be caused by not awaiting, such as the context may end up getting disposed before the call finishes.

Since we're now awaiting SaveChangesAsync, async must be added to the method signature, and you must return a Task<IActionResult>.

Body:
So say we have an aspnet core2 controller that's returning HttpPost object from another app.
Im using Entity framework core and both ways work but I'm just curious into best practices and performance to know what to use?

[HttpPost]
        public Message Post([FromBody] Message message)
        {
            // my old code
            // var msg = new Message { Owner = message.Owner, Text = message.Text };
            //db.Messages.AddAsync(msg)

            var msgEntity = db.Messages.Add(message).Entity;
            db.Messages.AddAsync(message);
            db.SaveChangesAsync();

            return message;

        }

Something strange happens when I use Entity as well it changed the auto incremented Id parameter {Id:1002} when before I added it the next consecutive Id was suppose to be {Id:11}

Body:
You should never save anything from a request directly. There's your best practice. The previous code is superior for the sole reason that you're explicitly choosing what posted values are actually persisted, rather than just blindly saving anything a user decides to send directly to your database.

The even better approach is to actually use a view model to accept user input. For example:

public class MessageViewModel
{
    public int OwnerId { get; set; }

    [Required]
    public string Text { get; set; }
}

Then, you accept this as a param, instead, and map it onto your entity:

public async Task<IActionResult> Post([FromBody]MessageViewModel model)
{
    if (ModelState.IsValid)
    {
        var message = new Message
        {
            Owner = db.Users.Find(model.OwnerId),
            Text = model.Text
        };
        db.Messages.Add(message);
        await db.SaveChangesAsync();

        return Ok(message);
    }

    return BadRequest(ModelState);
}

There's a number of important changes I made in the above code:

Added a conditional to check if ModelState.IsValid is true before proceeding with the save. As you have it now, you're just blindly attempting to save whatever gets passed in, even if doing so will end up raising a database exception because required values are missing and such.

With this conditional, you now need to handle the scenario where there's an issue. More likely than not, you'll want to return some sort of error object, to help the client fix issues. It's common to actually just return ModelState, which will serialize its list of validation errors, but you might want to do other things as well.

Since this now require potentially returning two different object types, the action signature has been changed to return IActionResult. It's usually better to just use this return type all the time. It's a catch-all, basically, whereas a specific return like Message can easily outgrow its usefulness, requiring you to just go ahead and change it later. You should really only return specific types when there's absolutely no chance of failure of any sort, i.e. the response will always be 200 OK. However, scenarios where that's the case are few and far between.

The view model just accepts the owner's id, instead of a full (presumably ApplicationUser) object. The same problem with accepting a Message and saving it directly exists here too. A malicious user could fudge with the Owner object properties, allowing them to potentially change all sorts of things that shouldn't be changed. In general, you should always set out to allow the user to manipulate as little data as possible. Anything you expose, should be done on purpose, fully understanding the implications. Since, we're now only accepting an id, we then need to look up the user with that id, to set the Owner property on the entity. If you happened to have an explicit foreign key property, such as OwnerId on Message, you could just set that directly.

Changed AddAsync to just Add. According to the documentation, you should almost never use AddAsync. It only exists for a very specific purpose that you're unlikely to ever encounter. It is recommend to always use Add, unless you have a good reason otherwise.

Added await to the SaveChangesAsync call. Always await asynchronous operations unless the completion of the operation as no bearing on anything. Here that's definitely not the case. SaveChangesAsync can raise exceptions, exceptions that your application will need to handle. Not awaiting it, basically just swallows these and lets the code happily continue as if there was no issue. Although that may sound like a positive, it is definitely not. There's also other issues that can be caused by not awaiting, such as the context may end up getting disposed before the call finishes.

Since we're now awaiting SaveChangesAsync, async must be added to the method signature, and you must return a Task<IActionResult>.


问:
IPython %store magic not persisting
I'm trying to get an IPython alias to persist, and according to docs the %store magic offers this feature. But it's not working:

```<code>$ echo 'print("hello world!")' > test.py
$ ipython
In [1]: alias potato python /tmp/test.py

In [2]: potato
hello world!

In [3]: %store potato
Alias stored: potato (python /tmp/test.py)

In [4]:
Do you really want to exit ([y]/n)?
$ ipython
In [1]: potato
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-e561f9248d75> in <module>()
----> 1 potato

NameError: name 'potato' is not defined
</code>```

What's missing?

答:
You can also restore in a regular script, for instance if your IDE (Spyder) doesn't support the ipython_config.py file:

```<code>from IPython import get_ipython
ipython = get_ipython()
ipython.magic("store -r")
</code>```

(Put this in a file that's called in the Startup tab of Spyder's IPython configuration.  This took me way too long to figure out.)

Title: IPython %store magic not persisting

Body:
I'm trying to get an IPython alias to persist, and according to docs the %store magic offers this feature. But it's not working:

$ echo 'print("hello world!")' > test.py
$ ipython
In [1]: alias potato python /tmp/test.py

In [2]: potato
hello world!

In [3]: %store potato
Alias stored: potato (python /tmp/test.py)

In [4]:
Do you really want to exit ([y]/n)?
$ ipython
In [1]: potato
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-e561f9248d75> in <module>()
----> 1 potato

NameError: name 'potato' is not defined

What's missing?

Body:
You can also restore in a regular script, for instance if your IDE (Spyder) doesn't support the ipython_config.py file:

from IPython import get_ipython
ipython = get_ipython()
ipython.magic("store -r")

(Put this in a file that's called in the Startup tab of Spyder's IPython configuration.  This took me way too long to figure out.)


问:
How to import google services plugin into library？
I have two application variants: google and china. But china variant doesn't need firebase. If I import google services plugin into the application, then china apk includes it. This apk throws

```<code>java.lang.IllegalAccessError-"Method 'void android.support.v4.content.ContextCompat.<init>()' is inaccessible to class 'com.google.firebase.iid.zzg'
(declaration of 'com.google.firebase.iid.zzg' appears in ".
</code>```

So, I want to let google services plugin to library A. In app, I can use googleCompile A . But now the plugin only uses the client object that matches the package name (for the current build type). How can I import google services plugin to library?

答:
```<code>getGradle().getTaskGraph().each {
    it.addTaskExecutionListener(new TaskExecutionListener() {
        @Override
        void beforeExecute(Task task) {
            if (task.name.contains("GoogleServices")) {
                Field field =  task.class.getField("packageName")
                field.setAccessible(true)
                field.set(task,"com.aaa.bbb.ccc")
            }
        }

        @Override
        void afterExecute(Task task, TaskState state) {

        }
    })

}
</code>```

Body:
I have two application variants: google and china. But china variant doesn't need firebase. If I import google services plugin into the application, then china apk includes it. This apk throws

java.lang.IllegalAccessError-"Method 'void android.support.v4.content.ContextCompat.<init>()' is inaccessible to class 'com.google.firebase.iid.zzg'
(declaration of 'com.google.firebase.iid.zzg' appears in ".

So, I want to let google services plugin to library A. In app, I can use googleCompile A . But now the plugin only uses the client object that matches the package name (for the current build type). How can I import google services plugin to library?


问:
I renamed a package and my app won't launch
I've been following this tutorial to create an android game. I downloaded the skeleton he provided but changed one of my packages from robotgame to highst. Whenever I try and deploy the application with the example code to my device I get the following error.

```<code>Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER]         cmp=com.ronyo.robotgame/com.ronyo.highst.Loader }
Error type 3
Error: Activity class {com.ronyo.robotgame/com.ronyo.highst.Loader} does not exist.
</code>```

I've searched for an instance of robotgame in my project and I can't find an instance of it. The tutorial above is created using Eclipse and I'm porting it to Android Studio. I'm wondering if I've overlooked something when switching IDEs?

Here is my AndroidManifest.xml

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.ronyo.highst"
   android:versionCode="1"
   android:versionName="1.0" >

    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.VIBRATE" />

    <application
       android:icon="@drawable/icon"
       android:label="Loader" >
        <activity
            android:name=".Loader"
            android:configChanges="keyboard|keyboardHidden|orientation"
            android:label="Loader"
            android:screenOrientation="landscape">
            <intent-filter>
                <action android:name="android.inten.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            </activity>
    </application>

</manifest>
</code>```

答: Delete the folders .idea and .gradle then click button "Sync project with gradle files"</p>

Body:
I've been following this tutorial to create an android game. I downloaded the skeleton he provided but changed one of my packages from robotgame to highst. Whenever I try and deploy the application with the example code to my device I get the following error.

Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER]         cmp=com.ronyo.robotgame/com.ronyo.highst.Loader }
Error type 3
Error: Activity class {com.ronyo.robotgame/com.ronyo.highst.Loader} does not exist.

I've searched for an instance of robotgame in my project and I can't find an instance of it. The tutorial above is created using Eclipse and I'm porting it to Android Studio. I'm wondering if I've overlooked something when switching IDEs?

Here is my AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.ronyo.highst"
   android:versionCode="1"
   android:versionName="1.0" >

    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.VIBRATE" />

    <application
       android:icon="@drawable/icon"
       android:label="Loader" >
        <activity
            android:name=".Loader"
            android:configChanges="keyboard|keyboardHidden|orientation"
            android:label="Loader"
            android:screenOrientation="landscape">
            <intent-filter>
                <action android:name="android.inten.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            </activity>
    </application>

</manifest>


问:
How to divide screen to two parts in react-native?
I'm new in react-native, and I'm trying to divide screen to tow part, the first part is the header or the navigation bar wish have a specific height about 40px the second part is the body or the content of the app wish his height must be the available height on the phone screen, I tried to use flex box method but it's not working!
That's my code:

```<code><View style={styles.mainContainer}>
    <View style={styles.navBar}>
    </View>
    <View style={styles.body}>
    </View>
</View>
</code>```

Style:

```<code>mainContainer: {
  height: '100%',
  display: 'flex',
  flexDirection: 'column',
},
navBar: {
  display: 'flex',
  flexDirection: 'row-reverse',
  justifyContent: 'space-between',
  alignItems: 'center',
  backgroundColor: '#f1f1f1',
  height: 30,
},
body: {
  flex: 3,
  display: 'flex',
},
</code>```

答:
Your code works perfectly fine. See it running on Snack at: https://snack.expo.io/S1LHFmFyG

It's likely that you use an older version of React Native that doesn't support percentages. They landed early this year so you need RN v0.42.3 or later in order to use them.

On a side note, there's a few unnecessary lines of code there in case you would like to make it more DRY. You don't need to declare display as it's flex by default, flexDirection is also set to column by default, and if you want a stripe of 40px your height should be 40 but I'm sure you're aware of that.

Body:
I'm new in react-native, and I'm trying to divide screen to tow part, the first part is the header or the navigation bar wish have a specific height about 40px the second part is the body or the content of the app wish his height must be the available height on the phone screen, I tried to use flex box method but it's not working!
That's my code:

<View style={styles.mainContainer}>
    <View style={styles.navBar}>
    </View>
    <View style={styles.body}>
    </View>
</View>

Style:

mainContainer: {
  height: '100%',
  display: 'flex',
  flexDirection: 'column',
},
navBar: {
  display: 'flex',
  flexDirection: 'row-reverse',
  justifyContent: 'space-between',
  alignItems: 'center',
  backgroundColor: '#f1f1f1',
  height: 30,
},
body: {
  flex: 3,
  display: 'flex',
},


问:
Replace every character with an element
This is what I have

```<code>$str = 'Just a <span class="green">little</span> -text åäö width 123#';
</code>```

This is what I need

Results in spans and spaces, might be newlines as well.

```<code>$result = '<span></span><span></span><span></span><span></span> <span></span> <span class="green"><span></span><span></span><span></span><span></span><span></span><span></span></span> <span></span><span></span><span></span><span></span><span></span> <span></span><span></span><span></span> <span></span><span></span><span></span><span></span><span></span> <span></span><span></span><span></span>';
</code>```

You might wonder what I can possible be needing this for. I want to build a thing where ever character is represented by a block. Will look a bit like Defrag on Windows XP.

Question

Replace every character with .

Do not touch the HTML span that already exists in the string (might be hard?). There can be more than one HTML element.

Do not touch spaces and newline.

Regexp should do it? or Xpath?

What have I done so far?

I have found articles about the regexp but not replacing every character (excerpt space and newline)

```<code>$result = preg_replace("/???/", "<span></span>", $str);
print_r($result);
</code>```

答:
This is NOT a hacky regex method.  This is a solid, concise, one-line-one-function-call solution that avoids having to iterate a battery of conditions on each character in a string, preserves tags, and cares for multi-byte characters.

alexn's solution does not maintain the visible character length of åäö.  His solution will print 6 opening and closing span tags to screen instead of just 3.  This is because mb_ functions are not used.  On this topic, be wary of any methods on this page that are not using mb_ prefixed string functions.

My suggested solution will leverage the (*SKIP)(*FAIL) technique to ignore/disqualify all encountered tags and then only match non-white-space characters in the string.

Code: (Demo)

```<code>$str = 'Just a <span class="green">little</span> -text åäö width 123#';
var_export(preg_replace('/<[^>]*>(*SKIP)(*FAIL)|\S/','<span></span>',$str));  // no "u" flag means åäö will be span x6
echo "\n";
var_export(preg_replace('/<[^>]*>(*SKIP)(*FAIL)|\S/u','<span></span>',$str)); // "u" flag means åäö will be span x3
</code>```

Output: (scroll right to see the impact of the unicode flag on the pattern)

```<code>'<span></span><span></span><span></span><span></span> <span></span> <span class="green"><span></span><span></span><span></span><span></span><span></span><span></span></span> <span></span><span></span><span></span><span></span><span></span> <span></span><span></span><span></span><span></span><span></span><span></span> <span></span><span></span><span></span><span></span><span></span> <span></span><span></span><span></span><span></span>'
// notice the number of replacements for åäö ->-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------111111111111122222222222223333333333333444444444444455555555555556666666666666
'<span></span><span></span><span></span><span></span> <span></span> <span class="green"><span></span><span></span><span></span><span></span><span></span><span></span></span> <span></span><span></span><span></span><span></span><span></span> <span></span><span></span><span></span> <span></span><span></span><span></span><span></span><span></span> <span></span><span></span><span></span><span></span>'
// notice the number of replacements for åäö ->-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------111111111111122222222222223333333333333
</code>```

Title: Replace every character with an element

Body:
This is what I have

$str = 'Just a little -text åäö width 123#';

This is what I need

Results in spans and spaces, might be newlines as well.

$result = '      ';

You might wonder what I can possible be needing this for. I want to build a thing where ever character is represented by a block. Will look a bit like Defrag on Windows XP.

Question

Replace every character with .

Do not touch the HTML span that already exists in the string (might be hard?). There can be more than one HTML element.

Do not touch spaces and newline.

Regexp should do it? or Xpath?

What have I done so far?

I have found articles about the regexp but not replacing every character (excerpt space and newline)

$result = preg_replace("/???/", "", $str);
print_r($result);

Body:
This is NOT a hacky regex method.  This is a solid, concise, one-line-one-function-call solution that avoids having to iterate a battery of conditions on each character in a string, preserves tags, and cares for multi-byte characters.

alexn's solution does not maintain the visible character length of åäö.  His solution will print 6 opening and closing span tags to screen instead of just 3.  This is because mb_ functions are not used.  On this topic, be wary of any methods on this page that are not using mb_ prefixed string functions.

My suggested solution will leverage the (*SKIP)(*FAIL) technique to ignore/disqualify all encountered tags and then only match non-white-space characters in the string.

Code: (Demo)

$str = 'Just a <span class="green">little</span> -text åäö width 123#';
var_export(preg_replace('/<[^>]*>(*SKIP)(*FAIL)|\S/','<span></span>',$str));  // no "u" flag means åäö will be span x6
echo "\n";
var_export(preg_replace('/<[^>]*>(*SKIP)(*FAIL)|\S/u','<span></span>',$str)); // "u" flag means åäö will be span x3

Output: (scroll right to see the impact of the unicode flag on the pattern)

'<span></span><span></span><span></span><span></span> <span></span> <span class="green"><span></span><span></span><span></span><span></span><span></span><span></span></span> <span></span><span></span><span></span><span></span><span></span> <span></span><span></span><span></span><span></span><span></span><span></span> <span></span><span></span><span></span><span></span><span></span> <span></span><span></span><span></span><span></span>'
// notice the number of replacements for åäö ->-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------111111111111122222222222223333333333333444444444444455555555555556666666666666
'<span></span><span></span><span></span><span></span> <span></span> <span class="green"><span></span><span></span><span></span><span></span><span></span><span></span></span> <span></span><span></span><span></span><span></span><span></span> <span></span><span></span><span></span> <span></span><span></span><span></span><span></span><span></span> <span></span><span></span><span></span><span></span>'
// notice the number of replacements for åäö ->-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------111111111111122222222222223333333333333


答:
You could filter the array based on values who's first and current indexes are not equal then run that array through a Set

const arr = [1, 2, 3, 4, 2, 3, 2, 3, 2, 3, 2, 3]; // added in some extras

const filtered = arr.filter((v, i) => arr.indexOf(v) !== i)
const unique = new Set(filtered)

console.info(Array.from(unique)) // using Array.from so it can be logged```

Title: get List of values exist more than once in array

Body:
I have to get a list of values that exist more than once in an array.
This is current code , but as you can see it's too complicated.

var arr = [1, 2, 3, 4, 2, 3];
var flag = {}
var exist2arr = [];

for(var i = 0; i < arr.length; i++){
  for(var j = 0 ; j < arr.length; j ++){
     if(i !=j && arr[i] == arr[j]){
       if(!flag[arr[i]])
         exist2arr.push(arr[i]);
       flag[arr[i]] = 1;
     }
  }
}
console.log(exist2arr);

Is there any other way (simple code using javascript built-in function) to achieve this?  Any kind of help appreciate.