问:
Form in ASP.NET Web API
I have a problem with a form in my Web API. The form is very simple. The user enters a string, the controller receives the string and inserts it into a database with an id. The connection with the database works and I can read from it safely.

EDIT  This is the code in the controller.
EDIT 2 This is the correct and working controler

```<code>public ActionResult PostMyData(string json)
{
        try
        {
            var newEntry = new Questions() { Id = json.Id, Question= json.Question};
            context.Questions.Add(newEntry);
            context.SaveChanges();
            return Ok();
        }
        catch (Exception e)
        {
            return BadRequest();
        }
}
</code>```

This is a part of the HTML page. EDIT
This is the updated script that does not return errors.
EDIT 2 This is the correct and working script

```<code><script language="Javascript">
    $(document).on('click', '#submitButt', function () {
        var myquestion = $('#question').val();
        var json = {
            Id : 1,
            Question: myquestion
        }
        $.ajax({
            type: "POST",
            url: "api/Simple",
            data: JSON.stringify(json),
            dataType: "json",
            contentType:"application/json",
            success: function (data) {
                alert(data);
            },
            error: function (data) {
                alert("An Issue has occured");
            }
        });
    })
</script>
</code>```

答:
Regarding your scenario, you can do something like this:

```<code><input type="text" id="question" name="question" />
<input type="button" id="submitBtn" name="submitBtn" value="Send"/>

<script>
$(document).on('click', '#submitBtn', function () {
    var myquestion=$('#question').val();
    var json = {
      myquestion: myquestion
     };

     $.ajax({
       type: 'POST',
       url: "api/Simple/PostMyData",
       dataType: "json",
       data: JSON.stringify(json),
       contentType: "application/json",
       success: function (data) {
        alert(data);
       },
       error: function (data) {
        alert("An Issue has occured");
       }
    });
})
</script>
</code>```

And your Controller will look like:

```<code>    using System.Web.Script.Serialization;

    [HttpPost]
    public ActionResult Post([FromBody] string json)
    {
        var serializer = new JavaScriptSerializer();
        dynamic jsondata = serializer.Deserialize(json, typeof(object));

        //Get your variables here from AJAX call
        var myquestion= jsondata["myquestion"];
        try
        {
            var newEntry = new Question() { Id = 1, Question= myquestion};
            context.Question.Add(newEntry);
            context.SaveChanges();
            return Ok();
        } catch (Exception e)
        {
            return BadRequest();
        }
    }
</code>```

Title: Form in ASP.NET Web API

Body:
I have a problem with a form in my Web API. The form is very simple. The user enters a string, the controller receives the string and inserts it into a database with an id. The connection with the database works and I can read from it safely.

EDIT  This is the code in the controller.
EDIT 2 This is the correct and working controler

public ActionResult PostMyData(string json)
{
        try
        {
            var newEntry = new Questions() { Id = json.Id, Question= json.Question};
            context.Questions.Add(newEntry);
            context.SaveChanges();
            return Ok();
        }
        catch (Exception e)
        {
            return BadRequest();
        }
}

This is a part of the HTML page. EDIT
This is the updated script that does not return errors.
EDIT 2 This is the correct and working script

Body:
Regarding your scenario, you can do something like this:

<input type="text" id="question" name="question" />
<input type="button" id="submitBtn" name="submitBtn" value="Send"/>

<script>
$(document).on('click', '#submitBtn', function () {
    var myquestion=$('#question').val();
    var json = {
      myquestion: myquestion
     };

     $.ajax({
       type: 'POST',
       url: "api/Simple/PostMyData",
       dataType: "json",
       data: JSON.stringify(json),
       contentType: "application/json",
       success: function (data) {
        alert(data);
       },
       error: function (data) {
        alert("An Issue has occured");
       }
    });
})
</script>

And your Controller will look like:

    using System.Web.Script.Serialization;

    [HttpPost]
    public ActionResult Post([FromBody] string json)
    {
        var serializer = new JavaScriptSerializer();
        dynamic jsondata = serializer.Deserialize(json, typeof(object));

        //Get your variables here from AJAX call
        var myquestion= jsondata["myquestion"];
        try
        {
            var newEntry = new Question() { Id = 1, Question= myquestion};
            context.Question.Add(newEntry);
            context.SaveChanges();
            return Ok();
        } catch (Exception e)
        {
            return BadRequest();
        }
    }


来源: stackexchange

问:
Combining two form values in a loop using jquery
Hi guys I got a tricky question for me.

I have this form in which i want them to combine into one array when i looped all the form fields that is located in a table header.

This is the loop i used to get all the data of the fields

```<code>$('#filterTable').find("table select, table input").each(function(key, value) {
                var name = $(this).attr('name');
                var input = {};

                if (this.value !== ''){
                     if (name === 'filter_select') {
                         input.col = $(this).data('col');
                         input.layer_id = $(this).data('layer');
                         input.filterSelect = $(this).val();
                     } else if (name === 'froms'){
                         input.col = $(this).data('col');
                         input.layer_id = $(this).data('layer');
                         input.from = $(this).val();
                     } else if (name === 'to'){
                         input.col = $(this).data('col');
                         input.layer_id = $(this).data('layer');
                         input.to = $(this).val();
                     }

                     if(layerId == "" && input)
                        layerId = input.layer_id;
                     filterForm.push(input);

                     previous_col = $(this).data('col');
                }

            });
</code>```

This code provide me the following output

```<code>0:
col: 2
layer_id: 139
from: "100"

1:
col: 2
layer_id: 139
to: "500"
</code>```

what i want to accomplish is to combine them since they have the same col or they are located in the same table header so the output will look like this

```<code>0:
col: 2
layer_id: 139
from: "100"
to: "500"
</code>```

any idea how can I solve this one? been stuck here for such a long time. Thanks

答:
You have to use merge

```<code>http://jsfiddle.net/jj7XZ/
</code>```

or directlly see similar

```<code>https://stackoverflow.com/questions/22208966/merging-of-two-arrays-store-unique-elements-and-sorting-in-jquery

https://stackoverflow.com/questions/38807704/trying-to-combine-all-value-from-jquery-each-function
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Hi guys I got a tricky question for me.

I have this form in which i want them to combine into one array when i looped all the form fields that is located in a table header.

This is the loop i used to get all the data of the fields

$('#filterTable').find("table select, table input").each(function(key, value) {
                var name = $(this).attr('name');
                var input = {};

                if (this.value !== ''){
                     if (name === 'filter_select') {
                         input.col = $(this).data('col');
                         input.layer_id = $(this).data('layer');
                         input.filterSelect = $(this).val();
                     } else if (name === 'froms'){
                         input.col = $(this).data('col');
                         input.layer_id = $(this).data('layer');
                         input.from = $(this).val();
                     } else if (name === 'to'){
                         input.col = $(this).data('col');
                         input.layer_id = $(this).data('layer');
                         input.to = $(this).val();
                     }

                     if(layerId == "" && input)
                        layerId = input.layer_id;
                     filterForm.push(input);

                     previous_col = $(this).data('col');
                }

            });

This code provide me the following output

0:
col: 2
layer_id: 139
from: "100"

1:
col: 2
layer_id: 139
to: "500"

what i want to accomplish is to combine them since they have the same col or they are located in the same table header so the output will look like this

0:
col: 2
layer_id: 139
from: "100"
to: "500"

any idea how can I solve this one? been stuck here for such a long time. Thanks

Body:
You have to use merge

http://jsfiddle.net/jj7XZ/

or directlly see similar

https://stackoverflow.com/questions/22208966/merging-of-two-arrays-store-unique-elements-and-sorting-in-jquery

https://stackoverflow.com/questions/38807704/trying-to-combine-all-value-from-jquery-each-function


问:
UITableview reloaddata with animation
I have a UITableView which is populated from array and a drop down list.

If I select any row of drop down list the array will be inserted with new values and tableview should get reloaded.

How to animate the tableview with new array contents?

Animation like I want to show the row one by one. i tried this method

```<code>- (void)reloadRowsAtIndexPaths:(NSArray )indexPaths withRowAnimation:(UITableViewRowAnimation)animation {
NSIndexPath rowToReload = [NSIndexPath indexPathForRow:[names count] inSection:0];
 NSArray* rowsToReload = [NSArray arrayWithObjects:rowToReload, nil];
[tableDetails reloadRowsAtIndexPaths:rowsToReload withRowAnimation:UITableViewRowAnimationNone];
 }
</code>```

答:
Swift 5:

```<code>let section = 0
tableView.reloadSections([section], with: .automatic)
</code>```

Title: UITableview reloaddata with animation

Body:
I have a UITableView which is populated from array and a drop down list.

If I select any row of drop down list the array will be inserted with new values and tableview should get reloaded.

How to animate the tableview with new array contents?

Animation like I want to show the row one by one. i tried this method

- (void)reloadRowsAtIndexPaths:(NSArray )indexPaths withRowAnimation:(UITableViewRowAnimation)animation {
NSIndexPath rowToReload = [NSIndexPath indexPathForRow:[names count] inSection:0];
 NSArray* rowsToReload = [NSArray arrayWithObjects:rowToReload, nil];
[tableDetails reloadRowsAtIndexPaths:rowsToReload withRowAnimation:UITableViewRowAnimationNone];
 }

Body:
Swift 5:

let section = 0
tableView.reloadSections([section], with: .automatic)


问:
How to convert 'false' to 0 and 'true' to 1?
Is there a way to convert true of type unicode to 1 and false of type unicode to 0 (in Python)?

For example: x == 'true' and type(x) == unicode

I want x = 1

PS: I don’t want to use if-else.

答:
only with this:

const a = true;
const b = false;

console.log(+a);//1
console.log(+b);//0


问:
Re-ordering of the rows and columns in a CSR matrix
I have a matrix in a sparse csr format for example:

```<code>from scipy.sparse import csr_matrix
import numpy as np
row = np.array([0, 0, 1, 2, 2, 2])
col = np.array([0, 2, 2, 0, 1, 2])
data = np.array([1, 2, 3, 4, 5, 6])
M  = csr_matrix((data, (row, col)), shape=(3, 3))
M.A =
array([[1, 0, 2],
       [0, 0, 3],
       [4, 5, 6]])
</code>```

I am re-ordering the matrix with the index [2,0,1] using the following approach:

```<code>order = np.array([2,0,1])
M = M[order,:]
M = M[:,order]
M.A
array([[6, 4, 5],
       [2, 1, 0],
       [3, 0, 0]])
