问:
How to show app custom icon in flutter_local_notification in flutter?
I am trying to send local notification in android using flutter_local_notifications and it's working nicely. But the problem is I can not show the app custom icon in notification bar. So, could anyone please help me sharing a solution. Thanks in advance!
Here you go with code and image-

```<code> const notificationChannelId = 'fit_jerk';
const notificationId = 1;

  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
  FlutterLocalNotificationsPlugin();

 const AndroidNotificationChannel channel = AndroidNotificationChannel(
    notificationChannelId, // id
    'MY FOREGROUND SERVICE', // title
    description:
    'This channel is used for sending daily quotation.', // description
    importance: Importance.low, // importance must be at low or higher level
  );

  await flutterLocalNotificationsPlugin
      .resolvePlatformSpecificImplementation<
      AndroidFlutterLocalNotificationsPlugin>()
      ?.createNotificationChannel(channel);

  await service.configure(
    androidConfiguration: AndroidConfiguration(
      onStart: onStart,
      autoStart: true,
      isForegroundMode: true,
      notificationChannelId: notificationChannelId, // this must match with notification channel you created above.
      initialNotificationTitle: 'FitJerk',
      initialNotificationContent: 'Welcome to FitJerk',
      foregroundServiceNotificationId: notificationId,
    ), iosConfiguration: IosConfiguration(),);}

  await flutterLocalNotificationsPlugin.show(
        notificationId,
        'FitJerk',
        todayQuote,
        const NotificationDetails(
          android: AndroidNotificationDetails(
            notificationChannelId,
            'MY FOREGROUND SERVICE',
            icon: 'mipmap/ic_launcher',
            ongoing: false,
          ),
        ),
      );
</code>```

Body:
I am trying to send local notification in android using flutter_local_notifications and it's working nicely. But the problem is I can not show the app custom icon in notification bar. So, could anyone please help me sharing a solution. Thanks in advance!
Here you go with code and image-

 const notificationChannelId = 'fit_jerk';
const notificationId = 1;

  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
  FlutterLocalNotificationsPlugin();

 const AndroidNotificationChannel channel = AndroidNotificationChannel(
    notificationChannelId, // id
    'MY FOREGROUND SERVICE', // title
    description:
    'This channel is used for sending daily quotation.', // description
    importance: Importance.low, // importance must be at low or higher level
  );

  await flutterLocalNotificationsPlugin
      .resolvePlatformSpecificImplementation<
      AndroidFlutterLocalNotificationsPlugin>()
      ?.createNotificationChannel(channel);

  await service.configure(
    androidConfiguration: AndroidConfiguration(
      onStart: onStart,
      autoStart: true,
      isForegroundMode: true,
      notificationChannelId: notificationChannelId, // this must match with notification channel you created above.
      initialNotificationTitle: 'FitJerk',
      initialNotificationContent: 'Welcome to FitJerk',
      foregroundServiceNotificationId: notificationId,
    ), iosConfiguration: IosConfiguration(),);}

  await flutterLocalNotificationsPlugin.show(
        notificationId,
        'FitJerk',
        todayQuote,
        const NotificationDetails(
          android: AndroidNotificationDetails(
            notificationChannelId,
            'MY FOREGROUND SERVICE',
            icon: 'mipmap/ic_launcher',
            ongoing: false,
          ),
        ),
      );


来源: stackexchange

问:
I want to create the simplest python socket server for chatting on AWS EC2
Server code:

```<code>import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('', 81))
client = []
print('Start Server')
while 1:
    data, addres = sock.recvfrom(1024)
    print(addres[0], addres[1])
    if addres not in client:
        client.append(addres)
    for clients in client:
        sock.sendto(data, clients)
</code>```

Client code:

```<code>import socket
import threading
def read_sok():
     while 1 :
         data = sor.recv(1024)
         print(data.decode('utf-8'))
server = '54.236.40.62', 81 # Public IP
alias = input()
sor = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sor.bind(('', 0))
sor.sendto((alias+' Connect to server').encode('utf-8'), server)
potok = threading.Thread(target= read_sok)
potok.start()
while 1 :
    mensahe = input()
    sor.sendto(('['+alias+']'+mensahe).encode('utf-8'), server)
</code>```

The server OS is the linux ubuntu(third in quick start).
Python 3.10.6 is on the server. 3.11.1 on the client.
The server must resend incoming message to everyone clients, which have ever sent messages to it(including the client, who sent this message). When everything is ok, the client sends a message to the server and receives it back.
The problem is that the client(on my PC) can't interact with the sever. It just can't see the server. The client sends the message to the server and does not receive the message(the same situation when the server is turned off or the IP is incorrect for it).

1)These codes work fine if they are on the same PC or on the same network.
2)I didn't forget about security group settings. Port 81 is opened as 80. I started apache2 default page through 80 and it works well in the browser. I also tried using port 80(which certainly works well) for python server(unsuccessful).
3) I know that I can't use public IP for sock.bind(('', 81)). I tried using both sock.bind(('', 81)) and sock.bind(('Private_IP', 81)) cases.
4) I also used ports like 12345 and etc.

I would be grateful for any advice:)

ContentLicense: CC BY-SA 4.0

Body:
Server code:

import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('', 81))
client = []
print('Start Server')
while 1:
    data, addres = sock.recvfrom(1024)
    print(addres[0], addres[1])
    if addres not in client:
        client.append(addres)
    for clients in client:
        sock.sendto(data, clients)

Client code:

import socket
import threading
def read_sok():
     while 1 :
         data = sor.recv(1024)
         print(data.decode('utf-8'))
server = '54.236.40.62', 81 # Public IP
alias = input()
sor = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sor.bind(('', 0))
sor.sendto((alias+' Connect to server').encode('utf-8'), server)
potok = threading.Thread(target= read_sok)
potok.start()
while 1 :
    mensahe = input()
    sor.sendto(('['+alias+']'+mensahe).encode('utf-8'), server)

The server OS is the linux ubuntu(third in quick start).
Python 3.10.6 is on the server. 3.11.1 on the client.
The server must resend incoming message to everyone clients, which have ever sent messages to it(including the client, who sent this message). When everything is ok, the client sends a message to the server and receives it back.
The problem is that the client(on my PC) can't interact with the sever. It just can't see the server. The client sends the message to the server and does not receive the message(the same situation when the server is turned off or the IP is incorrect for it).

1)These codes work fine if they are on the same PC or on the same network.
2)I didn't forget about security group settings. Port 81 is opened as 80. I started apache2 default page through 80 and it works well in the browser. I also tried using port 80(which certainly works well) for python server(unsuccessful).
3) I know that I can't use public IP for sock.bind(('', 81)). I tried using both sock.bind(('', 81)) and sock.bind(('Private_IP', 81)) cases.
4) I also used ports like 12345 and etc.

I would be grateful for any advice:)


问:
Long pause after mapping backslash to `gt`?
In my current workflow I use tabs quite a bit, and always end up either typing gtgtgtgt in quick succession or 4gt to skip to the 4th tab.

This seems unnecessary, so I mapped my backslash key to act like gt, i.e. 4<Bslash> that skips to the 4th tab:

```<code>map <Bslash> gt
</code>```

However when I use it there's a long pause before it actually goes and flips to that tab. Anything I can do to accelerate it?

Body:
In my current workflow I use tabs quite a bit, and always end up either typing gtgtgtgt in quick succession or 4gt to skip to the 4th tab.

This seems unnecessary, so I mapped my backslash key to act like gt, i.e. 4<Bslash> that skips to the 4th tab:

map <Bslash> gt

However when I use it there's a long pause before it actually goes and flips to that tab. Anything I can do to accelerate it?


问:
Google Search Console keeps telling me my content is wider than screen when it isn't
It's happening multiple times per month at this point, basically randomly, to different pages on my wiki. Every... single... time... I go to the page in question, view it with a simple inspect, check the narrowest mobile setting (typically iphone 6), and it's fine.

Then I just go back to the search console, and click validate fix. In the next day or two, it comes back and congratulates me for fixing the issue.

This is the url of the last iteration of this happening: https://golfcourse.wiki/course/presidio_golf_course-san_francisco/holes/1

This has been happening for months. Am I missing something here? Is this normal?


问:
fetching data. for user from firebase for flutter gives null
After i have created the sign in and signup in flutter and i have connect it to firebase, i added a textfield for the name of the user. So if the user register his name also will be stored, then this data is saved into firebase with the id of the user. The problem is when i try to fetch this data my these method it gives me null ,

This is the way how i am fetching the data of the user :

```<code>class WelcomePage  extends StatefulWidget {
  String email;
   WelcomePage ({Key? key, required this.email}) : super(key: key);
  @override
  State<WelcomePage> createState() => _WelcomePageState();
}

class _WelcomePageState extends State<WelcomePage> {
  ScrollController? _scrollcontroller;
  final FirebaseAuth _auth =FirebaseAuth.instance;
  String? _name ;
  String? _uid;
  @override
  void initState() {
    super.initState();
    _scrollcontroller = ScrollController();
    _scrollcontroller?.addListener(() {
      setState(() {});
    });
    getData();
  }

  void getData() async{
    User? user = _auth.currentUser;
    _uid = user!.uid;
    final DocumentSnapshot userDoc  =
    await FirebaseFirestore.instance.collection('users').doc(user.uid).get();

    _name = userDoc.get('name');
  }
</code>```

Body:
After i have created the sign in and signup in flutter and i have connect it to firebase, i added a textfield for the name of the user. So if the user register his name also will be stored, then this data is saved into firebase with the id of the user. The problem is when i try to fetch this data my these method it gives me null ,

