问:
How do I show validation error when users submit the form without selecting anything from the drop-down list in ASP.NET MVC?
In my ASP.NET MVC application, I have a form with drop-down list. If the user did not select a category and submitted the form, I will get exception. So How do I send validation error from the controller to the view? because I don't want to write JavaScript.

This is the drop-down list:

```<code>@Html.DropDownListFor(m => m.Article.CategoryId, new SelectList(Model.Categories, "Id", "Name"), "Select Category", new { @class = "form-control" })
</code>```

I know this way is working but I need that label (Select Category)

```<code> @Html.DropDownListFor(m => m.Article.CategoryId, new SelectList(Model.Categories, "Id", "Name"), null, new { @class = "form-control" })
</code>```

All and New controllers:

```<code>       [HttpPost]
       public ActionResult New(Article article)
        {

            if(ModelState.IsValid)
            {
                string FullName = HttpContext.GetOwinContext()
                    .GetUserManager<ApplicationUserManager>()
                    .FindById(User.Identity.GetUserId()).FullName;

                article.AuthorName = FullName;
                article.UserId = User.Identity.GetUserId();
                db.Aricles.Add(article);
                db.SaveChanges();
                return RedirectToAction("All");
            }
         }

        public ActionResult All()
        {
            var Articles = db.Aricles.ToList();
            return View(Articles);
        }
</code>```

My model:

```<code>  public class Article
{
    public int Id { get; set; }
    [Required]
    public string Title { get; set; }
    [Required]
    public string Body { get; set; }
    public string UserId { get; set; }
    public string AuthorName { get; set; }
    public ApplicationUser User { get; set; }
    public Category Category { get; set; }
    public int CategoryId { get; set; }
}
</code>```

I tried to use [Required] attribute but I don't know why it does not work.

This is a screenshot of the exception click

答: I found the issue after I thought about the comment written by Mannan Bahelim . I don't get validation error because the model in the view was ArticleCategoryViewModel while it should be Article model.

Body:
In my ASP.NET MVC application, I have a form with drop-down list. If the user did not select a category and submitted the form, I will get exception. So How do I send validation error from the controller to the view? because I don't want to write JavaScript.

This is the drop-down list:

@Html.DropDownListFor(m => m.Article.CategoryId, new SelectList(Model.Categories, "Id", "Name"), "Select Category", new { @class = "form-control" })

I know this way is working but I need that label (Select Category)

 @Html.DropDownListFor(m => m.Article.CategoryId, new SelectList(Model.Categories, "Id", "Name"), null, new { @class = "form-control" })

All and New controllers:

       [HttpPost]
       public ActionResult New(Article article)
        {

            if(ModelState.IsValid)
            {
                string FullName = HttpContext.GetOwinContext()
                    .GetUserManager<ApplicationUserManager>()
                    .FindById(User.Identity.GetUserId()).FullName;

                article.AuthorName = FullName;
                article.UserId = User.Identity.GetUserId();
                db.Aricles.Add(article);
                db.SaveChanges();
                return RedirectToAction("All");
            }
         }

        public ActionResult All()
        {
            var Articles = db.Aricles.ToList();
            return View(Articles);
        }

My model:

  public class Article
{
    public int Id { get; set; }
    [Required]
    public string Title { get; set; }
    [Required]
    public string Body { get; set; }
    public string UserId { get; set; }
    public string AuthorName { get; set; }
    public ApplicationUser User { get; set; }
    public Category Category { get; set; }
    public int CategoryId { get; set; }
}

I tried to use [Required] attribute but I don't know why it does not work.

This is a screenshot of the exception click


来源: stackexchange

问:
Find ratio within the grouped data in DataFrame
Here is the data frame - basically, there are two possible types - X and Y for different sources A,B,C,D...

```<code>Source | Type
-------------------
  A    |  X
  A    |  Y
  B    |  X
  C    |  Y
  A    |  X
  D    |  Y
 ...   | ...
</code>```

The ultimate goal is to gather percentage ratio: ratio(X in A) = count(X) / (count(X) + count(Y))

So, in our example, ratio(X in A) = 2 / (2 + 1) = 2 / 3 ~ 0.667

Very simple, but I can't get how to do this in one select using only Streaming API v2 (Structured streaming, Dataframes)?
From my perspective it's feasible only through the map functions...

This is what I have now - scattered counts for X and Y types

```<code>        msgDataFrame
                .select(SOURCE, TYPE)
                .where(msgDataFrame.col(TYPE).equalTo("X"))
                .groupBy(SOURCE)
                .count()
                .show(); // <-- gives me count for 'X'-es

        msgDataFrame
                .select(SOURCE, TYPE)
                .filter(msgDataFrame.col(TYPE).equalTo("Y"))
                .groupBy(SOURCE)
                .count()
                .show(); // <-- gives me count for 'Y'-cs
</code>```

答:
This should work:</p>

```<code>msgDataFrame
.select("SOURCE", "TYPE")
.groupBy("SOURCE").pivot("TYPE", Seq("X", "Y")).agg(count(col("TYPE")))
.withColumn("Ratio", col("X") / (col("X") + col("Y")))
.show
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here is the data frame - basically, there are two possible types - X and Y for different sources A,B,C,D...

Source | Type
-------------------
  A    |  X
  A    |  Y
  B    |  X
  C    |  Y
  A    |  X
  D    |  Y
 ...   | ...

The ultimate goal is to gather percentage ratio: ratio(X in A) = count(X) / (count(X) + count(Y))

So, in our example, ratio(X in A) = 2 / (2 + 1) = 2 / 3 ~ 0.667

Very simple, but I can't get how to do this in one select using only Streaming API v2 (Structured streaming, Dataframes)?
From my perspective it's feasible only through the map functions...

This is what I have now - scattered counts for X and Y types

        msgDataFrame
                .select(SOURCE, TYPE)
                .where(msgDataFrame.col(TYPE).equalTo("X"))
                .groupBy(SOURCE)
                .count()
                .show(); // <-- gives me count for 'X'-es

        msgDataFrame
                .select(SOURCE, TYPE)
                .filter(msgDataFrame.col(TYPE).equalTo("Y"))
                .groupBy(SOURCE)
                .count()
                .show(); // <-- gives me count for 'Y'-cs

Body:
This should work:

msgDataFrame
.select("SOURCE", "TYPE")
.groupBy("SOURCE").pivot("TYPE", Seq("X", "Y")).agg(count(col("TYPE")))
.withColumn("Ratio", col("X") / (col("X") + col("Y")))
.show


问:
How to fix an 'index out of range' error in Python?
I would like to write en auxiliar function which is counting the occurences of every integer between 0 and li[-1], saying that li is a sorted list.

I can't see my mistake... I know what this kind of error message means, but I don't know where the variable j is reaching a limit.

```<code>def aux_compter_occurence(li):
    resu = [0] * (li[-1]+1)
    i = 0
    j = 0
    while i < (li[-1] + 1):
        while li[j] == i:
            resu[i] += 1
            j +=1
        i += 1
    return resu
</code>```

For example, with the input [2,4,4,4,7,8,8], the output should be [0,0,1,0,3,0,0,1,2]

答:
I added "j < len(li)" to your code and now it works.</p>

```<code>def aux_compter_occurence(li):
    resu = [0] * (li[-1]+1)
    i = 0
    j = 0
    while i < (li[-1] + 1):
        while j < len(li) and li[j] == i:
            resu[i] += 1
            j +=1
        i += 1
    return resu

</code>```

Body:
I would like to write en auxiliar function which is counting the occurences of every integer between 0 and li[-1], saying that li is a sorted list.

I can't see my mistake... I know what this kind of error message means, but I don't know where the variable j is reaching a limit.

def aux_compter_occurence(li):
    resu = [0] * (li[-1]+1)
    i = 0
    j = 0
    while i < (li[-1] + 1):
        while li[j] == i:
            resu[i] += 1
            j +=1
        i += 1
    return resu

For example, with the input [2,4,4,4,7,8,8], the output should be [0,0,1,0,3,0,0,1,2]

Body:
I added "j < len(li)" to your code and now it works.

def aux_compter_occurence(li):
    resu = [0] * (li[-1]+1)
    i = 0
    j = 0
    while i < (li[-1] + 1):
        while j < len(li) and li[j] == i:
            resu[i] += 1
            j +=1
        i += 1
    return resu


问:
PHP: mysql_ping - auto reconnect problem
I'm working with an old but very complex piece of php code, which relies on direct mysql access via mysql_* functions. The code uses mysql_ping extensively, but it assumes each mysql_ping call will also reconnect in case it finds out connection timed out.
The problem is that since MySQL 5.0.something mysql_ping doesn't reconnect automatically. In the doc's I found I need to call mysql_options with appropriate flag, but there's no such function as mysql_options. Instead, there's mysqli_options but we literally can't switch to mysqli_* now, it'd take way too much time.
Downgrading MySQL is also not considered as a solution.
Any ideas how to fix that?

Thanks

答:
Upon checking the php manual i found this piece of code that may help you handle the db connection status:</p>

```<code><?php

$conn = mysql_connect('localhost','user','pass');
mysql_select_db('db',$conn);

if (!mysql_ping ($conn)) {
//here is the major trick, you have to close the connection (even though its not currently working) for it to recreate properly.
   mysql_close($conn);
   $conn = mysql_connect('localhost','user','pass');
   mysql_select_db('db',$conn);
}

//run queries knowing that your connection is alive....

?>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Upon checking the php manual i found this piece of code that may help you handle the db connection status:

<?php

$conn = mysql_connect('localhost','user','pass');
mysql_select_db('db',$conn);

if (!mysql_ping ($conn)) {
//here is the major trick, you have to close the connection (even though its not currently working) for it to recreate properly.
   mysql_close($conn);
   $conn = mysql_connect('localhost','user','pass');
   mysql_select_db('db',$conn);
}

//run queries knowing that your connection is alive....

?>


问:
Add "Checked" to radio button, either from cookie, or based on assigned class
I'm including some accessibility tools to a project I'm working on.
I have very little jQuery experience. So far I've followed an excellent guide by James Hibbard, which has brought me quite far. I'm able to change font, size and contrast via radio buttons, and save it to a cookie so the selected choices are remembered.

I'm stuck at getting the radio buttons to show "checked" for the right choice.

Ideally I would load from the cookie, and add "checked" to the appropriate radio button. But alternatively, I could read the class applied to , and use that to determine the checked box.

The script is more or less 1:1 ripped from the guide I followed.

Following the guide, each value is separated by a hyphen ("-"), starting with what it changes plus the actual value, as an example, value="text-sans" for the regular Sans Serif font, and value="text-dyslexic" for the speciality font.

Font selection works wonderfully.

Currently I have no ID for each radio button, I tried to add an ID, and add checked="checked" via jQuery, but I am nowhere near experienced enough to write that from scratch, as evidenced by the past few hour of failing to do so.

```<code>$(document).ready(function() {
    function changeStyles(optValue){
      var property = optValue.split("-")[0];
      removeOldClass(property);
      $("body").addClass(optValue);
      $.cookie('bodyClassList', $("body").attr('class'));
    }

    function removeOldClass(property){
      var classList = $("body").attr('class').split(/\s+/);
      $.each(classList, function(index, item){
        if (item.match(property)){
          $("body").removeClass(item);
        }
      });
    }

    $(".selector").change(function(){
      changeStyles(this.value);
    });

    $(".selector > option").each(function() {
      if(
          $.cookie('bodyClassList') != null &&
          $.cookie('bodyClassList')
           .match($(this).val())
        ){
        $(this).attr("selected","selected");
      }
    });

    $("#reset").click(function(){
      $("body").removeClass();
      $(".selector").each(function(){
        $(this[0]).attr('selected', true);
      })
      $.cookie('bodyClassList', null);
    });

    if($.cookie('bodyClassList') != null) {
      $("body").removeClass();
      $("body").addClass($.cookie('bodyClassList'));
    }
  });
</code>```