</code>```

This approach works but it is not feasible for my real csr_matrix which has the size of  16580746 X 1672751804 and causes memory error.
I took another approach like this:

```<code>edge_list = zip(row,col,dat)
index = dict(zip(order, range(len(order))))
all_coeff = zip(*((index[u], index[v],d) for u,v,d in edge_list if u in index and v in index))
new_row,new_col,new_data = all_coeff
n = len(order)
graph  = csr_matrix((new_data, (new_row, new_col)), shape=(n, n))
</code>```

This also works but fall into the same trap of memory error for large sparse matrix. Any suggestions to efficiently do this?

答:
Let's think smart.

Instead of reordering the matrix, why don't you work directly on the row and column indexes that you provided at the start?

So for example, you can replace your row indexes in this way, from:

```<code>[0, 0, 1, 2, 2, 2]
</code>```

to:

```<code>[2, 2, 0, 1, 1, 1]
</code>```

And your column indexes, from:

```<code>[0, 2, 2, 0, 1, 2]
</code>```

to:

```<code>[2, 1, 1, 2, 0, 1]
</code>```

Body:
I have a matrix in a sparse csr format for example:

from scipy.sparse import csr_matrix
import numpy as np
row = np.array([0, 0, 1, 2, 2, 2])
col = np.array([0, 2, 2, 0, 1, 2])
data = np.array([1, 2, 3, 4, 5, 6])
M  = csr_matrix((data, (row, col)), shape=(3, 3))
M.A =
array([[1, 0, 2],
       [0, 0, 3],
       [4, 5, 6]])

I am re-ordering the matrix with the index [2,0,1] using the following approach:

order = np.array([2,0,1])
M = M[order,:]
M = M[:,order]
M.A
array([[6, 4, 5],
       [2, 1, 0],
       [3, 0, 0]])

This approach works but it is not feasible for my real csr_matrix which has the size of  16580746 X 1672751804 and causes memory error.
I took another approach like this:

edge_list = zip(row,col,dat)
index = dict(zip(order, range(len(order))))
all_coeff = zip(*((index[u], index[v],d) for u,v,d in edge_list if u in index and v in index))
new_row,new_col,new_data = all_coeff
n = len(order)
graph  = csr_matrix((new_data, (new_row, new_col)), shape=(n, n))

This also works but fall into the same trap of memory error for large sparse matrix. Any suggestions to efficiently do this?

Body:
Let's think smart.

Instead of reordering the matrix, why don't you work directly on the row and column indexes that you provided at the start?

So for example, you can replace your row indexes in this way, from:

[0, 0, 1, 2, 2, 2]

to:

[2, 2, 0, 1, 1, 1]

And your column indexes, from:

[0, 2, 2, 0, 1, 2]

to:

[2, 1, 1, 2, 0, 1]


问:
Is Perl a good option for heavy text-processing?
I have this web application which needs to do several heavy text processing tasks: removing certain characters, parsing XML files, among others. Some of them involve regular expressions.

The web application has some implementations in Java and others in PHP. Is it worth using Perl or other specific text processing language for such tasks, or is there really no difference with using PHP?

I even thought of using Sed, Awk maybe even some compiled C scripts for processing texts. There's a lot of text to be processed...

答: Text processing is exactly what Perl was created for. After all it's  Practical Extraction and Report Language. On the other hand, for web application I'd prefer Python.</p>

OwnerDisplayName: Fernando

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: brian d foy


问:
Find all matching ids in an array of objects
We have two arrays of objects:

First:

```<code>const allUsers = [
  {
    id: 49,
    name: 'William'
  },
  {
    id: 82,
    name: 'Michael'
  },
]
</code>```

Second:

```<code>const usersWithActivity = [
  {
    id: 49,
    name: 'William',
    last_activity: "2019-06-20T12:09:55.000Z"
  },
  {
    id: 82,
    name: 'Michael',
    last_activity: "2020-02-20T11:08:50.000Z"
  }
]
</code>```

[QUESTION]:

How can I return an array of all the users that were INACTIVE for the last 3 months? (William's)

答:
you can try something</p>

```<code>function monthDiff(dateFrom, dateTo) {
 return dateTo.getMonth() - dateFrom.getMonth() +
   (12 * (dateTo.getFullYear() - dateFrom.getFullYear()))
}

const usersWithActivity = [
  {
    id: 49,
    name: 'William',
    last_activity: "2019-06-20T12:09:55.000Z"
  },
  {
    id: 82,
    name: 'Michael',
    last_activity: "2020-02-20T11:08:50.000Z"
  }
]

const res = usersWithActivity.filter(user => (monthDiff( new Date(user.last_activity),new Date()) > 3))
</code>```

Body:
We have two arrays of objects:

First:

const allUsers = [
  {
    id: 49,
    name: 'William'
  },
  {
    id: 82,
    name: 'Michael'
  },
]

Second:

const usersWithActivity = [
  {
    id: 49,
    name: 'William',
    last_activity: "2019-06-20T12:09:55.000Z"
  },
  {
    id: 82,
    name: 'Michael',
    last_activity: "2020-02-20T11:08:50.000Z"
  }
]

[QUESTION]:

How can I return an array of all the users that were INACTIVE for the last 3 months? (William's)

Body:
you can try something

function monthDiff(dateFrom, dateTo) {
 return dateTo.getMonth() - dateFrom.getMonth() +
   (12 * (dateTo.getFullYear() - dateFrom.getFullYear()))
}

const usersWithActivity = [
  {
    id: 49,
    name: 'William',
    last_activity: "2019-06-20T12:09:55.000Z"
  },
  {
    id: 82,
    name: 'Michael',
    last_activity: "2020-02-20T11:08:50.000Z"
  }
]

const res = usersWithActivity.filter(user => (monthDiff( new Date(user.last_activity),new Date()) > 3))


问:
Create a nested dictionary from pd dataframe Python
I have the following data frame like (in reality with hundreds of rows)

```<code>    Location Date       Court    Winner
0   Paris    10/2/2018  Outdoor  Flavio
1   Paris    10/2/2018  Indoor   Luca
2   Paris    10/2/2018  Indoor   Giovanni
3   Paris    10/2/2018  Indoor   Luca
</code>```

What I want to do is to get a nested dictionary that look like that:

```<code>{ 'Flavio' : { 'Outdoor' : 1 , 'Indoor' : 0 } , 'Luca' : {'Outdoor' : 0 , 'Indoor' : 2} }
</code>```

and so on. So in other words I want to determine the number of times winners won in the Outdoor and in the Indoor court.

Thank you in advance!

答:
Use crosstab with DataFrame.to_dict:

```<code>d = pd.crosstab(df['Court'],df['Winner']).to_dict()
print (d)
{'Flavio': {'Indoor': 0, 'Outdoor': 1},
 'Giovanni': {'Indoor': 1, 'Outdoor': 0},
 'Luca': {'Indoor': 2, 'Outdoor': 0}}
</code>```

Body:
I have the following data frame like (in reality with hundreds of rows)

    Location Date       Court    Winner
0   Paris    10/2/2018  Outdoor  Flavio
1   Paris    10/2/2018  Indoor   Luca
2   Paris    10/2/2018  Indoor   Giovanni
3   Paris    10/2/2018  Indoor   Luca

What I want to do is to get a nested dictionary that look like that:

{ 'Flavio' : { 'Outdoor' : 1 , 'Indoor' : 0 } , 'Luca' : {'Outdoor' : 0 , 'Indoor' : 2} }

and so on. So in other words I want to determine the number of times winners won in the Outdoor and in the Indoor court.

Thank you in advance!

Body:
Use crosstab with DataFrame.to_dict:

d = pd.crosstab(df['Court'],df['Winner']).to_dict()
print (d)
{'Flavio': {'Indoor': 0, 'Outdoor': 1},
 'Giovanni': {'Indoor': 1, 'Outdoor': 0},
 'Luca': {'Indoor': 2, 'Outdoor': 0}}


问:
Kotlin recursively get size of a folder
I have seen how to return size of a folder in Java: Get size of folder or file, but I couldn't find it in Kotlin.

How do I get the size of a folder in Kotlin?

答:
To get the total size of files in the directory and its children, recursively, you can use the .walkTopDown() function to build a sequence that enumerates all of the files, and then sum the .lengths of its file elements.

```<code>val directory: File = ...

val totalSize =
    directory.walkTopDown().filter { it.isFile }.map { it.length() }.sum()
