问:
Mysql query with and conditions
I've two tables,

table 1

```<code>userid  filter
thiru   1
thiru   2
thiru   3
raja    1
raja    2
</code>```

table 2

```<code>headline    filter1 filter2
test          1       3
test2         1       2
</code>```

If I want to select the users applicable for filters.

when i select test - thiru is applicable ( filter1 and filter2 ) matching

when i select test2 - thiru and raja are applicable ( filter1 and filter2 ) matching.

Basically the filters are with and condition.

Here is the query that i tried:

```<code>select userid
  from table1
 where filter in (select filter1
                    from table2
                   where headline = 'test')
   and filter in (select filter2
                    from table2
                   where headline = 'test');
</code>```

Please give me the query for this.
Thanks in advance.

答:
You can use the below structure to get the result</p>

```<code>select a.userid
 from table1 a
 join table2 b on (a.filter = b.filter1 or a.filter = b.filter2)
 where b.headline = 'test'
 group by a.userid
</code>```

Title: Mysql query with and conditions

Body:
I've two tables,

table 1

userid  filter
thiru   1
thiru   2
thiru   3
raja    1
raja    2

table 2

headline    filter1 filter2
test          1       3
test2         1       2

If I want to select the users applicable for filters.

when i select test - thiru is applicable ( filter1 and filter2 ) matching

when i select test2 - thiru and raja are applicable ( filter1 and filter2 ) matching.

Basically the filters are with and condition.

Here is the query that i tried:

select userid
  from table1
 where filter in (select filter1
                    from table2
                   where headline = 'test')
   and filter in (select filter2
                    from table2
                   where headline = 'test');

Please give me the query for this.
Thanks in advance.

Body:
You can use the below structure to get the result

select a.userid
 from table1 a
 join table2 b on (a.filter = b.filter1 or a.filter = b.filter2)
 where b.headline = 'test'
 group by a.userid


来源: stackexchange

问:
Image crop function not working in Wordpress
I have used this following function in my localhost which is working fine

// Image cropping

```<code>function cropImage($sourcePath, $thumbSize, $destination = null) {

      $parts = explode('.', $sourcePath);
      $ext = $parts[count($parts) - 1];
      if ($ext == 'jpg' || $ext == 'jpeg') {
        $format = 'jpg';
      } else {
        $format = 'png';
      }
      if ($format == 'jpg') {
        $sourceImage = imagecreatefromjpeg($sourcePath);
      }
      if ($format == 'png') {
        $sourceImage = imagecreatefrompng($sourcePath);
      }

      list($srcWidth, $srcHeight) = getimagesize($sourcePath);

      // calculating the part of the image to use for thumbnail
      if ($srcWidth > $srcHeight) {
        $y = 0;
        $x = ($srcWidth - $srcHeight) / 2;
        $smallestSide = $srcHeight;
      } else {
        $x = 0;
        $y = ($srcHeight - $srcWidth) / 2;
        $smallestSide = $srcWidth;
      }

      $destinationImage = imagecreatetruecolor($thumbSize, $thumbSize);
      imagecopyresampled($destinationImage, $sourceImage, 0, 0, $x, $y, $thumbSize, $thumbSize, $smallestSide, $smallestSide);

      if ($destination == null) {
        header('Content-Type: image/jpeg');
        if ($format == 'jpg') {
          imagejpeg($destinationImage, null, 100);
        }
        if ($format == 'png') {
          imagejpeg($destinationImage);
        }
        if ($destination = null) {
        }
      } else {
        if ($format == 'jpg') {
          imagejpeg($destinationImage, $destination, 100);
        }
        if ($format == 'png') {
          imagepng($destinationImage, $destination);
        }
      }
    }
</code>```

But i am using this in my wordpress theme and it is showing some errors