No error messages so far, I can echo the contents of the cookie, and seeing as the selection is remembered, I know the cookie bit works, yay!

Any help is most welcome.
Thank you.

答:
Instead of altering the selected attribute, try using prop (reference). Here's a quick demo:

$( document ).ready( function() {
  $( '.checker' ).click( function() {
    $( '#check-me' ).prop( 'checked', true );
  } );

  $( '.unchecker' ).click( function() {
    $( '#check-me' ).prop( 'checked', false );
  } );
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button class="checker">Check this</button>
<button class="unchecker">Uncheck this</button>
<input type="checkbox" id="check-me"></code>```

Let's say you have a cookie with the information mode: dyslexic and want to enable that checkbox on page load. With your pattern of value="text-dyslexic", you could have a function that looks like:

```<code>function activateMode( mode ) {
  $( '.mode-selector' ).find( `input[value="text-${ mode }"]` ).prop( 'checked', true );
}
</code>```

Where mode is one of your options 'dyslexic' or 'sans'. Call the function on page load with the cookie value to activate the element, which could then trigger a change event handler to execute the desired effects. The ${} notation is ES6 string interpolation in case that looks unfamiliar, though this will work without it (just make sure to update the syntax).

Body:
I'm including some accessibility tools to a project I'm working on.
I have very little jQuery experience. So far I've followed an excellent guide by James Hibbard, which has brought me quite far. I'm able to change font, size and contrast via radio buttons, and save it to a cookie so the selected choices are remembered.

I'm stuck at getting the radio buttons to show "checked" for the right choice.

Ideally I would load from the cookie, and add "checked" to the appropriate radio button. But alternatively, I could read the class applied to , and use that to determine the checked box.

The script is more or less 1:1 ripped from the guide I followed.

Following the guide, each value is separated by a hyphen ("-"), starting with what it changes plus the actual value, as an example, value="text-sans" for the regular Sans Serif font, and value="text-dyslexic" for the speciality font.

Font selection works wonderfully.

Currently I have no ID for each radio button, I tried to add an ID, and add checked="checked" via jQuery, but I am nowhere near experienced enough to write that from scratch, as evidenced by the past few hour of failing to do so.

$(document).ready(function() {
    function changeStyles(optValue){
      var property = optValue.split("-")[0];
      removeOldClass(property);
      $("body").addClass(optValue);
      $.cookie('bodyClassList', $("body").attr('class'));
    }

    function removeOldClass(property){
      var classList = $("body").attr('class').split(/\s+/);
      $.each(classList, function(index, item){
        if (item.match(property)){
          $("body").removeClass(item);
        }
      });
    }

    $(".selector").change(function(){
      changeStyles(this.value);
    });

    $(".selector > option").each(function() {
      if(
          $.cookie('bodyClassList') != null &&
          $.cookie('bodyClassList')
           .match($(this).val())
        ){
        $(this).attr("selected","selected");
      }
    });

    $("#reset").click(function(){
      $("body").removeClass();
      $(".selector").each(function(){
        $(this[0]).attr('selected', true);
      })
      $.cookie('bodyClassList', null);
    });

    if($.cookie('bodyClassList') != null) {
      $("body").removeClass();
      $("body").addClass($.cookie('bodyClassList'));
    }
  });

No error messages so far, I can echo the contents of the cookie, and seeing as the selection is remembered, I know the cookie bit works, yay!

Any help is most welcome.
Thank you.

Body:
Instead of altering the selected attribute, try using prop (reference). Here's a quick demo:

$( document ).ready( function() {
  $( '.checker' ).click( function() {
    $( '#check-me' ).prop( 'checked', true );
  } );

  $( '.unchecker' ).click( function() {
    $( '#check-me' ).prop( 'checked', false );
  } );
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button class="checker">Check this</button>
<button class="unchecker">Uncheck this</button>
<input type="checkbox" id="check-me">

Let's say you have a cookie with the information mode: dyslexic and want to enable that checkbox on page load. With your pattern of value="text-dyslexic", you could have a function that looks like:

function activateMode( mode ) {
  $( '.mode-selector' ).find( `input[value="text-${ mode }"]` ).prop( 'checked', true );
}

Where mode is one of your options 'dyslexic' or 'sans'. Call the function on page load with the cookie value to activate the element, which could then trigger a change event handler to execute the desired effects. The ${} notation is ES6 string interpolation in case that looks unfamiliar, though this will work without it (just make sure to update the syntax).


问:
Django restful API - get user id with token
How to obtain User ID from Django API having authentication token?
Basically, I want to send authentication token and get back User id.
I have tried this solution: How can I return user ID with token in Django?
but it is returning token with provided username and password, which is not what I want.</p>

答:
In the perform_create method you can assign the user to your model</p>

```<code>class EmailViewSet(viewsets.ModelViewSet):
    authentication_classes = (TokenAuthentication)
    permission_classes = (IsAuthenticated,)
    queryset = Email.objects.all()
    serializer_class = EmailSerializer

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)
</code>```

Body:
In the perform_create method you can assign the user to your model

class EmailViewSet(viewsets.ModelViewSet):
    authentication_classes = (TokenAuthentication)
    permission_classes = (IsAuthenticated,)
    queryset = Email.objects.all()
    serializer_class = EmailSerializer

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)


问:
c# - using : bad practice to use?
I have read more that year ago that there are a few bad practice to use </p>

```<code>using (some code) {

}
</code>```

<p>. Could someone explain me all these bad practice?
Thanks.</p>

答:
No - it isn't bad practice at all - in many cases it is extremely good practice.

Using the "using" approach, you can write code knowing that IDisposable types are automatically disposed of as soon as they go out of scope, meaning you don't need to manually call Dispose() at every exit point to your code.

Having said that, you can certainly come up with some bad usages of Dispose(), but it is not intrinsically bad, and more often than not is good.

Title: c# - using : bad practice to use?

Body:
I have read more that year ago that there are a few bad practice to use

using (some code) {

}

. Could someone explain me all these bad practice?
Thanks.


问:
Where to use CalendarPickerView's highlight() so that it has effect?
IDEA:

I want to highlight some days in the calendarPickerView to indicate that user cannot choose them.

WHAT I DO:

These days are fetched from a webservice using Retrofit. The problem is that retrofit takes some time in order to give me the result and because of that the calendarPickerView is already drawn and because of that highlight() method doesn't have any effect...!

MY THOUGHTS:

Somehow make the fragment wait for retrofit call to finish before drawing.

Call some method in CalendarPickerView so that I see the effects(I tried invalidate() but it did not work)

I don't get it why CalendarPickerView does not redraw himself after calling highlight() method.
Does anyone know why I cannot see the effects of this method right away??

答:
Actually it was a silly mistake. The CalendarPickerView is redrawing itself every time I call its highligh() method.

What I did was that for some reason I called init() multiple time in different lines:

```<code>calendarViewSquare.init(prevYear.getTime(), nextYear.getTime())
                .inMode(CalendarPickerView.SelectionMode.MULTIPLE)
                .withSelectedDates(dates);
</code>```

and when you do that I observed that everything is cleared, meaning you lose your highlighted days. Which means that if you have setted your highlighted days and then call init again then you will not see the results..

Body:
Actually it was a silly mistake. The CalendarPickerView is redrawing itself every time I call its highligh() method.

What I did was that for some reason I called init() multiple time in different lines:

calendarViewSquare.init(prevYear.getTime(), nextYear.getTime())
                .inMode(CalendarPickerView.SelectionMode.MULTIPLE)
                .withSelectedDates(dates);

and when you do that I observed that everything is cleared, meaning you lose your highlighted days. Which means that if you have setted your highlighted days and then call init again then you will not see the results..


问:
Move generated 0's to the beginning of the array
I would like to put all the seed [i] values to the right, causing the zeros to be left.
However, if the seed [i] = 0 I want this 0 to be on the right. For example, the value 1056 can be possible because if I chose that seed[i] to be 0.

// Download Function
function download(fileName, text) {
    let element = document.createElement('a');
    element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    element.setAttribute('download', fileName);

    element.style.display = 'none';
    document.body.appendChild(element);

    element.click();

    document.body.removeChild(element);
}
function genBatch (seed) {
    let result = new Array(4);
    for (var i = 0; i < 4; i++) {
        result[i] = seed[i] || "0";
    }
    return result.join("");
}

// Generate File
document.getElementById("generate").addEventListener("click", function(){

    let batch = document.getElementById("batchNumber").value;
    /* /header2 */
    let text =  genBatch(batch) + "  ";

    let fileName = document.getElementById("fileName").value + ".txt";

    download(fileName, text);
}, false);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
  <body>
    <div class="container">
          <label for="batchNumber" class="font-weight-bold">Batch Number:</label>
          <input id="batchNumber" type="number" maxlength="4" size="4"/>
          <label for="fileName" class="font-weight-bold">File Name:</label>
          <input id="fileName" type="text"/>
    </div>
    <button id="generate" type="button" class="btn btn-light font-weight-bold mx-auto">Generate File</button>
    <script src="js/app.js"></script>
  </body>
</html></code>```

答:
Use .toLocaleString() with the minimumIntegerDigits option.

const padZ = (num, min) => num.toLocaleString('en-US',{
  minimumIntegerDigits:min,useGrouping:false
});

console.log(padZ(4,4))
console.log(padZ(40,4))
console.log(padZ(400,4))
console.log(padZ(4000,4))```

Body:
I would like to put all the seed [i] values to the right, causing the zeros to be left.
However, if the seed [i] = 0 I want this 0 to be on the right. For example, the value 1056 can be possible because if I chose that seed[i] to be 0.

// Download Function
function download(fileName, text) {
    let element = document.createElement('a');
    element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    element.setAttribute('download', fileName);

    element.style.display = 'none';
    document.body.appendChild(element);

    element.click();

    document.body.removeChild(element);
}
function genBatch (seed) {
    let result = new Array(4);
    for (var i = 0; i < 4; i++) {
        result[i] = seed[i] || "0";
    }
    return result.join("");
}

// Generate File
document.getElementById("generate").addEventListener("click", function(){

    let batch = document.getElementById("batchNumber").value;
    /* /header2 */
    let text =  genBatch(batch) + "  ";

    let fileName = document.getElementById("fileName").value + ".txt";

    download(fileName, text);
}, false);

<!DOCTYPE html>

          Batch Number:
          <input id="batchNumber" type="number" maxlength="4" size="4"/>
          File Name:
          <input id="fileName" type="text"/>

    <button id="generate" type="button" class="btn btn-light font-weight-bold mx-auto">Generate File</button>


问:
How to extract strings before and after whitespace, special characters?
I have a dataframe "trial_df" with below column values as below:

```<code>Names

GHAITHA & AL MOOSA
ASEEL ELECTRONICS T
SUNRISE SUPERMARKET-QU
EMARAT-AL SAFIYAH(6735
LULU CENTRE LLC EFT TE
MAX
THEMAX
THE LULU
GHAITHA 123
SUNRISE %$#
</code>```

Requirement :

1) Extract only strings before and after whitespace, special characters.

For eg: "ASEEL ELECTRONICS T" will become "ASEEL ELECTRONICS

2) But only on below conditions :

a) the second string length should be greater than 2

b) the second string should be alphanumeric

Eg : 'GHAITHA & AL MOOSA' will be just 'GHAITHA' as the second string after white space is '&' ( both conditions fails : Not alphanumeric and length is not greater than 2)

Eg: 'MAX' will be 'MAX' as its only one string. similarly 'THE LULU' will be same as its already just 2 strings.

Final output :

```<code>Names

GHAITHA
ASEEL ELECTRONICS
SUNRISE SUPERMARKET-QU
EMARAT
LULU CENTRE
MAX
THEMAX
THE LULU
GHAITHA
SUNRISE
</code>```

My function to do the requirement :

```<code>def remove_strings(df, col):
    for i in df.index:
        x = df.at[i, col]
        x = x.split(' ')
        if len(x) > 1:
            if len(x[1]) > 2:
                x[1] = ''.join(e for e in x[1] if e.isalnum())
                x = ' '.join(x[0:2])
                df.at[i, col] = x
            else:
                df.at[i, col] = x[0]
        else:
            df.at[i, col] = df.at[i, col]

#calling my function
remove_strings(df=trial_df, col='Names')
</code>```

Issue with my function : Though it solves the requirement, but its not well optimized.
My data is of more than 1 million rows, so its looping that many times which is very time consuming.
Is there a very good optimized way to solve my requirement ?

答:
```<code> df.Names.replace(regex=r'^(\w+)(\s[A-Z-]{2,})?.*',value=r'\1\2')
Out[186]:
0                   GHAITHA
1         ASEEL ELECTRONICS
2    SUNRISE SUPERMARKET-QU
3                    EMARAT
4               LULU CENTRE
5                       MAX
6                    THEMAX
7                  THE LULU
8                   GHAITHA
9                   SUNRISE
Name: Names, dtype: object
</code>```

Body:
I have a dataframe "trial_df" with below column values as below:

Names

GHAITHA & AL MOOSA
ASEEL ELECTRONICS T
SUNRISE SUPERMARKET-QU
EMARAT-AL SAFIYAH(6735
LULU CENTRE LLC EFT TE
MAX
THEMAX
THE LULU
GHAITHA 123
SUNRISE %$#

Requirement :

1) Extract only strings before and after whitespace, special characters.

For eg: "ASEEL ELECTRONICS T" will become "ASEEL ELECTRONICS

2) But only on below conditions :

a) the second string length should be greater than 2

b) the second string should be alphanumeric

Eg : 'GHAITHA & AL MOOSA' will be just 'GHAITHA' as the second string after white space is '&' ( both conditions fails : Not alphanumeric and length is not greater than 2)

Eg: 'MAX' will be 'MAX' as its only one string. similarly 'THE LULU' will be same as its already just 2 strings.

Final output :

Names

GHAITHA
ASEEL ELECTRONICS
SUNRISE SUPERMARKET-QU
EMARAT
LULU CENTRE
MAX
THEMAX
THE LULU
GHAITHA
SUNRISE

My function to do the requirement :

def remove_strings(df, col):
    for i in df.index:
        x = df.at[i, col]
        x = x.split(' ')
        if len(x) > 1:
            if len(x[1]) > 2:
                x[1] = ''.join(e for e in x[1] if e.isalnum())
                x = ' '.join(x[0:2])
                df.at[i, col] = x
            else:
                df.at[i, col] = x[0]
        else:
            df.at[i, col] = df.at[i, col]

#calling my function
remove_strings(df=trial_df, col='Names')

Issue with my function : Though it solves the requirement, but its not well optimized.
My data is of more than 1 million rows, so its looping that many times which is very time consuming.
Is there a very good optimized way to solve my requirement ?


问:
Insert Statement into Derby Database
I am trying to insert a number of values into a table in my java derby database, I am getting the error java.sql.SQLSyntaxErrorException: VALUES clause must contain at least one element. Empty elements are not allowed.

```<code>    public boolean registerStudent(Student student)
    {
        try
        {
        Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/AceDrivingSchool", "ADC", "ADC");
        Statement stmt = conn.createStatement();
        stmt.executeUpdate("INSERT INTO ADC.STUDENT(EMAILADDRESS, FORENAME, SURNAME, ADDRESSLINE1, ADDRESSLINE2,"
                + " POSTCODE, TELEPHONENO, GENDER, PASSWORD, ISREGISTERED, ISVERIFIED, PASSEDTHEORY, PASSEDPRACTICAL, DRIVINGLICENSENO, DOB"
                + ") VALUES('" + student.getEmailAddress() +
                "', '" + student.getForename() + "', '" + student.getSurname() +
                "', '" + student.getAddressLine1() + "', '" + student.getAddressLine2() + "', '" + student.getPostcode() +
                "', '" + student.getTelephoneNo() + "', '" + student.getGender() + "', '" + student.getPassword() +
                "', '" + student.isIsRegistered() + "', '" + student.isIsVerified() + "', '" + student.isPassedTheory() + "', '" +
                "', '" + student.isPassedPractical() + "', '" + student.getdrivingLicenseNo() + "', '" +
                new SimpleDateFormat("yyyy-MM-dd").format(student.getDob()) + "')");
        conn.close();
        return true;
        }
        catch(SQLException ex)
        {
            ex.printStackTrace();
            return false;
        }
    }
</code>```

This should right the values to my table

答:
The correct Answer by Desai discovered your syntax error in the generated SQL statement: misplaced comma.

Here is a better way to write your SQL so you can discover this kind of error for yourself.

You should always build your SQL separately as a piece of text, to facilitate debugging this kind of problem.

Build up your SQL text, and examine

Use StringBuilder to build up the text.

Here is example code. You fill in the xxx with your object getter methods (I'm too lazy).

```<code>StringBuilder sql = new StringBuilder() ;
String eol = "\n" ;  // linefeed
String comma = " , " ;  // SPACE + COMMA + SPACE
sql.append( "INSERT INTO ADC.STUDENT ( " ).append( eol ) ;
sql.append( "    EMAILADDRESS, FORENAME, SURNAME, ADDRESSLINE1, ADDRESSLINE2, POSTCODE, TELEPHONENO, GENDER, PASSWORD, ISREGISTERED, ISVERIFIED, PASSEDTHEORY, PASSEDPRACTICAL, DRIVINGLICENSENO, DOB " ).append( eol) ;
sql.append( ") VALUES (" ).append(eol) ;
sql.append( student.getEmailAddress() ).append( comma ) ; // EMAILADDRESS
sql.append( student.getForename()  ).append( comma ) ; // FORENAME
sql.append( xxx ).append( comma ) ; // SURNAME
sql.append( xxx ).append( comma ) ; // ADDRESSLINE1
sql.append( xxx ).append( comma ) ; // ADDRESSLINE2
sql.append( xxx ).append( comma ) ; // POSTCODE
sql.append( xxx ).append( comma ) ; // TELEPHONENO
sql.append( xxx ).append( comma ) ; // GENDER
sql.append( xxx ).append( comma ) ; // PASSWORD
sql.append( xxx ).append( comma ) ; // ISREGISTERED
sql.append( xxx ).append( comma ) ; // ISVERIFIED
sql.append( xxx ).append( comma ) ; // PASSEDTHEORY
sql.append( xxx ).append( comma ) ; // PASSEDPRACTICAL
sql.append( xxx ).append( comma ) ; // DRIVINGLICENSENO
sql.append( xxx ) ; // DOB — IMPORTANT no comma on the last item.
sql.append( ") ;" ) ;
</code>```

Then print out that value to verify your SQL looks straight. Compare to other examples of SQL to spot your boo-boo.

We will politely ignore the saving of password without salting and hashing, license number, and date of birth as big security risks.

By the way, you should be representing a date-only value such as date-of-birth on your Java object as a LocalDate object. The terrible Date & SimpleDateFormat classes were supplanted years ago by the java.time classes. The LocalDate.toString() method generates text in standard ISO 8601 format, which for a date-only happens to be the same as is commonly used in SQL.

Prepared Statement

Much better way than the above is to use a prepared statement with placeholders. Executing generated text as you were doing is more complicated to read, and more importantly, exposes you to the risk of a SQL Injection attack.

```<code>StringBuilder sql = new StringBuilder() ;
String eol = "\n" ;  // linefeed
sql.append( "INSERT INTO ADC.STUDENT ( " ).append( eol ) ;
sql.append( "    EMAILADDRESS, FORENAME, SURNAME, ADDRESSLINE1, ADDRESSLINE2, POSTCODE, TELEPHONENO, GENDER, PASSWORD, ISREGISTERED, ISVERIFIED, PASSEDTHEORY, PASSEDPRACTICAL, DRIVINGLICENSENO, DOB " ).append( eol) ;
sql.append( ") VALUES (" ).append(eol) ;
sql.append( "? , " ) ; // EMAILADDRESS
sql.append( "? , " ) ; // FORENAME
sql.append( "? , " ) ; // SURNAME
sql.append( "? , " ) ; // ADDRESSLINE1
sql.append( "? , " ) ; // ADDRESSLINE2
sql.append( "? , " ) ; // POSTCODE
sql.append( "? , " ) ; // TELEPHONENO
sql.append( "? , " ) ; // GENDER
sql.append( "? , " ) ; // PASSWORD
sql.append( "? , " ) ; // ISREGISTERED
sql.append( "? , " ) ; // ISVERIFIED
sql.append( "? , " ) ; // PASSEDTHEORY
sql.append( "? , " ) ; // PASSEDPRACTICAL
sql.append( "? , " ) ; // DRIVINGLICENSENO
sql.append( "? " ) ;   // DOB — IMPORTANT no comma on the last item.
sql.append( ") ; " ) ;
</code>```

Again, print that out and examine.

```<code>String sqlOutput = sql.toString() ;
System.out.println( sqlOutput ) ;
</code>```

Create a PreparedStatement. On that object call the set… methods.

```<code>ps.setString( 1 , student.getEmailAddress() ) ;
…
ps.setObject( 15 , student.getDateOfBirth() ) ;  // Pass `LocalDate` object via `setObject` method using JDBC 4.2 or later.
</code>```

Title: Insert Statement into Derby Database

Body:
I am trying to insert a number of values into a table in my java derby database, I am getting the error java.sql.SQLSyntaxErrorException: VALUES clause must contain at least one element. Empty elements are not allowed.

    public boolean registerStudent(Student student)
    {
        try
        {
        Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/AceDrivingSchool", "ADC", "ADC");
        Statement stmt = conn.createStatement();
        stmt.executeUpdate("INSERT INTO ADC.STUDENT(EMAILADDRESS, FORENAME, SURNAME, ADDRESSLINE1, ADDRESSLINE2,"
                + " POSTCODE, TELEPHONENO, GENDER, PASSWORD, ISREGISTERED, ISVERIFIED, PASSEDTHEORY, PASSEDPRACTICAL, DRIVINGLICENSENO, DOB"
                + ") VALUES('" + student.getEmailAddress() +
                "', '" + student.getForename() + "', '" + student.getSurname() +
                "', '" + student.getAddressLine1() + "', '" + student.getAddressLine2() + "', '" + student.getPostcode() +
                "', '" + student.getTelephoneNo() + "', '" + student.getGender() + "', '" + student.getPassword() +
                "', '" + student.isIsRegistered() + "', '" + student.isIsVerified() + "', '" + student.isPassedTheory() + "', '" +
                "', '" + student.isPassedPractical() + "', '" + student.getdrivingLicenseNo() + "', '" +
                new SimpleDateFormat("yyyy-MM-dd").format(student.getDob()) + "')");
        conn.close();
        return true;
        }
        catch(SQLException ex)
        {
            ex.printStackTrace();
            return false;
        }
    }

This should right the values to my table

Body:
The correct Answer by Desai discovered your syntax error in the generated SQL statement: misplaced comma.

Here is a better way to write your SQL so you can discover this kind of error for yourself.

You should always build your SQL separately as a piece of text, to facilitate debugging this kind of problem.

Build up your SQL text, and examine

Use StringBuilder to build up the text.

Here is example code. You fill in the xxx with your object getter methods (I'm too lazy).

StringBuilder sql = new StringBuilder() ;
String eol = "\n" ;  // linefeed
String comma = " , " ;  // SPACE + COMMA + SPACE
sql.append( "INSERT INTO ADC.STUDENT ( " ).append( eol ) ;
sql.append( "    EMAILADDRESS, FORENAME, SURNAME, ADDRESSLINE1, ADDRESSLINE2, POSTCODE, TELEPHONENO, GENDER, PASSWORD, ISREGISTERED, ISVERIFIED, PASSEDTHEORY, PASSEDPRACTICAL, DRIVINGLICENSENO, DOB " ).append( eol) ;
sql.append( ") VALUES (" ).append(eol) ;
sql.append( student.getEmailAddress() ).append( comma ) ; // EMAILADDRESS
sql.append( student.getForename()  ).append( comma ) ; // FORENAME
sql.append( xxx ).append( comma ) ; // SURNAME
sql.append( xxx ).append( comma ) ; // ADDRESSLINE1
sql.append( xxx ).append( comma ) ; // ADDRESSLINE2
sql.append( xxx ).append( comma ) ; // POSTCODE
sql.append( xxx ).append( comma ) ; // TELEPHONENO
sql.append( xxx ).append( comma ) ; // GENDER
sql.append( xxx ).append( comma ) ; // PASSWORD
sql.append( xxx ).append( comma ) ; // ISREGISTERED
sql.append( xxx ).append( comma ) ; // ISVERIFIED
sql.append( xxx ).append( comma ) ; // PASSEDTHEORY
sql.append( xxx ).append( comma ) ; // PASSEDPRACTICAL
sql.append( xxx ).append( comma ) ; // DRIVINGLICENSENO
sql.append( xxx ) ; // DOB — IMPORTANT no comma on the last item.
sql.append( ") ;" ) ;

Then print out that value to verify your SQL looks straight. Compare to other examples of SQL to spot your boo-boo.

We will politely ignore the saving of password without salting and hashing, license number, and date of birth as big security risks.

By the way, you should be representing a date-only value such as date-of-birth on your Java object as a LocalDate object. The terrible Date & SimpleDateFormat classes were supplanted years ago by the java.time classes. The LocalDate.toString() method generates text in standard ISO 8601 format, which for a date-only happens to be the same as is commonly used in SQL.

Prepared Statement

Much better way than the above is to use a prepared statement with placeholders. Executing generated text as you were doing is more complicated to read, and more importantly, exposes you to the risk of a SQL Injection attack.

StringBuilder sql = new StringBuilder() ;
String eol = "\n" ;  // linefeed
sql.append( "INSERT INTO ADC.STUDENT ( " ).append( eol ) ;
sql.append( "    EMAILADDRESS, FORENAME, SURNAME, ADDRESSLINE1, ADDRESSLINE2, POSTCODE, TELEPHONENO, GENDER, PASSWORD, ISREGISTERED, ISVERIFIED, PASSEDTHEORY, PASSEDPRACTICAL, DRIVINGLICENSENO, DOB " ).append( eol) ;
sql.append( ") VALUES (" ).append(eol) ;
sql.append( "? , " ) ; // EMAILADDRESS
sql.append( "? , " ) ; // FORENAME
sql.append( "? , " ) ; // SURNAME
sql.append( "? , " ) ; // ADDRESSLINE1
sql.append( "? , " ) ; // ADDRESSLINE2
sql.append( "? , " ) ; // POSTCODE
sql.append( "? , " ) ; // TELEPHONENO
sql.append( "? , " ) ; // GENDER
sql.append( "? , " ) ; // PASSWORD
sql.append( "? , " ) ; // ISREGISTERED
sql.append( "? , " ) ; // ISVERIFIED
sql.append( "? , " ) ; // PASSEDTHEORY
sql.append( "? , " ) ; // PASSEDPRACTICAL
sql.append( "? , " ) ; // DRIVINGLICENSENO
sql.append( "? " ) ;   // DOB — IMPORTANT no comma on the last item.
sql.append( ") ; " ) ;

Again, print that out and examine.

String sqlOutput = sql.toString() ;
System.out.println( sqlOutput ) ;

Create a PreparedStatement. On that object call the set… methods.

ps.setString( 1 , student.getEmailAddress() ) ;
…
ps.setObject( 15 , student.getDateOfBirth() ) ;  // Pass `LocalDate` object via `setObject` method using JDBC 4.2 or later.


问:
How to detect hand palm and its orientation (like facing outwards)?
I am working on a hand detection project. There are many good project on web to do this, but what I need is a specific hand pose detection. It needs a totally open palm and the whole palm face to outwards, like the image below:

The first hand faces to inwards, so it will not be detected, and the right one faces to outwards, it will be detected. Now I can detect hand with OpenCV. but how to tell the hand orientation?

答:
well if you go for a MacGyver way you can notice that the left hand has bones sticking out in a certain direction, while the right hand has all finger lines and a few lines in the hand palms.

These lines are always sort of the same, so you could try to detect them with opencv edge detection or hough lines. Due to the dark color of the lines, you might even be able to threshold them out of it. Then gather the information from those lines, like angles, regressions, see which features you can collect and train a simple decision tree.

That was assuming you do not have enough data, if you have then you go into deeplearning, just take a basic inceptionV3 model and retrain the last dense layer to classify between two classes with a softmax, or to predict the probablity if the hand being up/down with sigmoid. Check this link, Tensorflow got your back on the training of this one, pure already ready code to execute.

Questions? Ask away


问:
Vectors passed in as construction arguments
If I have a class similar to this:

```<code>namespace Matrix {
  class Matrix;
  class Vector {
   public:
    //i want to create a vector the same size as contents with the same values
    Vector(const std::vector<ValueType>& contents);
   private:
   std::vector<ValueType> contents;
}
</code>```

When contents is passed in through the constructor, is it automatically copied to the vector called contents I defined within the class? Or is there something I have to do in the constructor definition to achieve that?

答:
No, you do not get automatic copying just by virtue of your constructor having an argument. You could write:

```<code>Vector(const std::vector<ValueType>& contents_) : contents{contents_} { };
</code>```

which would do the copying. However, this whole approach is not a good idea, for two reasons:

If you pass an rvalue to the constructor (e.g. a temporary vector you obtained from some function), a const & would make an extra copy.

Why only be willing to initialize your data from an std::vector? You should be willing to accept at least a std::span, or perhaps template over a container or a pair of iterators.

Actually, I would consider templating your entire inner vector class on the underlying container.

Body:
If I have a class similar to this:

namespace Matrix {
  class Matrix;
  class Vector {
   public:
    //i want to create a vector the same size as contents with the same values
    Vector(const std::vector<ValueType>& contents);
   private:
   std::vector<ValueType> contents;
}

When contents is passed in through the constructor, is it automatically copied to the vector called contents I defined within the class? Or is there something I have to do in the constructor definition to achieve that?

Body:
No, you do not get automatic copying just by virtue of your constructor having an argument. You could write:

Vector(const std::vector<ValueType>& contents_) : contents{contents_} { };

which would do the copying. However, this whole approach is not a good idea, for two reasons:

If you pass an rvalue to the constructor (e.g. a temporary vector you obtained from some function), a const & would make an extra copy.

Why only be willing to initialize your data from an std::vector? You should be willing to accept at least a std::span, or perhaps template over a container or a pair of iterators.

Actually, I would consider templating your entire inner vector class on the underlying container.


问:
extjs how to parametrize a component
I'm trying to pass two parameters oneOfAll and twoOfAll into a container. From the initComponent function I do:

```<code>initComponent: function () {
       this.callParent(arguments);
       console.log('Results', this.oneOfAll, this.twoOfAll);
}
</code>```

and the browser's console prints the correct data, but when:

```<code>items: [
          {
              xtype: 'button',
              text: 'Other click',
              id: 'buttonClick',
              handler: function(item) {
                  Ext.Msg.alert('Other Click', '!!!' + this.oneOfAll);
              }
          },
          {
              xtype: 'button',
              text: 'CLICK',
              id: 'buttonClick_2',
              handler: function(item) {
                 Ext.Msg.alert('Other Click', '!!!' + this.twoOfAll);
              }
           }
      ]
</code>```

these values are not seen by the container config, both times undefined is returned.

I have this fiddle: https://fiddle.sencha.com/#view/editor&fiddle/2sk3

How can I pass these parameters into the container and be seen by it?

答:
Inside the handler, this refers to the item object, not your component.

To fix this, you could try accessing the component by ID, and get its property directly.

For example (using your mypanel id from your fiddle):

```<code>{
    xtype: 'button',
    text: 'Other click',
    id: 'buttonClick',
    handler: function (item) {
        var cmp = Ext.getCmp('mypanel');
        Ext.Msg.alert('Other Click', '~~!!' + cmp.oneOfAll);
    }
},
</code>```

Title: extjs how to parametrize a component

Body:
I'm trying to pass two parameters oneOfAll and twoOfAll into a container. From the initComponent function I do:

initComponent: function () {
       this.callParent(arguments);
       console.log('Results', this.oneOfAll, this.twoOfAll);
}

and the browser's console prints the correct data, but when:

items: [
          {
              xtype: 'button',
              text: 'Other click',
              id: 'buttonClick',
              handler: function(item) {
                  Ext.Msg.alert('Other Click', '!!!' + this.oneOfAll);
              }
          },
          {
              xtype: 'button',
              text: 'CLICK',
              id: 'buttonClick_2',
              handler: function(item) {
                 Ext.Msg.alert('Other Click', '!!!' + this.twoOfAll);
              }
           }
      ]

these values are not seen by the container config, both times undefined is returned.

I have this fiddle: https://fiddle.sencha.com/#view/editor&fiddle/2sk3

How can I pass these parameters into the container and be seen by it?

Body:
Inside the handler, this refers to the item object, not your component.

To fix this, you could try accessing the component by ID, and get its property directly.

For example (using your mypanel id from your fiddle):

{
    xtype: 'button',
    text: 'Other click',
    id: 'buttonClick',
    handler: function (item) {
        var cmp = Ext.getCmp('mypanel');
        Ext.Msg.alert('Other Click', '~~!!' + cmp.oneOfAll);
    }
},


问:
Matplotlib iterate to combine legend handles and labels
If I have the following plotting routine that plots a scatter plot and corresponding linear regression and combines the legend handles:

```<code>import pandas as pd
from scipy.stats import linregress
import numpy as np
import matplotlib.pyplot as plt

#data and Regression
x = np.arange(0,5,1)
y = np.arange(0,10,2)
df = pd.DataFrame(data = {'x':x,'y':y})
s, intcpt, r, p, serr = linregress(df.x, df.y)
xHat = np.linspace(0,5,100)

# do the plotting
fig,ax = plt.subplots()
df.plot(x='x',y='y',ax=ax,label='series1',ls=' ',marker='x',c='blue')
ls_handle, = ax.plot(xHat, s*xHat + intcpt, linestyle='-', marker=None, c='blue')
handle2merge = [ls_handle]
handles, labels = ax.get_legend_handles_labels()
handle_combined = zip(handles, handle2merge)
ax.legend(handle_combined, labels)
</code>```

Which returns the where the marker and line handles are merged looking like:

Now I want to plot another dataset in a similar fashion:

```<code>#get current axis handles and labels
handle_start, label_start = ax.get_legend_handles_labels()

#second dataset and regression
x1 = np.arange(0,5,1)
y1 = np.arange(0,2.5,0.5)
df1 = pd.DataFrame(data = {'x':x1,'y':y1})
s1, intcpt1, r1, p1, serr1 = linregress(df1.x, df1.y)
xHat1 = np.linspace(0,5,100)

#plot second data set on same figure
marker_handle2, = ax.plot(df1.x, df1.y, marker = 'x', zorder=10,c='k', linestyle=' ')
line_handle2, = ax.plot(xHat, s1*xHat1 + intcpt1, linestyle='--', marker=None, c='k')
new_line_handles = [line_handle2]
new_marker_handles= [marker_handle2]

ax.legend(handle_start + zip(new_marker_handles,new_line_handles), label_start + ['series2'])
</code>```

This returns a plot where the handles for series1 legend handle only contains the marker.

Why is len(handle_start)=1 when I constructed the handle with handle_combined = zip(handles, handle2merge)?

答:
In the last line, just use the already created merged handle handle_combined instead of the handle_start.

```<code>ax.legend(handle_combined + list(zip(new_marker_handles,new_line_handles)),
          label_start + ['series2'])
</code>```

The length is 1 but if you look into the contents of the list, it is a tuple consisting of two objects. If you print handle_combined, you get a list of two Line2D objects, one of which is marker and the other is the line.

```<code>print (handle_combined)
# [(<matplotlib.lines.Line2D object at xxxxxxxxx>, <matplotlib.lines.Line2D object at xxxxxxxxx>)]
</code>```

However, if you print handle_start, it returns just a single Line2D object

```<code>print (handle_start)
# [<matplotlib.lines.Line2D object at xxxxxxxxx>]
</code>```

Body:
If I have the following plotting routine that plots a scatter plot and corresponding linear regression and combines the legend handles:

import pandas as pd
from scipy.stats import linregress
import numpy as np
import matplotlib.pyplot as plt

#data and Regression
x = np.arange(0,5,1)
y = np.arange(0,10,2)
df = pd.DataFrame(data = {'x':x,'y':y})
s, intcpt, r, p, serr = linregress(df.x, df.y)
xHat = np.linspace(0,5,100)

# do the plotting
fig,ax = plt.subplots()
df.plot(x='x',y='y',ax=ax,label='series1',ls=' ',marker='x',c='blue')
ls_handle, = ax.plot(xHat, s*xHat + intcpt, linestyle='-', marker=None, c='blue')
handle2merge = [ls_handle]
handles, labels = ax.get_legend_handles_labels()
handle_combined = zip(handles, handle2merge)
ax.legend(handle_combined, labels)

Which returns the where the marker and line handles are merged looking like:

Now I want to plot another dataset in a similar fashion:

#get current axis handles and labels
handle_start, label_start = ax.get_legend_handles_labels()

#second dataset and regression
x1 = np.arange(0,5,1)
y1 = np.arange(0,2.5,0.5)
df1 = pd.DataFrame(data = {'x':x1,'y':y1})
s1, intcpt1, r1, p1, serr1 = linregress(df1.x, df1.y)
xHat1 = np.linspace(0,5,100)

#plot second data set on same figure
marker_handle2, = ax.plot(df1.x, df1.y, marker = 'x', zorder=10,c='k', linestyle=' ')
line_handle2, = ax.plot(xHat, s1*xHat1 + intcpt1, linestyle='--', marker=None, c='k')
new_line_handles = [line_handle2]
new_marker_handles= [marker_handle2]

ax.legend(handle_start + zip(new_marker_handles,new_line_handles), label_start + ['series2'])

This returns a plot where the handles for series1 legend handle only contains the marker.

Why is len(handle_start)=1 when I constructed the handle with handle_combined = zip(handles, handle2merge)?

Body:
In the last line, just use the already created merged handle handle_combined instead of the handle_start.

ax.legend(handle_combined + list(zip(new_marker_handles,new_line_handles)),
          label_start + ['series2'])

The length is 1 but if you look into the contents of the list, it is a tuple consisting of two objects. If you print handle_combined, you get a list of two Line2D objects, one of which is marker and the other is the line.

print (handle_combined)
# [(<matplotlib.lines.Line2D object at xxxxxxxxx>, <matplotlib.lines.Line2D object at xxxxxxxxx>)]

However, if you print handle_start, it returns just a single Line2D object

print (handle_start)
# [<matplotlib.lines.Line2D object at xxxxxxxxx>]


问:
What's the difference between casting a long to int versus using a bitwise AND in order to get the 4 least significant bytes?
I know that in order to get the 4 least significant bytes of a number of type long I can cast it to int/unsigned int or use a bitwise AND (& 0xFFFFFFFF).

This code produces the following output:

#include <stdio.h>

int main()
{
  long n = 0x8899AABBCCDDEEFF;
  printf("0x%016lX\n", n);
  printf("0x%016X\n", (int)n);
  printf("0x%016X\n", (unsigned int)n);
  printf("0x%016lX\n", n & 0xFFFFFFFF);
}
```

<p>Output:</p>

```0x8899AABBCCDDEEFF
0x00000000CCDDEEFF
0x00000000CCDDEEFF
0x00000000CCDDEEFF
```

Does that mean that the two methods used are equivalent? If so, do they always produce the same output regardless of the platform/compiler?

Also, is there any catch or pitfall while casting to unsigned int rather than int for the purpose of this question?

Finally, why is the output the same if you change the number n to be an unsigned long instead?

答:
For your first question, as others have pointed out, the size of int and long is dependent on the platform, so the methods are not equivalent. In C data types, check that the types say "at least XX bits in size"

For the second question, it comes down to this: long and int are signed, meaning that one bit is reserved for sign (take a look also to two's complement). If you were the compiler, what can you do with negative values (especially the long ones)? As Stepahn Lechner mentioned, this is implementation defined (that is, is up to the compiler).

Finally, in the spirit of "your code must do what it says it does", the best thing to do if you need to do masks is to use masks (and, if you use masks, use unsigned types). Don't try to use cleaver answers. Believe me, they always bite you in the rear. I've dealt with a lot of legacy code to know that by heart.

Body:
I know that in order to get the 4 least significant bytes of a number of type long I can cast it to int/unsigned int or use a bitwise AND (& 0xFFFFFFFF).

This code produces the following output:

#include <stdio.h>

int main()
{
  long n = 0x8899AABBCCDDEEFF;
  printf("0x%016lX\n", n);
  printf("0x%016X\n", (int)n);
  printf("0x%016X\n", (unsigned int)n);
  printf("0x%016lX\n", n & 0xFFFFFFFF);
}

Output:

0x8899AABBCCDDEEFF
0x00000000CCDDEEFF
0x00000000CCDDEEFF
0x00000000CCDDEEFF

Does that mean that the two methods used are equivalent? If so, do they always produce the same output regardless of the platform/compiler?

Also, is there any catch or pitfall while casting to unsigned int rather than int for the purpose of this question?

Finally, why is the output the same if you change the number n to be an unsigned long instead?


问:
Python asyncio confused about await and tasks
Complete newb here, reading about Asycnio Tasks which has this example:

```<code>import asyncio
import time

async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

async def main():
    task1 = asyncio.create_task(
        say_after(1, 'hello'))

    task2 = asyncio.create_task(
        say_after(2, 'world'))

    print(f"started at {time.strftime('%X')}")

    # Wait until both tasks are completed (should take
    # around 2 seconds.)
    await task1
    await task2

    print(f"finished at {time.strftime('%X')}")

asyncio.run(main())
</code>```

My original understanding of await is that it blocks the execution of current function and wait for the async function to return.

But in this case both coroutines are executed concurrently, it doesn't fit well my understanding of await. Could someone please explain?

Further investigation, by adding extra print in say_after, it seems to me the coroutine doesn't start until await happens...

```<code>import asyncio
import time

async def say_after(delay, what):
    print('Received {}'.format(what))
    await asyncio.sleep(delay)
    print(what)

async def main():
    task1 = asyncio.create_task(
        say_after(1, 'hello'))

    task2 = asyncio.create_task(
        say_after(2, 'world'))

    print(f"started at {time.strftime('%X')}")

    # Wait until both tasks are completed (should take
    # around 2 seconds.)
    await task1
    await task2

    print(f"finished at {time.strftime('%X')}")

asyncio.run(main())
</code>```

prints

```<code>started at 13:41:23
Received hello
Received world
hello
world
finished at 13:41:25
</code>```

答:
OK Both @tsuyoku and @Fanto answers are correct, this answer is just to compliment the existing answers, the important bit for me that I could not grasp was the execution started on create_task():

```<code>import asyncio
import time

async def say_after(delay, what):
    print('Received {}'.format(what))
    await asyncio.sleep(delay)
    print(what)

async def main():
    task1 = asyncio.create_task(
        say_after(1, 'hello')
    )

    task2 = asyncio.create_task(
        say_after(2, 'world')
    )

    print(f"started at {time.strftime('%X')}")
    await asyncio.sleep(10)

    # Wait until both tasks are completed (should take
    # around 2 seconds.)
    await task2
    print('task 2 finished')
    await task1
    print('task 1 finished')

    print(f"finished at {time.strftime('%X')}")

asyncio.run(main())
</code>```

prints

```<code>started at 10:42:10
Received hello
Received world
hello
world
task 2 finished
task 1 finished
finished at 10:42:20
</code>```

the original misunderstanding is that stuff takes a bit of time to run the tasks, and the original print out in my question misguided me to think the task doesn't run until the await statement.

Body:
Complete newb here, reading about Asycnio Tasks which has this example:

import asyncio
import time

async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

async def main():
    task1 = asyncio.create_task(
        say_after(1, 'hello'))

    task2 = asyncio.create_task(
        say_after(2, 'world'))

    print(f"started at {time.strftime('%X')}")

    # Wait until both tasks are completed (should take
    # around 2 seconds.)
    await task1
    await task2

    print(f"finished at {time.strftime('%X')}")

asyncio.run(main())

My original understanding of await is that it blocks the execution of current function and wait for the async function to return.

But in this case both coroutines are executed concurrently, it doesn't fit well my understanding of await. Could someone please explain?

Further investigation, by adding extra print in say_after, it seems to me the coroutine doesn't start until await happens...

import asyncio
import time

async def say_after(delay, what):
    print('Received {}'.format(what))
    await asyncio.sleep(delay)
    print(what)

async def main():
    task1 = asyncio.create_task(
        say_after(1, 'hello'))

    task2 = asyncio.create_task(
        say_after(2, 'world'))

    print(f"started at {time.strftime('%X')}")

    # Wait until both tasks are completed (should take
    # around 2 seconds.)
    await task1
    await task2

    print(f"finished at {time.strftime('%X')}")

asyncio.run(main())

prints

started at 13:41:23
Received hello
Received world
hello
world
finished at 13:41:25

Body:
OK Both @tsuyoku and @Fanto answers are correct, this answer is just to compliment the existing answers, the important bit for me that I could not grasp was the execution started on create_task():

import asyncio
import time

async def say_after(delay, what):
    print('Received {}'.format(what))
    await asyncio.sleep(delay)
    print(what)

async def main():
    task1 = asyncio.create_task(
        say_after(1, 'hello')
    )

    task2 = asyncio.create_task(
        say_after(2, 'world')
    )

    print(f"started at {time.strftime('%X')}")
    await asyncio.sleep(10)

    # Wait until both tasks are completed (should take
    # around 2 seconds.)
    await task2
    print('task 2 finished')
    await task1
    print('task 1 finished')

    print(f"finished at {time.strftime('%X')}")

asyncio.run(main())

prints

started at 10:42:10
Received hello
Received world
hello
world
task 2 finished
task 1 finished
finished at 10:42:20

the original misunderstanding is that stuff takes a bit of time to run the tasks, and the original print out in my question misguided me to think the task doesn't run until the await statement.


问:
Select-Option value inserting as "0" to database instead of actual value
I'm trying to insert select-option values into my database using Ajax, but it will keep inserting a "0" to the database rather than the actual value or it will return as "null" value. I'm able to successfully insert select-option value without the Ajax code however. But I am able to insert values using a text input field with the Ajax code. The name values for my select and text input are the same (as they both should insert the same data to the database). When the select-option is hidden, the text input will insert its value to the database and vise versa. So my main question is, how do I get the actual value for the select-option to be inserted to the database (because all it inserts is "0" or returns with an error of "null")?

This is the html for the form, which includes the select-option and text input field which both carry the name="toctquant" attribute:

```<code><form method="post" action="tocarthand.php?strid=<?php echo $prodtab->strid; ?>&prodid=<?php echo $prodtab->prodid; ?>" id="toctform">
    <select name="toctquant" id="quantsel" class="qinp">
        <?php $q = $prodtab->quant; ?>
        <?php for ($q = 1; $q <= 10; $q++): ?>
            <option value="<?php echo $q; ?>"><?php echo $q; ?></option>
        <?php endfor; ?>
        <?php if ($q > 10): ?>
            <option value="<?php echo $q; ?>"><?php echo $q; ?>+</option>
        <?php endif; ?>
    </select>
    <input type="text" name="toctquant" class="inphid qinp">
    <button type="submit" name="tocartbut" id="tocartbut">Add to Cart</button>
</form>
<div id="result"></div>
</code>```

This is the Ajax code I am having problems with. It will only submit value for text input but not for the select-option value:

```<code>$("#toctform").submit(function(e) {
    var data = $("#toctform").serialize();
    $.ajax({
        data: data,
        type: "post",
        url: "tocarthand.php",
        success: function(data){
            alert("Data Save: " + data);
        }
    });
});
</code>```

EDIT: Included php code for file tocarthand.php

```<code>$strid = (int)$_GET['strid'];
$prodid = (int)$_GET['prodid'];
$toctprodid = (int)$_GET['prodid'];
$toctuserid = $_SESSION['userid'];
$toctquant = $_POST['toctquant'];
$stmt = $conn->prepare("INSERT INTO tocart (toctprodid, toctuserid, toctquant) VALUES (?, ?, ?)");
$stmt->bind_param("iii", $toctprodid, $toctuserid, $toctquant);
$stmt->execute();
$stmt->close();
header('Location: itempage.php?strid='.$strid.'&prodid='.$prodid.'&insert=success');
$conn->close();
</code>```

答:
Typo your select has name=toctquant but <input type="text" name="toctquant"> has same name which override the select before. Change different name.

Is it OK to have multiple HTML forms with the same name?

Body:
I'm trying to insert select-option values into my database using Ajax, but it will keep inserting a "0" to the database rather than the actual value or it will return as "null" value. I'm able to successfully insert select-option value without the Ajax code however. But I am able to insert values using a text input field with the Ajax code. The name values for my select and text input are the same (as they both should insert the same data to the database). When the select-option is hidden, the text input will insert its value to the database and vise versa. So my main question is, how do I get the actual value for the select-option to be inserted to the database (because all it inserts is "0" or returns with an error of "null")?

This is the html for the form, which includes the select-option and text input field which both carry the name="toctquant" attribute:

<form method="post" action="tocarthand.php?strid=<?php echo $prodtab->strid; ?>&prodid=<?php echo $prodtab->prodid; ?>" id="toctform">
    <select name="toctquant" id="quantsel" class="qinp">
        <?php $q = $prodtab->quant; ?>
        <?php for ($q = 1; $q <= 10; $q++): ?>
            <option value="<?php echo $q; ?>"><?php echo $q; ?></option>
        <?php endfor; ?>
        <?php if ($q > 10): ?>
            <option value="<?php echo $q; ?>"><?php echo $q; ?>+</option>
        <?php endif; ?>
    </select>
    <input type="text" name="toctquant" class="inphid qinp">
    <button type="submit" name="tocartbut" id="tocartbut">Add to Cart</button>
</form>

This is the Ajax code I am having problems with. It will only submit value for text input but not for the select-option value:

$("#toctform").submit(function(e) {
    var data = $("#toctform").serialize();
    $.ajax({
        data: data,
        type: "post",
        url: "tocarthand.php",
        success: function(data){
            alert("Data Save: " + data);
        }
    });
});

EDIT: Included php code for file tocarthand.php

$strid = (int)$_GET['strid'];
$prodid = (int)$_GET['prodid'];
$toctprodid = (int)$_GET['prodid'];
$toctuserid = $_SESSION['userid'];
$toctquant = $_POST['toctquant'];
$stmt = $conn->prepare("INSERT INTO tocart (toctprodid, toctuserid, toctquant) VALUES (?, ?, ?)");
$stmt->bind_param("iii", $toctprodid, $toctuserid, $toctquant);
$stmt->execute();
$stmt->close();
header('Location: itempage.php?strid='.$strid.'&prodid='.$prodid.'&insert=success');
$conn->close();


问:
segmentation fault when calling fortran subroutine in C++
I am trying to call a Fortran subroutine in C++.

this is the subroutine start:

```<code>    subroutine fireballess(ear,ne,parames,ifl,photar,photer)
    integer ne,ifl
    real*4 ear(0:ne),parames(10),photar(ne),photer(ne)
</code>```

The subroutine works fine in Fortran, but when I try to call it in C++ I get a segmentation fault. Here is my code:

```<code>    #include <stdlib.h>
    #include <stdio.h>
    #include <iostream>

    using namespace std;

    extern "C" void fireballess_( double *fear, int fne,double* fparames, nt fifl, double *fphotar, double *fphoter);

    int main(int argc, char ** argv)
    {
            int ne,ifl;
            double *ear;
        double *parames;

        double *photar;
            double *photer;

        parames = new double[9];

            parames[0]=4.3;
           parames[1]=0.23;
           parames[2]=0.5;
           parames[3]=0.5;
           parames[4]=1.5;
           parames[5]=1.;
           parames[6]=1000.;
           parames[7]=2.15;
           parames[8]=3.;

        ne = 3;

            ear = new double[ne];
        ear[0] = 0.;
        ear[1] = 20.;
        ear[2] = 40.;
        ifl=2;

            photar = new double[ne];
            photer = new double[ne];

    // Check on variables initialization

        for (int i=0;i<=2;i++)    cout << ear[i] <<",";
        cout <<"    "<< ne<<"   ";
        for (int i=0;i<=8;i++)    cout << parames[i] <<",";
        cout <<"    "<< ifl <<" "<< photar[0] <<"   "<< photer[0] << endl;

            cout << "Calling a Fortran subroutine" << endl;
            cout << "===============================" << endl;

    // call to the subroutine -->segmentation fault
            fireballess_(ear,ne,parames,ifl,photar,photer);

        for (int i=0;i<=ne;i++){
        cout << "ear = " <<ear[i-1]<< " - "<<ear[i] << endl;
        cout << "photar = " << photar[i] << endl;
        cout << "photer = " << photer[i] << endl << endl;
        }

            delete[] ear;
            delete[] parames;
            delete[] photar;
            delete[] photer;
    }
</code>```

The program crashes on the call to the subroutine. I am not very experienced in C++ or Fortran coding, so I am not sure about what to do. So far I have checked the format of the variables passed to the subroutine was correct, and it looks so.

Thanks in advance for any help

---------EDIT------
after reading some comments I revised the code as follows, still getting the same segmentation fault error when the routine is invoked:

```<code>using namespace std;

extern "C" void fireballess_( std::vector<float> fear, int fne,std::vector<float> fparames, int fifl, std::vector<float> fphotar, std::vector<float> fphoter);

int main(int argc, char ** argv)
{
    int ne,ifl;
ifl=2;
ne = 3;
    std::vector<float> parames = {4.3,0.23,0.5,0.5,1.5,1.,1000.,2.15,3.};
std::vector<float> ear={0,20,40};
    std::vector<float> photar;
    std::vector<float> photer;

    cout << "Calling a Fortran subroutine" << endl;
    cout << "===============================" << endl;
        fireballess_(ear,ne,parames,ifl,photar,photer);

for (int i=0;i<ne;i++){
        cout << "ear = " <<ear[i-1]<< " - "<<ear[i] << endl;
        cout << "photar = " << photar[i] << endl;
        cout << "photer = " << photer[i] << endl << endl;
}

}
</code>```

答:
Combining various info in the comments and the other answer, I guess a minimum-modified version of the original code may look like this:

fortsub.f90

```<code>subroutine fireballess(ear, ne, parames, ifl, photar, photer)
    implicit none
    integer ne, ifl
    real*4 ear(0:ne), parames(10), photar(ne), photer(ne)

    print *, "ear     = ", ear
    print *, "ne      = ", ne
    print *, "parames = ", parames
    print *, "ifl     = ", ifl
    print *, "photar  = ", photar
    print *, "photer  = ", photer
    print *
    print *, "sizeof(integer) = ", sizeof(ne)
    print *, "sizeof(real*4)  = ", sizeof(ear(1))
end
</code>```

main.cpp

```<code>#include <iostream>

extern "C"
void fireballess_( float *ear, int *ne, float *parames,
                   int *ifl, float *photar, float *photer );

int main()
{
    std::cout << "sizeof(int)   = " << sizeof(int)   << std::endl;
    std::cout << "sizeof(float) = " << sizeof(float) << std::endl;

    int ne = 3, ifl = 2;

    float *ear = new float[ne + 1] { 0.0f, 20.0f, 40.0f, 60.0f };

    float *parames = new float[10]
        { 0.1f, 0.2f, 0.3f, 0.4f, 0.5f,
          0.6f, 0.7f, 0.8f, 0.9f, 1.0f };

    float *photar = new float[ne] { 1.0f, 2.0f, 3.0f };
    float *photer = new float[ne] { 4.0f, 5.0f, 6.0f };

    fireballess_( ear, &ne, parames, &ifl, photar, photer );

    delete[] ear;
    delete[] parames;
    delete[] photar;
    delete[] photer;
}
</code>```

Here, the modified parts are: (1) real*4 in Fortran usually corresponds to float in C++; (2) we need to pass the address of actual arguments (particularly for ne and ifl); and (3) ear should have ne + 1 elements because it is defined as ear(0:ne) on the Fortran side. Then, compiling the codes as

```<code>$ gfortran-8 -c fortsub.f90
$ g++-8 main.cpp fortsub.o -lgfortran
</code>```

gives (with GCC8 + MacOS10.13)

```<code>sizeof(int)   = 4
sizeof(float) = 4
 ear     =    0.00000000       20.0000000       40.0000000       60.0000000
 ne      =            3
 parames =   0.100000001      0.200000003      0.300000012      0.400000006      0.500000000      0.600000024      0.699999988      0.800000012      0.899999976       1.00000000
 ifl     =            2
 photar  =    1.00000000       2.00000000       3.00000000
 photer  =    4.00000000       5.00000000       6.00000000

 sizeof(integer) =                     4
 sizeof(real*4)  =                     4
</code>```

If we use std::vector, the corresponding code may look like this (by looking at some tutorials on std::vector...)

```<code>// main2.cpp
#include <iostream>
#include <vector>

extern "C"
void fireballess_( float *ear, int *ne, float *parames,
                   int *ifl, float *photar, float *photer );

using Vecf = std::vector<float>;

int main()
{
    int ne = 3, ifl = 2;

    Vecf ear { 0.0f, 20.0f, 40.0f, 60.0f };

    Vecf parames { 0.1f, 0.2f, 0.3f, 0.4f, 0.5f,
                   0.6f, 0.7f, 0.8f, 0.9f, 1.0f };

    Vecf photar { 1.0f, 2.0f, 3.0f };
    Vecf photer { 4.0f, 5.0f, 6.0f };

    fireballess_( ear.data(), &ne, parames.data(),
                  &ifl, photar.data(), photer.data() );
}
</code>```

which seems to give the same result (by replacing main.cpp by main2.cpp).

Body:
I am trying to call a Fortran subroutine in C++.

this is the subroutine start:

    subroutine fireballess(ear,ne,parames,ifl,photar,photer)
    integer ne,ifl
    real*4 ear(0:ne),parames(10),photar(ne),photer(ne)

The subroutine works fine in Fortran, but when I try to call it in C++ I get a segmentation fault. Here is my code:

    #include <stdlib.h>
    #include <stdio.h>
    #include <iostream>

    using namespace std;

    extern "C" void fireballess_( double *fear, int fne,double* fparames, nt fifl, double *fphotar, double *fphoter);

    int main(int argc, char ** argv)
    {
            int ne,ifl;
            double *ear;
        double *parames;

        double *photar;
            double *photer;

        parames = new double[9];

            parames[0]=4.3;
           parames[1]=0.23;
           parames[2]=0.5;
           parames[3]=0.5;
           parames[4]=1.5;
           parames[5]=1.;
           parames[6]=1000.;
           parames[7]=2.15;
           parames[8]=3.;

        ne = 3;

            ear = new double[ne];
        ear[0] = 0.;
        ear[1] = 20.;
        ear[2] = 40.;
        ifl=2;

            photar = new double[ne];
            photer = new double[ne];

    // Check on variables initialization

        for (int i=0;i<=2;i++)    cout << ear[i] <<",";
        cout <<"    "<< ne<<"   ";
        for (int i=0;i<=8;i++)    cout << parames[i] <<",";
        cout <<"    "<< ifl <<" "<< photar[0] <<"   "<< photer[0] << endl;

            cout << "Calling a Fortran subroutine" << endl;
            cout << "===============================" << endl;

    // call to the subroutine -->segmentation fault
            fireballess_(ear,ne,parames,ifl,photar,photer);

        for (int i=0;i<=ne;i++){
        cout << "ear = " <<ear[i-1]<< " - "<<ear[i] << endl;
        cout << "photar = " << photar[i] << endl;
        cout << "photer = " << photer[i] << endl << endl;
        }

            delete[] ear;
            delete[] parames;
            delete[] photar;
            delete[] photer;
    }

The program crashes on the call to the subroutine. I am not very experienced in C++ or Fortran coding, so I am not sure about what to do. So far I have checked the format of the variables passed to the subroutine was correct, and it looks so.

Thanks in advance for any help

---------EDIT------
after reading some comments I revised the code as follows, still getting the same segmentation fault error when the routine is invoked:

using namespace std;

extern "C" void fireballess_( std::vector<float> fear, int fne,std::vector<float> fparames, int fifl, std::vector<float> fphotar, std::vector<float> fphoter);

int main(int argc, char ** argv)
{
    int ne,ifl;
ifl=2;
ne = 3;
    std::vector<float> parames = {4.3,0.23,0.5,0.5,1.5,1.,1000.,2.15,3.};
std::vector<float> ear={0,20,40};
    std::vector<float> photar;
    std::vector<float> photer;

    cout << "Calling a Fortran subroutine" << endl;
    cout << "===============================" << endl;
        fireballess_(ear,ne,parames,ifl,photar,photer);

for (int i=0;i<ne;i++){
        cout << "ear = " <<ear[i-1]<< " - "<<ear[i] << endl;
        cout << "photar = " << photar[i] << endl;
        cout << "photer = " << photer[i] << endl << endl;
}

}

Body:
Combining various info in the comments and the other answer, I guess a minimum-modified version of the original code may look like this:

fortsub.f90

subroutine fireballess(ear, ne, parames, ifl, photar, photer)
    implicit none
    integer ne, ifl
    real*4 ear(0:ne), parames(10), photar(ne), photer(ne)

    print *, "ear     = ", ear
    print *, "ne      = ", ne
    print *, "parames = ", parames
    print *, "ifl     = ", ifl
    print *, "photar  = ", photar
    print *, "photer  = ", photer
    print *
    print *, "sizeof(integer) = ", sizeof(ne)
    print *, "sizeof(real*4)  = ", sizeof(ear(1))
end

main.cpp

#include <iostream>

extern "C"
void fireballess_( float *ear, int *ne, float *parames,
                   int *ifl, float *photar, float *photer );

int main()
{
    std::cout << "sizeof(int)   = " << sizeof(int)   << std::endl;
    std::cout << "sizeof(float) = " << sizeof(float) << std::endl;

    int ne = 3, ifl = 2;

    float *ear = new float[ne + 1] { 0.0f, 20.0f, 40.0f, 60.0f };

    float *parames = new float[10]
        { 0.1f, 0.2f, 0.3f, 0.4f, 0.5f,
          0.6f, 0.7f, 0.8f, 0.9f, 1.0f };

    float *photar = new float[ne] { 1.0f, 2.0f, 3.0f };
    float *photer = new float[ne] { 4.0f, 5.0f, 6.0f };

    fireballess_( ear, &ne, parames, &ifl, photar, photer );

    delete[] ear;
    delete[] parames;
    delete[] photar;
    delete[] photer;
}

Here, the modified parts are: (1) real*4 in Fortran usually corresponds to float in C++; (2) we need to pass the address of actual arguments (particularly for ne and ifl); and (3) ear should have ne + 1 elements because it is defined as ear(0:ne) on the Fortran side. Then, compiling the codes as

$ gfortran-8 -c fortsub.f90
$ g++-8 main.cpp fortsub.o -lgfortran

gives (with GCC8 + MacOS10.13)

sizeof(int)   = 4
sizeof(float) = 4
 ear     =    0.00000000       20.0000000       40.0000000       60.0000000
 ne      =            3
 parames =   0.100000001      0.200000003      0.300000012      0.400000006      0.500000000      0.600000024      0.699999988      0.800000012      0.899999976       1.00000000
 ifl     =            2
 photar  =    1.00000000       2.00000000       3.00000000
 photer  =    4.00000000       5.00000000       6.00000000

 sizeof(integer) =                     4
 sizeof(real*4)  =                     4

If we use std::vector, the corresponding code may look like this (by looking at some tutorials on std::vector...)

// main2.cpp
#include <iostream>
#include <vector>

extern "C"
void fireballess_( float *ear, int *ne, float *parames,
                   int *ifl, float *photar, float *photer );

using Vecf = std::vector<float>;

int main()
{
    int ne = 3, ifl = 2;

    Vecf ear { 0.0f, 20.0f, 40.0f, 60.0f };

    Vecf parames { 0.1f, 0.2f, 0.3f, 0.4f, 0.5f,
                   0.6f, 0.7f, 0.8f, 0.9f, 1.0f };

    Vecf photar { 1.0f, 2.0f, 3.0f };
    Vecf photer { 4.0f, 5.0f, 6.0f };

    fireballess_( ear.data(), &ne, parames.data(),
                  &ifl, photar.data(), photer.data() );
}

which seems to give the same result (by replacing main.cpp by main2.cpp).


问:
How to fix an 'index out of range' error in Python?
I would like to write en auxiliar function which is counting the occurences of every integer between 0 and li[-1], saying that li is a sorted list.

I can't see my mistake... I know what this kind of error message means, but I don't know where the variable j is reaching a limit.

```<code>def aux_compter_occurence(li):
    resu = [0] * (li[-1]+1)
    i = 0
    j = 0
    while i < (li[-1] + 1):
        while li[j] == i:
            resu[i] += 1
            j +=1
        i += 1
    return resu
</code>```

For example, with the input [2,4,4,4,7,8,8], the output should be [0,0,1,0,3,0,0,1,2]

答:
collections.Counter can be passed an iteratable and will count each occurance, we can then use a simple comprehension to generate the result

```<code>import collections

def aux_compter_occurence(li):
    counts = collections.Counter(li)
    return [counts.get(i, 0) for i in range(li[-1] + 1)]
</code>```

Or if you wish to use the previous method of incrementing the values in a list, you already know the index in the list because it is equal to the integer value. We can simplify quite a bit

```<code>def aux_compter_occurence(li):
    resu = [0] * (li[-1] + 1)
    for i in li:
        resu[i] += 1
    return resu
</code>```

Body:
I would like to write en auxiliar function which is counting the occurences of every integer between 0 and li[-1], saying that li is a sorted list.

I can't see my mistake... I know what this kind of error message means, but I don't know where the variable j is reaching a limit.

def aux_compter_occurence(li):
    resu = [0] * (li[-1]+1)
    i = 0
    j = 0
    while i < (li[-1] + 1):
        while li[j] == i:
            resu[i] += 1
            j +=1
        i += 1
    return resu

For example, with the input [2,4,4,4,7,8,8], the output should be [0,0,1,0,3,0,0,1,2]

Body:
collections.Counter can be passed an iteratable and will count each occurance, we can then use a simple comprehension to generate the result

import collections

def aux_compter_occurence(li):
    counts = collections.Counter(li)
    return [counts.get(i, 0) for i in range(li[-1] + 1)]

Or if you wish to use the previous method of incrementing the values in a list, you already know the index in the list because it is equal to the integer value. We can simplify quite a bit

def aux_compter_occurence(li):
    resu = [0] * (li[-1] + 1)
    for i in li:
        resu[i] += 1
    return resu


问:
Trouble adding Physijs.Vehicle to Scene
Error adding a Physijs.Vehicle to a Physijs.Scene
    THREE.Object3D.add: object not an instance of THREE.Object3D

Have tried going through the vehicle example on the Physijs page, but the same steps do not work. Relevant code from the example is:

```<code>var loader = new THREE.JSONLoader();
loader.load( "models/mustang.js", function( car, car_materials ) {
    loader.load( "models/mustang_wheel.js", function( wheel, wheel_materials ) {
            var mesh = new Physijs.BoxMesh(
                car,
                new THREE.MeshFaceMaterial( car_materials )
            );
            mesh.position.y = 2;
            mesh.castShadow = mesh.receiveShadow = true;

            vehicle = new Physijs.Vehicle(mesh, new Physijs.VehicleTuning(
                10.88,
                1.83,
                0.28,
                500,
                10.5,
                6000
            ));
            scene.add( vehicle );
</code>```

my code:

```<code>var physiBox = new Physijs.BoxMesh(
         box.geometry,
         box.material
    );
physiBox.name = "PhysiBox";
var vehicle = new Physijs.Vehicle(physiBox, new Physijs.VehicleTuning(
                10.88,
                1.83,
                0.28,
                500,
                10.5,
                6000
            ));
scene.add(vehicle );
</code>```

Its worth mentioning I can get past this error by passing in the vehicle.mesh, but then the vehicle clearly does not have the physijs properly configured on it. It seems that the other Physijs Meshes are extension of THREE.Mesh but not Vehicle, which is causing problems.

答:
Seems this is a known issue w/ Physijs:
https://github.com/chandlerprall/Physijs/issues/282</p>

Title: Trouble adding Physijs.Vehicle to Scene

Body:
Error adding a Physijs.Vehicle to a Physijs.Scene
    THREE.Object3D.add: object not an instance of THREE.Object3D

Have tried going through the vehicle example on the Physijs page, but the same steps do not work. Relevant code from the example is:

var loader = new THREE.JSONLoader();
loader.load( "models/mustang.js", function( car, car_materials ) {
    loader.load( "models/mustang_wheel.js", function( wheel, wheel_materials ) {
            var mesh = new Physijs.BoxMesh(
                car,
                new THREE.MeshFaceMaterial( car_materials )
            );
            mesh.position.y = 2;
            mesh.castShadow = mesh.receiveShadow = true;

            vehicle = new Physijs.Vehicle(mesh, new Physijs.VehicleTuning(
                10.88,
                1.83,
                0.28,
                500,
                10.5,
                6000
            ));
            scene.add( vehicle );

my code:

var physiBox = new Physijs.BoxMesh(
         box.geometry,
         box.material
    );
physiBox.name = "PhysiBox";
var vehicle = new Physijs.Vehicle(physiBox, new Physijs.VehicleTuning(
                10.88,
                1.83,
                0.28,
                500,
                10.5,
                6000
            ));
scene.add(vehicle );

Its worth mentioning I can get past this error by passing in the vehicle.mesh, but then the vehicle clearly does not have the physijs properly configured on it. It seems that the other Physijs Meshes are extension of THREE.Mesh but not Vehicle, which is causing problems.


问:
Ionic 4 - check if can go back
I’m looking for a way to redirect a user back after a click on a button if said back exists, and to a specific route otherwise.

I need to add a condition to my code, but I don’t seem to find a way.

```<code>  goback() {
    if("something") {
      this.navCtlr.setDirection('back');
      this.location.back();
    }
    else {
      this.router.navigate(['/']);
    }
  }
</code>```

In Ionic 3 we had canGoBack() 1 function… Any idea for Ionic 4? Since it's using Angular router...

Thanks.

答:
Since Ionic 4 uses Angular Routing, so you can achieve this functionality the Angular way, you can achieve it by creating a service like this:

```<code>import { Injectable } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';

@Injectable()
export class PreviousRouteService {

  private previousUrl: string;
  private currentUrl: string;

  constructor(private router: Router) {
    this.currentUrl = this.router.url;
    router.events.subscribe(event => {
      if (event instanceof NavigationEnd) {
        this.previousUrl = this.currentUrl;
        this.currentUrl = event.url;
      };
    });
  }

  public getPreviousUrl() {
    return this.previousUrl;
  }
}
</code>```

And now inject that service to the component in which you want to check your condition:

In your component:

```<code>import { Component } from '@angular/core';
import { PreviousRouteService } from '../services/previous-route.service';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html'
})
export class AppComponent {
  constructor(private previousRouteService: PreviousRouteService) {}

  goback() {
    if(this.previousRouteService.getPreviousUrl()) {
      this.navCtlr.setDirection('back');
      this.location.back();
    }
    else {
      this.router.navigate(['/']);
    }
  }
}
</code>```

Title: Ionic 4 - check if can go back

Body:
I’m looking for a way to redirect a user back after a click on a button if said back exists, and to a specific route otherwise.

I need to add a condition to my code, but I don’t seem to find a way.

  goback() {
    if("something") {
      this.navCtlr.setDirection('back');
      this.location.back();
    }
    else {
      this.router.navigate(['/']);
    }
  }

In Ionic 3 we had canGoBack() 1 function… Any idea for Ionic 4? Since it's using Angular router...

Thanks.

Body:
Since Ionic 4 uses Angular Routing, so you can achieve this functionality the Angular way, you can achieve it by creating a service like this:

import { Injectable } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';

@Injectable()
export class PreviousRouteService {

  private previousUrl: string;
  private currentUrl: string;

  constructor(private router: Router) {
    this.currentUrl = this.router.url;
    router.events.subscribe(event => {
      if (event instanceof NavigationEnd) {
        this.previousUrl = this.currentUrl;
        this.currentUrl = event.url;
      };
    });
  }

  public getPreviousUrl() {
    return this.previousUrl;
  }
}

And now inject that service to the component in which you want to check your condition:

In your component:

import { Component } from '@angular/core';
import { PreviousRouteService } from '../services/previous-route.service';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html'
})
export class AppComponent {
  constructor(private previousRouteService: PreviousRouteService) {}

  goback() {
    if(this.previousRouteService.getPreviousUrl()) {
      this.navCtlr.setDirection('back');
      this.location.back();
    }
    else {
      this.router.navigate(['/']);
    }
  }
}


问:
Asynchronous socket send on Linux
When send on an asynchronous socket returns EAGAIN, does that mean :
that the current call has just been successfully queued or that nothing was done because the system is still processing a previous send ?

Thank you in advance.

答:
From man 2 send:

The socket is marked nonblocking and the requested operation would block. POSIX.1-2001 allows either error to be returned for this case, and does not require this constants [EAGAIN EWOULDBLOCK] to have the same value, so a portable application should check for both possibilities.

So, I think EAGAIN means: be careful, the message did not fit into send buffer, this call would be blocked in normal (blocking) mode. Use select(2) to determine whether you can send more data.

P.S. Actually, looks like the call failed and nothing was done.

Title: Asynchronous socket send on Linux


问:
How generate a pdf file with django-wkhtmltopdf on IIS 7.5 - 8
I use django-wkhtmltopdf to generate pdfs in my webapp, Works fine using the django integrate server, but when I use IIS 7.5 or 8 gives me this error: WindowsError [Error 6] The handle is invalid

Environment:

```<code>Request Method: GET
Request URL: http://127.0.0.1:8006/blabla/pdf/10/

Django Version: 1.8.5
Python Version: 2.7.10
Installed Applications:
('django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.admin',
 'django.contrib.admindocs',
 'NuevoTicket',
 'crispy_forms',
 'wkhtmltopdf',
 'ckeditor',
 'ckeditor_uploader')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')

Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
  164.                 response = response.render()
File "C:\Python27\lib\site-packages\django\template\response.py" in render
  158.             self.content = self.rendered_content
File "C:\Python27\lib\site-packages\wkhtmltopdf\views.py" in rendered_content
  78.             cmd_options=cmd_options
File "C:\Python27\lib\site-packages\wkhtmltopdf\utils.py" in render_pdf_from_template
  159.                               cmd_options=cmd_options)
File "C:\Python27\lib\site-packages\wkhtmltopdf\utils.py" in convert_to_pdf
  121.     return wkhtmltopdf(pages=[filename], **cmd_options)
File "C:\Python27\lib\site-packages\wkhtmltopdf\utils.py" in wkhtmltopdf
  109.     return check_output(ck_args, **ck_kwargs)
File "C:\Python27\lib\subprocess.py" in check_output
  566.     process = Popen(stdout=PIPE, *popenargs, **kwargs)
File "C:\Python27\lib\subprocess.py" in __init__
  702.          errread, errwrite), to_close = self._get_handles(stdin, stdout, stderr)
File "C:\Python27\lib\subprocess.py" in _get_handles
  857.                 errwrite = _subprocess.GetStdHandle(_subprocess.STD_ERROR_HANDLE)

Exception Type: WindowsError at /blabla/pdf/10/
Exception Value: 6 The handle is invalid
</code>```

答:
I used to have the same problem. Add the option quiet to the pdfkit and also try to modify the file configuration.py from pdfkit

```<code>options = {'quiet': ''}
pdfkit.from_file('in.html', 'out.pdf',options = options)
</code>```

configuration.py

from this:

```<code>self.wkhtmltopdf = subprocess.Popen(['where','wkhtmltopdf'],stdout=subprocess.PIPE).communicate()[0].strip()
</code>```

to:

```<code>self.wkhtmltopdf = subprocess.Popen(['which','wkhtmltopdf'],stdin=subprocess.PIPE,stderr=subprocess.PIPE, stdout=subprocess.PIPE).communicate()[0].strip()
</code>```

Body:
I use django-wkhtmltopdf to generate pdfs in my webapp, Works fine using the django integrate server, but when I use IIS 7.5 or 8 gives me this error: WindowsError [Error 6] The handle is invalid

Environment:

Request Method: GET
Request URL: http://127.0.0.1:8006/blabla/pdf/10/

Django Version: 1.8.5
Python Version: 2.7.10
Installed Applications:
('django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.admin',
 'django.contrib.admindocs',
 'NuevoTicket',
 'crispy_forms',
 'wkhtmltopdf',
 'ckeditor',
 'ckeditor_uploader')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')

Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
  164.                 response = response.render()
File "C:\Python27\lib\site-packages\django\template\response.py" in render
  158.             self.content = self.rendered_content
File "C:\Python27\lib\site-packages\wkhtmltopdf\views.py" in rendered_content
  78.             cmd_options=cmd_options
File "C:\Python27\lib\site-packages\wkhtmltopdf\utils.py" in render_pdf_from_template
  159.                               cmd_options=cmd_options)
File "C:\Python27\lib\site-packages\wkhtmltopdf\utils.py" in convert_to_pdf
  121.     return wkhtmltopdf(pages=[filename], **cmd_options)
File "C:\Python27\lib\site-packages\wkhtmltopdf\utils.py" in wkhtmltopdf
  109.     return check_output(ck_args, **ck_kwargs)
File "C:\Python27\lib\subprocess.py" in check_output
  566.     process = Popen(stdout=PIPE, *popenargs, **kwargs)
File "C:\Python27\lib\subprocess.py" in __init__
  702.          errread, errwrite), to_close = self._get_handles(stdin, stdout, stderr)
File "C:\Python27\lib\subprocess.py" in _get_handles
  857.                 errwrite = _subprocess.GetStdHandle(_subprocess.STD_ERROR_HANDLE)

Exception Type: WindowsError at /blabla/pdf/10/
Exception Value: 6 The handle is invalid

Body:
I used to have the same problem. Add the option quiet to the pdfkit and also try to modify the file configuration.py from pdfkit

options = {'quiet': ''}
pdfkit.from_file('in.html', 'out.pdf',options = options)

configuration.py

from this:

self.wkhtmltopdf = subprocess.Popen(['where','wkhtmltopdf'],stdout=subprocess.PIPE).communicate()[0].strip()

to:

self.wkhtmltopdf = subprocess.Popen(['which','wkhtmltopdf'],stdin=subprocess.PIPE,stderr=subprocess.PIPE, stdout=subprocess.PIPE).communicate()[0].strip()


问:
Python, BeautifulSoup - Can't get specific element's text without its siblings as well
I'm a bit of a novice here, so please forgive my ignorance. I'm trying to get a line of code to return just on specific tag's elements. The problem is, my approaches yield these respective results...:

```<code>for items in soup.find('td', text='Trading Symbol').parent.find_all('td'):
ticker = [items.text.strip()]
print(ticker)

['Trading Symbol']
['AAPL']
['']
</code>```

and

```<code>    for items in soup.find('td', text='Trading Symbol').parent.find_all('td'):
    for td in items.find('td', {'class':['text']}):
        ticker = [td.text.strip()]
        print(ticker)

....error message....for td in items.find('td', {'class':['text']}):
    TypeError: 'NoneType' object is not iterable
</code>```

I understand why the first code does what it does-I've not specified exactly what I'm after (the stock ticker AAPL), but I don't know why adding one additional line of code specifying the class doesn't narrow the list down. By looking at the soup (which I've provided below) I figure the additional line of code would remove 'Trading Symbol' and leave 'AAPL' and '[]' but it comes up with nothing. Any help here?

Here's the soup. There are hundreds of "re" class tags so filtering using that may be helpful but it won't be the end-all.

```<code>##      <tr class="re">
##      <td class="pl " style="border-bottom: 0px;" valign="top"><a class="a" href="javascript:void(0);" onclick="top.Show.showAR( this, 'defref_dei_TradingSymbol', window );">Trading Symbol</a></td>
##      <td class="text">AAPL<span></span>
##      </td>
</code>```

答:
This did the trick. Thanks all!</p>

```<code>for item in soup.find('td', text='Trading Symbol').parent.find_all('td', {'class':['text']}):
    ticker = [item.text.strip()]
    print(ticker)
</code>```

Body:
I'm a bit of a novice here, so please forgive my ignorance. I'm trying to get a line of code to return just on specific tag's elements. The problem is, my approaches yield these respective results...:

for items in soup.find('td', text='Trading Symbol').parent.find_all('td'):
ticker = [items.text.strip()]
print(ticker)

['Trading Symbol']
['AAPL']
['']

and

    for items in soup.find('td', text='Trading Symbol').parent.find_all('td'):
    for td in items.find('td', {'class':['text']}):
        ticker = [td.text.strip()]
        print(ticker)

....error message....for td in items.find('td', {'class':['text']}):
    TypeError: 'NoneType' object is not iterable

I understand why the first code does what it does-I've not specified exactly what I'm after (the stock ticker AAPL), but I don't know why adding one additional line of code specifying the class doesn't narrow the list down. By looking at the soup (which I've provided below) I figure the additional line of code would remove 'Trading Symbol' and leave 'AAPL' and '[]' but it comes up with nothing. Any help here?

Here's the soup. There are hundreds of "re" class tags so filtering using that may be helpful but it won't be the end-all.

##

##      Trading Symbol
##      AAPL
##

Body:
This did the trick. Thanks all!

for item in soup.find('td', text='Trading Symbol').parent.find_all('td', {'class':['text']}):
    ticker = [item.text.strip()]
    print(ticker)