</code>```

Filtering the elements using .isFile is needed here because it is unspecified what .length returns when called on a File denoting a directory.

Title: Kotlin recursively get size of a folder

Body:
To get the total size of files in the directory and its children, recursively, you can use the .walkTopDown() function to build a sequence that enumerates all of the files, and then sum the .lengths of its file elements.

val directory: File = ...

val totalSize =
    directory.walkTopDown().filter { it.isFile }.map { it.length() }.sum()

Filtering the elements using .isFile is needed here because it is unspecified what .length returns when called on a File denoting a directory.


问:
.net mvc email as username returning error - InvalidProviderUserKey
I have a .Net MVC application that I am trying to use an email address as the username. I implemented the logic from this article where the username is masked as the email. However, when I try to call

```<code>private readonly MembershipProvider _provider;
MembershipCreateStatus status;
_provider.CreateUser(userName, password, email, null, null, true, false, out status);
</code>```

where the username is "email@email.com", the status always returns as InvalidProviderUserKey. If i use a standard username (without the @), it works fine. I tried searching for a solution but i can really find an explanation of InvalidProviderUserKey anywhere.

I was wondering if someone has run into this problem before or might be able to offer an explanation of why this scenario would be returning this specific status. Thanks in advance for any help.

UPDATE

I used Guid.NewGuid for the ProviderUserKey and it worked.

```<code>_provider.CreateUser(userName, password, email,null, null, true, Guid.NewGuid(), out status);
</code>```

Thank you Daniel A. White for your help. The article link that you provided was what I needed to understand it.

答:
Make sure you pass something to providerUserKey, not just false.

providerUserKey Type: System.Object
  The unique identifier from the
  membership data source for the user.

http://msdn.microsoft.com/en-us/library/system.web.security.membershipprovider.createuser.aspx

ContentLicense: CC BY-SA 3.0

Body:
I have a .Net MVC application that I am trying to use an email address as the username. I implemented the logic from this article where the username is masked as the email. However, when I try to call

private readonly MembershipProvider _provider;
MembershipCreateStatus status;
_provider.CreateUser(userName, password, email, null, null, true, false, out status);

where the username is "email@email.com", the status always returns as InvalidProviderUserKey. If i use a standard username (without the @), it works fine. I tried searching for a solution but i can really find an explanation of InvalidProviderUserKey anywhere.

I was wondering if someone has run into this problem before or might be able to offer an explanation of why this scenario would be returning this specific status. Thanks in advance for any help.

UPDATE

I used Guid.NewGuid for the ProviderUserKey and it worked.

_provider.CreateUser(userName, password, email,null, null, true, Guid.NewGuid(), out status);

Thank you Daniel A. White for your help. The article link that you provided was what I needed to understand it.


问:
Server sent event: best practice for identifying reconnecting clients
I am creating a "digital queue ticket" application, where people can host a queue and others, line up. If you line up you will basically see the nr currently being served, nr of people in line, ETA, etc. It's web-based and I decided to use SSE to push changes (for example when nr currently being served changes) to everyone in that specific queue.

I need a way to map/identify each client so that if they disconnect for a while and then reconnect they will still keep their place in line. I am aware that if there is an error, the browser or SSE client will automatically attempt to reconnect. Usually delayed a few seconds depending on the browser. Furthermore, the data stream continues from the point it disconnected, so no messages are lost using Last-Event-Id.

But if, for example, the user quits safari by mistake, reopens it and head back to the same URL, a new connection will be set up, ie it does not "reconnect".

I have considered tokens or cookies to accomplish this. However, SSE standard does not support sending headers (or POST data). Only GET data and cookies. I could pass a token as a query parameter. Here some info I've read on this:

https://community.apigee.com/questions/28794/best-practices-for-passing-an-access-token-without.html

https://www.rfc-editor.org/rfc/rfc6750#section-2.3

People discuss security issues regarding this but I was thinking that since people line up anonymously and the fact that token would only be used to identify reconnecting clients this would not be an issue. Also, I am in charge of both the back end and front end.

Using cookies might also work, but I know pretty much nothing about how they work. I assume I need a persistent cookie to identify a client that is "reconnecting"? If not perhaps I should use WebSockets instead, or polling?. The reason I chose SSE was that I only need unidirectional communication.

I am quite new to this so any tips are appreciated! Been reading everything I can get my hands on for days but haven't found a good solution so far. Perhaps there is some other way to accomplish what I want?

答:
I would definitely go with the cookie. I haven't tried this in Go, but this link shows how to set and receive cookies.

Downsides would be that a user can bypass it by deleting cookies (and they may be motivated to do this, so they can jump the queue?), and (in the EU at least) having to show a "we use cookies" notice. You mentioned the case of the user closing their browser, so a session cookie is not enough, you'd need to use a cookie with an expiration time.

A second choice would be to try and "fingerprint" the user, by a combination of user-agent, IP address, and maybe some other headers. That is unreliable though, especially if users are sharing a proxy, VPN, etc.  (And someone could still get round it, e.g. switching browser, or using a plugin that allows changing user-agent.)


问:
Remove comma only from number separators (regular expression grouping)
I have a column of alpha-numeric string in pandas dataframe.
The goal is to only remove comma from number separators. For example:

```<code>Hello, world! -> Hello, world!
</code>```

but

```<code>Warhammer 40,000 -> Warhammer 40000
Codename 1,337 -> Codename 1337
</code>```

I can deduce that only when both sides are numerics '[0-9]+,[0-9]+' do I want to remove the comma. However, I can't seem to figure out a way to keep the same digits. Could someone help? If related, the size of the dataframe is a few hundred thousand rows and an average string is about 100 words.

p.s. this is my first post. I tried searching for related issue but found none. English is not my mother-tougue, chances are, I might have missed the keyword for this issue. Please do link me to the right place should this happens. Many thanks and much appreciated :)

Update: added the keyword 'grouping' as reminder for myself.

答: I think this is what you need. please refer below screenshot

Body:
I have a column of alpha-numeric string in pandas dataframe.
The goal is to only remove comma from number separators. For example:

Hello, world! -> Hello, world!

but

Warhammer 40,000 -> Warhammer 40000
Codename 1,337 -> Codename 1337

I can deduce that only when both sides are numerics '[0-9]+,[0-9]+' do I want to remove the comma. However, I can't seem to figure out a way to keep the same digits. Could someone help? If related, the size of the dataframe is a few hundred thousand rows and an average string is about 100 words.

p.s. this is my first post. I tried searching for related issue but found none. English is not my mother-tougue, chances are, I might have missed the keyword for this issue. Please do link me to the right place should this happens. Many thanks and much appreciated :)

Update: added the keyword 'grouping' as reminder for myself.


问:
Excel DNA function without parameters still shows one parameter in Excel function wizard
Consider function MyFunc without parameters:

```<code>[ExcelFunction(Name = "MyFunc", Description = "My func")]
public static object MyFunc()
{
    return "My-Func";
}
</code>```

Although it has no parameters, when called from Excel using the function wizard there is one parameter listed:

Where is this parameter coming from?

Can it be removed?

答:
This is a long-standing Excel bug. The extra argument box only goes away when you remove the function description completely.

See also: Register Excel UDF without arguments

Body:
Consider function MyFunc without parameters:

[ExcelFunction(Name = "MyFunc", Description = "My func")]
public static object MyFunc()
{
    return "My-Func";
}

Although it has no parameters, when called from Excel using the function wizard there is one parameter listed:

Where is this parameter coming from?

Can it be removed?


问:
Software for browsing classes in a C/C++ project
I have seen that some developers have a graphical representation of all their classes in an image file which comes with their project. How can I myself create these graphics?

Basically they show what classes exist in a file and how these files relate to each other.

Thanks

答: Another great tool for creating UML class diagrams is Dia.</p>


问:
Adding default tag ('asp-for') in custom tag helper
Please help me to add default tag ('asp-for') in custom tag helper for checkboxlist.
I want to use the tag like default.

Tag helper:

```<code> [HtmlTargetElement(Attributes = "asp-checklistbox, asp-modelname")]
public class CheckListBoxTagHelper : TagHelper
{
    [HtmlAttributeName("asp-checklistbox")]
    public IEnumerable<SelectListItem> Items { get; set; }