����JFIF����?I��^��l�i�����76����6m�0ib�~���X��KR����J��W�9��.�7wK~��J��)�J��)�.�������A�_�]�pw��@��'��{1M{���5���7�#X��|�w�#9W^�t�]������t}ms�l���%���W{���G��1T+8�2s���0a��3�XX� �yL��FrU��@�Y٦'���r���{g��簪�;c�[�0r0q�q���N9��G��{?�c�w�K�ӯE�|ެ�Td2���F�?!#�G�z>ЀP�����u۝�ᓒ����d��A8��9't��=���b���'#'ג}O��\����P�S�]���o�h�Zy$|�Ns�q��Y��t8f+�O�

I have used this code for showing the image

```<code>                                    $docimg = $doctor_img['url'];

                                    if ($docimg):
                                        ?>
                                        <?php cropImage( $docimg, 200, null); ?>
</code>```

Is there anything to change in this code. So that i can get the image src instead of wired characters

答:
I have found a solution for this,but i cant understand what will happen if png file will come.

```<code>ob_start();
header( "Content-type: image/jpeg" );
cropImage( $docimg, 200, null);
$i = ob_get_clean();
echo "<img src='data:image/jpeg;base64," . base64_encode( $i )."'>";
</code>```

Because as you see, there is written for jpeg file only.

ContentLicense: CC BY-SA 3.0

Body:
I have used this following function in my localhost which is working fine

// Image cropping

function cropImage($sourcePath, $thumbSize, $destination = null) {

      $parts = explode('.', $sourcePath);
      $ext = $parts[count($parts) - 1];
      if ($ext == 'jpg' || $ext == 'jpeg') {
        $format = 'jpg';
      } else {
        $format = 'png';
      }
      if ($format == 'jpg') {
        $sourceImage = imagecreatefromjpeg($sourcePath);
      }
      if ($format == 'png') {
        $sourceImage = imagecreatefrompng($sourcePath);
      }

      list($srcWidth, $srcHeight) = getimagesize($sourcePath);

      // calculating the part of the image to use for thumbnail
      if ($srcWidth > $srcHeight) {
        $y = 0;
        $x = ($srcWidth - $srcHeight) / 2;
        $smallestSide = $srcHeight;
      } else {
        $x = 0;
        $y = ($srcHeight - $srcWidth) / 2;
        $smallestSide = $srcWidth;
      }

      $destinationImage = imagecreatetruecolor($thumbSize, $thumbSize);
      imagecopyresampled($destinationImage, $sourceImage, 0, 0, $x, $y, $thumbSize, $thumbSize, $smallestSide, $smallestSide);

      if ($destination == null) {
        header('Content-Type: image/jpeg');
        if ($format == 'jpg') {
          imagejpeg($destinationImage, null, 100);
        }
        if ($format == 'png') {
          imagejpeg($destinationImage);
        }
        if ($destination = null) {
        }
      } else {
        if ($format == 'jpg') {
          imagejpeg($destinationImage, $destination, 100);
        }
        if ($format == 'png') {
          imagepng($destinationImage, $destination);
        }
      }
    }

But i am using this in my wordpress theme and it is showing some errors

����JFIF����?I��^��l�i�����76����6m�0ib�~���X��KR����J��W�9��.�7wK~��J��)�J��)�.�������A�_�]�pw��@��'��{1M{���5���7�#X��|�w�#9W^�t�]������t}ms�l���%���W{���G��1T+8�2s���0a��3�XX� �yL��FrU��@�Y٦'���r���{g��簪�;c�[�0r0q�q���N9��G��{?�c�w�K�ӯE�|ެ�Td2���F�?!#�G�z>ЀP�����u۝�ᓒ����d��A8��9't��=���b���'#'ג}O��\����P�S�]���o�h�Zy$|�Ns�q��Y��t8f+�O�

I have used this code for showing the image

                                    $docimg = $doctor_img['url'];

                                    if ($docimg):
                                        ?>
                                        <?php cropImage( $docimg, 200, null); ?>

Is there anything to change in this code. So that i can get the image src instead of wired characters

Body:
I have found a solution for this,but i cant understand what will happen if png file will come.

ob_start();
header( "Content-type: image/jpeg" );
cropImage( $docimg, 200, null);
$i = ob_get_clean();
echo "<img src='data:image/jpeg;base64," . base64_encode( $i )."'>";

Because as you see, there is written for jpeg file only.


问:
Convert a list of objects to an array of one of the object's properties
Say I have the following class:

```<code>public class ConfigItemType
{
    public string Name { get; set; }
    public double SomeOtherThing { get; set; }
}
</code>```

and then I make a list of the following classes (List<ConfigItemType> MyList)

Now I have a method with the following signature:

```<code>void AggregateValues(string someUnrelatedValue, params string[] listGoesHere)
</code>```

How can I fit MyList in to the listGoesHere using the value in ConfigItemType.Name as the params string array?

I am fairly sure that Linq can do this.... but MyList does not have a select method on it (which is what I would have used).

答:
This should also work:</p>

```<code>AggregateValues("hello", MyList.ConvertAll(c => c.Name).ToArray())
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Say I have the following class:

public class ConfigItemType
{
    public string Name { get; set; }
    public double SomeOtherThing { get; set; }
}

and then I make a list of the following classes (List<ConfigItemType> MyList)

Now I have a method with the following signature:

void AggregateValues(string someUnrelatedValue, params string[] listGoesHere)

How can I fit MyList in to the listGoesHere using the value in ConfigItemType.Name as the params string array?

I am fairly sure that Linq can do this.... but MyList does not have a select method on it (which is what I would have used).

Body:
This should also work:

AggregateValues("hello", MyList.ConvertAll(c => c.Name).ToArray())


问:
not able to read attribute in foreach?
I am trying to remove the style property of some divs, but I am not able to do so, when I console log the style property I am getting undefined.

```<code>var divs = $('#addDescription').parent().children('div');
        divs.each(function (i)
        {
            //console.log("wid", $(i).css("width"))
           console.log( $(i).attr("style"))
            $(i).removeAttr("style");

        });
</code>```

why I am not able to read the style property using foreach?

答:
Use this in place of  var i. The i is the Index, the nth item of the selection (e.g. 0,1,2,3, etc).
jQuery gives you a this, which refers to one element per itteration.

```<code>var divs = $('#addDescription').parent().children('div');
divs.each(function (i){
    //console.log("wid", $(i).css("width"))
    console.log( $(this).attr("style"))
    $(this).removeAttr("style");
});
</code>```

Title: not able to read attribute in foreach?

Body:
I am trying to remove the style property of some divs, but I am not able to do so, when I console log the style property I am getting undefined.

var divs = $('#addDescription').parent().children('div');
        divs.each(function (i)
        {
            //console.log("wid", $(i).css("width"))
           console.log( $(i).attr("style"))
            $(i).removeAttr("style");

        });

why I am not able to read the style property using foreach?

Body:
Use this in place of  var i. The i is the Index, the nth item of the selection (e.g. 0,1,2,3, etc).
jQuery gives you a this, which refers to one element per itteration.

var divs = $('#addDescription').parent().children('div');
divs.each(function (i){
    //console.log("wid", $(i).css("width"))
    console.log( $(this).attr("style"))
    $(this).removeAttr("style");
});


问:
SMTP stopped sending mails
I have a mail delivering script running on various pages in my website for localhost XAMPP. It was working fine till last evening and as I started today again any page having phpmailer script gives error as

```<code>SMTP ERROR: Failed to connect to server: (0)
SMTP connect() failed.
</code>```

I haven't changed anything into the local server configuration and my GMAIL credentials but unable to figure out possibly what has gone wrong into the SMTP settings so that this error is coming up. I have done all my settings neatly for this setup and as I said it was working well till last evening.

```<code><?php
require('phpmailer/class.phpmailer.php');
$mail = new PHPMailer();
$subject = "Test Mail using PHP mailer";
$content = "<b>This is a test mail using PHP mailer class.</b>";

$mail->IsSMTP();
$mail->SMTPDebug = 1;
$mail->SMTPAuth = TRUE;
$mail->SMTPSecure = "ssl";
$mail->Debugoutput = 'html';
$mail->Port     = 465;
$mail->Username = "emailsender@email.com";
$mail->Password = "*******";
$mail->Host     = "ssl://smtp.gmail.com";
$mail->Mailer   = "smtp";
$mail->SetFrom("emailsender@email.com", "");
$mail->AddAddress("emailreceiver@email.com");
$mail->Subject = $subject;
$mail->WordWrap   = 80;
$mail->MsgHTML($content);
$mail->IsHTML(true);

if(!$mail->Send())
    echo "Problem on sending mail";
else
echo "Mail sent";
?>
</code>```

I am just unable to find out any possible reason for this . Any help or advice will be appreciated.

答:
PHPMailer   6.0.2

Download:
https://github.com/PHPMailer/PHPMailer/archive/master.zip

and use the code

https://github.com/PHPMailer/PHPMailer/blob/master/examples/gmail.phps

and insert code:

$mail->SMTPOptions = array ( 'ssl' => array( 'verify_peer' => false,
'verify_peer_name' => false, 'allow_self_signed' => true));

========================================================================

Title: SMTP stopped sending mails

Body:
I have a mail delivering script running on various pages in my website for localhost XAMPP. It was working fine till last evening and as I started today again any page having phpmailer script gives error as

SMTP ERROR: Failed to connect to server: (0)
SMTP connect() failed.

I haven't changed anything into the local server configuration and my GMAIL credentials but unable to figure out possibly what has gone wrong into the SMTP settings so that this error is coming up. I have done all my settings neatly for this setup and as I said it was working well till last evening.

<?php
require('phpmailer/class.phpmailer.php');
$mail = new PHPMailer();
$subject = "Test Mail using PHP mailer";
$content = "This is a test mail using PHP mailer class.";

$mail->IsSMTP();
$mail->SMTPDebug = 1;
$mail->SMTPAuth = TRUE;
$mail->SMTPSecure = "ssl";
$mail->Debugoutput = 'html';
$mail->Port     = 465;
$mail->Username = "emailsender@email.com";
$mail->Password = "*******";
$mail->Host     = "ssl://smtp.gmail.com";
$mail->Mailer   = "smtp";
$mail->SetFrom("emailsender@email.com", "");
$mail->AddAddress("emailreceiver@email.com");
$mail->Subject = $subject;
$mail->WordWrap   = 80;
$mail->MsgHTML($content);
$mail->IsHTML(true);

if(!$mail->Send())
    echo "Problem on sending mail";
else
echo "Mail sent";
?>

I am just unable to find out any possible reason for this . Any help or advice will be appreciated.


问:
Mongo Sort Documents by value in array

I have a list of Students. Each one has an array of points they've earned by category in an array named lightTrail. I want the top 5 people with the most behavior points which is shown at index 1 in the lightTrail array. If it is a tie the second sort field is their total points which is shown at index 0.

Here is what I tried:

```<code>db.students.aggregate([{
        $project: {
            fname: 1,
            surname: 1,
            lightTrails: 1,
            '_id': 0
        }
    },
    {
        $sort: {
            "lightTrails.1": -1,
            "lightTrails.0": -1
        }
    }, {
        $limit: 5
    }
], {
    allowDiskUse: true
})
</code>```

This is the result I wanted:

```<code>{
    "fname": "Jim",
    surname: "Jones",
    lightTrails: [200, 70, 30, 30, 15, 15, 40]
}, {
    "fname": "Sean",
    surname: "Marx",
    lightTrails: [180, 50, 50, 20, 20, 15, 25]
}, {
    "fname": "Todd",
    surname: "Lull",
    lightTrails: [150, 40, 60, 15, 15, 10, 10]
}, {
    "fname": "Flynn",
    surname: "Moore",
    lightTrails: [100, 40, 25, 15, 5, 10, 5]
}, {
    "fname": "Al",
    surname: "Ryan",
    lightTrails: [80, 20, 20, 10, 10, 10, 10]
}
</code>```

The result I got was just 5 students no order:

```<code>{
  "fname": "Flynn",
    surname: "Moore",
      lightTrails: [100, 40, 25, 15, 5, 10, 5]
}, {
  "fname": "Jim",
    surname: "Jones",
      lightTrails: [200, 70, 30, 30, 15, 15, 40]
}, {
  "fname": "Al",
    surname: "Ryan",
      lightTrails: [80, 20, 20, 10, 10, 10, 10]
}, {
  "fname": "Todd",
    surname: "Lull",
      lightTrails: [150, 40, 60, 15, 15, 10, 10]
}, {
  "fname": "Sean",
    surname: "Marx",
      lightTrails: [180, 50, 50, 20, 20, 15, 25]
}
</code>```

I found 2 similar questions but one was for an array of documents which didn't work for me and the other wasn't really asking the same question at all.

答:
You can achieve this by find query. No need to use aggregation.

Query:

```<code>db.students.find({},{fname:1,surname:1,lightTrails:1,_id:0}).sort({"lightTrails.0":-1,"lightTrails.1":-1}).limit(5)
</code>```

Result:

```<code>{ "fname" : "Jim", "surname" : "Jones", "lightTrails" : [ 200, 70, 30, 30, 15, 15, 40 ] }
{ "fname" : "Sean", "surname" : "Marx", "lightTrails" : [ 180, 50, 50, 20, 20, 15, 25 ] }
{ "fname" : "Todd", "surname" : "Lull", "lightTrails" : [ 150, 40, 60, 15, 15, 10, 10 ] }
{ "fname" : "Flynn", "surname" : "Moore", "lightTrails" : [ 100, 40, 25, 15, 5, 10, 5 ] }
{ "fname" : "Al", "surname" : "Ryan", "lightTrails" : [ 80, 20, 20, 10, 10, 10, 10 ] }
</code>```

Title: Mongo Sort Documents by value in array

Body:
I have a list of Students. Each one has an array of points they've earned by category in an array named lightTrail. I want the top 5 people with the most behavior points which is shown at index 1 in the lightTrail array. If it is a tie the second sort field is their total points which is shown at index 0.

Here is what I tried:

db.students.aggregate([{
        $project: {
            fname: 1,
            surname: 1,
            lightTrails: 1,
            '_id': 0
        }
    },
    {
        $sort: {
            "lightTrails.1": -1,
            "lightTrails.0": -1
        }
    }, {
        $limit: 5
    }
], {
    allowDiskUse: true
})

This is the result I wanted:

{
    "fname": "Jim",
    surname: "Jones",
    lightTrails: [200, 70, 30, 30, 15, 15, 40]
}, {
    "fname": "Sean",
    surname: "Marx",
    lightTrails: [180, 50, 50, 20, 20, 15, 25]
}, {
    "fname": "Todd",
    surname: "Lull",
    lightTrails: [150, 40, 60, 15, 15, 10, 10]
}, {
    "fname": "Flynn",
    surname: "Moore",
    lightTrails: [100, 40, 25, 15, 5, 10, 5]
}, {
    "fname": "Al",
    surname: "Ryan",
    lightTrails: [80, 20, 20, 10, 10, 10, 10]
}

The result I got was just 5 students no order:

{
  "fname": "Flynn",
    surname: "Moore",
      lightTrails: [100, 40, 25, 15, 5, 10, 5]
}, {
  "fname": "Jim",
    surname: "Jones",
      lightTrails: [200, 70, 30, 30, 15, 15, 40]
}, {
  "fname": "Al",
    surname: "Ryan",
      lightTrails: [80, 20, 20, 10, 10, 10, 10]
}, {
  "fname": "Todd",
    surname: "Lull",
      lightTrails: [150, 40, 60, 15, 15, 10, 10]
}, {
  "fname": "Sean",
    surname: "Marx",
      lightTrails: [180, 50, 50, 20, 20, 15, 25]
}

I found 2 similar questions but one was for an array of documents which didn't work for me and the other wasn't really asking the same question at all.

Body:
You can achieve this by find query. No need to use aggregation.

Query:

db.students.find({},{fname:1,surname:1,lightTrails:1,_id:0}).sort({"lightTrails.0":-1,"lightTrails.1":-1}).limit(5)

Result:

{ "fname" : "Jim", "surname" : "Jones", "lightTrails" : [ 200, 70, 30, 30, 15, 15, 40 ] }
{ "fname" : "Sean", "surname" : "Marx", "lightTrails" : [ 180, 50, 50, 20, 20, 15, 25 ] }
{ "fname" : "Todd", "surname" : "Lull", "lightTrails" : [ 150, 40, 60, 15, 15, 10, 10 ] }
{ "fname" : "Flynn", "surname" : "Moore", "lightTrails" : [ 100, 40, 25, 15, 5, 10, 5 ] }
{ "fname" : "Al", "surname" : "Ryan", "lightTrails" : [ 80, 20, 20, 10, 10, 10, 10 ] }


问:
jQuery: Conflict with removeData() executing at inadequate times
I have a modal window used to update or add a new object Store.

This modal is called remotely which information is loaded from a GET method constructed in ASP.NET.

Button that calls the modal:

```<code><div class="btn-group" id="modalbutton">
    <a id="createEditStoreModal" data-toggle="modal" asp-action="Create"
         data-target="#modal-action-store" class="btn btn-primary">
            <i class="glyphicon glyphicon-plus"></i>  NEW STORE
        </a>
</div>
</code>```

Html of the modal:

```<code>@model Application.Models.ApplicationviewModels.StoreIndexData
@using Application.Models

<form asp-action="Create" role="form">
        @await Html.PartialAsync("_ModalHeader", new ModalHeader
    { Heading = String.Format("Actualización de Modelo: Tiendas") })

        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="modal-body form-horizontal">
            <div class="form-group">
                <label asp-for="DepartmentID" class="col-md-2 control-label"></label>
                <div class="col-md-10">
                    <select asp-for="DepartmentID" class="form-control"
                            asp-items="@(new SelectList(@ViewBag.ListofDepartment,"DepartmentID","DepartmentName"))"></select>
                </div>
            </div>
            <div class="form-group">
                <label class="col-md-2 control-label">Distrito</label>
                <div class="col-md-10">
                    <select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID"
                            asp-items="@(new SelectList(@ViewBag.ListofDistrict,"DistrictID","DistrictName"))"></select>
                </div>
            </div>
            {... more elements}
       </div>
</form>
</code>```

GET Method:

```<code>    public IActionResult Create(int? id)
    {
        List<Department> DepartmentList = new List<Department>();
        DepartmentList = (from department in _context.Departments
                          select department).ToList();
        DepartmentList.Insert(0, new Department { DepartmentID = 0, DepartmentName = "-- Seleccione Departamento --" });
        ViewBag.ListofDepartment = DepartmentList;

        StoreIndexData edit = new StoreIndexData();
        List<District> ListofDistrict = new List<District>();
        ListofDistrict.Insert(0, new District { DistrictID = 0, DistrictName = "-- PRUEBA --" });
        ViewBag.ListofDistrict = ListofDistrict;

        return PartialView("~/Views/Shared/Stores/_Create.cshtml");
    }
</code>```

The problem:

I have the following jQuery which asigns a value to DistrictID once the modal opens:

```<code><script type="text/javascript">

    var wasclicked = 0;
    var $this = this;

    $(document).ready(function () {

        document.getElementById("modalbutton").onclick = function () {
            //is AddNew Store button is hitted, this var = 1
            wasclicked = 1;
        };

        $('#modal-action-store').on('hidden.bs.modal', function () {
            //global.wasclicked = 0;
            wasclicked = 0;
            $(this).removeData('bs.modal');
        });

        $('#modal-action-store').on('shown.bs.modal', function (e) {
            console.log($('#DistrictID').length);
            //if wasclicked equals 1 that means we are in the AddNew Store scenario.
            if (wasclicked == 1) {
                //a default value is sent to District dropdownlist
                var items = "<option value='0'>-- Seleccione Distrito --</option>";
                $('#DistrictID').html(items);
            };
        });
    });
</script>
</code>```

The problem right now is that after this line jQuery is executed, the value that was assigned to DistrictID gets overwritten by :

```<code>  ViewBag.ListofDistrict = ListofDistrict; //"-- PRUEBA --"
</code>```

And this line is lost:

```<code>var items = "<option value='0'>-- Seleccione Distrito --</option>";
</code>```

What I suspect is that the information coming from the Controller overwrites any result from jQuery over the  in the modal.

After debugging I have identified three diferent moments:

Moment 1: First time we open the modal

The modal hasn't opened yet and the jQuery executes

For this reason it does not identify DistrictID

The result from the GET Action fills the modal's inputs.

Moment 2 - Part 1: Second time we open the modal

This time the modal opens before the jQuery is executed

The DistrictID has the value from the GET Method before we assign the value from jQuery

Moment 2 - Part 2: When the value from jQuery is assigned

The value from jQuery is assigned to DistrictID

This value will be overwritten by the result of the GET Action

Question:

Can anyone explain or help me understand what might be causing this? What else can I do to identify the reason behind this?

答:
I would update your http://plataformafantasypark.azurewebsites.net/Stores/create to contain <option value='0'>-- Seleccione Distrito --</option> by default. This would limit the options to overwrite the element with zero entries.
This would make your js code easier too.

By the way, why do you use document.getElementById("modalbutton").onclick  when you can use $("#modalbutton").on("click", function(){}); because you are using jQuery for everything else.

Body:
I have a modal window used to update or add a new object Store.

This modal is called remotely which information is loaded from a GET method constructed in ASP.NET.

Button that calls the modal:

              NEW STORE

Html of the modal:

@model Application.Models.ApplicationviewModels.StoreIndexData
@using Application.Models

<form asp-action="Create" role="form">
        @await Html.PartialAsync("_ModalHeader", new ModalHeader
    { Heading = String.Format("Actualización de Modelo: Tiendas") })

                    <select asp-for="DepartmentID" class="form-control"
                            asp-items="@(new SelectList(@ViewBag.ListofDepartment,"DepartmentID","DepartmentName"))"></select>

                Distrito

                    <select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID"
                            asp-items="@(new SelectList(@ViewBag.ListofDistrict,"DistrictID","DistrictName"))"></select>

            {... more elements}

</form>

GET Method:

    public IActionResult Create(int? id)
    {
        List<Department> DepartmentList = new List<Department>();
        DepartmentList = (from department in _context.Departments
                          select department).ToList();
        DepartmentList.Insert(0, new Department { DepartmentID = 0, DepartmentName = "-- Seleccione Departamento --" });
        ViewBag.ListofDepartment = DepartmentList;

        StoreIndexData edit = new StoreIndexData();
        List<District> ListofDistrict = new List<District>();
        ListofDistrict.Insert(0, new District { DistrictID = 0, DistrictName = "-- PRUEBA --" });
        ViewBag.ListofDistrict = ListofDistrict;

        return PartialView("~/Views/Shared/Stores/_Create.cshtml");
    }

The problem:

I have the following jQuery which asigns a value to DistrictID once the modal opens:

The problem right now is that after this line jQuery is executed, the value that was assigned to DistrictID gets overwritten by :

  ViewBag.ListofDistrict = ListofDistrict; //"-- PRUEBA --"

And this line is lost:

var items = "<option value='0'>-- Seleccione Distrito --</option>";

What I suspect is that the information coming from the Controller overwrites any result from jQuery over the  in the modal.

After debugging I have identified three diferent moments:

Moment 1: First time we open the modal

The modal hasn't opened yet and the jQuery executes

For this reason it does not identify DistrictID

The result from the GET Action fills the modal's inputs.

Moment 2 - Part 1: Second time we open the modal

This time the modal opens before the jQuery is executed

The DistrictID has the value from the GET Method before we assign the value from jQuery

Moment 2 - Part 2: When the value from jQuery is assigned

The value from jQuery is assigned to DistrictID

This value will be overwritten by the result of the GET Action

Question:

Can anyone explain or help me understand what might be causing this? What else can I do to identify the reason behind this?


问:
Django TemplateDoesNotExist
Ok so I have a project called tvlistings and an app called progguide.

In my tvlistings directory I have the following in these files

settings.py

```<code>TEMPLATE_DIRS = (
    '/home/paul/tvlistings/progguide/templates',
)
</code>```

urls.py

```<code>from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'^progguide/', include('progguide.urls')),
)
</code>```

In my progguide directory I have

urls.py

```<code>from django.conf.urls.defaults import *

urlpatterns = patterns('progguide.views',
    (r'^$', 'index'),
    (r'^(?P<prog_id>\d+)/$', 'programme'),
)
</code>```

views.py

```<code>from django.shortcuts import render_to_response
from progguide.models import *

def index(request):
    chan_prog_list = ChannelProgramme.objects.all().order_by('progdate','starttime')[:5]
    return render_to_response('progguide/index.html', {'chan_prog_list': chan_prog_list})
</code>```

And in /home/paul/tvlistings/progguide/templates I have

index.html

```<code>{% if chan_prog_list % }
    <ul>
    {% for prog in chan_prog_list %}
        <li>{{ prog.channelid.channelname}} {{ prog.programmeid.progtitle }}</li>
    {% endfor %}
    </ul>
{% else %}
    <p>No programmes.</p>
{% endif %}
</code>```

If I try to load http://localhost:8000/progguide I get

TemplateDoesNotExist at /progguide/

progguide/index.html

Request Method:  GET Request URL:
   http://127.0.0.1:8000/progguide/
  Django Version:  1.2.4 Exception Type:
   TemplateDoesNotExist Exception Value:

progguide/index.html

Still very new to this, the above looks ok from what I understand. What am I missing?

答:
You were close though it's actually supposed to be</p>

```<code>return render_to_response('index.html', {'chan_prog_list': chan_prog_list})
</code>```

Title: Django TemplateDoesNotExist

Body:
Ok so I have a project called tvlistings and an app called progguide.

In my tvlistings directory I have the following in these files

settings.py

TEMPLATE_DIRS = (
    '/home/paul/tvlistings/progguide/templates',
)

urls.py

from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'^progguide/', include('progguide.urls')),
)

In my progguide directory I have

urls.py

from django.conf.urls.defaults import *

urlpatterns = patterns('progguide.views',
    (r'^$', 'index'),
    (r'^(?P<prog_id>\d+)/$', 'programme'),
)

views.py

from django.shortcuts import render_to_response
from progguide.models import *

def index(request):
    chan_prog_list = ChannelProgramme.objects.all().order_by('progdate','starttime')[:5]
    return render_to_response('progguide/index.html', {'chan_prog_list': chan_prog_list})

And in /home/paul/tvlistings/progguide/templates I have

index.html

{% if chan_prog_list % }

    {% for prog in chan_prog_list %}

{{ prog.channelid.channelname}} {{ prog.programmeid.progtitle }}

    {% endfor %}

{% else %}

No programmes.

{% endif %}

If I try to load http://localhost:8000/progguide I get

TemplateDoesNotExist at /progguide/

progguide/index.html

Request Method:  GET Request URL:
   http://127.0.0.1:8000/progguide/
  Django Version:  1.2.4 Exception Type:
   TemplateDoesNotExist Exception Value:

progguide/index.html

Still very new to this, the above looks ok from what I understand. What am I missing?

Body:
You were close though it's actually supposed to be

return render_to_response('index.html', {'chan_prog_list': chan_prog_list})


问:
Set color of text in status bar it is not working (swift 3 - iOS 10)
My status bar is black and I'm trying to set as white, so I did what I found in some questions here and put this on my AppDelegate...

```<code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    //Status bar color
    UIApplication.shared.statusBarStyle = .lightContent

    return true
}
</code>```

There is no error in my console, nothing about this. The status bar text is still black. What could be causing this? There is another way to do that in swift 3.0?

答:
In Swift3 you have to use following code, put anywhere in your view controller</p>

```<code>override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
}
</code>```

Body:
My status bar is black and I'm trying to set as white, so I did what I found in some questions here and put this on my AppDelegate...

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    //Status bar color
    UIApplication.shared.statusBarStyle = .lightContent

    return true
}

There is no error in my console, nothing about this. The status bar text is still black. What could be causing this? There is another way to do that in swift 3.0?

Body:
In Swift3 you have to use following code, put anywhere in your view controller

override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
}


问:
Unit testing Alexa skill that uses alexa-sdk
I'm developing an Alexa skill in node and I'd like to know how I can unit test my code. I'm using the alexa sdk that Amazon released.

I've found many libraries to accomplish this, but they seem to be developed before the alexa sdk was available.

Thanks in advance.

答: I am using alexa-skill-test-framework with mocha for generating the alexa intent json. Can setup AWS services in local PC using localstack, which supports DynamoDB, SQS, Lambda and other services</p>


问:
qml component connects with signal
I have a component/delegate declared in qml and  I would like to connect one o its actions to a signal in another qml or C++ class. So, the Component looks like this:

```<code>Component
{
     id: mainButtonDelegate
     Button {
        id: buttonOperation
        text: qsTr(buttonText)
        buttonEnabled: false
        onIsEnableChanged:
        {
            buttonEnabled = cppRegisteredClass.isButtonEnabled(text)
        }
    }
}
</code>```

Can I create connection for the component (so for every button), like the following expressed in Qt?
    connect(loginForm, SIGNAL(loginChanged()), this, SLOT(onIsEnableChanged()))

My model is a ListModel expressed in a qml file.

Edit

If this is not the correct approach could somebody suggest me another way to do sth like this?

答:
I am posting how I have done what I wanted, just if anyone else need this.
I have added a function in the model and used set property.

```<code>function action()
{
    for(var i= 0; i<count; ++i)
    {
        if(backend.disable())
        {
            setProperty(i, "enable", false)
            setProperty(i, "opac", 0.3)
        }
        else
        {
            setProperty(i, "enable", true)
            setProperty(i, "opac", 1)
        }
    }
}
</code>```

In the component (inside an Item parent), I have added:

```<code>            LoginForm{
            id: loginForm
            onLoginIdentityChanged: {
                mymodel.action()
            }
</code>```

Title: qml component connects with signal

Body:
I have a component/delegate declared in qml and  I would like to connect one o its actions to a signal in another qml or C++ class. So, the Component looks like this:

Component
{
     id: mainButtonDelegate
     Button {
        id: buttonOperation
        text: qsTr(buttonText)
        buttonEnabled: false
        onIsEnableChanged:
        {
            buttonEnabled = cppRegisteredClass.isButtonEnabled(text)
        }
    }
}

Can I create connection for the component (so for every button), like the following expressed in Qt?
    connect(loginForm, SIGNAL(loginChanged()), this, SLOT(onIsEnableChanged()))

My model is a ListModel expressed in a qml file.

Edit

If this is not the correct approach could somebody suggest me another way to do sth like this?

Body:
I am posting how I have done what I wanted, just if anyone else need this.
I have added a function in the model and used set property.

function action()
{
    for(var i= 0; i<count; ++i)
    {
        if(backend.disable())
        {
            setProperty(i, "enable", false)
            setProperty(i, "opac", 0.3)
        }
        else
        {
            setProperty(i, "enable", true)
            setProperty(i, "opac", 1)
        }
    }
}

In the component (inside an Item parent), I have added:

            LoginForm{
            id: loginForm
            onLoginIdentityChanged: {
                mymodel.action()
            }


问:
rails carrierwave backgrounder with delayed jobs taking too much time to upload
I am using carrierwave and carrierwave backgrounder(https://github.com/lardawge/carrierwave_backgrounder) with delayed job for uploading file in a background.whernver i try to upload my file, it uploads successfully and i can see that jobs are executed in the background , but i cant see any difference with using delayed job and without using delayed job.it takes same time to execute without delayed job as it takes with delayed job.dont know what went wrong plz help.Thanks in advance.

here is my Uploader

```<code>             # encoding: utf-8

        class AvatarUploader < CarrierWave::Uploader::Base

          # Include RMagick or MiniMagick support:
          # include CarrierWave::RMagick
          # include CarrierWave::MiniMagick

          include ::CarrierWave::Backgrounder::Delay
          include Sprockets::Helpers::RailsHelper

          include Sprockets::Helpers::IsolatedHelper
         # Choose what kind of storage to use for this uploader:
           storage :file
           # storage :fog

        # Override the directory where uploaded files will be stored.
        # This is a sensible default for uploaders that are meant to be mounted:
        def store_dir
          "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
        end

       def cache_dir
           ""
       end

        # Provide a default URL as a default if there hasn't been a file uploaded:
       def default_url
         "rails.png"
       end

    end
</code>```

carrierwave backgrounder file inside config/initializers/carrierwave_backgrounder.rb

```<code>            CarrierWave::Backgrounder.configure do |c|
             c.backend :delayed_job, queue: :carrierwave
            end
</code>```

Post model

```<code>        class Post < ActiveRecord::Base
          attr_accessible :description , :avatar, :remote_avatar_url
          mount_uploader :avatar,   AvatarUploader
          process_in_background :avatar
          validates_presence_of :description
        end
</code>```

Post controller action

```<code>        def create
          @post = Post.new(params[:post])
          respond_to do |format|
         if @post.save
           format.html { redirect_to @post, notice: 'Post was successfully created.' }
           format.json { render json: @post, status: :created, location: @post }
         else
           format.html { render action: "new" }
           format.json { render json: @post.errors, status: :unprocessable_entity }
         end
      end
    end
</code>```

and here is my view

```<code>        <%= form_for(@post) do |f| %>
          <% if @post.errors.any? %>
          <div id="error_explanation">
          <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from      being saved:</h2>

         <ul>
         <% @post.errors.full_messages.each do |msg| %>
         <li><%= msg %></li>
         <% end %>
         </ul>
        </div>
       <% end %>

      <div class="field">
       <%= f.label :description %><br />
       <%= f.text_area :description %>
      </div>
      <div class="field">
       <%= f.file_field :avatar %>
      </div>
        <div class="actions">
        <%= f.submit %>
      </div>
     <% end %>
</code>```

答: I recommend you to use Carrierwave Direct instead.</p>

Body:
I am using carrierwave and carrierwave backgrounder(https://github.com/lardawge/carrierwave_backgrounder) with delayed job for uploading file in a background.whernver i try to upload my file, it uploads successfully and i can see that jobs are executed in the background , but i cant see any difference with using delayed job and without using delayed job.it takes same time to execute without delayed job as it takes with delayed job.dont know what went wrong plz help.Thanks in advance.

here is my Uploader

             # encoding: utf-8

        class AvatarUploader < CarrierWave::Uploader::Base

          # Include RMagick or MiniMagick support:
          # include CarrierWave::RMagick
          # include CarrierWave::MiniMagick

          include ::CarrierWave::Backgrounder::Delay
          include Sprockets::Helpers::RailsHelper

          include Sprockets::Helpers::IsolatedHelper
         # Choose what kind of storage to use for this uploader:
           storage :file
           # storage :fog

        # Override the directory where uploaded files will be stored.
        # This is a sensible default for uploaders that are meant to be mounted:
        def store_dir
          "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
        end

       def cache_dir
           ""
       end

        # Provide a default URL as a default if there hasn't been a file uploaded:
       def default_url
         "rails.png"
       end

    end

carrierwave backgrounder file inside config/initializers/carrierwave_backgrounder.rb

            CarrierWave::Backgrounder.configure do |c|
             c.backend :delayed_job, queue: :carrierwave
            end

Post model

        class Post < ActiveRecord::Base
          attr_accessible :description , :avatar, :remote_avatar_url
          mount_uploader :avatar,   AvatarUploader
          process_in_background :avatar
          validates_presence_of :description
        end

Post controller action

        def create
          @post = Post.new(params[:post])
          respond_to do |format|
         if @post.save
           format.html { redirect_to @post, notice: 'Post was successfully created.' }
           format.json { render json: @post, status: :created, location: @post }
         else
           format.html { render action: "new" }
           format.json { render json: @post.errors, status: :unprocessable_entity }
         end
      end
    end

and here is my view

        <%= form_for(@post) do |f| %>
          <% if @post.errors.any? %>

<%= pluralize(@post.errors.count, "error") %> prohibited this post from      being saved:

         <% @post.errors.full_messages.each do |msg| %>

<%= msg %>

         <% end %>

       <% end %>

       <%= f.label :description %>

       <%= f.text_area :description %>

       <%= f.file_field :avatar %>

        <%= f.submit %>

     <% end %>


问:
Reading file from another system in node.js
Can anyone provide me some solution to read files from a remote machine in node.js.</p>

答:
I found a way to read a file over file protocol. If you want to read a file or fetch file data over file protocol, then checkout below code.

```<code>const fs = require('fs');
const { URL } = require('url');
const fileUrl = new URL('file://tmp/hello.txt');

fs.readFileSync(fileUrl);
</code>```

Also go through Node.js documentation.

Body:
I found a way to read a file over file protocol. If you want to read a file or fetch file data over file protocol, then checkout below code.

const fs = require('fs');
const { URL } = require('url');
const fileUrl = new URL('file://tmp/hello.txt');

fs.readFileSync(fileUrl);

Also go through Node.js documentation.


问:
My current MySQL join is not working
I have the following tables:

Users

```<code>id | name
-----------------
 1 | Johny Bravo
</code>```

Orders

```<code>id | users_id | number
----------------------
 1 |    1    | 111111
 2 |    1    | 222222
 3 |    1    | 333333
 4 |    1    | 444444
</code>```

Example

```<code>id | text | number
------------------
 1 | test | 111111
 2 | test | 111111
 3 | test | 222222
 4 | test | 222222
 5 | test | 333333
 6 | test | 333333
</code>```

Desired Outcome

```<code>id: 1
name: Johny Brawo
count(orders): 4
count(example): 6
</code>```

My current query, which doesn't work

```<code>SELECT users.id, users.name, count(orders.id), count(example.id)
FROM users
LEFT JOIN orders ON orders.users_id=users.id
LEFT JOIN example ON example.number=orders.number
GROUP BY users.id
</code>```

My current result

```<code>id: 1
name: Johny Brawo
count(orders): 8
count(example): 8
</code>```

Any help would be greatly appreciated.

答:
Starting - a little bit of theory. What does your query do?

First it SELECTs something from users table.

Then it LEFT JOINs with orders table. Number of returned rows is a multiplication of rows from users table and matching rows from orders table. So with only this join you will have 6 rows, each one with Johny Bravo as user, but with different orders data.

Then - another LEFT JOIN. This time with example table. Again - a number of returned rows is a multiplication of rows from orders table and matching rows from example table. So without GROUP BY and COUNT you will have eight rows of result.

Now, the GROUP BY query part. What does it do? It just groups rows with matching GROUP BY column(s). So it will group all rows with same users.id. There are eight of them.

Standard COUNT() will return a number of rows with not null value. As there were eight rows, both counts will return 8.

Now, as @GPW suggested, the solution is a COUNT(DISTINCT x). This function returns a count of unique not null rows.

Thus, the query should look like:

SELECT users.id, users.name, count(DISTINCT orders.id), count(DISTINCT example.id)
FROM users
LEFT JOIN orders ON orders.users_id=users.id
LEFT JOIN example ON example.number=orders.number
GROUP BY users.id
```

<p><strong>UPDATE - ordering and strict databases</strong></p>

<p>You have also asked about ordering the result. You can order it by any column from your query. As MySQL is not very strict when it comes to grouping, you will also be able to order by any column from <code>users</code> table, as <code>users</code> table results are unique (grouped by id). You can also add, for example <code>ORDER BY COUNT(DISTINCT orders.id) DESC</code> to find users with largest number of orders.</p>

<p>Most databases, though, is more strict in <code>GROUP BY</code> queries. It allows to <code>SELECT</code> only columns with aggregated values or those explicitly contained in <code>GROUP BY</code> clause. So your <code>GROUP BY</code> clause should rather look like</p>

<pre class="lang-sql prettyprint-override"><code>GROUP BY users.id, users.name
</code>```

Title: My current MySQL join is not working

Body:
I have the following tables:

Users

id | name
-----------------
 1 | Johny Bravo

Orders

id | users_id | number
----------------------
 1 |    1    | 111111
 2 |    1    | 222222
 3 |    1    | 333333
 4 |    1    | 444444

Example

id | text | number
------------------
 1 | test | 111111
 2 | test | 111111
 3 | test | 222222
 4 | test | 222222
 5 | test | 333333
 6 | test | 333333

Desired Outcome

id: 1
name: Johny Brawo
count(orders): 4
count(example): 6

My current query, which doesn't work

SELECT users.id, users.name, count(orders.id), count(example.id)
FROM users
LEFT JOIN orders ON orders.users_id=users.id
LEFT JOIN example ON example.number=orders.number
GROUP BY users.id

My current result

id: 1
name: Johny Brawo
count(orders): 8
count(example): 8

Any help would be greatly appreciated.

Body:
Starting - a little bit of theory. What does your query do?

First it SELECTs something from users table.

Then it LEFT JOINs with orders table. Number of returned rows is a multiplication of rows from users table and matching rows from orders table. So with only this join you will have 6 rows, each one with Johny Bravo as user, but with different orders data.

Then - another LEFT JOIN. This time with example table. Again - a number of returned rows is a multiplication of rows from orders table and matching rows from example table. So without GROUP BY and COUNT you will have eight rows of result.

Now, the GROUP BY query part. What does it do? It just groups rows with matching GROUP BY column(s). So it will group all rows with same users.id. There are eight of them.

Standard COUNT() will return a number of rows with not null value. As there were eight rows, both counts will return 8.

Now, as @GPW suggested, the solution is a COUNT(DISTINCT x). This function returns a count of unique not null rows.

Thus, the query should look like:

SELECT users.id, users.name, count(DISTINCT orders.id), count(DISTINCT example.id)
FROM users
LEFT JOIN orders ON orders.users_id=users.id
LEFT JOIN example ON example.number=orders.number
GROUP BY users.id

UPDATE - ordering and strict databases

You have also asked about ordering the result. You can order it by any column from your query. As MySQL is not very strict when it comes to grouping, you will also be able to order by any column from users table, as users table results are unique (grouped by id). You can also add, for example ORDER BY COUNT(DISTINCT orders.id) DESC to find users with largest number of orders.

Most databases, though, is more strict in GROUP BY queries. It allows to SELECT only columns with aggregated values or those explicitly contained in GROUP BY clause. So your GROUP BY clause should rather look like

GROUP BY users.id, users.name


问:
Python code reflection and modification
Perhaps I'm not using the proper term, but I'm looking to take a block of Python code (in Python), get the token tree for the code, make some kind of modification, and re-assemble it to Python.

For instance, consider this block of code:

```<code>def x(y):
    b = 2
    if y == b:
        foo(y)
</code>```

I would like to be able to take this and programmatically do this:

```<code>def x(y):
    b = 2
    if y == b:
        bar(y)
</code>```

I can't imagine that there's not a library that does something like this. Thanks in advance.

EDIT

Perhaps I wasn't entirely clear. I'm looking for a tool to read and manipulate arbitrary code, not code that I'm writing. I'd like to be able to modify code on-the-fly. The project I'm working on is a test app: it uses the Netflix philosophy to try to randomly break the functionality of an app in as many ways as it can, running the test suite each time. When the tests don't fail, there's an indication that there's either a gap in code coverage and/or the code is dead.

答:
I was curious about this so I looked into the link Apalala posted, here is what I came up with:

```<code>from token import NAME
from tokenize import generate_tokens, untokenize
from StringIO import StringIO

source = """def x(y):
    b = 2
    if y == b:
        foo(y)"""
result = []
tokens = generate_tokens(StringIO(source).readline)
for toknum, tokval, _, _, _ in tokens:
    if toknum == NAME and tokval == "foo":
        tokval = "bar"
    result.append((toknum, tokval))

print untokenize(result)
</code>```

And the result is:

```<code>def x (y ):
    b =2
    if y ==b :
        bar (y )
</code>```

Yeah I know, the spacing is ugly.  I could not figure out how to maintain the format from the original code, but as far as functionality goes, this does what you want.

Title: Python code reflection and modification

Body:
Perhaps I'm not using the proper term, but I'm looking to take a block of Python code (in Python), get the token tree for the code, make some kind of modification, and re-assemble it to Python.

For instance, consider this block of code:

def x(y):
    b = 2
    if y == b:
        foo(y)

I would like to be able to take this and programmatically do this:

def x(y):
    b = 2
    if y == b:
        bar(y)

I can't imagine that there's not a library that does something like this. Thanks in advance.

EDIT

Perhaps I wasn't entirely clear. I'm looking for a tool to read and manipulate arbitrary code, not code that I'm writing. I'd like to be able to modify code on-the-fly. The project I'm working on is a test app: it uses the Netflix philosophy to try to randomly break the functionality of an app in as many ways as it can, running the test suite each time. When the tests don't fail, there's an indication that there's either a gap in code coverage and/or the code is dead.

Body:
I was curious about this so I looked into the link Apalala posted, here is what I came up with:

from token import NAME
from tokenize import generate_tokens, untokenize
from StringIO import StringIO

source = """def x(y):
    b = 2
    if y == b:
        foo(y)"""
result = []
tokens = generate_tokens(StringIO(source).readline)
for toknum, tokval, _, _, _ in tokens:
    if toknum == NAME and tokval == "foo":
        tokval = "bar"
    result.append((toknum, tokval))

print untokenize(result)

And the result is:

def x (y ):
    b =2
    if y ==b :
        bar (y )

Yeah I know, the spacing is ugly.  I could not figure out how to maintain the format from the original code, but as far as functionality goes, this does what you want.


问:
git push: refs/heads/my/subbranch exists, cannot create
Is this not possible to create somme sub-sub-folder in a repo on a server?

if i do:

```<code>git push origin dev/master
</code>```

everything work find

but if i do

```<code>git push origin dev/sub/master
</code>```

i got this:

```<code>error: 'refs/heads/dev/sub' exists; cannot create 'refs/heads/dev/sub/master'
</code>```

i checked with git branch -r and directly with ssh, there isn't dev/sub folder already created.

what's wrong?

答:
```<code>#!/usr/bin/env bash
echo "update-ref delete refs/tags"
log="git-update-ref-errors.log"
script="./git-update-ref-exist-tags-delete.sh"
git_command="git update-ref -d refs/tags"

echo "log errors from ${git_command} to ${log}"
${git_command} 2>&1 | > ${log}
echo "show errors to ${log}"
cat ${log}
echo create ${script}
touch ${script}
echo "add execute (+x) permissions to ${script}"
chmod +x ${script}
echo "generate ${script} from errors log ${log}"
${git_command} 2>&1 | grep 'exists' | sed -n "s:.*\: 'refs/tags/\(.*\)' exists;.*:git tag -d '\1':p" >> ${script}
echo "execute ${script}"
${script}

echo fetch
log="git-fetch-errors.log"
script="./git-fetch-exist-tags-delete.sh"
git_command="git fetch"
echo "log errors from ${git_command} to ${log}"
${git_command} 2>&1 | > ${log}
echo "show errors from ${log}"
cat ${log}
echo create ${script}
touch ${script}
echo "add execute (+x) permissions to ${script}"
chmod +x ${script}
echo "generate ${script} from errors log ${log}"
${git_command} 2>&1 | grep 'exists' | sed -n "s:.*\: 'refs/tags/\(.*\)' exists;.*:git tag -d '\1':p" >> ${script}
echo "execute ${script}"
${script}
git fetch

echo pull
log="git-pull-errors.log"
script="./git-pull-exist-tags-delete.sh"
git_command="git pull"
echo "log errors from ${git_command} to ${log}"
${git_command} 2>&1 | > ${log}
echo "show errors from ${log}"
cat ${log}
echo create ${script}
touch ${script}
echo "add execute (+x) permissions to ${script}"
chmod +x ${script}
echo "generate ${script} from errors log ${log}"
${git_command} 2>&1 | grep 'exists' | sed -n "s:.*\: 'refs/tags/\(.*\)' exists;.*:git tag -d '\1':p" >> ${script}
echo "execute ${script}"
${script}
git pull

echo push
log="git-push-errors.log"
script="./git-push-exist-tags-delete.sh"
git_command="git push"
echo "log errors from ${git_command} to ${log}"
${git_command} 2>&1 | > ${log}
echo "show errors from ${log}"
cat ${log}
echo create ${script}
touch ${script}
echo "add execute (+x) permissions to ${script}"
chmod +x ${script}
echo "generate ${script} from errors log ${log}"
${git_command} 2>&1 | grep 'exists' | sed -n "s:.*\: 'refs/tags/\(.*\)' exists;.*:git tag -d '\1':p" >> ${script}
echo "execute ${script}"
${script}
git push
</code>```

The script above will log errors to XXX-errors.log and fix them by generating and running a XXX-exist-tags-delete.sh automatically from the XXX-errors.log using the following commands:

git update-ref -d refs/tags

git fetch

git pull

git push

ContentLicense: CC BY-SA 4.0

Body:
Is this not possible to create somme sub-sub-folder in a repo on a server?

if i do:

git push origin dev/master

everything work find

but if i do

git push origin dev/sub/master

i got this:

error: 'refs/heads/dev/sub' exists; cannot create 'refs/heads/dev/sub/master'

i checked with git branch -r and directly with ssh, there isn't dev/sub folder already created.

what's wrong?

Body:
#!/usr/bin/env bash
echo "update-ref delete refs/tags"
log="git-update-ref-errors.log"
script="./git-update-ref-exist-tags-delete.sh"
git_command="git update-ref -d refs/tags"

echo "log errors from ${git_command} to ${log}"
${git_command} 2>&1 | > ${log}
echo "show errors to ${log}"
cat ${log}
echo create ${script}
touch ${script}
echo "add execute (+x) permissions to ${script}"
chmod +x ${script}
echo "generate ${script} from errors log ${log}"
${git_command} 2>&1 | grep 'exists' | sed -n "s:.*\: 'refs/tags/\(.*\)' exists;.*:git tag -d '\1':p" >> ${script}
echo "execute ${script}"
${script}

echo fetch
log="git-fetch-errors.log"
script="./git-fetch-exist-tags-delete.sh"
git_command="git fetch"
echo "log errors from ${git_command} to ${log}"
${git_command} 2>&1 | > ${log}
echo "show errors from ${log}"
cat ${log}
echo create ${script}
touch ${script}
echo "add execute (+x) permissions to ${script}"
chmod +x ${script}
echo "generate ${script} from errors log ${log}"
${git_command} 2>&1 | grep 'exists' | sed -n "s:.*\: 'refs/tags/\(.*\)' exists;.*:git tag -d '\1':p" >> ${script}
echo "execute ${script}"
${script}
git fetch

echo pull
log="git-pull-errors.log"
script="./git-pull-exist-tags-delete.sh"
git_command="git pull"
echo "log errors from ${git_command} to ${log}"
${git_command} 2>&1 | > ${log}
echo "show errors from ${log}"
cat ${log}
echo create ${script}
touch ${script}
echo "add execute (+x) permissions to ${script}"
chmod +x ${script}
echo "generate ${script} from errors log ${log}"
${git_command} 2>&1 | grep 'exists' | sed -n "s:.*\: 'refs/tags/\(.*\)' exists;.*:git tag -d '\1':p" >> ${script}
echo "execute ${script}"
${script}
git pull

echo push
log="git-push-errors.log"
script="./git-push-exist-tags-delete.sh"
git_command="git push"
echo "log errors from ${git_command} to ${log}"
${git_command} 2>&1 | > ${log}
echo "show errors from ${log}"
cat ${log}
echo create ${script}
touch ${script}
echo "add execute (+x) permissions to ${script}"
chmod +x ${script}
echo "generate ${script} from errors log ${log}"
${git_command} 2>&1 | grep 'exists' | sed -n "s:.*\: 'refs/tags/\(.*\)' exists;.*:git tag -d '\1':p" >> ${script}
echo "execute ${script}"
${script}
git push

The script above will log errors to XXX-errors.log and fix them by generating and running a XXX-exist-tags-delete.sh automatically from the XXX-errors.log using the following commands:

git update-ref -d refs/tags

git fetch

git pull

git push


问:
Role of Webpack in Angular's ng serve
I am new to Angular and was wondering what role does Webpack play behind the scene when we ng serve the application. During initial impressions, I have come to know that webpack acts as a build and package tool that groups all the required JS files into separate bundles. I could not, however, find the webpack configuration file and could not figure how angular and webpack come together in the picture.

So when I serve the angular 4 app, this is what is printed on the terminal. Can't exactly understand what is happening behind the scenes.

```<code>webpack: Compiling...
Date: 2017-12-05T07:13:25.436Z
Hash: a6d360a858a29480ebbc
Time: 310ms
chunk {inline} inline.bundle.js, inline.bundle.js.map (inline) 5.83 kB [entry]
chunk {main} main.bundle.js, main.bundle.js.map (main) 35.4 kB {vendor} [initial] [rendered]
kB {vendor} [initial] [rendered]                            ap (polyfills) 200 kB {inline} [initial]chunk {polyfills} polyfills.bundle.js, polyfills.bundle.js.map (polyfills) 200 kB {inline} [initial]
chunk {styles} styles.bundle.js, styles.bundle.js.map (styles) 195 kB {inline} [initial]chunk {vendor} vendor.bundle.js, vendor.bundle.js.map (vendor) 3.65 MB [initial]
webpack: Compiled successfully.
</code>```

Any help would be appreciated.

答:
basically youre totally right!

maybe you want to have a look at the webpack article in the official documentation?
https://angular.io/guide/webpack

btw: webpack is used since late 2016 and has some benefits compared to Broccoli & SystemJS for example AoT and faster build times.

Title: Role of Webpack in Angular's ng serve

Body:
I am new to Angular and was wondering what role does Webpack play behind the scene when we ng serve the application. During initial impressions, I have come to know that webpack acts as a build and package tool that groups all the required JS files into separate bundles. I could not, however, find the webpack configuration file and could not figure how angular and webpack come together in the picture.

So when I serve the angular 4 app, this is what is printed on the terminal. Can't exactly understand what is happening behind the scenes.

webpack: Compiling...
Date: 2017-12-05T07:13:25.436Z
Hash: a6d360a858a29480ebbc
Time: 310ms
chunk {inline} inline.bundle.js, inline.bundle.js.map (inline) 5.83 kB [entry]
chunk {main} main.bundle.js, main.bundle.js.map (main) 35.4 kB {vendor} [initial] [rendered]
kB {vendor} [initial] [rendered]                            ap (polyfills) 200 kB {inline} [initial]chunk {polyfills} polyfills.bundle.js, polyfills.bundle.js.map (polyfills) 200 kB {inline} [initial]
chunk {styles} styles.bundle.js, styles.bundle.js.map (styles) 195 kB {inline} [initial]chunk {vendor} vendor.bundle.js, vendor.bundle.js.map (vendor) 3.65 MB [initial]
webpack: Compiled successfully.

Any help would be appreciated.


问:
Cannot compile interface-based projection in spring
I've got an entity:

```<code>@Entity
class Person {

    @Id
    @GeneratedValue
    private Long id;
    private String firstname, lastname;
    private int age;

    public Person() {
    }
    //getters and setters
</code>```

And a projection interface:

```<code>public interface NamesOnly {

    String getFirstname();
    String getLastname();
}
</code>```

The methods names in projection are exactly the same as getters in the entity class.

My repository:

```<code>public interface PersonRepository extends JpaRepository<Person, Long> {

    List<NamesOnly> findAll();
}
</code>```

I can't compile it.

```<code>test/projectiontest/PersonRepository.java:[20,21] findAll() in test.projectiontest.PersonRepository clashes with findAll() in org.springframework.data.jpa.repository.JpaRepository
return type java.util.List<test.projectiontest.projection.NamesOnly> is not compatible with java.util.List<test.projectiontest.Person>
</code>```

https://docs.spring.io/spring-data/jpa/docs/2.0.2.RELEASE/reference/html/#projections

What I'm doing wrong?

答:
Well, as @M.Deinum has mentioned in the comments, I can't use findAll, because it is already defined in JpaRepository.
Instead of using projection interface I wrote the DTO class:

```<code>public class NamesOnlyDto {

    private String firstname, lastname;

    public NamesOnlyDto(String firstname, String lastname) {
        this.firstname = firstname;
        this.lastname = lastname;
    }

    public String getFirstname() {
        return firstname;
    }

    public String getLastname() {
        return lastname;
    }
}
</code>```

Then I could use it in my repository like this:

```<code>@Query("SELECT new test.projectiontest.projection.NamesOnlyDto(p.firstname, p.lastname) FROM Person p")
List<NamesOnlyDto> findEveryone();
</code>```

It works fine. I'm pretty sure this is a workaround and there is a way to solve this with projection interface, so I leave this question unanswared. I hope someone else provide a better solution.

Body:
I've got an entity:

@Entity
class Person {

    @Id
    @GeneratedValue
    private Long id;
    private String firstname, lastname;
    private int age;

    public Person() {
    }
    //getters and setters

And a projection interface:

public interface NamesOnly {

    String getFirstname();
    String getLastname();
}

The methods names in projection are exactly the same as getters in the entity class.

My repository:

public interface PersonRepository extends JpaRepository<Person, Long> {

    List<NamesOnly> findAll();
}

I can't compile it.

test/projectiontest/PersonRepository.java:[20,21] findAll() in test.projectiontest.PersonRepository clashes with findAll() in org.springframework.data.jpa.repository.JpaRepository
return type java.util.List<test.projectiontest.projection.NamesOnly> is not compatible with java.util.List<test.projectiontest.Person>

https://docs.spring.io/spring-data/jpa/docs/2.0.2.RELEASE/reference/html/#projections

What I'm doing wrong?

Body:
Well, as @M.Deinum has mentioned in the comments, I can't use findAll, because it is already defined in JpaRepository.
Instead of using projection interface I wrote the DTO class:

public class NamesOnlyDto {

    private String firstname, lastname;

    public NamesOnlyDto(String firstname, String lastname) {
        this.firstname = firstname;
        this.lastname = lastname;
    }

    public String getFirstname() {
        return firstname;
    }

    public String getLastname() {
        return lastname;
    }
}

Then I could use it in my repository like this:

@Query("SELECT new test.projectiontest.projection.NamesOnlyDto(p.firstname, p.lastname) FROM Person p")
List<NamesOnlyDto> findEveryone();

It works fine. I'm pretty sure this is a workaround and there is a way to solve this with projection interface, so I leave this question unanswared. I hope someone else provide a better solution.


问:
NodeJS - infinite call on promise functions
I'm looking for a way to call infinitely a functions with promises.
I tried 2 scenarios, one works the other don't.
The aim of the code that doesn't works is to: get data from an API and then store it into a database.

I'm learning promises, can someone explain me why one is working and the other don't ?
Below my codes

Working code
The function is called only once, I'm looking to get it called infinitly

```<code>const request = require('request') //node to facilitate http request
var nano    = require('nano')('http://admin:12345@localhost:5984'); //connect to couchdb using id and password
var db_name  = nano.db.use('bitfinex'); //couchdb database name
var ltc_url = 'https://api.bitfinex.com/v1/pubticker/ltcusd' //entry point
var nonce = new Date().toISOString()  //gives a unique id
                      .replace(/T/, ' ')    // replace T with a space
                      .replace(/\..+/, '')     // delete the dot and everything after

let cleanTheRoom = function() {
      return new Promise(function(resolve, reject) {
        resolve('Cleaned the Room, ');
      });
    };

  let removedTheGarbage = function(msg) {
    return new Promise(function(resolve, reject) {
      resolve(msg + 'removed the garbage, ');
    });
  };

  let getIcecream = function(msg) {
    return new Promise(function(resolve, reject) {
      resolve(msg +'got icecream.');
    });
  };

setInterval(function(){
  cleanTheRoom()
    .then(removedTheGarbage)
    .then(getIcecream)
    .then(function(msg) {
    console.log(msg );
  });
}, 2000);
</code>```

Failing code

```<code>const request = require('request') //node to facilitate http request
    var nano    = require('nano')('http://admin:12345@localhost:5984'); //connect to couchdb using id and password
    var db_name  = nano.db.use('bitfinex'); //couchdb database name
    var ltc_url = 'https://api.bitfinex.com/v1/pubticker/ltcusd' //entry point
    var nonce = new Date().toISOString()  //gives a unique id
                          .replace(/T/, ' ')    // replace T with a space
                          .replace(/\..+/, '')     // delete the dot and everything after

// get current litecoin price from Bitfinex

function getLtcPrice(){
  return new Promise(function(resolve, reject){
    request.get(ltc_url,
        function (error, response, body) {
        var rep = JSON.parse(body);
        var ltc_price = rep.ask;
          resolve (ltc_price)
        if (error){
          reject(ltc_price)
          }
      });
    })
  }

//save current litecoin price to the database

function saveLtcPrice (ltc_price){
      return new Promise(function(resolve, reject){
        resolve(
        db_name.insert({ _id: nonce, currency:"Litecoin", price: ltc_price},
           function(err, body) {
             if (!err)
             console.log(" ltc price : "+ ltc_price +", uploaded to the database ");
          })
          )
      });
    }

setInterval(function(){
  getLtcPrice()
    .then(function(ltcPrice){
      saveLtcPrice(ltcPrice);
    });
}, 2000);
</code>```

答:
Your saveLtcPrice function has a very weird placement of the call to resolve

```<code>function saveLtcPrice (ltc_price){
  return new Promise(function(resolve, reject){
    resolve( /* <--- HERE */
    db_name.insert({ _id: nonce, currency:"Litecoin", price: ltc_price},
       function(err, body) {
         if (!err)
         console.log(" ltc price : "+ ltc_price +", uploaded to the database ");
      })
      )
  });
}
</code>```

Maybe you should call the resolve after the database operation has finished in the final callback.

```<code>function saveLtcPrice (ltc_price){
  return new Promise(function(resolve, reject){
    db_name.insert({ _id: nonce, currency:"Litecoin", price: ltc_price},
       function(err, body) {
         if (!err) {
           resolve(body) /* <-- Move to here */
           console.log(" ltc price : "+ ltc_price +", uploaded to the database ");
         } else {
           reject(err);
         }
       })
  });
}
</code>```

What it appears is that you attempt to resolve with a call to a database async operation.  Since this database operation accepts a callback as a parameter it is very unlikely your promise is resolved with anything other than undefined.

Make sure you handle your promise rejects correctly and try to use .catch() so that you can catch your errors otherwise locating the source of code problems in promises can be difficult.

Body:
I'm looking for a way to call infinitely a functions with promises.
I tried 2 scenarios, one works the other don't.
The aim of the code that doesn't works is to: get data from an API and then store it into a database.

I'm learning promises, can someone explain me why one is working and the other don't ?
Below my codes

Working code
The function is called only once, I'm looking to get it called infinitly

const request = require('request') //node to facilitate http request
var nano    = require('nano')('http://admin:12345@localhost:5984'); //connect to couchdb using id and password
var db_name  = nano.db.use('bitfinex'); //couchdb database name
var ltc_url = 'https://api.bitfinex.com/v1/pubticker/ltcusd' //entry point
var nonce = new Date().toISOString()  //gives a unique id
                      .replace(/T/, ' ')    // replace T with a space
                      .replace(/\..+/, '')     // delete the dot and everything after

let cleanTheRoom = function() {
      return new Promise(function(resolve, reject) {
        resolve('Cleaned the Room, ');
      });
    };

  let removedTheGarbage = function(msg) {
    return new Promise(function(resolve, reject) {
      resolve(msg + 'removed the garbage, ');
    });
  };

  let getIcecream = function(msg) {
    return new Promise(function(resolve, reject) {
      resolve(msg +'got icecream.');
    });
  };

setInterval(function(){
  cleanTheRoom()
    .then(removedTheGarbage)
    .then(getIcecream)
    .then(function(msg) {
    console.log(msg );
  });
}, 2000);

Failing code

const request = require('request') //node to facilitate http request
    var nano    = require('nano')('http://admin:12345@localhost:5984'); //connect to couchdb using id and password
    var db_name  = nano.db.use('bitfinex'); //couchdb database name
    var ltc_url = 'https://api.bitfinex.com/v1/pubticker/ltcusd' //entry point
    var nonce = new Date().toISOString()  //gives a unique id
                          .replace(/T/, ' ')    // replace T with a space
                          .replace(/\..+/, '')     // delete the dot and everything after

// get current litecoin price from Bitfinex

function getLtcPrice(){
  return new Promise(function(resolve, reject){
    request.get(ltc_url,
        function (error, response, body) {
        var rep = JSON.parse(body);
        var ltc_price = rep.ask;
          resolve (ltc_price)
        if (error){
          reject(ltc_price)
          }
      });
    })
  }

//save current litecoin price to the database

function saveLtcPrice (ltc_price){
      return new Promise(function(resolve, reject){
        resolve(
        db_name.insert({ _id: nonce, currency:"Litecoin", price: ltc_price},
           function(err, body) {
             if (!err)
             console.log(" ltc price : "+ ltc_price +", uploaded to the database ");
          })
          )
      });
    }

setInterval(function(){
  getLtcPrice()
    .then(function(ltcPrice){
      saveLtcPrice(ltcPrice);
    });
}, 2000);

Body:
Your saveLtcPrice function has a very weird placement of the call to resolve

function saveLtcPrice (ltc_price){
  return new Promise(function(resolve, reject){
    resolve( /* <--- HERE */
    db_name.insert({ _id: nonce, currency:"Litecoin", price: ltc_price},
       function(err, body) {
         if (!err)
         console.log(" ltc price : "+ ltc_price +", uploaded to the database ");
      })
      )
  });
}

Maybe you should call the resolve after the database operation has finished in the final callback.

function saveLtcPrice (ltc_price){
  return new Promise(function(resolve, reject){
    db_name.insert({ _id: nonce, currency:"Litecoin", price: ltc_price},
       function(err, body) {
         if (!err) {
           resolve(body) /* <-- Move to here */
           console.log(" ltc price : "+ ltc_price +", uploaded to the database ");
         } else {
           reject(err);
         }
       })
  });
}

What it appears is that you attempt to resolve with a call to a database async operation.  Since this database operation accepts a callback as a parameter it is very unlikely your promise is resolved with anything other than undefined.

Make sure you handle your promise rejects correctly and try to use .catch() so that you can catch your errors otherwise locating the source of code problems in promises can be difficult.


问:
JQuery not adding class on click
I'm struggeling with some code, I have code to when I click a
 element it changes the iframe src and removes the class 'active' of all the elements in the .html file and then add the class 'active' to the clicked element.

But the class 'active' never gets added to the clicked element.

JAVASCRIPT

```<code>function loadIframe(url){
    $('.iframe_settings').attr('src', url);
    $('.nav li').removeClass('active');
    $(this).addClass('active');
};
</code>```

HTML

```<code><li class="w-100" id="http://whatever.com/" onclick="return loadIframe(this.id);">
    <p>

        <i class="fa fa-id-badge" aria-hidden="true"></i>
        <span class="nav-label">Intranet</span>

    </p>
</li>
</code>```

答:
You need to correct your code add identifier in correct way.</p>

```<code>function loadIframe(url){
    $('.iframe_settings').attr('src', url);
    $('.nav li').removeClass('active');
    $("#"+url).addClass('active');
};
</code>```

Title: JQuery not adding class on click

Body:
I'm struggeling with some code, I have code to when I click a
 element it changes the iframe src and removes the class 'active' of all the elements in the .html file and then add the class 'active' to the clicked element.

But the class 'active' never gets added to the clicked element.

JAVASCRIPT

function loadIframe(url){
    $('.iframe_settings').attr('src', url);
    $('.nav li').removeClass('active');
    $(this).addClass('active');
};

HTML

        Intranet

Body:
You need to correct your code add identifier in correct way.

function loadIframe(url){
    $('.iframe_settings').attr('src', url);
    $('.nav li').removeClass('active');
    $("#"+url).addClass('active');
};


问:
SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: 'column_name' in Laravel
Laravel Multiple Data Insert Error

SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: '' for column 'unit_id' at row 2 (SQL: insert into product_prices (created_at, product_id, unit_id, updated_at) values (2016-12-06 06:56:01, 27, 1,2016-12-06 06:56:01), (2016-12-06 06:56:01,27, , 2016-12-06 06:56:01))

But my unit_id field in nullable();
Please someone help me
Here column_name=unit_id

答:
Just had the same issue and in my case it was a silly mistake in my controller.

What I did was I returned the whole object instead of just the id, like so:

```<code>  public function store($id, Request $request) {

    $post = Post::find($id);

    $comment = new Comment;
    $comment->text = $request->comment;
    $comment->post_id = $post; <--- HERE IS THE MISTAKE
    $comment->post_id = $post->id; <--- HERE IS THE FIX
    $comment->user_id = Auth::id();

    $comment->save();

    return back();

  }
</code>```

Body:
Just had the same issue and in my case it was a silly mistake in my controller.

What I did was I returned the whole object instead of just the id, like so:

  public function store($id, Request $request) {

    $post = Post::find($id);

    $comment = new Comment;
    $comment->text = $request->comment;
    $comment->post_id = $post; <--- HERE IS THE MISTAKE
    $comment->post_id = $post->id; <--- HERE IS THE FIX
    $comment->user_id = Auth::id();

    $comment->save();

    return back();

  }


问:
BLE device writeCharacteristic failing
Trying to get data from a BLE blood pressure device. Docs say that the date/time must be synced each time the device is connected.
Code:

```<code>interactionSub = Observable.concat(
        deviceConnection
                .writeCharacteristic( ReactiveBluetoothHelpers.DATE_TIME_CHARACTERISTIC_UUID, testDateTime )
                .doOnSubscribe(() -> Log.d(TAG, "doOnSubscribe called inside writeCharacteristic!"))
                .doOnError(Error -> Log.e(TAG, "doOnError called inside writeCharacteristic. " + Error.getMessage()))
                .doOnNext(bytes -> Log.d(TAG, "doOnNext called inside writeCharacteristic."))
                .delay( 500L, TimeUnit.MILLISECONDS )
                .ignoreElements(),
        deviceConnection
                .setupIndication( ReactiveBluetoothHelpers.BLOOD_PRESSURE_MEASUREMENT_UUID )
                .doOnNext( indicationObservable -> {
                    Log.d(TAG, "Blood Pressure measurement indication has been set up.");
                } )
                .flatMap(indicationObservable -> indicationObservable) //
)  // end of concat
        .subscribe(
                this::handleBpMeasurement,
                this::handleBpMeasurementError
        );
</code>```

The device connects and is subscribed but the attempt to write the Characteristic causes an error. The error message from the BleDisconnectedException is just "Disconnected from F4:5E:AB:10:DF:5C" without explanation.

I can't imagine where this error is coming from. The test date/time I'm trying to write has valid values for year (16-bit little-endian) and the other 1-byte quantities.

Typical log sequence:

```<code>12-04 15:47:46.617 16544-16612/com.calderadev.truecareccm.truecareservice D/RxBle#ClientOperationQueue:   QUEUED ConnectOperation(13884208)
12-04 15:47:46.618 16544-16571/com.calderadev.truecareccm.truecareservice D/BluetoothGatt: unregisterApp() - mClientIf=8
12-04 15:47:46.621 16544-16565/com.calderadev.truecareccm.truecareservice D/RxBle#ClientOperationQueue: FINISHED DisconnectOperation(252854751)
12-04 15:47:46.624 16544-16565/com.calderadev.truecareccm.truecareservice D/RxBle#ClientOperationQueue:  STARTED ConnectOperation(13884208)
12-04 15:47:46.630 16544-16571/com.calderadev.truecareccm.truecareservice D/BluetoothGatt: connect() - device: F4:5E:AB:10:DF:5C, auto: false
12-04 15:47:46.630 16544-16571/com.calderadev.truecareccm.truecareservice D/BluetoothGatt: registerApp()
12-04 15:47:46.630 16544-16571/com.calderadev.truecareccm.truecareservice D/BluetoothGatt: registerApp() - UUID=91617ce4-e91f-4117-acd4-95a1b2acbf29
12-04 15:47:46.633 16544-16575/com.calderadev.truecareccm.truecareservice D/BluetoothGatt: onClientRegistered() - status=0 clientIf=8
12-04 15:47:47.042 16544-16575/com.calderadev.truecareccm.truecareservice D/BluetoothGatt: onClientConnectionState() - status=0 clientIf=8 device=F4:5E:AB:10:DF:5C
12-04 15:47:47.043 16544-16575/com.calderadev.truecareccm.truecareservice D/RxBle#BluetoothGatt: onConnectionStateChange newState=2 status=0
12-04 15:47:47.044 16544-16575/com.calderadev.truecareccm.truecareservice D/BluetoothGatt: onClientConnectionState() - status=62 clientIf=8 device=F4:5E:AB:10:DF:5C
12-04 15:47:47.044 16544-16575/com.calderadev.truecareccm.truecareservice D/RxBle#BluetoothGatt: onConnectionStateChange newState=0 status=62
12-04 15:47:47.045 16544-16575/com.calderadev.truecareccm.truecareservice I/RxBle#ConnectionOperationQueue: Connection operations queue to be terminated (F4:5E:AB:10:DF:5C)
12-04 15:47:47.047 16544-16565/com.calderadev.truecareccm.truecareservice D/RxBle#ClientOperationQueue: FINISHED ConnectOperation(13884208)
12-04 15:47:47.054 16544-16612/com.calderadev.truecareccm.truecareservice D/BPMonitor: We have connected to A&D_UA-651BLE_10DF5C with MAC F4:5E:AB:10:DF:5C
12-04 15:47:47.062 16544-16611/com.calderadev.truecareccm.truecareservice D/RxBle#Executors$RunnableAdapter: Terminated.
12-04 15:47:47.083 16544-16612/com.calderadev.truecareccm.truecareservice D/BPMonitor: doOnSubscribe called inside writeCharacteristic!
12-04 15:47:47.100 16544-16612/com.calderadev.truecareccm.truecareservice E/BPMonitor: doOnError called inside writeCharacteristic. Disconnected from F4:5E:AB:10:DF:5C
12-04 15:47:47.118 16544-16612/com.calderadev.truecareccm.truecareservice D/RxBle#ClientOperationQueue:   QUEUED DisconnectOperation(246198672)
12-04 15:47:47.120 16544-16565/com.calderadev.truecareccm.truecareservice D/RxBle#ClientOperationQueue:  STARTED DisconnectOperation(246198672)
12-04 15:47:47.121 16544-16571/com.calderadev.truecareccm.truecareservice D/BluetoothManager: getConnectionState()
12-04 15:47:47.121 16544-16571/com.calderadev.truecareccm.truecareservice D/BluetoothManager: getConnectedDevices
12-04 15:47:47.125 16544-16612/com.calderadev.truecareccm.truecareservice D/RxBle#ClientOperationQueue:   QUEUED ConnectOperation(589767105)
12-04 15:47:47.125 16544-16571/com.calderadev.truecareccm.truecareservice D/BluetoothGatt: close()
12-04 15:47:47.127 16544-16571/com.calderadev.truecareccm.truecareservice D/BluetoothGatt: unregisterApp() - mClientIf=8
12-04 15:47:47.131 16544-16565/com.calderadev.truecareccm.truecareservice D/RxBle#ClientOperationQueue: FINISHED DisconnectOperation(246198672)
</code>```

答:
As you can see in the logs the onConnectionStateChange() is called with status=62 which corresponds to 0x3E. The Android Sources point to:

```<code>#define GATT_CONN_FAIL_ESTABLISH    HCI_ERR_CONN_FAILED_ESTABLISHMENT /* 0x03E connection fail to establish  */
</code>```

So it seems that the connection is not really established on the lower layers of the OS though it is reported as connected first:

```<code>12-04 15:47:47.043 16544-16575/com.calderadev.truecareccm.truecareservice D/RxBle#BluetoothGatt: onConnectionStateChange newState=2 status=0
12-04 15:47:47.044 16544-16575/com.calderadev.truecareccm.truecareservice D/RxBle#BluetoothGatt: onConnectionStateChange newState=0 status=62
</code>```

Title: BLE device writeCharacteristic failing

Body:
Trying to get data from a BLE blood pressure device. Docs say that the date/time must be synced each time the device is connected.
Code:

interactionSub = Observable.concat(
        deviceConnection
                .writeCharacteristic( ReactiveBluetoothHelpers.DATE_TIME_CHARACTERISTIC_UUID, testDateTime )
                .doOnSubscribe(() -> Log.d(TAG, "doOnSubscribe called inside writeCharacteristic!"))
                .doOnError(Error -> Log.e(TAG, "doOnError called inside writeCharacteristic. " + Error.getMessage()))
                .doOnNext(bytes -> Log.d(TAG, "doOnNext called inside writeCharacteristic."))
                .delay( 500L, TimeUnit.MILLISECONDS )
                .ignoreElements(),
        deviceConnection
                .setupIndication( ReactiveBluetoothHelpers.BLOOD_PRESSURE_MEASUREMENT_UUID )
                .doOnNext( indicationObservable -> {
                    Log.d(TAG, "Blood Pressure measurement indication has been set up.");
                } )
                .flatMap(indicationObservable -> indicationObservable) //
)  // end of concat
        .subscribe(
                this::handleBpMeasurement,
                this::handleBpMeasurementError
        );

The device connects and is subscribed but the attempt to write the Characteristic causes an error. The error message from the BleDisconnectedException is just "Disconnected from F4:5E:AB:10:DF:5C" without explanation.

I can't imagine where this error is coming from. The test date/time I'm trying to write has valid values for year (16-bit little-endian) and the other 1-byte quantities.

Typical log sequence:

12-04 15:47:46.617 16544-16612/com.calderadev.truecareccm.truecareservice D/RxBle#ClientOperationQueue:   QUEUED ConnectOperation(13884208)
12-04 15:47:46.618 16544-16571/com.calderadev.truecareccm.truecareservice D/BluetoothGatt: unregisterApp() - mClientIf=8
12-04 15:47:46.621 16544-16565/com.calderadev.truecareccm.truecareservice D/RxBle#ClientOperationQueue: FINISHED DisconnectOperation(252854751)
12-04 15:47:46.624 16544-16565/com.calderadev.truecareccm.truecareservice D/RxBle#ClientOperationQueue:  STARTED ConnectOperation(13884208)
12-04 15:47:46.630 16544-16571/com.calderadev.truecareccm.truecareservice D/BluetoothGatt: connect() - device: F4:5E:AB:10:DF:5C, auto: false
12-04 15:47:46.630 16544-16571/com.calderadev.truecareccm.truecareservice D/BluetoothGatt: registerApp()
12-04 15:47:46.630 16544-16571/com.calderadev.truecareccm.truecareservice D/BluetoothGatt: registerApp() - UUID=91617ce4-e91f-4117-acd4-95a1b2acbf29
12-04 15:47:46.633 16544-16575/com.calderadev.truecareccm.truecareservice D/BluetoothGatt: onClientRegistered() - status=0 clientIf=8
12-04 15:47:47.042 16544-16575/com.calderadev.truecareccm.truecareservice D/BluetoothGatt: onClientConnectionState() - status=0 clientIf=8 device=F4:5E:AB:10:DF:5C
12-04 15:47:47.043 16544-16575/com.calderadev.truecareccm.truecareservice D/RxBle#BluetoothGatt: onConnectionStateChange newState=2 status=0
12-04 15:47:47.044 16544-16575/com.calderadev.truecareccm.truecareservice D/BluetoothGatt: onClientConnectionState() - status=62 clientIf=8 device=F4:5E:AB:10:DF:5C
12-04 15:47:47.044 16544-16575/com.calderadev.truecareccm.truecareservice D/RxBle#BluetoothGatt: onConnectionStateChange newState=0 status=62
12-04 15:47:47.045 16544-16575/com.calderadev.truecareccm.truecareservice I/RxBle#ConnectionOperationQueue: Connection operations queue to be terminated (F4:5E:AB:10:DF:5C)
12-04 15:47:47.047 16544-16565/com.calderadev.truecareccm.truecareservice D/RxBle#ClientOperationQueue: FINISHED ConnectOperation(13884208)
12-04 15:47:47.054 16544-16612/com.calderadev.truecareccm.truecareservice D/BPMonitor: We have connected to A&D_UA-651BLE_10DF5C with MAC F4:5E:AB:10:DF:5C
12-04 15:47:47.062 16544-16611/com.calderadev.truecareccm.truecareservice D/RxBle#Executors$RunnableAdapter: Terminated.
12-04 15:47:47.083 16544-16612/com.calderadev.truecareccm.truecareservice D/BPMonitor: doOnSubscribe called inside writeCharacteristic!
12-04 15:47:47.100 16544-16612/com.calderadev.truecareccm.truecareservice E/BPMonitor: doOnError called inside writeCharacteristic. Disconnected from F4:5E:AB:10:DF:5C
12-04 15:47:47.118 16544-16612/com.calderadev.truecareccm.truecareservice D/RxBle#ClientOperationQueue:   QUEUED DisconnectOperation(246198672)
12-04 15:47:47.120 16544-16565/com.calderadev.truecareccm.truecareservice D/RxBle#ClientOperationQueue:  STARTED DisconnectOperation(246198672)
12-04 15:47:47.121 16544-16571/com.calderadev.truecareccm.truecareservice D/BluetoothManager: getConnectionState()
12-04 15:47:47.121 16544-16571/com.calderadev.truecareccm.truecareservice D/BluetoothManager: getConnectedDevices
12-04 15:47:47.125 16544-16612/com.calderadev.truecareccm.truecareservice D/RxBle#ClientOperationQueue:   QUEUED ConnectOperation(589767105)
12-04 15:47:47.125 16544-16571/com.calderadev.truecareccm.truecareservice D/BluetoothGatt: close()
12-04 15:47:47.127 16544-16571/com.calderadev.truecareccm.truecareservice D/BluetoothGatt: unregisterApp() - mClientIf=8
12-04 15:47:47.131 16544-16565/com.calderadev.truecareccm.truecareservice D/RxBle#ClientOperationQueue: FINISHED DisconnectOperation(246198672)

Body:
As you can see in the logs the onConnectionStateChange() is called with status=62 which corresponds to 0x3E. The Android Sources point to:

#define GATT_CONN_FAIL_ESTABLISH    HCI_ERR_CONN_FAILED_ESTABLISHMENT /* 0x03E connection fail to establish  */

So it seems that the connection is not really established on the lower layers of the OS though it is reported as connected first:

12-04 15:47:47.043 16544-16575/com.calderadev.truecareccm.truecareservice D/RxBle#BluetoothGatt: onConnectionStateChange newState=2 status=0
12-04 15:47:47.044 16544-16575/com.calderadev.truecareccm.truecareservice D/RxBle#BluetoothGatt: onConnectionStateChange newState=0 status=62


问:
c# .net: Extend existing class with method that should be overriden when initialized
Is something like that possible?

Let's say I have the String Class. And I want to add a Method DoStringCalc(). Now I want one Class which holds all these special strings and calls DoStringCalc() on all of them. But every String can have a different logic in DoStringCalc() and there can be thousands of them.

Most logical for me (coming from java) would be to override the Method DoStringCalc() when initializing a new String. e.g:

```<code>String hello = new String() {
    public override DoStringCalc() {
        //do something here
    }
}
</code>```

How is this solved in C#?

答:
If I understand correctly interface is what you are looking for.

Create an interface that requires a method DoStringCalc(). Then have all the string classes inherit the interface and implement their DoStringCalc() method. After that you can e.g. use a strongly typed List List<IExampleInterface> that allows instances of any of the string classes and call their respective DoStringCalc() from it.

Body:
Is something like that possible?

Let's say I have the String Class. And I want to add a Method DoStringCalc(). Now I want one Class which holds all these special strings and calls DoStringCalc() on all of them. But every String can have a different logic in DoStringCalc() and there can be thousands of them.

Most logical for me (coming from java) would be to override the Method DoStringCalc() when initializing a new String. e.g:

String hello = new String() {
    public override DoStringCalc() {
        //do something here
    }
}

How is this solved in C#?


问:
Problems with <select> filter
i coded an select filter for my website:

             Filter

```<code>        <div class="row">

                <select class="event-type-select" id="selection" >
                    <optgroup label="categorygroup1">
                        <option value="category1">category1</option>
                    </optgroup>
                    <optgroup label="categorygroup2">
                        <option value="category2">category2n</option>
                        <option value="category3">category3</option>
                    </optgroup>
                    <optgroup label="categorygroup3">
                        <option value="category4">category4</option>
                    </optgroup>
                </select>

        </div>

        <div class="row">

            <button type="submit" class="btn btn-default"> filter </button>

        </div>
    </form>
</code>```

before selecting anything in the "selection-window" on the website you read "category1". i guess thats default(?).

but if i selected a category (and that works: you can read in the "selection-window" e.g. category3) and then click on the "filter"-button the website refreshes but in the "selection-window" you again read "category1" and not the selected category e.g "category3". i guess the selection doesn't work right.

how can i solve this that when clicking the button you still read your selected category?

also i want to display the selected option on a different part of the website.

my current code for this:

```<code>    <script type='text/javascript'>
        var m = document.getElementById("selection").value;}
        document.write(m);

    </script>
</code>```

that as well doesn't work.

i hope you can understand what i mean, my english is pretty bad. sorry for that.

答:
The script has an error, you should use a function:

            function test()
            {
                var m = document.getElementById("selection").value;
                alert(m);
            }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>

<html>

    <head>
        <title>Test</title>
    </head>

    <body>
        <div class="row">

            <select id="selection" class="event-type-select">
                <optgroup label="categorygroup1">
                    <option value="category1">category1</option>
                </optgroup>
                <optgroup label="categorygroup2">
                    <option value="category2" selected="selected">category2n</option> <!-- with selected="selected" you set the default -->
                    <option value="category3">category3</option>
                </optgroup>
                <optgroup label="categorygroup3">
                    <option value="category4">category4</option>
                </optgroup>
            </select>

        </div>

        <div class="row">

            <button type="submit" class="btn btn-default" onclick="test()"> filter </button>
        </div>

    </body>

</html></code>```

Title: Problems with <select> filter

Body:
i coded an select filter for my website:

             Filter

                <select class="event-type-select" id="selection" >
                    <optgroup label="categorygroup1">
                        <option value="category1">category1</option>
                    </optgroup>
                    <optgroup label="categorygroup2">
                        <option value="category2">category2n</option>
                        <option value="category3">category3</option>
                    </optgroup>
                    <optgroup label="categorygroup3">
                        <option value="category4">category4</option>
                    </optgroup>
                </select>

            <button type="submit" class="btn btn-default"> filter </button>

    </form>

before selecting anything in the "selection-window" on the website you read "category1". i guess thats default(?).

but if i selected a category (and that works: you can read in the "selection-window" e.g. category3) and then click on the "filter"-button the website refreshes but in the "selection-window" you again read "category1" and not the selected category e.g "category3". i guess the selection doesn't work right.

how can i solve this that when clicking the button you still read your selected category?

also i want to display the selected option on a different part of the website.

my current code for this:

that as well doesn't work.

i hope you can understand what i mean, my english is pretty bad. sorry for that.

Body:
The script has an error, you should use a function:

            function test()
            {
                var m = document.getElementById("selection").value;
                alert(m);
            }

<!DOCTYPE html>

<html>

    <head>
        <title>Test</title>
    </head>

    <body>
        <div class="row">

            <select id="selection" class="event-type-select">
                <optgroup label="categorygroup1">
                    <option value="category1">category1</option>
                </optgroup>
                <optgroup label="categorygroup2">
                    <option value="category2" selected="selected">category2n</option> <!-- with selected="selected" you set the default -->
                    <option value="category3">category3</option>
                </optgroup>
                <optgroup label="categorygroup3">
                    <option value="category4">category4</option>
                </optgroup>
            </select>

        </div>

        <div class="row">

            <button type="submit" class="btn btn-default" onclick="test()"> filter </button>
        </div>

    </body>

</html>