This is the way how i am fetching the data of the user :

class WelcomePage  extends StatefulWidget {
  String email;
   WelcomePage ({Key? key, required this.email}) : super(key: key);
  @override
  State<WelcomePage> createState() => _WelcomePageState();
}

class _WelcomePageState extends State<WelcomePage> {
  ScrollController? _scrollcontroller;
  final FirebaseAuth _auth =FirebaseAuth.instance;
  String? _name ;
  String? _uid;
  @override
  void initState() {
    super.initState();
    _scrollcontroller = ScrollController();
    _scrollcontroller?.addListener(() {
      setState(() {});
    });
    getData();
  }

  void getData() async{
    User? user = _auth.currentUser;
    _uid = user!.uid;
    final DocumentSnapshot userDoc  =
    await FirebaseFirestore.instance.collection('users').doc(user.uid).get();

    _name = userDoc.get('name');
  }


问:
How to acquire CSRF Token from request that browser made when sign in using MechanicalSoup?

How to acquire this value from browser POST HTTP request?

I've tried to search in response, but found nothing.

```<code>browser = mechanicalsoup.StatefulBrowser()
browser.open(url)
browser.select_form('form[id="login"]')
browser["username"] = username
browser["password"] = password
response = browser.submit_selected()

responseHeaders = response.headers
responseContent = response.content
responseText = response.text

print("Headers", responseHeaders)
print("responseJson", responseContent)
print("responseText", responseText)
</code>```

I know this token is generated by javascript code, but maybe there is more simple way than studying this code.

Body:
How to acquire this value from browser POST HTTP request?

I've tried to search in response, but found nothing.

browser = mechanicalsoup.StatefulBrowser()
browser.open(url)
browser.select_form('form[id="login"]')
browser["username"] = username
browser["password"] = password
response = browser.submit_selected()

responseHeaders = response.headers
responseContent = response.content
responseText = response.text

print("Headers", responseHeaders)
print("responseJson", responseContent)
print("responseText", responseText)

I know this token is generated by javascript code, but maybe there is more simple way than studying this code.


问:
Web scraping with urllib.request - data is not refreshing
I am trying to read a table on a website.  The first (initial) read is correct, but the subsequent requests in the loop are out of date (the information doesn't change even though the website changes).  Any suggestions?

The link shown in the code is not the actual website that I am looking at.  Also, I am going through proxy server.

I don't get an error, just out of date information.

Here is my code:

```<code>import time
import urllib.request
from pprint import pprint
from html_table_parser.parser import HTMLTableParser
import pandas as pd

def url_get_contents(url):
    #making request to the website
    req = urllib.request.Request(url=url)
    f = urllib.request.urlopen(req)
    return f.read()

link='https://www.w3schools.com/html/html_tables.asp'
xhtml = url_get_contents(link).decode('utf-8')
p = HTMLTableParser()
p.feed(xhtml)
stored_page=p.tables[0]

while True:
    try:

        xhtml = url_get_contents(link).decode('utf-8')
        p = HTMLTableParser()
        p.feed(xhtml)
        print('now: ',p.tables[0] )
        time.sleep(120)
        continue

    # To handle exceptions
    except Exception as e:
        print("error")
</code>```

Body:
I am trying to read a table on a website.  The first (initial) read is correct, but the subsequent requests in the loop are out of date (the information doesn't change even though the website changes).  Any suggestions?

The link shown in the code is not the actual website that I am looking at.  Also, I am going through proxy server.

I don't get an error, just out of date information.

Here is my code:

import time
import urllib.request
from pprint import pprint
from html_table_parser.parser import HTMLTableParser
import pandas as pd

def url_get_contents(url):
    #making request to the website
    req = urllib.request.Request(url=url)
    f = urllib.request.urlopen(req)
    return f.read()

link='https://www.w3schools.com/html/html_tables.asp'
xhtml = url_get_contents(link).decode('utf-8')
p = HTMLTableParser()
p.feed(xhtml)
stored_page=p.tables[0]

while True:
    try:

        xhtml = url_get_contents(link).decode('utf-8')
        p = HTMLTableParser()
        p.feed(xhtml)
        print('now: ',p.tables[0] )
        time.sleep(120)
        continue

    # To handle exceptions
    except Exception as e:
        print("error")


问:
Entities with problems and limitations
I have these entities:

```<code>    public class Project : Base
    {
        public string Name { get; set; }
        public string Description { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime? EndDate { get; set; }
        public ProjectStatus CurrentStatus { get; set; } = ProjectStatus.New;
        public List<StatusHistory>? StatusHistories { get; set; }
        public Team? Team { get; set; }
        public int? TeamId { get; set; }
        // public ProgressTrackerValue trackerValue { get; set; }
        public List<AttachedFile> AttachedFiles { get; set; }

    }
</code>```
```<code>    public class Task : Base
    {
        public string Name { get; set; }
        public string  Description { get; set; }
        public DateTime? EstimatedDueDate { get; set; }
        public DateTime? ActualDueDate { get; set; }
        public DateTime? StartDate { get; set; }
        public DateTime? EndDate { get; set; } // ?? End DATE same as ActualDueDate
        public TaskStatus CurrentStatus { get; set; } = TaskStatus.Draft;
        public int ProjectId { get; set; }
        public Project Project { get; set; }
        public List<StatusHistory> StatusHistories { get; set; }
        public TaskType TaskType { get; set; }
        public TaskPriority Priority { get; set; }
        public float ? DurationProgress { get; set; }
        public List<AttachedFile> AttachedFiles { get; set; }
    }
</code>```
```<code>    public class Team : Base
    {
        public string TeamLeaderId { get; set; }
        public List<TeamMember>? TeamMembers { get; set; }
        public virtual Project Project { get; set; }

    }
</code>```
```<code>    public class AttachedFile : Base
    {
        public string OriginalFileName { get; set; }
        public string FileName { get; set; }
        public string MimeType { get; set; }
        public string FileType { get; set; }
        public string OwnerType { get; set; }
        public int OwnerId {get; set;}
        public string FilePath { get; set; }
        public long FileSize { get; set; }
    }
</code>```
```<code>    public class Comment : Base
    {
        public string Content { get; set; }
        public int? ParentCommentId { get; set; }
        public List<Comment>? Replies { get; private set; }
        public Task Task { get; set; }
        public int taskId { get; set; }
        public List<AttachedFile>? AttachedFiles { get; set; }
    }
</code>```
```<code>    public class StatusHistory : Base
    {
        public string OwnerType { get; set; }
        public int OwnerId {get; set;}
        public string State { get; set; }
    }
</code>```
```<code>    public class TaskEmployee : Base
    {

        public int TaskId { get; set; }
        public Task Task { get; set; }
        public string EmployeeId { get; set; }
    }
</code>```
```<code>    public class TeamMember : Base
    {
        public string UserId { get; set; }

    }
</code>```

What can I do to improve the above entities? Any suggestions.

Also there is UserId,EmployeeId,TeamLeaderId.... all of these supposed to be FK to IdentityUser but this project is isolated from Identity and i can't find a way to link them together. if there is a suggestion on how could I make such relationship in EFCore. (I could make relationship manually but I can't put navigation properties for Identity inside these entities thus not benefiting from EFCore).

Finally there is OwnerType, OwnerId, for example in the AttachedFile entity the attached file could be related to Project, Task, Comment. So I will store the type and id for them in these fields, the problem however that I will not benefit form EF Core functionality this way. For example: I must write SQL manually for every query.

currently the schema look like this:

enter image description here

Title: Entities with problems and limitations

Body:
I have these entities:

    public class Project : Base
    {
        public string Name { get; set; }
        public string Description { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime? EndDate { get; set; }
        public ProjectStatus CurrentStatus { get; set; } = ProjectStatus.New;
        public List<StatusHistory>? StatusHistories { get; set; }
        public Team? Team { get; set; }
        public int? TeamId { get; set; }
        // public ProgressTrackerValue trackerValue { get; set; }
        public List<AttachedFile> AttachedFiles { get; set; }

    }

    public class Task : Base
    {
        public string Name { get; set; }
        public string  Description { get; set; }
        public DateTime? EstimatedDueDate { get; set; }
        public DateTime? ActualDueDate { get; set; }
        public DateTime? StartDate { get; set; }
        public DateTime? EndDate { get; set; } // ?? End DATE same as ActualDueDate
        public TaskStatus CurrentStatus { get; set; } = TaskStatus.Draft;
        public int ProjectId { get; set; }
        public Project Project { get; set; }
        public List<StatusHistory> StatusHistories { get; set; }
        public TaskType TaskType { get; set; }
        public TaskPriority Priority { get; set; }
        public float ? DurationProgress { get; set; }
        public List<AttachedFile> AttachedFiles { get; set; }
    }

    public class Team : Base
    {
        public string TeamLeaderId { get; set; }
        public List<TeamMember>? TeamMembers { get; set; }
        public virtual Project Project { get; set; }

    }

    public class AttachedFile : Base
    {
        public string OriginalFileName { get; set; }
        public string FileName { get; set; }
        public string MimeType { get; set; }
        public string FileType { get; set; }
        public string OwnerType { get; set; }
        public int OwnerId {get; set;}
        public string FilePath { get; set; }
        public long FileSize { get; set; }
    }

    public class Comment : Base
    {
        public string Content { get; set; }
        public int? ParentCommentId { get; set; }
        public List<Comment>? Replies { get; private set; }
        public Task Task { get; set; }
        public int taskId { get; set; }
        public List<AttachedFile>? AttachedFiles { get; set; }
    }

    public class StatusHistory : Base
    {
        public string OwnerType { get; set; }
        public int OwnerId {get; set;}
        public string State { get; set; }
    }

    public class TaskEmployee : Base
    {

        public int TaskId { get; set; }
        public Task Task { get; set; }
        public string EmployeeId { get; set; }
    }

    public class TeamMember : Base
    {
        public string UserId { get; set; }

    }

What can I do to improve the above entities? Any suggestions.

Also there is UserId,EmployeeId,TeamLeaderId.... all of these supposed to be FK to IdentityUser but this project is isolated from Identity and i can't find a way to link them together. if there is a suggestion on how could I make such relationship in EFCore. (I could make relationship manually but I can't put navigation properties for Identity inside these entities thus not benefiting from EFCore).

Finally there is OwnerType, OwnerId, for example in the AttachedFile entity the attached file could be related to Project, Task, Comment. So I will store the type and id for them in these fields, the problem however that I will not benefit form EF Core functionality this way. For example: I must write SQL manually for every query.

currently the schema look like this:

enter image description here


问:
Are reference types stored contiguously in Memory<T> in C#?
If I use memory to store a list of objects, there is no indirection when accessing them? If this is so, why not use memory instead of normal array always?</p>


问:
Log file locked in a web application
My web application in c# writes in a log file the tasks performed by the users.
Everything goes well as long as the number of users is small.
However, when there are many users working with the application, the writes to the log file fail because it is in use.

Is there a way to sequence the writes to the log file so that all user activity is recorded?

I know can use a database for writing log but i want to make it simpler.

Title: Log file locked in a web application


问:
CriteriaBuilder.or returns no values if entity mapping is empty
I have a spring project with two entities.

```<code>public class Parent {
    private integer id;
    private String name;
    private List<Child> children
}

public class Child {
    private integer id;
    private integer parentId;
    private String name;
}
</code>```

I am attempting to use the Hibernate criteriaBuilder to construct a query that will return all parents who has a name, or has a child with a given name.

```<code>criteriaBuilder.or(
    criteriaBuilder.like(parent.join("children").get("name"),
        "%" + query.getValue() + "%"),
    criteriaBuilder.like(parent.get("name"),
        "%" + query.getValue() + "%"));
</code>```

The query works with no problems if a parent has children but will return no results if the parent has no children.

I've tried adding additional an additional predicate that will only check the parent's name if they are childless.

I have completely run out of ideas, any help will be greatly appreciated.

Body:
I have a spring project with two entities.

public class Parent {
    private integer id;
    private String name;
    private List<Child> children
}

public class Child {
    private integer id;
    private integer parentId;
    private String name;
}

I am attempting to use the Hibernate criteriaBuilder to construct a query that will return all parents who has a name, or has a child with a given name.

criteriaBuilder.or(
    criteriaBuilder.like(parent.join("children").get("name"),
        "%" + query.getValue() + "%"),
    criteriaBuilder.like(parent.get("name"),
        "%" + query.getValue() + "%"));

The query works with no problems if a parent has children but will return no results if the parent has no children.

I've tried adding additional an additional predicate that will only check the parent's name if they are childless.

I have completely run out of ideas, any help will be greatly appreciated.


问:
How to append a blob to formData when looping through maps() function
I'm curious why this happens when I use await to get a blob from a data url, append it to a formData, inside of a map() function

Long story short I need to convert all image data urls into a blob, and then append them to a form data, then send the form data every time someone hits submit.

Everytime I hit submit, and I add an image, the first image vanishes from the formData after I've appended:

```<code>//executes on every form submission, so if there are two images in the form then I should have two blobs attached, Image 0, and Image 1, but instead the first image vanishes, why does that happen?
//if images exist
     if(urls){
        const blobs = urls.map(async (url, index)=>{

        console.log('current url index: ', index)

        //remove double quotes
        const sliced = url.slice(1,-1)

        //blob lines are causing an image to vanish
        const res = await fetch(sliced);

        const blob = await res.blob();

        formData.append(`image ${index}`, blob);

         if(index==urls.length-1){
             console.log([...formData]) //send form data to server here
         }
})

</code>```

Body:
I'm curious why this happens when I use await to get a blob from a data url, append it to a formData, inside of a map() function

Long story short I need to convert all image data urls into a blob, and then append them to a form data, then send the form data every time someone hits submit.

Everytime I hit submit, and I add an image, the first image vanishes from the formData after I've appended:

//executes on every form submission, so if there are two images in the form then I should have two blobs attached, Image 0, and Image 1, but instead the first image vanishes, why does that happen?
//if images exist
     if(urls){
        const blobs = urls.map(async (url, index)=>{

        console.log('current url index: ', index)

        //remove double quotes
        const sliced = url.slice(1,-1)

        //blob lines are causing an image to vanish
        const res = await fetch(sliced);

        const blob = await res.blob();

        formData.append(`image ${index}`, blob);

         if(index==urls.length-1){
             console.log([...formData]) //send form data to server here
         }
})


问:
Function url and path not reconize in template twig -- TemplatedMail
This is the example found in internet in https://github.com/symfony/mailer:

    use Symfony\Bridge\Twig\Mime\BodyRenderer;
    use Symfony\Bridge\Twig\Mime\TemplatedEmail;
    use Symfony\Component\EventDispatcher\EventDispatcher;
    use Symfony\Component\Mailer\EventListener\MessageListener;
    use Symfony\Component\Mailer\Mailer;
    use Symfony\Component\Mailer\Transport;
    use Twig\Environment as TwigEnvironment;

    $twig = new TwigEnvironment(...);
    $messageListener = new MessageListener(null, new BodyRenderer($twig));

    $eventDispatcher = new EventDispatcher();
    $eventDispatcher->addSubscriber($messageListener);

    $transport = Transport::fromDsn('smtp://localhost', $eventDispatcher);
    $mailer = new Mailer($transport, null, $eventDispatcher);

    $email = (new TemplatedEmail())
        // ...
        ->htmlTemplate('emails/signup.html.twig')
        ->context([
            'expiration_date' => new \DateTime('+7 days'),
            'username' => 'foo',
        ])
    ;
    $mailer->send($email);
```
<p>I modified it with  this code :</p>
<pre class="lang-php prettyprint-override"><code>use Symfony\Bridge\Twig\Mime\BodyRenderer;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\Mailer\EventListener\MessageListener;
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mailer\Transport;
use Twig\Environment as TwigEnvironment;
use Twig\Loader\FilesystemLoader;

$loader = new FilesystemLoader(__DIR__ . '/../../templates');
$twig = new TwigEnvironment($loader);

$messageListener = new MessageListener(null, new BodyRenderer($twig));

$eventDispatcher = new EventDispatcher();
$eventDispatcher->addSubscriber($messageListener);

$transport = Transport::fromDsn('smtp://localhost?verify_peer=false', $eventDispatcher);
$mailer = new Mailer($transport, null, $eventDispatcher);

$email = (new TemplatedEmail())
    ->from(new Address('email@test.localdomain', 'TEST'))
    ->to($user->getEmail())
    ->subject('Your password reset request')
    ->htmlTemplate('reset_password/email.html.twig')
    ->context([
        'resetToken' => $resetToken,
    ]) ;
</code>```

It's for a reset password and i use the controller generate by the command Symfony.
So, in view, there is a generation about token url and it's use the function url which is not injected in template twig.

What do you suggest for to have the function url or path in twig?

I use Postfix with ubunbu 22.04 and i receive the email correctly without the token url.

Body:
This is the example found in internet in https://github.com/symfony/mailer:

    use Symfony\Bridge\Twig\Mime\BodyRenderer;
    use Symfony\Bridge\Twig\Mime\TemplatedEmail;
    use Symfony\Component\EventDispatcher\EventDispatcher;
    use Symfony\Component\Mailer\EventListener\MessageListener;
    use Symfony\Component\Mailer\Mailer;
    use Symfony\Component\Mailer\Transport;
    use Twig\Environment as TwigEnvironment;

    $twig = new TwigEnvironment(...);
    $messageListener = new MessageListener(null, new BodyRenderer($twig));

    $eventDispatcher = new EventDispatcher();
    $eventDispatcher->addSubscriber($messageListener);

    $transport = Transport::fromDsn('smtp://localhost', $eventDispatcher);
    $mailer = new Mailer($transport, null, $eventDispatcher);

    $email = (new TemplatedEmail())
        // ...
        ->htmlTemplate('emails/signup.html.twig')
        ->context([
            'expiration_date' => new \DateTime('+7 days'),
            'username' => 'foo',
        ])
    ;
    $mailer->send($email);

I modified it with  this code :

use Symfony\Bridge\Twig\Mime\BodyRenderer;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\Mailer\EventListener\MessageListener;
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mailer\Transport;
use Twig\Environment as TwigEnvironment;
use Twig\Loader\FilesystemLoader;

$loader = new FilesystemLoader(__DIR__ . '/../../templates');
$twig = new TwigEnvironment($loader);

$messageListener = new MessageListener(null, new BodyRenderer($twig));

$eventDispatcher = new EventDispatcher();
$eventDispatcher->addSubscriber($messageListener);

$transport = Transport::fromDsn('smtp://localhost?verify_peer=false', $eventDispatcher);
$mailer = new Mailer($transport, null, $eventDispatcher);

$email = (new TemplatedEmail())
    ->from(new Address('email@test.localdomain', 'TEST'))
    ->to($user->getEmail())
    ->subject('Your password reset request')
    ->htmlTemplate('reset_password/email.html.twig')
    ->context([
        'resetToken' => $resetToken,
    ]) ;

It's for a reset password and i use the controller generate by the command Symfony.
So, in view, there is a generation about token url and it's use the function url which is not injected in template twig.

What do you suggest for to have the function url or path in twig?

I use Postfix with ubunbu 22.04 and i receive the email correctly without the token url.


问:
How to run code at startup when not having access to application entry point
We have a legacy (.net 4.8.x) backend application which is hosting remoting components in a Windows Service. Now I want to add a continuously running worker service which should start when application is started.

Normally this would be no problem to add but in our case the actual windows service (the .exe) is a generic windows service host application used for several applications. So that part is outide the solution. So I can't just add the startup code there. We have the code for host application though so can do changes to it.

One option is to change the host application that I add some options to configure startup code and use Reflection to instantiate the worker service class.

But is there any other options ? Like run code at assembly load in some way?


问:
Is it possible to pass a parameter to iOS App Store which can be retrieved after installation of the app?
following situation: I have an app in the app store, where among other things, user can communicate with each other. In order to do so, they first have to connect to each other and confirm the connection. Now, I want to add an invitation functionality, basically:

userA sends a link to website to newUser

new user opens website, with a link to the app store

new user installs the app

a connection between user A and new user (now user B) is established.

In the conventional web-world I would have an invite link: www.mysite.com?invitingUser=userA and I could evaluate it after sign up.
Is there something similar in iOS world, a way to provide the installed app with a parameter directly after or during installation?

Thanks in advance


问:
Error sending emails in Ruby 2.6.2 / Rails 6.1.4 on Centos 8 in production mode
I have a rather strange problem. I have an app mounted on rails by "rvm use 2.6.2@rails6.1.4". Apparently everything works correctly in production environment, except for sending emails. The strange thing is that from development mode it works correctly, but in production mode it returns the following error:

NameError (uninitialized constant Mail::TestMailer)

I have already tried completely reinstalling all the gems including the rvm. The problem persists the same.

The web app runs on top of Apache/Phusion Passenger on Centos 8 Stream.

Please, I need guidance on it, since I am totally stuck with my project.

Completely reinstall gems, update gems to latest versions, disable firewall, disable SELinux


问:
How to use a config.ini file to change button attributes? (Windows Forms)
New to windows forms so please bear with me.

I have a simple application that displays a few buttons, and I'd like the attributes of these buttons to be set by the user using some kind of external config file e.g. config.ini.

In the config file, the attributes would be set out something like this:

```<code>[Button 1]          //button identifier
isEnabled = True    //show/hide the button
colour = "#FFFF"    //button background colour
caption = "Button"  //text to display on button
action = "Action"   //action when button is clicked
</code>```

The config file should be stored with the program executable, and when the program is launched, it will display the buttons and text defined in this file.

The action determines what happens when the button is clicked. This could either be opening a new page, or writing a string to a variable. The aim of the program is to allow users to navigate through a couple of menus, and then select a button which will print out the string.

Edit: if the action is to go to a new page, it will just say 'Next Page' so I guess I can just use an if/else for this. I.E.

```<code>if(string.Equals("Next Page"){
    //go to next page
} else{
    //save string to variable
}
</code>```

I know how to set button attributes in the code, but I don't understand how I can read the config file. Its important that these attributes can be set from the external file so that the program can be easily configured without needing to rebuild it.

Body:
New to windows forms so please bear with me.

I have a simple application that displays a few buttons, and I'd like the attributes of these buttons to be set by the user using some kind of external config file e.g. config.ini.

In the config file, the attributes would be set out something like this:

[Button 1]          //button identifier
isEnabled = True    //show/hide the button
colour = "#FFFF"    //button background colour
caption = "Button"  //text to display on button
action = "Action"   //action when button is clicked

The config file should be stored with the program executable, and when the program is launched, it will display the buttons and text defined in this file.

The action determines what happens when the button is clicked. This could either be opening a new page, or writing a string to a variable. The aim of the program is to allow users to navigate through a couple of menus, and then select a button which will print out the string.

Edit: if the action is to go to a new page, it will just say 'Next Page' so I guess I can just use an if/else for this. I.E.

if(string.Equals("Next Page"){
    //go to next page
} else{
    //save string to variable
}

I know how to set button attributes in the code, but I don't understand how I can read the config file. Its important that these attributes can be set from the external file so that the program can be easily configured without needing to rebuild it.


问:
How do I pass input type ="tel" information to email at formsubmit.co? Everything works for me except for that
I am using a form to send information to my email using formsubmit.co.  Everything sends to the email except for "tel" input type.  When I use "tel" it skips the reCaptcha page and sends a confirmation that the form was submitted.  However, nothing gets submitted when this happens.

I have tried isolating the issue by skipping the link of code with the "tel" input type and it works fine.  I tried changing the input type to "text" like all the other ones that work fine and it still doesn't work for some reason.


问:
One-to-many Primary /Foreign Key in Entity Framework
How to map one-to-many relationship on following entites using Fluent API.

```<code>[Table("LU_COMMODITY_ID")]
public class LU_COMMODITY_ID
{
    [Key]
    public string COMMODITY_ID { get; set; }
    public virtual string COMMODITY_DESC { get; set; }
    ...

    public virtual ICollection<LU_SUPPLIER_COMMODITY> LU_SUPPLIER_COMMODITIES { get; set; }
}

[Table("LU_SUPPLIER_COMMODITY")]
public class LU_SUPPLIER_COMMODITY
{
    [Key, Column(Order = 0)]
    public string COMMODITY_ID { get; set; }
    [Key, Column(Order = 1)]
    public virtual string SUPPLIER_NAME { get; set; }
    ...
    public virtual LU_COMMODITY_ID LU_COMMODITY_ID  {get; set; }
}
</code>```

I've tried the following mapping:

```<code>modelBuilder.Entity<LU_SUPPLIER_COMMODITY>()
           .HasRequired(l => l.LU_COMMODITY_ID)
           .WithMany(a => a.LU_SUPPLIER_COMMODITIES)
           .HasForeignKey(l => l.COMMODITY_ID);
</code>```

and it gave me next error:

The 'LU_SUPPLIER_COMMODITIES' property does not exist or is not mapped for the type 'LU_COMMODITY_ID'.

ContentLicense: CC BY-SA 3.0

Body:
How to map one-to-many relationship on following entites using Fluent API.

[Table("LU_COMMODITY_ID")]
public class LU_COMMODITY_ID
{
    [Key]
    public string COMMODITY_ID { get; set; }
    public virtual string COMMODITY_DESC { get; set; }
    ...

    public virtual ICollection<LU_SUPPLIER_COMMODITY> LU_SUPPLIER_COMMODITIES { get; set; }
}

[Table("LU_SUPPLIER_COMMODITY")]
public class LU_SUPPLIER_COMMODITY
{
    [Key, Column(Order = 0)]
    public string COMMODITY_ID { get; set; }
    [Key, Column(Order = 1)]
    public virtual string SUPPLIER_NAME { get; set; }
    ...
    public virtual LU_COMMODITY_ID LU_COMMODITY_ID  {get; set; }
}

I've tried the following mapping:

modelBuilder.Entity<LU_SUPPLIER_COMMODITY>()
           .HasRequired(l => l.LU_COMMODITY_ID)
           .WithMany(a => a.LU_SUPPLIER_COMMODITIES)
           .HasForeignKey(l => l.COMMODITY_ID);

and it gave me next error:

The 'LU_SUPPLIER_COMMODITIES' property does not exist or is not mapped for the type 'LU_COMMODITY_ID'.


问:
Href Interpolation Failed in NextJs button
I have this code to create a button that makes the app change the language from English to Spanish (just add the 'es' after the root):

```<code>  const { locale, locales, push, isReady } = useRouter()
  const handleClick = l => () => {
      push(`${currentPath}`, undefined, {locale:l})
</code>```

this is the button code:

```<code>  {locales.map(l => (
     <button className="px-6 py-2 font-bold" key={l} onClick={handleClick(l)}>
       {l}
     </button>
   ))}
</code>```

I click the language button in example.com/guides the app change the language to example.com/es/guides; but when I go to the dynamic path route example.com/guides/[url_en] and try to change the language, the following error it shows:

Unhandled Runtime Error
Error: The provided href (/guides/[url_en]) value is missing query values (url_en) to be interpolated properly. Read more: https://nextjs.org/docs/messages/href-interpolation-failed.

Body:
I have this code to create a button that makes the app change the language from English to Spanish (just add the 'es' after the root):

  const { locale, locales, push, isReady } = useRouter()
  const handleClick = l => () => {
      push(`${currentPath}`, undefined, {locale:l})

this is the button code:

  {locales.map(l => (
     <button className="px-6 py-2 font-bold" key={l} onClick={handleClick(l)}>
       {l}
     </button>
   ))}

I click the language button in example.com/guides the app change the language to example.com/es/guides; but when I go to the dynamic path route example.com/guides/[url_en] and try to change the language, the following error it shows:

Unhandled Runtime Error
Error: The provided href (/guides/[url_en]) value is missing query values (url_en) to be interpolated properly. Read more: https://nextjs.org/docs/messages/href-interpolation-failed.


问:
Following trajectory with timestamps in CARLA
I'm trying to simulate a multi-agent intersection scenario in CARLA. I've generated a trajectory for each vehicle in the scenario using Python. A trajectory is defined discretely by a sequence of waypoints, each with components (x, y, t).

In the CARLA documentation, I've seen two ways that vehicles can be manually controlled:

Define a set of waypoints (without time components) on the road for a vehicle to follow using feedback control.

Use VehicleControl on a vehicle to define motion using throttle and steering angle values.

I'm not sure how to use either of these strategies to execute the trajectories, since I need the timestamps to be conserved and I want to generate actions online. How can I do this?


问:
Cannot find module './routes/index'
Error: Cannot find module './routes/index'
Require stack:

C:\Users\serch\travlr\app.js

C:\Users\serch\travlr\bin\www
at Module._resolveFilename (node:internal/modules/cjs/loader:995:15)
at Module._load (node:internal/modules/cjs/loader:841:27)
at Module.require (node:internal/modules/cjs/loader:1061:19)
at require (node:internal/modules/cjs/helpers:103:18)
at Object.<anonymous> (C:\Users\serch\travlr\app.js:7:19)
at Module._compile (node:internal/modules/cjs/loader:1159:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
at Module.load (node:internal/modules/cjs/loader:1037:32)
at Module._load (node:internal/modules/cjs/loader:878:12)
at Module.require (node:internal/modules/cjs/loader:1061:19) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'C:\Users\serch\travlr\app.js',
'C:\Users\serch\travlr\bin\www'

```<code>index.js
const express = require('express');
const router = express.Router();
const ctrlMain = require('../controllers/main');

/* GET homepage. */
router.get('/', ctrlMain.index);

module.exports = router;

app.js

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const hbs = require('hbs');

var indexRouter = require('./app_server/routes/index');
var usersRouter = require('./app_server/routes/users');
var travelRouter = require('./app_server/routes/travel');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'app_server', 'views'));

// register handlebars partials (https://www.npmjs.com/package/hbs)
hbs.registerPartials(path.join(__dirname, 'app_server', 'views/partials'))

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

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/travel', travelRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
</code>```

I don't know why is not running the code. I double check my spelling on the the classes and every detail

Title: Cannot find module './routes/index'

Body:
Error: Cannot find module './routes/index'
Require stack:

C:\Users\serch\travlr\app.js

C:\Users\serch\travlr\bin\www
at Module._resolveFilename (node:internal/modules/cjs/loader:995:15)
at Module._load (node:internal/modules/cjs/loader:841:27)
at Module.require (node:internal/modules/cjs/loader:1061:19)
at require (node:internal/modules/cjs/helpers:103:18)
at Object.<anonymous> (C:\Users\serch\travlr\app.js:7:19)
at Module._compile (node:internal/modules/cjs/loader:1159:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
at Module.load (node:internal/modules/cjs/loader:1037:32)
at Module._load (node:internal/modules/cjs/loader:878:12)
at Module.require (node:internal/modules/cjs/loader:1061:19) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'C:\Users\serch\travlr\app.js',
'C:\Users\serch\travlr\bin\www'

index.js
const express = require('express');
const router = express.Router();
const ctrlMain = require('../controllers/main');

/* GET homepage. */
router.get('/', ctrlMain.index);

module.exports = router;

app.js

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const hbs = require('hbs');

var indexRouter = require('./app_server/routes/index');
var usersRouter = require('./app_server/routes/users');
var travelRouter = require('./app_server/routes/travel');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'app_server', 'views'));

// register handlebars partials (https://www.npmjs.com/package/hbs)
hbs.registerPartials(path.join(__dirname, 'app_server', 'views/partials'))

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

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/travel', travelRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

I don't know why is not running the code. I double check my spelling on the the classes and every detail


问:
Trying to find how many hits a team had in each game in baseballr
I'm trying to find the number of hits and runs the Mets had in each game of 2022 (and then possibly extend that to each team in baseball game-by-game). I have the runs, but finding the hits isn't working.

For the runs, I used bref_team_results('NYM', 2022).

For the hits, I'd want to use mlb_game_linescore(), but it asks for the game_pk as a variable. When I try to find game_pks, it's throwing me the following error:

```<code>get_game_pks_mlb('04-10-2022', level_ids = 1)

Invalid arguments provided
Error in get_game_pks_mlb("04-10-2022", level_ids = 1) :
  object 'payload' not found
</code>```

Does anyone know why this is happening or have an alternative suggestion for how to get the game-by-game hit results for each team?

Body:
I'm trying to find the number of hits and runs the Mets had in each game of 2022 (and then possibly extend that to each team in baseball game-by-game). I have the runs, but finding the hits isn't working.

For the runs, I used bref_team_results('NYM', 2022).

For the hits, I'd want to use mlb_game_linescore(), but it asks for the game_pk as a variable. When I try to find game_pks, it's throwing me the following error:

get_game_pks_mlb('04-10-2022', level_ids = 1)

Invalid arguments provided
Error in get_game_pks_mlb("04-10-2022", level_ids = 1) :
  object 'payload' not found

Does anyone know why this is happening or have an alternative suggestion for how to get the game-by-game hit results for each team?


问:
Why I am not able to send an email using Amazon SES service?
I created a wd site, where a user1 can send email to user2.  My account is removed from the Amazon SES sandbox. You will find, my code bellow.
My  SMTP credentials are configured in US East (Ohio). But my location is in Canada. And the two emails that i am using are Canadian addresses (yahoo.ca)
I don’t understand why the User1 is not able to send an email to User2?

Here is my code:

```<code> public void SendEmail(string sender, string recipient, string messageBODY)
    {
        // Replace sender@example.com with your "From" address.
        // This address must be verified with Amazon SES.
        String FROM = sender;
        String FROMNAME = "Sender Name";

        // Replace recipient@example.com with a "To" address. If your account
        // is still in the sandbox, this address must be verified.
        String TO = recipient;

        // Replace smtp_username with your Amazon SES SMTP user name.
        String SMTP_USERNAME = "CAIASJA3JM5CXUEYAIAB";

        // Replace smtp_password with your Amazon SES SMTP password.
        String SMTP_PASSWORD = "RD75K2MbhvOYnBf20WYZ5O9oZlj9lCBH/hqrEIYnClYT";

        // (Optional) the name of a configuration set to use for this message.
        // If you comment out this line, you also need to remove or comment out
        // the "X-SES-CONFIGURATION-SET" header below.
        //String CONFIGSET = "ConfigSet";

        // If you're using Amazon SES in a region other than US West (Oregon),
        // replace email-smtp.us-west-2.amazonaws.com with the Amazon SES SMTP
        // endpoint in the appropriate AWS Region.
        String HOST = "email-smtp.us-east-2.amazonaws.com";

        // The port you will connect to on the Amazon SES SMTP endpoint. We
        // are choosing port 587 because we will use STARTTLS to encrypt
        // the connection.
        int PORT = 587;

        // The subject line of the email
        String SUBJECT =
            "Amazon SES test (SMTP interface accessed using C#)";

        // The body of the email
        String BODY = messageBODY;

        // Create and build a new MailMessage object
        MailMessage message = new MailMessage();
        message.IsBodyHtml = true;
        message.From = new MailAddress(FROM, FROMNAME);
        message.To.Add(new MailAddress(TO));
        message.Subject = SUBJECT;
        message.Body = BODY;
        // Comment or delete the next line if you are not using a configuration set
        //message.Headers.Add("X-SES-CONFIGURATION-SET", CONFIGSET);

        using (var client = new System.Net.Mail.SmtpClient(HOST, PORT))
        {
            // Pass SMTP credentials
            client.Credentials =
                new NetworkCredential(SMTP_USERNAME, SMTP_PASSWORD);

            // Enable SSL encryption
            client.EnableSsl = true;

            // Try to send the message. Show status in console.
            try
            {
                Console.WriteLine("Attempting to send email...");
                client.Send(message);
                Console.WriteLine("Email sent!");
            }
            catch (Exception ex)
            {
                Console.WriteLine("The email was not sent.");
                Console.WriteLine("Error message: " + ex.Message);
            }
        }
    }
</code>```

Thank you for help

Body:
I created a wd site, where a user1 can send email to user2.  My account is removed from the Amazon SES sandbox. You will find, my code bellow.
My  SMTP credentials are configured in US East (Ohio). But my location is in Canada. And the two emails that i am using are Canadian addresses (yahoo.ca)
I don’t understand why the User1 is not able to send an email to User2?

Here is my code:

 public void SendEmail(string sender, string recipient, string messageBODY)
    {
        // Replace sender@example.com with your "From" address.
        // This address must be verified with Amazon SES.
        String FROM = sender;
        String FROMNAME = "Sender Name";

        // Replace recipient@example.com with a "To" address. If your account
        // is still in the sandbox, this address must be verified.
        String TO = recipient;

        // Replace smtp_username with your Amazon SES SMTP user name.
        String SMTP_USERNAME = "CAIASJA3JM5CXUEYAIAB";

        // Replace smtp_password with your Amazon SES SMTP password.
        String SMTP_PASSWORD = "RD75K2MbhvOYnBf20WYZ5O9oZlj9lCBH/hqrEIYnClYT";

        // (Optional) the name of a configuration set to use for this message.
        // If you comment out this line, you also need to remove or comment out
        // the "X-SES-CONFIGURATION-SET" header below.
        //String CONFIGSET = "ConfigSet";

        // If you're using Amazon SES in a region other than US West (Oregon),
        // replace email-smtp.us-west-2.amazonaws.com with the Amazon SES SMTP
        // endpoint in the appropriate AWS Region.
        String HOST = "email-smtp.us-east-2.amazonaws.com";

        // The port you will connect to on the Amazon SES SMTP endpoint. We
        // are choosing port 587 because we will use STARTTLS to encrypt
        // the connection.
        int PORT = 587;

        // The subject line of the email
        String SUBJECT =
            "Amazon SES test (SMTP interface accessed using C#)";

        // The body of the email
        String BODY = messageBODY;

        // Create and build a new MailMessage object
        MailMessage message = new MailMessage();
        message.IsBodyHtml = true;
        message.From = new MailAddress(FROM, FROMNAME);
        message.To.Add(new MailAddress(TO));
        message.Subject = SUBJECT;
        message.Body = BODY;
        // Comment or delete the next line if you are not using a configuration set
        //message.Headers.Add("X-SES-CONFIGURATION-SET", CONFIGSET);

        using (var client = new System.Net.Mail.SmtpClient(HOST, PORT))
        {
            // Pass SMTP credentials
            client.Credentials =
                new NetworkCredential(SMTP_USERNAME, SMTP_PASSWORD);

            // Enable SSL encryption
            client.EnableSsl = true;

            // Try to send the message. Show status in console.
            try
            {
                Console.WriteLine("Attempting to send email...");
                client.Send(message);
                Console.WriteLine("Email sent!");
            }
            catch (Exception ex)
            {
                Console.WriteLine("The email was not sent.");
                Console.WriteLine("Error message: " + ex.Message);
            }
        }
    }

Thank you for help


问:
Remove empty spaces from columns on import of Excel/csv file
I have dataframes that in essence have the same columns but as a result of how they are exported into Excel by the source system, empty/white spaces are added randomly making it difficult to quickly import all these files at once using a function.

For example, the first dataframe is:

```<code>df_1 = pd.read_excel('df_1.xlsx', engine='openpyxl', usecols=['Name ', 'Title'])
</code>```

The second dataframe is:

```<code>df_2 = pd.read_excel('df_2.xlsx', engine='openpyxl', usecols=['Name ', 'Title '])
</code>```

I want to use the following function to import several such datasets from different locations as dataframes and join them thereafter:

```<code>def import_datasets(files):
    columns = ['Name', 'Title']
    df = pd.read_excel(files, engine='openpyxl', usecols=columns)
    return df
</code>```

How can I do this without having to go into each Excel file and deleting the empty spaces in the column headers? I know there are .strip() and .replace() functions available, however, these would only work once the dataset has been imported into Python already.

Body:
I have dataframes that in essence have the same columns but as a result of how they are exported into Excel by the source system, empty/white spaces are added randomly making it difficult to quickly import all these files at once using a function.

For example, the first dataframe is:

df_1 = pd.read_excel('df_1.xlsx', engine='openpyxl', usecols=['Name ', 'Title'])

The second dataframe is:

df_2 = pd.read_excel('df_2.xlsx', engine='openpyxl', usecols=['Name ', 'Title '])

I want to use the following function to import several such datasets from different locations as dataframes and join them thereafter:

def import_datasets(files):
    columns = ['Name', 'Title']
    df = pd.read_excel(files, engine='openpyxl', usecols=columns)
    return df

How can I do this without having to go into each Excel file and deleting the empty spaces in the column headers? I know there are .strip() and .replace() functions available, however, these would only work once the dataset has been imported into Python already.


问:
pass ctrl+c to jupyter notebook launched remotely (ssh) by bash script
I have a bash script that launches a jupyter notebook remotely (ssh):

```<code>#!/bin/bash
ssh -T user@remotehost << HERE
    # some code ...
    jupyter notebook --no-browser
HERE
</code>```

I would like to terminate the notebook by pressing ctrl+c but have not found a way to pass the termination signal to the notebook while running it in the foreground (I would like to see the notebook output), so this does not work:

```<code>jupyer notebook --no-browser &
pid=$!
trap 'kill -2 ${pid}' SIGINT
</code>```

Body:
I have a bash script that launches a jupyter notebook remotely (ssh):

#!/bin/bash
ssh -T user@remotehost << HERE
    # some code ...
    jupyter notebook --no-browser
HERE

I would like to terminate the notebook by pressing ctrl+c but have not found a way to pass the termination signal to the notebook while running it in the foreground (I would like to see the notebook output), so this does not work:

jupyer notebook --no-browser &
pid=$!
trap 'kill -2 ${pid}' SIGINT


问:
SpEL - Convert Json Objects with list into single list
I'm using Spring Expression Language to manipulate json due application requirements.

I have the following json response:

[
    {
        "steps": [
            {
                "id": 000,
                "sequence": 4,
                "type": "my_referente_value",
                [...]
                "route_time": {}
            },
            {
                "id": 111,
                "sequence": 5,
                "type": "any_value",
                [...]
                "route_time": {}
            }
        ]
    },
    {
        "steps": [
            {
                "id": 222,
                "sequence": 4,
                "type": "my_referente_value",
                [...]
                "route_time": {}
            },
            {
                "id": 333,
                "sequence": 5,
                "type": "any_value",
                [...]
                "route_time": {}
            }
        ]
    },
    {
        "steps": [
            {
                "id": 444,
                "sequence": 4,
                "type": "my_referente_value",
                [...]
                "route_time": {}
            },
            {
                "id": 555,
                "sequence": 5,
                "type": "any_value",
                [...]
                "route_time": {}
            }
        ]
    },
    {
        "steps": [
            {
                "id": 666,
                "sequence": 4,
                "type": "my_referente_value",
                [...]
                "route_time": {}
            },
            {
                "id": 777,
                "sequence": 5,
                "type": "any_value",
                [...]
                "route_time": {}
            }
        ]
    },
    {
        "steps": [
            {
                "id": 888,
                "sequence": 4,
                "type": "my_referente_value",
                [...]
                "route_time": {}
            },
            {
                "id": 999,
                "sequence": 5,
                "type": "any_value",
                [...]
                "route_time": {}
            }
        ]
    }
]```
</div>
</div>
</p>
<p>I tried something like <code>parser.parseExpression("#jsonPath(#response, '$[0].steps[?(@.type == \"my_referente_value\")]')").getValue(evaluationContext)</code> but I got only the first step. I'm trying to figure out how to not use the index <code>$[0]</code></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>[
    {
        "steps": [
            {
                "id": 000,
                "sequence": 4,
                "type": "my_referente_value",
                [...],
                "route_time": {}
            }
        ]
    }
]</code>```

I would like to get only objects (or structure) with type == my_reference_value, as something like below:

"steps": [
    {
        "id": 000,
        "sequence": 4,
        "type": "my_referente_value",
        [...],
        "route_time": {}
    },
    {
        "id": 222,
        "sequence": 4,
        "type": "my_referente_value",
        [...,]
        "route_time": {}
    },
    {
        "id": 444,
        "sequence": 4,
        "type": "my_referente_value",
        [...],
        "route_time": {}
    },
    {
        "id": 666,
        "sequence": 4,
        "type": "my_referente_value",
        [...],
        "route_time": {}
    },
    {
        "id": 888,
        "sequence": 4,
        "type": "my_referente_value",
        [...],
        "route_time": {}
    }
]```

There is any way to do that only using spring expression language? Unfortunately, I can't register methods or any variables on evaluationContext, only expressions.

Thanks for any help or idea.

Body:
I'm using Spring Expression Language to manipulate json due application requirements.

I have the following json response:

[
    {
        "steps": [
            {
                "id": 000,
                "sequence": 4,
                "type": "my_referente_value",
                [...]
                "route_time": {}
            },
            {
                "id": 111,
                "sequence": 5,
                "type": "any_value",
                [...]
                "route_time": {}
            }
        ]
    },
    {
        "steps": [
            {
                "id": 222,
                "sequence": 4,
                "type": "my_referente_value",
                [...]
                "route_time": {}
            },
            {
                "id": 333,
                "sequence": 5,
                "type": "any_value",
                [...]
                "route_time": {}
            }
        ]
    },
    {
        "steps": [
            {
                "id": 444,
                "sequence": 4,
                "type": "my_referente_value",
                [...]
                "route_time": {}
            },
            {
                "id": 555,
                "sequence": 5,
                "type": "any_value",
                [...]
                "route_time": {}
            }
        ]
    },
    {
        "steps": [
            {
                "id": 666,
                "sequence": 4,
                "type": "my_referente_value",
                [...]
                "route_time": {}
            },
            {
                "id": 777,
                "sequence": 5,
                "type": "any_value",
                [...]
                "route_time": {}
            }
        ]
    },
    {
        "steps": [
            {
                "id": 888,
                "sequence": 4,
                "type": "my_referente_value",
                [...]
                "route_time": {}
            },
            {
                "id": 999,
                "sequence": 5,
                "type": "any_value",
                [...]
                "route_time": {}
            }
        ]
    }
]

I tried something like parser.parseExpression("#jsonPath(#response, '$[0].steps[?(@.type == \"my_referente_value\")]')").getValue(evaluationContext) but I got only the first step. I'm trying to figure out how to not use the index $[0]

[
    {
        "steps": [
            {
                "id": 000,
                "sequence": 4,
                "type": "my_referente_value",
                [...],
                "route_time": {}
            }
        ]
    }
]

I would like to get only objects (or structure) with type == my_reference_value, as something like below:

"steps": [
    {
        "id": 000,
        "sequence": 4,
        "type": "my_referente_value",
        [...],
        "route_time": {}
    },
    {
        "id": 222,
        "sequence": 4,
        "type": "my_referente_value",
        [...,]
        "route_time": {}
    },
    {
        "id": 444,
        "sequence": 4,
        "type": "my_referente_value",
        [...],
        "route_time": {}
    },
    {
        "id": 666,
        "sequence": 4,
        "type": "my_referente_value",
        [...],
        "route_time": {}
    },
    {
        "id": 888,
        "sequence": 4,
        "type": "my_referente_value",
        [...],
        "route_time": {}
    }
]

There is any way to do that only using spring expression language? Unfortunately, I can't register methods or any variables on evaluationContext, only expressions.

Thanks for any help or idea.


问:
Back Tracking Maze Algorithm not removing node walls
First of relatively new to Stack overflow and not the best developer out there.

I'm essentially attempting to generate a maze in the Unity game development software.  There is a known algorithm called the depth-first search. It works by choosing a random starting node (box if you will) then chooses another node next to it.  When there is no available nodes next to it, back tracks until there a node available.

You can use this algorithm to generate a maze by removing walls when the algorithm backtracks.  So far my code can generate, a gird, run through the algorithm until all nodes have been picked.  However when I add in the code to remove a wall and switch statements that dictate which wall to be removed, program only selects one node and stops.  Nothing else is completed.

Dictates the Nodes

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public enum NodeState
{
    Available,
    Current,
    Completed
}

public class mazenode : MonoBehaviour
{
    [SerializeField] GameObject[] walls;
    [SerializeField] MeshRenderer floor;

    public void Removewall(int walltoremove)
    {
        walls[walltoremove].gameObject.SetActive(false);
    }

    public void SetState(NodeState state)
    {
        switch (state)
        {
            case NodeState.Available:
                floor.material.color = Color.white;
                break;
            case NodeState.Current:
                floor.material.color = Color.yellow;
                break;
            case NodeState.Completed:
                floor.material.color = Color.blue;
                break;

        }
    }
}
</code>```

Generates the Maze

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class mazegenerator : MonoBehaviour
{
    [SerializeField] mazenode nodePrefab;
    [SerializeField] Vector2Int mazeSize;

    private void Start()
    {
        StartCoroutine(GenerateMaze(mazeSize));

    }

    IEnumerator GenerateMaze(Vector2Int size)
    {
        List<mazenode> nodes = new List<mazenode>();

        //This is creating nodes
        for (int x = 0; x < size.x; x++)
        {
            for (int y = 0; y < size.y; y++)

            {
                Vector3 nodePos = new Vector3(x - (size.x / 2f), 0, y - (size.y / 2f));
                mazenode newNode = Instantiate(nodePrefab, nodePos, Quaternion.identity, transform);
                nodes.Add(newNode);

                yield return null;
            }

        }

        List<mazenode> currentPath = new List<mazenode>();
        List<mazenode> completedNodes = new List<mazenode>();

        // Choose starting node at random
        currentPath.Add(nodes[Random.Range(0, nodes.Count)]);
        currentPath[0].SetState(NodeState.Current);

        while (completedNodes.Count < nodes.Count)
        {
            //Check nodes next to the current node
            List<int> posnexNodes = new List<int>();
            List<int> posdirectionNodes = new List<int>();

            int currentNodeIndex = nodes.IndexOf(currentPath[currentPath.Count - 1]);
            int currentNodeX = currentNodeIndex / size.y;
            int currentNodeY = currentNodeIndex % size.y;

            if (currentNodeX < size.x - 1) //checking if it's on the rigt wall
            {
                if (!completedNodes.Contains(nodes[currentNodeIndex + size.y]) &&
                    !currentPath.Contains(nodes[currentNodeIndex + size.y]))

                {
                    posdirectionNodes.Add(1);
                    posnexNodes.Add(currentNodeIndex + size.y);
                }
            }

            if (currentNodeX > 0)  // Check node to left of the current node
            {

                if(!completedNodes.Contains(nodes[currentNodeIndex - size.y]) &&
                        !currentPath.Contains(nodes[currentNodeIndex - size.y]))
                    {
                    posdirectionNodes.Add(2);
                    posnexNodes.Add(currentNodeIndex - size.y);
                    }
            }

            if (currentNodeY < size.y - 1) //Check node above the current node
            {
                if (!completedNodes.Contains(nodes[currentNodeIndex + 1]) &&
                    !currentPath.Contains(nodes[currentNodeIndex + 1]))
                {
                    posdirectionNodes.Add(3);
                    posnexNodes.Add(currentNodeIndex + 1);

                }
            }

            if(currentNodeY > 0)  //Check node below current node
            {
                if (!completedNodes.Contains(nodes[currentNodeIndex - 1]) &&
                     !currentPath.Contains(nodes[currentNodeIndex -1]))
                {
                    posdirectionNodes.Add(4);
                    posnexNodes.Add(currentNodeIndex - 1);
                }

            }

            if(posdirectionNodes.Count > 0)  //Choose next node
            {
                int chosenDirection = Random.Range(0, posdirectionNodes.Count);
                mazenode chosenNode = nodes[posnexNodes[chosenDirection]];

               switch (posdirectionNodes[chosenDirection])
                {
                    case 1:
                        chosenNode.Removewall(1);
                        currentPath[currentPath.Count - 1].Removewall(0);
                        break;
                    case 2:
                        chosenNode.Removewall(0);
                        currentPath[currentPath.Count - 1].Removewall(1);
                        break;
                    case 3:
                        chosenNode.Removewall(3);
                        currentPath[currentPath.Count - 1].Removewall(2);
                        break;
                    case 4:
                        chosenNode.Removewall(2);
                        currentPath[currentPath.Count - 1].Removewall(3);
                        break;

                }

                currentPath.Add(chosenNode);
                chosenNode.SetState(NodeState.Current);
            }

            else
            {
                completedNodes.Add(currentPath[currentPath.Count - 1]);

                currentPath[currentPath.Count - 1].SetState(NodeState.Completed);
                currentPath.RemoveAt(currentPath.Count -1);

            }

            yield return new WaitForSeconds(1.5f);

        }
    }

}
</code>```

This is what it produces without removing walls

This is what it produces with code that it's suppose to remove the wall

Body:
First of relatively new to Stack overflow and not the best developer out there.

I'm essentially attempting to generate a maze in the Unity game development software.  There is a known algorithm called the depth-first search. It works by choosing a random starting node (box if you will) then chooses another node next to it.  When there is no available nodes next to it, back tracks until there a node available.

You can use this algorithm to generate a maze by removing walls when the algorithm backtracks.  So far my code can generate, a gird, run through the algorithm until all nodes have been picked.  However when I add in the code to remove a wall and switch statements that dictate which wall to be removed, program only selects one node and stops.  Nothing else is completed.

Dictates the Nodes

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public enum NodeState
{
    Available,
    Current,
    Completed
}

public class mazenode : MonoBehaviour
{
    [SerializeField] GameObject[] walls;
    [SerializeField] MeshRenderer floor;

    public void Removewall(int walltoremove)
    {
        walls[walltoremove].gameObject.SetActive(false);
    }

    public void SetState(NodeState state)
    {
        switch (state)
        {
            case NodeState.Available:
                floor.material.color = Color.white;
                break;
            case NodeState.Current:
                floor.material.color = Color.yellow;
                break;
            case NodeState.Completed:
                floor.material.color = Color.blue;
                break;

        }
    }
}

Generates the Maze

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class mazegenerator : MonoBehaviour
{
    [SerializeField] mazenode nodePrefab;
    [SerializeField] Vector2Int mazeSize;

    private void Start()
    {
        StartCoroutine(GenerateMaze(mazeSize));

    }

    IEnumerator GenerateMaze(Vector2Int size)
    {
        List<mazenode> nodes = new List<mazenode>();

        //This is creating nodes
        for (int x = 0; x < size.x; x++)
        {
            for (int y = 0; y < size.y; y++)

            {
                Vector3 nodePos = new Vector3(x - (size.x / 2f), 0, y - (size.y / 2f));
                mazenode newNode = Instantiate(nodePrefab, nodePos, Quaternion.identity, transform);
                nodes.Add(newNode);

                yield return null;
            }

        }

        List<mazenode> currentPath = new List<mazenode>();
        List<mazenode> completedNodes = new List<mazenode>();

        // Choose starting node at random
        currentPath.Add(nodes[Random.Range(0, nodes.Count)]);
        currentPath[0].SetState(NodeState.Current);

        while (completedNodes.Count < nodes.Count)
        {
            //Check nodes next to the current node
            List<int> posnexNodes = new List<int>();
            List<int> posdirectionNodes = new List<int>();

            int currentNodeIndex = nodes.IndexOf(currentPath[currentPath.Count - 1]);
            int currentNodeX = currentNodeIndex / size.y;
            int currentNodeY = currentNodeIndex % size.y;

            if (currentNodeX < size.x - 1) //checking if it's on the rigt wall
            {
                if (!completedNodes.Contains(nodes[currentNodeIndex + size.y]) &&
                    !currentPath.Contains(nodes[currentNodeIndex + size.y]))

                {
                    posdirectionNodes.Add(1);
                    posnexNodes.Add(currentNodeIndex + size.y);
                }
            }

            if (currentNodeX > 0)  // Check node to left of the current node
            {

                if(!completedNodes.Contains(nodes[currentNodeIndex - size.y]) &&
                        !currentPath.Contains(nodes[currentNodeIndex - size.y]))
                    {
                    posdirectionNodes.Add(2);
                    posnexNodes.Add(currentNodeIndex - size.y);
                    }
            }

            if (currentNodeY < size.y - 1) //Check node above the current node
            {
                if (!completedNodes.Contains(nodes[currentNodeIndex + 1]) &&
                    !currentPath.Contains(nodes[currentNodeIndex + 1]))
                {
                    posdirectionNodes.Add(3);
                    posnexNodes.Add(currentNodeIndex + 1);

                }
            }

            if(currentNodeY > 0)  //Check node below current node
            {
                if (!completedNodes.Contains(nodes[currentNodeIndex - 1]) &&
                     !currentPath.Contains(nodes[currentNodeIndex -1]))
                {
                    posdirectionNodes.Add(4);
                    posnexNodes.Add(currentNodeIndex - 1);
                }

            }

            if(posdirectionNodes.Count > 0)  //Choose next node
            {
                int chosenDirection = Random.Range(0, posdirectionNodes.Count);
                mazenode chosenNode = nodes[posnexNodes[chosenDirection]];

               switch (posdirectionNodes[chosenDirection])
                {
                    case 1:
                        chosenNode.Removewall(1);
                        currentPath[currentPath.Count - 1].Removewall(0);
                        break;
                    case 2:
                        chosenNode.Removewall(0);
                        currentPath[currentPath.Count - 1].Removewall(1);
                        break;
                    case 3:
                        chosenNode.Removewall(3);
                        currentPath[currentPath.Count - 1].Removewall(2);
                        break;
                    case 4:
                        chosenNode.Removewall(2);
                        currentPath[currentPath.Count - 1].Removewall(3);
                        break;

                }

                currentPath.Add(chosenNode);
                chosenNode.SetState(NodeState.Current);
            }

            else
            {
                completedNodes.Add(currentPath[currentPath.Count - 1]);

                currentPath[currentPath.Count - 1].SetState(NodeState.Completed);
                currentPath.RemoveAt(currentPath.Count -1);

            }

            yield return new WaitForSeconds(1.5f);

        }
    }

}

This is what it produces without removing walls

This is what it produces with code that it's suppose to remove the wall


问:
No data in Firebase Analytics, spotty "last 30 minutes" data
I'm trying to integrate with Firebase Analytics. I was following the guide in https://firebase.google.com/docs/unity/setup and didn't encounter anything that would end up with an error.

However, when I launch my game it says that Firebase has been initialized and there are no obvious errors in logcat. For my test user I would eventually get an entry in "Users in last 30 minutes", but it will only be for 1 minute, even if I keep the app open for the whole duration. The next day there is no data available in the analytics, even though I have been using the app for a bit while connected to the internet. Even the "last 30 minutes" data is spotty - e.g. I just launched the game but the only event I see is "session_start", with no active users per minute. I am using Firebase Auth, and it shows my test user account there signed in via Google Play Games.

Anyone could suggest debugging steps?

Here is the code I use to initialize everything on my first scene, in an empty GameObject:

```<code>using UnityEngine;
using System.Collections;
using Firebase;
using Firebase.Extensions;

#if UNITY_ANDROID
using GooglePlayGames;
#endif

public class FirebaseInitializer : MonoBehaviour
{
    private FirebaseApp app;
    private bool firebaseInitialized;

    void Awake()
    {
        //Initialize PlayGamesPlatform
#if UNITY_ANDROID
        PlayGamesPlatform.DebugLogEnabled = true;
        PlayGamesPlatform.Activate();
#endif
    }

    // Start is called before the first frame update
    IEnumerator Start()
    {
        InitializeFirebaseAndStart();
        while (!firebaseInitialized)
        {
            yield return null;
        }

        Social.localUser.Authenticate((bool success) => {
            print("Auth " + success);

            Firebase.Analytics.FirebaseAnalytics
                .LogEvent(Firebase.Analytics.FirebaseAnalytics.EventLogin);

            PlayGamesPlatform.Instance.RequestServerSideAccess(/* forceRefreshToken= */ false,
            authCode => {
                Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
                Firebase.Auth.Credential credential = Firebase.Auth.PlayGamesAuthProvider.GetCredential(authCode);
                auth.SignInWithCredentialAsync(credential).ContinueWith(task => {
                    if (task.IsCanceled)
                    {
                        Debug.LogError("SignInWithCredentialAsync was canceled.");
                        return;
                    }
                    if (task.IsFaulted)
                    {
                        Debug.LogError("SignInWithCredentialAsync encountered an error: " + task.Exception);
                        return;
                    }

                    Firebase.Auth.FirebaseUser newUser = task.Result;
                    Debug.LogFormat("User signed in successfully: {0} ({1})",
                        newUser.DisplayName, newUser.UserId);
                });
            });
        });

        Firebase.Analytics.FirebaseAnalytics
                .LogEvent(Firebase.Analytics.FirebaseAnalytics.EventAppOpen);

        yield break;
    }

    // When the app starts, check to make sure that we have
    // the required dependencies to use Firebase, and if not,
    // add them if possible.
    void InitializeFirebaseAndStart()
    {
        FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task => {
            var dependencyStatus = task.Result;
            if (dependencyStatus == DependencyStatus.Available)
            {
                app = FirebaseApp.DefaultInstance;
                firebaseInitialized = true;
            }
            else
            {
                Debug.LogError("Could not resolve all Firebase dependencies: " + dependencyStatus);
            }
        });
    }
}
</code>```

That object also has the DoNotDestroy script attached:

```<code>public class DoNotDestroy : MonoBehaviour
{
    private static DoNotDestroy _instance;

    // Start is called before the first frame update
    void Awake()
    {
        if (_instance == null)
        {
            _instance = this;
        }
        else
        {
            Destroy(this.gameObject);
        }
        DontDestroyOnLoad(transform.gameObject);
    }
}
</code>```

There are no obvious errors in logcat, and some data does go through into the realtime overview, but nothing shows up in the normal analytics view and when I do get user activity in realtime overview, it's just for single minute and sometimes missing some entries (like that session_start event without an actual user logged in)

Body:
I'm trying to integrate with Firebase Analytics. I was following the guide in https://firebase.google.com/docs/unity/setup and didn't encounter anything that would end up with an error.

However, when I launch my game it says that Firebase has been initialized and there are no obvious errors in logcat. For my test user I would eventually get an entry in "Users in last 30 minutes", but it will only be for 1 minute, even if I keep the app open for the whole duration. The next day there is no data available in the analytics, even though I have been using the app for a bit while connected to the internet. Even the "last 30 minutes" data is spotty - e.g. I just launched the game but the only event I see is "session_start", with no active users per minute. I am using Firebase Auth, and it shows my test user account there signed in via Google Play Games.

Anyone could suggest debugging steps?

Here is the code I use to initialize everything on my first scene, in an empty GameObject:

using UnityEngine;
using System.Collections;
using Firebase;
using Firebase.Extensions;

#if UNITY_ANDROID
using GooglePlayGames;
#endif

public class FirebaseInitializer : MonoBehaviour
{
    private FirebaseApp app;
    private bool firebaseInitialized;

    void Awake()
    {
        //Initialize PlayGamesPlatform
#if UNITY_ANDROID
        PlayGamesPlatform.DebugLogEnabled = true;
        PlayGamesPlatform.Activate();
#endif
    }

    // Start is called before the first frame update
    IEnumerator Start()
    {
        InitializeFirebaseAndStart();
        while (!firebaseInitialized)
        {
            yield return null;
        }

        Social.localUser.Authenticate((bool success) => {
            print("Auth " + success);

            Firebase.Analytics.FirebaseAnalytics
                .LogEvent(Firebase.Analytics.FirebaseAnalytics.EventLogin);

            PlayGamesPlatform.Instance.RequestServerSideAccess(/* forceRefreshToken= */ false,
            authCode => {
                Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
                Firebase.Auth.Credential credential = Firebase.Auth.PlayGamesAuthProvider.GetCredential(authCode);
                auth.SignInWithCredentialAsync(credential).ContinueWith(task => {
                    if (task.IsCanceled)
                    {
                        Debug.LogError("SignInWithCredentialAsync was canceled.");
                        return;
                    }
                    if (task.IsFaulted)
                    {
                        Debug.LogError("SignInWithCredentialAsync encountered an error: " + task.Exception);
                        return;
                    }

                    Firebase.Auth.FirebaseUser newUser = task.Result;
                    Debug.LogFormat("User signed in successfully: {0} ({1})",
                        newUser.DisplayName, newUser.UserId);
                });
            });
        });

        Firebase.Analytics.FirebaseAnalytics
                .LogEvent(Firebase.Analytics.FirebaseAnalytics.EventAppOpen);

        yield break;
    }

    // When the app starts, check to make sure that we have
    // the required dependencies to use Firebase, and if not,
    // add them if possible.
    void InitializeFirebaseAndStart()
    {
        FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task => {
            var dependencyStatus = task.Result;
            if (dependencyStatus == DependencyStatus.Available)
            {
                app = FirebaseApp.DefaultInstance;
                firebaseInitialized = true;
            }
            else
            {
                Debug.LogError("Could not resolve all Firebase dependencies: " + dependencyStatus);
            }
        });
    }
}

That object also has the DoNotDestroy script attached:

public class DoNotDestroy : MonoBehaviour
{
    private static DoNotDestroy _instance;

    // Start is called before the first frame update
    void Awake()
    {
        if (_instance == null)
        {
            _instance = this;
        }
        else
        {
            Destroy(this.gameObject);
        }
        DontDestroyOnLoad(transform.gameObject);
    }
}

There are no obvious errors in logcat, and some data does go through into the realtime overview, but nothing shows up in the normal analytics view and when I do get user activity in realtime overview, it's just for single minute and sometimes missing some entries (like that session_start event without an actual user logged in)