    [HtmlAttributeName("asp-modelname")]
    public string ModelName { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {

        var i = 0;
        foreach (var item in Items)
        {
            var selected = item.Selected ? @"checked=""checked""" : "";
            var disabled = item.Disabled ? @"disabled=""disabled""" : "";

            var html = $@"<label><input type=""checkbox"" {selected} {disabled} id=""{ModelName}_{i}__Selected"" name=""{ModelName}[{i}].Selected"" value=""true"" /> {item.Text}</label>";
            html += $@"<input type=""hidden"" id=""{ModelName}_{i}__Value"" name=""{ModelName}[{i}].Value"" value=""{item.Value}"">";
            html += $@"<input type=""hidden"" id=""{ModelName}_{i}__Text"" name=""{ModelName}[{i}].Text"" value=""{item.Text}"">";

            output.Content.AppendHtml(html);

            i++;
        }

        output.Attributes.SetAttribute("class", "th-chklstbx");
    }

}
</code>```

View:

```<code> <div asp-checklistbox="workTypeList" asp-modelname="workTypeId" asp-for="workTypeId"></div>
</code>```

答:
You can mimic asp-for implementation from standard helpers.

Mark your tag helper with [HtmlTargetElement("mychecklistbox", Attributes = "asp-for")] and add to your CheckListBoxTagHelper class this property:

```<code>/// <summary>
/// An expression to be evaluated against the current model.
/// </summary>
[HtmlAttributeName("asp-for")]
public ModelExpression For { get; set; }
</code>```

And use this For property for output HTML you need to access the Model detail like Name. See standard helpers which use it - e.g. LabelTagHelper or others.

Body:
Please help me to add default tag ('asp-for') in custom tag helper for checkboxlist.
I want to use the tag like default.

Tag helper:

 [HtmlTargetElement(Attributes = "asp-checklistbox, asp-modelname")]
public class CheckListBoxTagHelper : TagHelper
{
    [HtmlAttributeName("asp-checklistbox")]
    public IEnumerable<SelectListItem> Items { get; set; }

    [HtmlAttributeName("asp-modelname")]
    public string ModelName { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {

        var i = 0;
        foreach (var item in Items)
        {
            var selected = item.Selected ? @"checked=""checked""" : "";
            var disabled = item.Disabled ? @"disabled=""disabled""" : "";

            var html = $@"<input type=""checkbox"" {selected} {disabled} id=""{ModelName}_{i}__Selected"" name=""{ModelName}[{i}].Selected"" value=""true"" /> {item.Text}";
            html += $@"<input type=""hidden"" id=""{ModelName}_{i}__Value"" name=""{ModelName}[{i}].Value"" value=""{item.Value}"">";
            html += $@"<input type=""hidden"" id=""{ModelName}_{i}__Text"" name=""{ModelName}[{i}].Text"" value=""{item.Text}"">";

            output.Content.AppendHtml(html);

            i++;
        }

        output.Attributes.SetAttribute("class", "th-chklstbx");
    }

}

View:

Body:
You can mimic asp-for implementation from standard helpers.

Mark your tag helper with [HtmlTargetElement("mychecklistbox", Attributes = "asp-for")] and add to your CheckListBoxTagHelper class this property:

/// <summary>
/// An expression to be evaluated against the current model.
/// </summary>
[HtmlAttributeName("asp-for")]
public ModelExpression For { get; set; }

And use this For property for output HTML you need to access the Model detail like Name. See standard helpers which use it - e.g. LabelTagHelper or others.


问:
Need help resolving an Angular 9 TypeScript Error (TypeCasting)
I've updated Angular from 4 to 9 and now, after being able to getting it to work, still getting some errors which I am not able to resolve.

My code:

```<code>this.getTrades().then( ( trades ) => {
    console.log( trades );
    this.trades = new MatTableDataSource<Trade>( trades );
});

getTrades() {
    let promise = new Promise( ( resolve, reject ) => {
        this.dataService.getTrades().subscribe( ( trades ) => {
            resolve( trades );
        });
    });
    return promise;
}

export interface Trade {
    ID: number;
    UserID: number;
    DateTime: Date;
    Exchange: Exchange;
    BaseCoin: Coin;
    MarketCoin: MarketCoin;
    Price: number;
    Amount: number;
    Total: number;
    Last: number;
    Type: Type;
    Status: Status;
    Symbol: string;
}
</code>```

getTrades() datasource:

```<code>getTrades() {

    return this.http.get( 'http://localhost:8888/currencytracker-api/json/get-trades.php' ).pipe(
    map( res => res.json() ));

}
</code>```

getTrades() returns a json array with the following data:

```<code>ID: 1
UserID: 1
DateTime: "2017-12-25T00:00:00+0000"
Exchange: {ID: 1, Title: "BitTrex"}
BaseCoin: {ID: 718, Abbr: "BTC"}
MarketCoin: {ID: 743, Abbr: "XVG"}
Price: "0.000013470000"
Amount: "1019.014328640000"
Total: 0.0137261230067808
Last: "0.000005470000"
Type: {ID: 1, Title: "Limit Buy"}
Status: {ID: 2, Title: "Closed"}
Symbol: "Ƀ"
</code>```

This is the error I get:

ERROR in src/app/components/trades/trades.component.ts:100:68 - error TS2345: Argument of type 'unknown' is not assignable to parameter of type 'Trade[]'. Type '{}' is missing the following properties from type 'Trade[]': length, pop, push, concat, and 26 more.

this.trades = new MatTableDataSource( trades );

Any help understanding this error and resolving it would be very appreciated. Thank you.

Update

When I declared the trades variable I did it as:

```<code>Trade[]
</code>```

Instead I have now declared it as:

```<code>MatTableDataSource<Trade>
</code>```

答:
It's not good practice to subscribe inside a Promise callback. It might lead to memory leaks.

If you need to convert an Observable into a Promise, use toPromise()

Try strong typing getTrades():

```<code>getTrades(): Promise<Trade[]> {
    return this.dataService.getTrades().toPromise()
}
</code>```

Body:
I've updated Angular from 4 to 9 and now, after being able to getting it to work, still getting some errors which I am not able to resolve.

My code:

this.getTrades().then( ( trades ) => {
    console.log( trades );
    this.trades = new MatTableDataSource<Trade>( trades );
});

getTrades() {
    let promise = new Promise( ( resolve, reject ) => {
        this.dataService.getTrades().subscribe( ( trades ) => {
            resolve( trades );
        });
    });
    return promise;
}

export interface Trade {
    ID: number;
    UserID: number;
    DateTime: Date;
    Exchange: Exchange;
    BaseCoin: Coin;
    MarketCoin: MarketCoin;
    Price: number;
    Amount: number;
    Total: number;
    Last: number;
    Type: Type;
    Status: Status;
    Symbol: string;
}

getTrades() datasource:

getTrades() {

    return this.http.get( 'http://localhost:8888/currencytracker-api/json/get-trades.php' ).pipe(
    map( res => res.json() ));

}

getTrades() returns a json array with the following data:

ID: 1
UserID: 1
DateTime: "2017-12-25T00:00:00+0000"
Exchange: {ID: 1, Title: "BitTrex"}
BaseCoin: {ID: 718, Abbr: "BTC"}
MarketCoin: {ID: 743, Abbr: "XVG"}
Price: "0.000013470000"
Amount: "1019.014328640000"
Total: 0.0137261230067808
Last: "0.000005470000"
Type: {ID: 1, Title: "Limit Buy"}
Status: {ID: 2, Title: "Closed"}
Symbol: "Ƀ"

This is the error I get:

ERROR in src/app/components/trades/trades.component.ts:100:68 - error TS2345: Argument of type 'unknown' is not assignable to parameter of type 'Trade[]'. Type '{}' is missing the following properties from type 'Trade[]': length, pop, push, concat, and 26 more.

this.trades = new MatTableDataSource( trades );

Any help understanding this error and resolving it would be very appreciated. Thank you.

Update

When I declared the trades variable I did it as:

Trade[]

Instead I have now declared it as:

MatTableDataSource<Trade>

Body:
It's not good practice to subscribe inside a Promise callback. It might lead to memory leaks.

If you need to convert an Observable into a Promise, use toPromise()

Try strong typing getTrades():

getTrades(): Promise<Trade[]> {
    return this.dataService.getTrades().toPromise()
}


问:
Use spring reactive webclient to pass protobuff request
I am using spring framework reactive webclient to make a call like below

```<code>webClient.post()
    .uri("/v/score/$model")
    .contentType(MediaType.APPLICATION_JSON)
    .bodyValue(gson.toJson(request))
    .accept(MediaType.APPLICATION_JSON)
    .header("Client-Id", clientId)
    .awaitExchange()
    .awaitBody<ScoringResponse>()
</code>```

which is working fine. Now I wan to pass the request as a protobuff object instead of json. How can I do that ?

答:
Set the media type to application/octet-stream and pass your proto model in a byte array form by using the .toByteArray() method. On the receiving end you can use the static method {proto generated class}.parseFrom({your bytes come here}) to rebuild the proto object.

Do not forget the POST method request is basically a body content ;)

Body:
I am using spring framework reactive webclient to make a call like below

webClient.post()
    .uri("/v/score/$model")
    .contentType(MediaType.APPLICATION_JSON)
    .bodyValue(gson.toJson(request))
    .accept(MediaType.APPLICATION_JSON)
    .header("Client-Id", clientId)
    .awaitExchange()
    .awaitBody<ScoringResponse>()

which is working fine. Now I wan to pass the request as a protobuff object instead of json. How can I do that ?


问:
The best way to store the following temporal data in DB
Imagine we have a set of entities each of which has its state: free, busy or broken. The state is specified for a day, for example, today on 2011-05-17 an entity E1 is free and tomorrow on 2011-05-18 it is busy.

There is a need to store ~10^5 entities for 1000 days. Which is the best way to do so?

I am thinking about 2 options:

represent each day as a character "0", "1" or "2" and store for every entity a string of 1000 characters

store each day with entity's state in a row, i.e. 1000 rows for an entity

The most important query for such data is: given start date and end date identify which entities are free.

Performance is of higher priority than storage.

All suggestions and comments are welcome.

答:
I would broadly go for a Kimball Star Schema (http://en.wikipedia.org/wiki/Star_schema) type structure with three tables (initially)

FactEntity (FK kStatus, kDate)

DimStatus (PK kStatus)

DimDate (PK kDate)

This can be loaded quite simply (Dims first followed by Fact(s)), and queried also very simply. Performance can be optimised by suitable indexing.

A big advantage of this design is that it is very extensible; if you want to increase the date range, or increase the number of valid states it is trivial to extend.

Other dimensions could be sensibly added e.g. DimEntity which could have richer information that gives categorical information that migth be interesting to slice/dice your Entities.

The DimDate is normally enriched by adding DayNo, MonthNo, YearNo, DayOfWeek, WeekendFlag, WeekdayFlag, PublicHolidayFlag. These allow some very interesting analyses to be performed.

As @Elad asks, what would ahppen if you added Time based information, then this also can be inforporated by a DimTime dimension having one record per hour or minute.

Apologies for my naming, as I don't have a good understanding of your data. Given more time I could come up with some better ones!


问:
How can I integrate Opencv into a Tkinter window
I'm trying to put face recogniton code that uses opencv to the left hand side of a tkinter window. By doing this I wish to leave the right hand side of the window free so I can output text. e.g. when a face is detected the program will display "Name: Present" I am new to both Tkinter and OpenCV andI can't seem to find a straight answer online. Any Help is appreciated, thanks!

Here is my code below:

```<code>import face_recognition
import cv2
import numpy as np
import tkinter
from tkinter import *
import PySimpleGUI as sg
import xlsxwriter
import os
from PIL import ImageTk,Image
from datetime import datetime;
import datetime

#Defines time
now = datetime.datetime.now().time()

#Setup for period segment of spreadsheetname
if now.hour<9:
    name = "HomeRoom "
elif now.hour==9 and now.min<=50:
    name = "Period1 "
elif now.hour==10 and now.min<=40:
    name = "Period2 "
elif now.hour==11 and now.min<=50:
    name = "Period3 "
elif now.hour==12 and now.min<=40:
    name = "Period4 "
elif now.hour==14 and now.min<=10:
    name = "Period5 "
elif now.hour<=15:
    name = "Period6 "
else:
    name = "Testing "

# Webcam #0 (the default one)
video_capture = cv2.VideoCapture(0)

# to break loop
Printed = False

#Defines todays date                               #day/month/year-HourAM/PM
todays_date = str(datetime.datetime.now().strftime("%d-%m-%Y %I%p"))

#Sets up spreadsheet
workbook = xlsxwriter.Workbook(name + todays_date +'.xlsx')
worksheet = workbook.add_worksheet()
worksheet.write('A1', 'Name')
worksheet.write('B1', 'Attendance')
worksheet.write('A6', 'Jordan Terzian')
worksheet.write('B6', 'Absent')
worksheet.write('A5', 'Daniel Pearce')
worksheet.write('B5', 'Absent')
worksheet.write('A4', 'Ewan Krall')
worksheet.write('B4', 'Absent')
worksheet.write('A3', 'Norman Brosow')
worksheet.write('B3', 'Absent')
worksheet.write('A2', 'Mitchell Benson')
worksheet.write('B2', 'Absent')

# classmates

jordan_image = face_recognition.load_image_file("jordan.jpg")
jordan_face_encoding = face_recognition.face_encodings(jordan_image)[0]

daniel_image = face_recognition.load_image_file("daniel.jpg")
daniel_face_encoding = face_recognition.face_encodings(daniel_image)[0]

ewan_image = face_recognition.load_image_file("ewan.jpg")
ewan_face_encoding = face_recognition.face_encodings(ewan_image)[0]

norman_image = face_recognition.load_image_file("norman.jpg")
norman_face_encoding = face_recognition.face_encodings(norman_image)[0]

mitch_image = face_recognition.load_image_file("mitch.jpg")
mitch_face_encoding = face_recognition.face_encodings(mitch_image)[0]

# Create arrays of known face encodings and their names
known_face_encodings = [
    jordan_face_encoding,
    daniel_face_encoding,
    ewan_face_encoding,
    norman_face_encoding,
    mitch_face_encoding,

]
known_face_names = [
    "Jordan Terzian",
    "Daniel Pearce",
    "Ewan Krall",
    "Norman Brosow",
    "Mitchell Benson",

]

# Initialize variables
face_locations = []
face_encodings = []
face_names = []
process_this_frame = True

while True:
    # Grab a single frame of video
    ret, frame = video_capture.read()

    # Resize frame of video to 1/4 size for faster face recognition processing
    small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)

    # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
    rgb_small_frame = small_frame[:, :, ::-1]

    # Only process every other frame of video to save time
    if process_this_frame:
        # Find all the faces and face encodings in the current frame of video
        face_locations = face_recognition.face_locations(rgb_small_frame)
        face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)

        face_names = []
        for face_encoding in face_encodings:
            # See if the face is a match for the known face(s)
            matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
            name = "Unknown"

            # use the known face with the smallest distance to the new face
            face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
            best_match_index = np.argmin(face_distances)
            if matches[best_match_index]:
                name = known_face_names[best_match_index]

            face_names.append(name)

    process_this_frame = not process_this_frame

    # Display the results
    for (top, right, bottom, left), name in zip(face_locations, face_names):
        # Scale back up face locations since the frame we detected in was scaled to 1/4 size
        top *= 4
        right *= 4
        bottom *= 4
        left *= 4

        # Draw a box around the face
        cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)

        # Draw a label with a name below the face,
        cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
        font = cv2.FONT_HERSHEY_DUPLEX
        cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)
        #Writes to spreadsheet and GUI
        if name == "Jordan Terzian" and not Printed:
            print("Jordan Terzian is Present")
            Printed = True
            worksheet.write('B6', 'Present')
        elif name == "Daniel Pearce" and not Printed:
            print("Daniel Pearce is Present")
            Printed = True
            worksheet.write('B5', 'Present')
        elif name == "Ewan Krall" and not Printed:
            print("Ewan Krall is Present")
            Printed = True
            worksheet.write('B4', 'Present')
        elif name == "Norman Brosow" and not Printed:
            print("Norman Brosow is Present")
            Printed = True
            worksheet.write('B3', 'Present')
        elif name == "Mitchell Benson" and not Printed:
            print("Michell Benson is Present")
            Printed = True
            worskheet.write('B2', 'Present')

    # Display the resulting image
    cv2.imshow('Video', frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Release handle to the webcam, Closes webcam
video_capture.release()
cv2.destroyAllWindows()
workbook.close()
</code>```

答:
It is simple example which gets frame from cv2 and replaces it in PhotoImage which is displayed on Canvas. It uses after() to run function update_frame() periodically so it doesn't block root.mainloop() which has to run all time.

You will have to run code from while True in function update_frame() without using  while True

```<code>import tkinter as tk
from PIL import Image, ImageTk
import cv2

# --- functions ---

def update_frame():

    ret, frame = cap.read()

    image = Image.fromarray(frame)
    photo.paste(image)

    #description['text'] = 'new text'

    root.after(10, update_frame) # update it again after 10ms

# --- main ---

cap = cv2.VideoCapture(0)

# get first frame
ret, frame = cap.read()

# - GUI -

root = tk.Tk()

image = Image.fromarray(frame)
photo = ImageTk.PhotoImage(image)  # it has to be after `tk.Tk()`

canvas = tk.Canvas(root, width=photo.width(), height=photo.height())
canvas.pack(side='left', fill='both', expand=True)

canvas.create_image((0,0), image=photo, anchor='nw')

description = tk.Label(root, text="Place for description")
description.pack(side='right')

# - start -

update_frame() # update it first time

root.mainloop() # start program - this loop runs all time

# - after close -

cap.release()
</code>```

BTW: I have example with buttons Play, Stop, Save Image: python-examples/cv2/tkinter-CV

EDIT: I can test it but it could be something like this.

```<code>import face_recognition
import cv2
import numpy as np
import tkinter
#from tkinter import * # PEP8: `import *` is not preferred
#import PySimpleGUI as sg #
import xlsxwriter
import os
from PIL import ImageTk, Image
#from datetime import datetime;
import datetime

# --- functions ---

def process_frame():
    global process_this_frame

    # Grab a single frame of video
    ret, frame = video_capture.read()

    # Resize frame of video to 1/4 size for faster face recognition processing
    small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)

    # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
    rgb_small_frame = small_frame[:, :, ::-1]

    # Only process every other frame of video to save time
    if process_this_frame:
        # Find all the faces and face encodings in the current frame of video
        face_locations = face_recognition.face_locations(rgb_small_frame)
        face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)

        face_names = []
        for face_encoding in face_encodings:
            # See if the face is a match for the known face(s)
            matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
            name = "Unknown"

            # use the known face with the smallest distance to the new face
            face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
            best_match_index = np.argmin(face_distances)
            if matches[best_match_index]:
                name = known_face_names[best_match_index]

            face_names.append(name)

    process_this_frame = not process_this_frame

    # Display the results
    for (top, right, bottom, left), name in zip(face_locations, face_names):
        # Scale back up face locations since the frame we detected in was scaled to 1/4 size
        top *= 4
        right *= 4
        bottom *= 4
        left *= 4

        # Draw a box around the face
        cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)

        # Draw a label with a name below the face,
        cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
        font = cv2.FONT_HERSHEY_DUPLEX
        cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)
        #Writes to spreadsheet and GUI
        if name == "Jordan Terzian" and not Printed:
            print("Jordan Terzian is Present")
            Printed = True
            worksheet.write('B6', 'Present')
        elif name == "Daniel Pearce" and not Printed:
            print("Daniel Pearce is Present")
            Printed = True
            worksheet.write('B5', 'Present')
        elif name == "Ewan Krall" and not Printed:
            print("Ewan Krall is Present")
            Printed = True
            worksheet.write('B4', 'Present')
        elif name == "Norman Brosow" and not Printed:
            print("Norman Brosow is Present")
            Printed = True
            worksheet.write('B3', 'Present')
        elif name == "Mitchell Benson" and not Printed:
            print("Michell Benson is Present")
            Printed = True
            worskheet.write('B2', 'Present')

        description['text'] = name

    image = Image.fromarray(frame)
    photo.paste(image)

    root.after(40, process_frame) # update it again after 40ms - it gives 25 FPS (1000ms/40ms=25)

# --- init ---

#Defines time
now = datetime.datetime.now().time()

#Setup for period segment of spreadsheetname
if now.hour<9:
    name = "HomeRoom "
elif now.hour==9 and now.min<=50:
    name = "Period1 "
elif now.hour==10 and now.min<=40:
    name = "Period2 "
elif now.hour==11 and now.min<=50:
    name = "Period3 "
elif now.hour==12 and now.min<=40:
    name = "Period4 "
elif now.hour==14 and now.min<=10:
    name = "Period5 "
elif now.hour<=15:
    name = "Period6 "
else:
    name = "Testing "

# to break loop
Printed = False

#Defines todays date                               #day/month/year-HourAM/PM
todays_date = str(datetime.datetime.now().strftime("%d-%m-%Y %I%p"))

#Sets up spreadsheet
workbook = xlsxwriter.Workbook(name + todays_date +'.xlsx')
worksheet = workbook.add_worksheet()
worksheet.write('A1', 'Name')
worksheet.write('B1', 'Attendance')
worksheet.write('A6', 'Jordan Terzian')
worksheet.write('B6', 'Absent')
worksheet.write('A5', 'Daniel Pearce')
worksheet.write('B5', 'Absent')
worksheet.write('A4', 'Ewan Krall')
worksheet.write('B4', 'Absent')
worksheet.write('A3', 'Norman Brosow')
worksheet.write('B3', 'Absent')
worksheet.write('A2', 'Mitchell Benson')
worksheet.write('B2', 'Absent')

# classmates

#jordan_image = face_recognition.load_image_file("jordan.jpg")
#jordan_face_encoding = face_recognition.face_encodings(jordan_image)[0]
#
#daniel_image = face_recognition.load_image_file("daniel.jpg")
#daniel_face_encoding = face_recognition.face_encodings(daniel_image)[0]
#
#ewan_image = face_recognition.load_image_file("ewan.jpg")
#ewan_face_encoding = face_recognition.face_encodings(ewan_image)[0]
#
#norman_image = face_recognition.load_image_file("norman.jpg")
#norman_face_encoding = face_recognition.face_encodings(norman_image)[0]
#
#mitch_image = face_recognition.load_image_file("mitch.jpg")
#mitch_face_encoding = face_recognition.face_encodings(mitch_image)[0]

# Create arrays of known face encodings and their names
#known_face_encodings = [
#    jordan_face_encoding,
#    daniel_face_encoding,
#    ewan_face_encoding,
#    norman_face_encoding,
#    mitch_face_encoding,
#]

filenames = [
    "jordan.jpg",
    "daniel.jpg",
    "ewan.jpg",
    "norman.jpg",
    "mitch.jpg"
]

known_face_encodings = []

for name in filenames:
    image = face_recognition.load_image_file(name)
    face_encoding = face_recognition.face_encodings(image)[0]
    known_face_encodings.append(face_encoding)

known_face_names = [
    "Jordan Terzian",
    "Daniel Pearce",
    "Ewan Krall",
    "Norman Brosow",
    "Mitchell Benson",
]

# Initialize variables
face_locations = []
face_encodings = []
face_names = []
process_this_frame = True

# --- main ---

# Webcam #0 (the default one)
video_capture = cv2.VideoCapture(0)

# get first frame to get size
ret, frame = cap.read()

# - GUI -

root = tk.Tk()

image = Image.fromarray(frame)
photo = ImageTk.PhotoImage(image)  # it has to be after `tk.Tk()`

canvas = tk.Canvas(root, width=photo.width(), height=photo.height())
canvas.pack(side='left', fill='both', expand=True)

canvas.create_image((0,0), image=photo, anchor='nw')

description = tk.Label(root, text="Place for description")
description.pack(side='right')

# - start -

process_frame() # update it first time

root.mainloop() # start program - this loop runs all time

# --- end ---

# Release handle to the webcam, Closes webcam
video_capture.release()
#cv2.destroyAllWindows()
workbook.close()
</code>```

Body:
I'm trying to put face recogniton code that uses opencv to the left hand side of a tkinter window. By doing this I wish to leave the right hand side of the window free so I can output text. e.g. when a face is detected the program will display "Name: Present" I am new to both Tkinter and OpenCV andI can't seem to find a straight answer online. Any Help is appreciated, thanks!

Here is my code below:

import face_recognition
import cv2
import numpy as np
import tkinter
from tkinter import *
import PySimpleGUI as sg
import xlsxwriter
import os
from PIL import ImageTk,Image
from datetime import datetime;
import datetime

#Defines time
now = datetime.datetime.now().time()

#Setup for period segment of spreadsheetname
if now.hour<9:
    name = "HomeRoom "
elif now.hour==9 and now.min<=50:
    name = "Period1 "
elif now.hour==10 and now.min<=40:
    name = "Period2 "
elif now.hour==11 and now.min<=50:
    name = "Period3 "
elif now.hour==12 and now.min<=40:
    name = "Period4 "
elif now.hour==14 and now.min<=10:
    name = "Period5 "
elif now.hour<=15:
    name = "Period6 "
else:
    name = "Testing "

# Webcam #0 (the default one)
video_capture = cv2.VideoCapture(0)

# to break loop
Printed = False

#Defines todays date                               #day/month/year-HourAM/PM
todays_date = str(datetime.datetime.now().strftime("%d-%m-%Y %I%p"))

#Sets up spreadsheet
workbook = xlsxwriter.Workbook(name + todays_date +'.xlsx')
worksheet = workbook.add_worksheet()
worksheet.write('A1', 'Name')
worksheet.write('B1', 'Attendance')
worksheet.write('A6', 'Jordan Terzian')
worksheet.write('B6', 'Absent')
worksheet.write('A5', 'Daniel Pearce')
worksheet.write('B5', 'Absent')
worksheet.write('A4', 'Ewan Krall')
worksheet.write('B4', 'Absent')
worksheet.write('A3', 'Norman Brosow')
worksheet.write('B3', 'Absent')
worksheet.write('A2', 'Mitchell Benson')
worksheet.write('B2', 'Absent')

# classmates

jordan_image = face_recognition.load_image_file("jordan.jpg")
jordan_face_encoding = face_recognition.face_encodings(jordan_image)[0]

daniel_image = face_recognition.load_image_file("daniel.jpg")
daniel_face_encoding = face_recognition.face_encodings(daniel_image)[0]

ewan_image = face_recognition.load_image_file("ewan.jpg")
ewan_face_encoding = face_recognition.face_encodings(ewan_image)[0]

norman_image = face_recognition.load_image_file("norman.jpg")
norman_face_encoding = face_recognition.face_encodings(norman_image)[0]

mitch_image = face_recognition.load_image_file("mitch.jpg")
mitch_face_encoding = face_recognition.face_encodings(mitch_image)[0]

# Create arrays of known face encodings and their names
known_face_encodings = [
    jordan_face_encoding,
    daniel_face_encoding,
    ewan_face_encoding,
    norman_face_encoding,
    mitch_face_encoding,

]
known_face_names = [
    "Jordan Terzian",
    "Daniel Pearce",
    "Ewan Krall",
    "Norman Brosow",
    "Mitchell Benson",

]

# Initialize variables
face_locations = []
face_encodings = []
face_names = []
process_this_frame = True

while True:
    # Grab a single frame of video
    ret, frame = video_capture.read()

    # Resize frame of video to 1/4 size for faster face recognition processing
    small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)

    # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
    rgb_small_frame = small_frame[:, :, ::-1]

    # Only process every other frame of video to save time
    if process_this_frame:
        # Find all the faces and face encodings in the current frame of video
        face_locations = face_recognition.face_locations(rgb_small_frame)
        face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)

        face_names = []
        for face_encoding in face_encodings:
            # See if the face is a match for the known face(s)
            matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
            name = "Unknown"

            # use the known face with the smallest distance to the new face
            face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
            best_match_index = np.argmin(face_distances)
            if matches[best_match_index]:
                name = known_face_names[best_match_index]

            face_names.append(name)

    process_this_frame = not process_this_frame

    # Display the results
    for (top, right, bottom, left), name in zip(face_locations, face_names):
        # Scale back up face locations since the frame we detected in was scaled to 1/4 size
        top *= 4
        right *= 4
        bottom *= 4
        left *= 4

        # Draw a box around the face
        cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)

        # Draw a label with a name below the face,
        cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
        font = cv2.FONT_HERSHEY_DUPLEX
        cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)
        #Writes to spreadsheet and GUI
        if name == "Jordan Terzian" and not Printed:
            print("Jordan Terzian is Present")
            Printed = True
            worksheet.write('B6', 'Present')
        elif name == "Daniel Pearce" and not Printed:
            print("Daniel Pearce is Present")
            Printed = True
            worksheet.write('B5', 'Present')
        elif name == "Ewan Krall" and not Printed:
            print("Ewan Krall is Present")
            Printed = True
            worksheet.write('B4', 'Present')
        elif name == "Norman Brosow" and not Printed:
            print("Norman Brosow is Present")
            Printed = True
            worksheet.write('B3', 'Present')
        elif name == "Mitchell Benson" and not Printed:
            print("Michell Benson is Present")
            Printed = True
            worskheet.write('B2', 'Present')

    # Display the resulting image
    cv2.imshow('Video', frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Release handle to the webcam, Closes webcam
video_capture.release()
cv2.destroyAllWindows()
workbook.close()

Body:
It is simple example which gets frame from cv2 and replaces it in PhotoImage which is displayed on Canvas. It uses after() to run function update_frame() periodically so it doesn't block root.mainloop() which has to run all time.

You will have to run code from while True in function update_frame() without using  while True

import tkinter as tk
from PIL import Image, ImageTk
import cv2

# --- functions ---

def update_frame():

    ret, frame = cap.read()

    image = Image.fromarray(frame)
    photo.paste(image)

    #description['text'] = 'new text'

    root.after(10, update_frame) # update it again after 10ms

# --- main ---

cap = cv2.VideoCapture(0)

# get first frame
ret, frame = cap.read()

# - GUI -

root = tk.Tk()

image = Image.fromarray(frame)
photo = ImageTk.PhotoImage(image)  # it has to be after `tk.Tk()`

canvas = tk.Canvas(root, width=photo.width(), height=photo.height())
canvas.pack(side='left', fill='both', expand=True)

canvas.create_image((0,0), image=photo, anchor='nw')

description = tk.Label(root, text="Place for description")
description.pack(side='right')

# - start -

update_frame() # update it first time

root.mainloop() # start program - this loop runs all time

# - after close -

cap.release()

BTW: I have example with buttons Play, Stop, Save Image: python-examples/cv2/tkinter-CV

EDIT: I can test it but it could be something like this.

import face_recognition
import cv2
import numpy as np
import tkinter
#from tkinter import * # PEP8: `import *` is not preferred
#import PySimpleGUI as sg #
import xlsxwriter
import os
from PIL import ImageTk, Image
#from datetime import datetime;
import datetime

# --- functions ---

def process_frame():
    global process_this_frame

    # Grab a single frame of video
    ret, frame = video_capture.read()

    # Resize frame of video to 1/4 size for faster face recognition processing
    small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)

    # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
    rgb_small_frame = small_frame[:, :, ::-1]

    # Only process every other frame of video to save time
    if process_this_frame:
        # Find all the faces and face encodings in the current frame of video
        face_locations = face_recognition.face_locations(rgb_small_frame)
        face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)

        face_names = []
        for face_encoding in face_encodings:
            # See if the face is a match for the known face(s)
            matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
            name = "Unknown"

            # use the known face with the smallest distance to the new face
            face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
            best_match_index = np.argmin(face_distances)
            if matches[best_match_index]:
                name = known_face_names[best_match_index]

            face_names.append(name)

    process_this_frame = not process_this_frame

    # Display the results
    for (top, right, bottom, left), name in zip(face_locations, face_names):
        # Scale back up face locations since the frame we detected in was scaled to 1/4 size
        top *= 4
        right *= 4
        bottom *= 4
        left *= 4

        # Draw a box around the face
        cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)

        # Draw a label with a name below the face,
        cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
        font = cv2.FONT_HERSHEY_DUPLEX
        cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)
        #Writes to spreadsheet and GUI
        if name == "Jordan Terzian" and not Printed:
            print("Jordan Terzian is Present")
            Printed = True
            worksheet.write('B6', 'Present')
        elif name == "Daniel Pearce" and not Printed:
            print("Daniel Pearce is Present")
            Printed = True
            worksheet.write('B5', 'Present')
        elif name == "Ewan Krall" and not Printed:
            print("Ewan Krall is Present")
            Printed = True
            worksheet.write('B4', 'Present')
        elif name == "Norman Brosow" and not Printed:
            print("Norman Brosow is Present")
            Printed = True
            worksheet.write('B3', 'Present')
        elif name == "Mitchell Benson" and not Printed:
            print("Michell Benson is Present")
            Printed = True
            worskheet.write('B2', 'Present')

        description['text'] = name

    image = Image.fromarray(frame)
    photo.paste(image)

    root.after(40, process_frame) # update it again after 40ms - it gives 25 FPS (1000ms/40ms=25)

# --- init ---

#Defines time
now = datetime.datetime.now().time()

#Setup for period segment of spreadsheetname
if now.hour<9:
    name = "HomeRoom "
elif now.hour==9 and now.min<=50:
    name = "Period1 "
elif now.hour==10 and now.min<=40:
    name = "Period2 "
elif now.hour==11 and now.min<=50:
    name = "Period3 "
elif now.hour==12 and now.min<=40:
    name = "Period4 "
elif now.hour==14 and now.min<=10:
    name = "Period5 "
elif now.hour<=15:
    name = "Period6 "
else:
    name = "Testing "

# to break loop
Printed = False

#Defines todays date                               #day/month/year-HourAM/PM
todays_date = str(datetime.datetime.now().strftime("%d-%m-%Y %I%p"))

#Sets up spreadsheet
workbook = xlsxwriter.Workbook(name + todays_date +'.xlsx')
worksheet = workbook.add_worksheet()
worksheet.write('A1', 'Name')
worksheet.write('B1', 'Attendance')
worksheet.write('A6', 'Jordan Terzian')
worksheet.write('B6', 'Absent')
worksheet.write('A5', 'Daniel Pearce')
worksheet.write('B5', 'Absent')
worksheet.write('A4', 'Ewan Krall')
worksheet.write('B4', 'Absent')
worksheet.write('A3', 'Norman Brosow')
worksheet.write('B3', 'Absent')
worksheet.write('A2', 'Mitchell Benson')
worksheet.write('B2', 'Absent')

# classmates

#jordan_image = face_recognition.load_image_file("jordan.jpg")
#jordan_face_encoding = face_recognition.face_encodings(jordan_image)[0]
#
#daniel_image = face_recognition.load_image_file("daniel.jpg")
#daniel_face_encoding = face_recognition.face_encodings(daniel_image)[0]
#
#ewan_image = face_recognition.load_image_file("ewan.jpg")
#ewan_face_encoding = face_recognition.face_encodings(ewan_image)[0]
#
#norman_image = face_recognition.load_image_file("norman.jpg")
#norman_face_encoding = face_recognition.face_encodings(norman_image)[0]
#
#mitch_image = face_recognition.load_image_file("mitch.jpg")
#mitch_face_encoding = face_recognition.face_encodings(mitch_image)[0]

# Create arrays of known face encodings and their names
#known_face_encodings = [
#    jordan_face_encoding,
#    daniel_face_encoding,
#    ewan_face_encoding,
#    norman_face_encoding,
#    mitch_face_encoding,
#]

filenames = [
    "jordan.jpg",
    "daniel.jpg",
    "ewan.jpg",
    "norman.jpg",
    "mitch.jpg"
]

known_face_encodings = []

for name in filenames:
    image = face_recognition.load_image_file(name)
    face_encoding = face_recognition.face_encodings(image)[0]
    known_face_encodings.append(face_encoding)

known_face_names = [
    "Jordan Terzian",
    "Daniel Pearce",
    "Ewan Krall",
    "Norman Brosow",
    "Mitchell Benson",
]

# Initialize variables
face_locations = []
face_encodings = []
face_names = []
process_this_frame = True

# --- main ---

# Webcam #0 (the default one)
video_capture = cv2.VideoCapture(0)

# get first frame to get size
ret, frame = cap.read()

# - GUI -

root = tk.Tk()

image = Image.fromarray(frame)
photo = ImageTk.PhotoImage(image)  # it has to be after `tk.Tk()`

canvas = tk.Canvas(root, width=photo.width(), height=photo.height())
canvas.pack(side='left', fill='both', expand=True)

canvas.create_image((0,0), image=photo, anchor='nw')

description = tk.Label(root, text="Place for description")
description.pack(side='right')

# - start -

process_frame() # update it first time

root.mainloop() # start program - this loop runs all time

# --- end ---

# Release handle to the webcam, Closes webcam
video_capture.release()
#cv2.destroyAllWindows()
workbook.close()


问:
Octet Stream to PDF Azure Python
I'm trying to upload a PDF to an Azure blob store, and then download and read it. The upload works fine, and when I open it in the Azure Storage Explorer, the file opens fine. However, when I try to download it, I get an Octet stream and I cant figure out how to convert it back into a PDF. Im doing this all through a Function App so I'm not sure if writing everything to a temporary file will help. I tried it and I got a corrupted pdf as my output. My code is as follows.

Upload:

```<code>blob_service_client = BlobServiceClient.from_connection_string(connect_str)
container_name = 'testblobstore123'

file = req.files['file']
try:
    blob_client = blob_service_client.get_blob_client(container=container_name, blob=file.filename)
    blob_client.upload_blob(file)
except Exception as e:
    print(e)
    return "Unspecified Error"
</code>```

Download:

```<code>blob_service_client = BlobServiceClient.from_connection_string(connect_str)
container_name = 'testblobstore123'
file = req.form['file']
blob_client = blob_service_client.get_blob_client(container=container_name, blob=file)
# data = blob_service_client.get_data_to_text(container_name, file)

data = blob_client.download_blob().readall()
</code>```

答:
Firstly in my test, I open the file link or download it to local, the content-type is Octet stream, however they are able to read.

Below is my download code.

```<code>blob_service_client = BlobServiceClient.from_connection_string(connect_str)
container_name = 'test'
blob_name='nodejschinese.pdf'
download_file_path = os.path.join('D:', blob_name)
blob_client = blob_service_client.get_blob_client(container=container_name, blob=blob_name)

with open(download_file_path, "wb") as download_file:
    download_file.write(blob_client.download_blob().readall())
</code>```

Secondly if you want to change the content-type when y ou upload it, you could add ContentSettings in the upload_blob method.

Below is my upload code with ContentSettings.

```<code>from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient,ContentSettings

connect_str='connection string'
blob_service_client = BlobServiceClient.from_connection_string(connect_str)
container_name = 'test'
local_file_name='nodejs.pdf'
upload_file_path='E:\\nodejs.pdf'

blob_client = blob_service_client.get_blob_client(container=container_name, blob=local_file_name)
with open(upload_file_path, "rb") as data:
    blob_client.upload_blob(data,content_settings=ContentSettings(content_type='application/pdf'))
</code>```

Title: Octet Stream to PDF Azure Python

Body:
I'm trying to upload a PDF to an Azure blob store, and then download and read it. The upload works fine, and when I open it in the Azure Storage Explorer, the file opens fine. However, when I try to download it, I get an Octet stream and I cant figure out how to convert it back into a PDF. Im doing this all through a Function App so I'm not sure if writing everything to a temporary file will help. I tried it and I got a corrupted pdf as my output. My code is as follows.

Upload:

blob_service_client = BlobServiceClient.from_connection_string(connect_str)
container_name = 'testblobstore123'

file = req.files['file']
try:
    blob_client = blob_service_client.get_blob_client(container=container_name, blob=file.filename)
    blob_client.upload_blob(file)
except Exception as e:
    print(e)
    return "Unspecified Error"

Download:

blob_service_client = BlobServiceClient.from_connection_string(connect_str)
container_name = 'testblobstore123'
file = req.form['file']
blob_client = blob_service_client.get_blob_client(container=container_name, blob=file)
# data = blob_service_client.get_data_to_text(container_name, file)

data = blob_client.download_blob().readall()

Body:
Firstly in my test, I open the file link or download it to local, the content-type is Octet stream, however they are able to read.

Below is my download code.

blob_service_client = BlobServiceClient.from_connection_string(connect_str)
container_name = 'test'
blob_name='nodejschinese.pdf'
download_file_path = os.path.join('D:', blob_name)
blob_client = blob_service_client.get_blob_client(container=container_name, blob=blob_name)

with open(download_file_path, "wb") as download_file:
    download_file.write(blob_client.download_blob().readall())

Secondly if you want to change the content-type when y ou upload it, you could add ContentSettings in the upload_blob method.

Below is my upload code with ContentSettings.

from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient,ContentSettings

connect_str='connection string'
blob_service_client = BlobServiceClient.from_connection_string(connect_str)
container_name = 'test'
local_file_name='nodejs.pdf'
upload_file_path='E:\\nodejs.pdf'

blob_client = blob_service_client.get_blob_client(container=container_name, blob=local_file_name)
with open(upload_file_path, "rb") as data:
    blob_client.upload_blob(data,content_settings=ContentSettings(content_type='application/pdf'))


问:
Emitting an array using socket.io
For a school project I'am making a multiplayer snake game with socket.io. I tried to sync the body of the snake you play (snake1, which is an array with vectors as location. The snakes them self are objects) and send that with socket.io to the other player. To send the body I use socket.emit('snakeBody', snake1.body). But when I load the page i get the error "Uncaught RangeError: Maximum call stack size exceeded". I first thought it was the array but when i try to sync a normal variable with a vector i still got the error (when i sync normal variables or arrays, without a vector in it, it does work). My question is if it is possible to sync an array with a vectors as values using socket.io.

The index.js file (the file where all the socket things happen):

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

var server = app.listen(3000);
app.use(express.static('public'));

console.log("The server is live");

var socket = require('socket.io');
var io = socket(server);

io.sockets.on('connection', newConnection);

function newConnection(socket) {
  socket.on('snakeBody', body);

  function body(data) {
    socket.broadcast.emit('testBody', data);
  }
}

</code>```

The game.js file (the base of the game. Where the socket sends and receives)

```<code>//Defines both snakes
var snake1;
var snake2;

var socket;

function setup() {
  //The canvas for p5js to show something
  createCanvas(400, 400);

  //The starting location for the snakes (the snakes are objects in a class)
  snake1 = new Snake(200, 200);
  snake2 = new Snake(150, 250);

  //Socket server ip
  socket = io.connect('https://myIP.com');
  socket.on('snakeBody', newSnake);
}

function draw() {
  background(0);

  snake1.loop(255, 0, 0, 1, 340);

  //Sends all the players data to the server to be send to the other player
  socket.emit('snakeBody', snake1.body);
}

function newSnake(newSnake) {
  //The function that will do thing when it receives something from the socket
}
</code>```

The snake class:
It is possible that it will call function that do not exist in this part but thats because I removed them because they were not directly important for this question.

```<code>class Snake {

  //----------------------------------------------//
  //                 Snake Setup:                 //
  //----------------------------------------------//

  //Contains all building info
  constructor(x, y) {
    //Snake elements:
    this.body = [];
    this.body[0] = createVector(x, y);
    this.head = '';
    this.part = '';

    //Game elements:
    //Dimension
    this.dim = 10;
    //Direction
    this.x = 0;
    this.y = 0;
    //Speed
    this.s = 2;
    //Score
    this.scoreLeng = 0;
  }

  //Contains all functions that needs to be looped
  loop(r, g, b, p, t) {
    //Move and update
    this.move(p);
    this.update();

    //If snake is dead
    if (this.gameOver()) {
      //Respawn
      this.respawn(p);
    }

    //If snake eat
    if (this.eat(food)) {
      //Grow
      this.grow();
      //Update food location
      food.update();
      //Play eat sound
      // eatSound.play();
    }
    //Show snake
    this.show(r, g, b, t);
  }

  //----------------------------------------------//
  //            All snake functions:              //
  //----------------------------------------------//

  show(r, g, b, t) {
    //Loop thru every body part of array
    for (var i = 0; i < this.body.length; i++) {
      //Rectangle with rgb color:
      fill(r, g, b);
      noStroke();
      rect(this.body[i].x, this.body[i].y, this.dim, this.dim);
    }
    //Score text:
    textSize(17);
    text("score:" + this.scoreLeng, t, 395);
  }

  dir(x, y) {
    //Directions:
    this.x = x;
    this.y = y;
  }

  update() {
    //Copy of the last element of the array:
    this.head = this.body[this.body.length - 1].copy();
    //Shift the array
    this.body.shift();

    //Add direction to snake location
    this.head.x += this.x;
    this.head.y += this.y;

    //Push head to end of array
    this.body.push(this.head);
  }

  gameOver() {
    //If snake is outside play area
    if (this.head.x == 400 || this.head.y == 400 || this.head.x < 0 || this.head.y < 0) {
      return true;
    }

    //Loop thru body parts in array
    for (var i = 0; i < this.body.length - 1; i++) {
      //Alle body parts in part variable
      this.part = this.body[i];
      //If head of snake hits part
      if (this.part.x == this.head.x && this.part.y == this.head.y) {
        return true;
      }
    }

    //Loop thru body array
    for (var j = 0; j < this.body.length - 1; j++) {
      //If snake 1 or snake 2 head hits parts of other snake
      if (snake1.head.x == this.body[j].x && snake1.head.y == this.body[j].y) {
        console.log("snake 1 is dead");
      }
      if (snake2.head.x == this.body[j].x && snake2.head.y == this.body[j].y) {
        console.log("snake 2 is dead");
      }
    }

    return false;
  }
}
</code>```

答:
When you get a `Maximum call stack size exceeded" error, it means that somewhere in your code, you are calling a function which in turn calls another function and so forth, until you hit the call stack limit. I'm not sure how that would apply in your case here, you're not sharing much.

My quick suggestion for you would be to send your data as string:

```<code>socket.emit('snakeBody', JSON.stringify(snake1.body))
</code>```

Then on the other end, parse it:

```<code>const snakeBody = JSON.parse(snakeBody)
</code>```

Title: Emitting an array using socket.io

Body:
For a school project I'am making a multiplayer snake game with socket.io. I tried to sync the body of the snake you play (snake1, which is an array with vectors as location. The snakes them self are objects) and send that with socket.io to the other player. To send the body I use socket.emit('snakeBody', snake1.body). But when I load the page i get the error "Uncaught RangeError: Maximum call stack size exceeded". I first thought it was the array but when i try to sync a normal variable with a vector i still got the error (when i sync normal variables or arrays, without a vector in it, it does work). My question is if it is possible to sync an array with a vectors as values using socket.io.

The index.js file (the file where all the socket things happen):

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

var server = app.listen(3000);
app.use(express.static('public'));

console.log("The server is live");

var socket = require('socket.io');
var io = socket(server);

io.sockets.on('connection', newConnection);

function newConnection(socket) {
  socket.on('snakeBody', body);

  function body(data) {
    socket.broadcast.emit('testBody', data);
  }
}

The game.js file (the base of the game. Where the socket sends and receives)

//Defines both snakes
var snake1;
var snake2;

var socket;

function setup() {
  //The canvas for p5js to show something
  createCanvas(400, 400);

  //The starting location for the snakes (the snakes are objects in a class)
  snake1 = new Snake(200, 200);
  snake2 = new Snake(150, 250);

  //Socket server ip
  socket = io.connect('https://myIP.com');
  socket.on('snakeBody', newSnake);
}

function draw() {
  background(0);

  snake1.loop(255, 0, 0, 1, 340);

  //Sends all the players data to the server to be send to the other player
  socket.emit('snakeBody', snake1.body);
}

function newSnake(newSnake) {
  //The function that will do thing when it receives something from the socket
}

The snake class:
It is possible that it will call function that do not exist in this part but thats because I removed them because they were not directly important for this question.

class Snake {

  //----------------------------------------------//
  //                 Snake Setup:                 //
  //----------------------------------------------//

  //Contains all building info
  constructor(x, y) {
    //Snake elements:
    this.body = [];
    this.body[0] = createVector(x, y);
    this.head = '';
    this.part = '';

    //Game elements:
    //Dimension
    this.dim = 10;
    //Direction
    this.x = 0;
    this.y = 0;
    //Speed
    this.s = 2;
    //Score
    this.scoreLeng = 0;
  }

  //Contains all functions that needs to be looped
  loop(r, g, b, p, t) {
    //Move and update
    this.move(p);
    this.update();

    //If snake is dead
    if (this.gameOver()) {
      //Respawn
      this.respawn(p);
    }

    //If snake eat
    if (this.eat(food)) {
      //Grow
      this.grow();
      //Update food location
      food.update();
      //Play eat sound
      // eatSound.play();
    }
    //Show snake
    this.show(r, g, b, t);
  }

  //----------------------------------------------//
  //            All snake functions:              //
  //----------------------------------------------//

  show(r, g, b, t) {
    //Loop thru every body part of array
    for (var i = 0; i < this.body.length; i++) {
      //Rectangle with rgb color:
      fill(r, g, b);
      noStroke();
      rect(this.body[i].x, this.body[i].y, this.dim, this.dim);
    }
    //Score text:
    textSize(17);
    text("score:" + this.scoreLeng, t, 395);
  }

  dir(x, y) {
    //Directions:
    this.x = x;
    this.y = y;
  }

  update() {
    //Copy of the last element of the array:
    this.head = this.body[this.body.length - 1].copy();
    //Shift the array
    this.body.shift();

    //Add direction to snake location
    this.head.x += this.x;
    this.head.y += this.y;

    //Push head to end of array
    this.body.push(this.head);
  }

  gameOver() {
    //If snake is outside play area
    if (this.head.x == 400 || this.head.y == 400 || this.head.x < 0 || this.head.y < 0) {
      return true;
    }

    //Loop thru body parts in array
    for (var i = 0; i < this.body.length - 1; i++) {
      //Alle body parts in part variable
      this.part = this.body[i];
      //If head of snake hits part
      if (this.part.x == this.head.x && this.part.y == this.head.y) {
        return true;
      }
    }

    //Loop thru body array
    for (var j = 0; j < this.body.length - 1; j++) {
      //If snake 1 or snake 2 head hits parts of other snake
      if (snake1.head.x == this.body[j].x && snake1.head.y == this.body[j].y) {
        console.log("snake 1 is dead");
      }
      if (snake2.head.x == this.body[j].x && snake2.head.y == this.body[j].y) {
        console.log("snake 2 is dead");
      }
    }

    return false;
  }
}

Body:
When you get a `Maximum call stack size exceeded" error, it means that somewhere in your code, you are calling a function which in turn calls another function and so forth, until you hit the call stack limit. I'm not sure how that would apply in your case here, you're not sharing much.

My quick suggestion for you would be to send your data as string:

socket.emit('snakeBody', JSON.stringify(snake1.body))

Then on the other end, parse it:

const snakeBody = JSON.parse(snakeBody)


问:
Show image on SCNPlane in Scene kit & AR kit in swift iOS
I followed this raywenderlich tutorial to detect image using AR and Scene Kit. In this example they showed displaying video on top of detected image.

https://www.raywenderlich.com/6957-building-a-museum-app-with-arkit-2

I want to display image on top of detected image. Please help me how can I add childNode to SCNNode so that I can display image on top of it.

Here is the code which I tried it's not working  showing a blank white screen.

```<code>                            DispatchQueue.main.async {

                        let size = imageAnchor.referenceImage.physicalSize

                        let imageView = UIImageView(image: UIImage(named: "BG.png")!)

                        let imgMaterial = SCNMaterial()
                        imgMaterial.diffuse.contents = imageView

                        let imgPlane = SCNPlane(width: size.width, height: size.height)
                        imgPlane.materials = [imgMaterial]

                        let imgNode = SCNNode(geometry: imgPlane)
                        imgNode.eulerAngles.x = -.pi / 2

                        node.addChildNode(imgNode)
                         node.opacity = 1

                        }
</code>```

Please help to show image on top of detected image. Thanks in advance.

I'm able to show image on top of detected image but it takes lot of memory what is wrong in that code.

And same as image view I'm displaying gif play on top of detected image with the below code.

```<code>                                let size = imageAnchor.referenceImage.physicalSize

                            let imgNameFromDoc = person["actionToTake"] as! String

                            let documentsPathURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first

                            let imgpath = documentsPathURL?.appendingPathComponent("/Packages/\(self.selectedDatasetName)/3DScenes/\(imgNameFromDoc)")

                            let imageData = try! Data(contentsOf: URL(fileURLWithPath: imgpath!.path))

                            let imageURL = UIImage.gifImageWithData(imageData)

                            self.gifImgView = UIImageView(image: imageURL)

                            let imgMaterial = SCNMaterial()
                            imgMaterial.diffuse.contents = self.gifImgView

                            let imgPlane = SCNPlane(width: CGFloat(scaleActionSize(wid: Float(size.width), hei:Float(size.height))[0]), height: CGFloat(scaleActionSize(wid: Float(size.width), hei:Float(size.height))[1]))

                            imgPlane.materials = [imgMaterial]

                            let imgNode = SCNNode(geometry: imgPlane)
                            imgNode.eulerAngles.x = -.pi / 2

                            node.addChildNode(imgNode)
                            node.opacity = 1
</code>```

With the help of image extension I'm showing GIF on image view on top of detected image.
https://github.com/kiritmodi2702/GIF-Swift/blob/master/GIF-Swift/iOSDevCenters%2BGIF.swift

How to load GIF image in Swift?

I dragged iOSDevCenters+GIF.swift class inside app and displayed gif.

When I use this gif image viewto display gif and image view to display image it takes more than 800 MB memory in Xcode running with iPad.

can somebody help me to find any memory leaks(tried with instruments not able to fix) or anything wrong in this code.

答:
I guess you have image tracking working.

The next method is called when a new anchor is added. In this case when your image tracked is detected. So the parameter node is the image tracked and you can add a child to that image as in the tutorial. So you can try the next (use ARSCNViewDelegate):

```<code>    func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {

    DispatchQueue.main.async {
        let imageView = UIImageView(image: UIImage())

        let imgMaterial = SCNMaterial()
        imgMaterial.diffuse.contents = imageView

        let imgPlane = SCNPlane(width: 0.1, height: 0.1)
        imgPlane.materials = [imgMaterial]

        let imgNode = SCNNode(geometry: imgPlane)
        imgNode.eulerAngles.x = -.pi / 2

        node.addChildNode(imgNode)
        node.opacity = 1

    }

}
</code>```

The imgNode is added to the node and the node is already added to the scene. So what happen if the node is not added to the scene? You have to add it by your own. So in case you are not using the renderer method, an example of it is the next one:

```<code>self.imgNode?.position = SCNVector3(0, 0, 0)
sceneView.scene.rootNode.addChildNode(self.imgNode)
</code>```

Body:
I followed this raywenderlich tutorial to detect image using AR and Scene Kit. In this example they showed displaying video on top of detected image.

https://www.raywenderlich.com/6957-building-a-museum-app-with-arkit-2

I want to display image on top of detected image. Please help me how can I add childNode to SCNNode so that I can display image on top of it.

Here is the code which I tried it's not working  showing a blank white screen.

                            DispatchQueue.main.async {

                        let size = imageAnchor.referenceImage.physicalSize

                        let imageView = UIImageView(image: UIImage(named: "BG.png")!)

                        let imgMaterial = SCNMaterial()
                        imgMaterial.diffuse.contents = imageView

                        let imgPlane = SCNPlane(width: size.width, height: size.height)
                        imgPlane.materials = [imgMaterial]

                        let imgNode = SCNNode(geometry: imgPlane)
                        imgNode.eulerAngles.x = -.pi / 2

                        node.addChildNode(imgNode)
                         node.opacity = 1

                        }

Please help to show image on top of detected image. Thanks in advance.

I'm able to show image on top of detected image but it takes lot of memory what is wrong in that code.

And same as image view I'm displaying gif play on top of detected image with the below code.

                                let size = imageAnchor.referenceImage.physicalSize

                            let imgNameFromDoc = person["actionToTake"] as! String

                            let documentsPathURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first

                            let imgpath = documentsPathURL?.appendingPathComponent("/Packages/\(self.selectedDatasetName)/3DScenes/\(imgNameFromDoc)")

                            let imageData = try! Data(contentsOf: URL(fileURLWithPath: imgpath!.path))

                            let imageURL = UIImage.gifImageWithData(imageData)

                            self.gifImgView = UIImageView(image: imageURL)

                            let imgMaterial = SCNMaterial()
                            imgMaterial.diffuse.contents = self.gifImgView

                            let imgPlane = SCNPlane(width: CGFloat(scaleActionSize(wid: Float(size.width), hei:Float(size.height))[0]), height: CGFloat(scaleActionSize(wid: Float(size.width), hei:Float(size.height))[1]))

                            imgPlane.materials = [imgMaterial]

                            let imgNode = SCNNode(geometry: imgPlane)
                            imgNode.eulerAngles.x = -.pi / 2

                            node.addChildNode(imgNode)
                            node.opacity = 1

With the help of image extension I'm showing GIF on image view on top of detected image.
https://github.com/kiritmodi2702/GIF-Swift/blob/master/GIF-Swift/iOSDevCenters%2BGIF.swift

How to load GIF image in Swift?

I dragged iOSDevCenters+GIF.swift class inside app and displayed gif.

When I use this gif image viewto display gif and image view to display image it takes more than 800 MB memory in Xcode running with iPad.

can somebody help me to find any memory leaks(tried with instruments not able to fix) or anything wrong in this code.

Body:
I guess you have image tracking working.

The next method is called when a new anchor is added. In this case when your image tracked is detected. So the parameter node is the image tracked and you can add a child to that image as in the tutorial. So you can try the next (use ARSCNViewDelegate):

    func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {

    DispatchQueue.main.async {
        let imageView = UIImageView(image: UIImage())

        let imgMaterial = SCNMaterial()
        imgMaterial.diffuse.contents = imageView

        let imgPlane = SCNPlane(width: 0.1, height: 0.1)
        imgPlane.materials = [imgMaterial]

        let imgNode = SCNNode(geometry: imgPlane)
        imgNode.eulerAngles.x = -.pi / 2

        node.addChildNode(imgNode)
        node.opacity = 1

    }

}

The imgNode is added to the node and the node is already added to the scene. So what happen if the node is not added to the scene? You have to add it by your own. So in case you are not using the renderer method, an example of it is the next one:

self.imgNode?.position = SCNVector3(0, 0, 0)
sceneView.scene.rootNode.addChildNode(self.imgNode)