问:
Image Pipeline was not initialized (React Native)
Description
So I installed a library and since then I kept getting this error, I have tried for hours to fix it but it wouldn't work.

Version
0.70.6

Output of npx react-native info

```<code>System:
    OS: Windows 10 10.0.19045
    CPU: (16) x64 AMD Ryzen 7 5700G with Radeon Graphics
    Memory: 1.39 GB / 15.87 GB
Binaries:
    Node: 16.15.0 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.22.19 - ~\AppData\Roaming\npm\yarn.CMD
    npm: 8.10.0 - C:\Program Files\nodejs\npm.CMD
    Watchman: Not Found
SDKs:
    Android SDK: Not Found
    Windows SDK:
    AllowDevelopmentWithoutDevLicense: Enabled
    Versions: 10.0.19041.0
IDEs:
    Android Studio: Version 2021.1.0.0 AI-211.7628.21.2111.8309675
    Visual Studio: 17.1.32414.318 (Visual Studio Community 2022)
    Languages:
    Java: 11.0.12
npmPackages:
    @react-native-community/cli: Not Found
    react: 18.1.0 = 18.1.0
    react-native: 0.70.6 = 0.70.6
    react-native-windows: Not Found
    npmGlobalPackages:
    react-native: Not Found
</code>```

Steps to reproduce
Download from the repo provided below
Install the packages
And run the command: npx react-native run-android (Only configured for android)
Snack, code example, screenshot, or link to a repository
https://github.com/koen1711/react-native-ble-scala/tree/unstable

I couldn't find anything on the topic, and I am expecting no error.

Body:
Description
So I installed a library and since then I kept getting this error, I have tried for hours to fix it but it wouldn't work.

Version
0.70.6

Output of npx react-native info

System:
    OS: Windows 10 10.0.19045
    CPU: (16) x64 AMD Ryzen 7 5700G with Radeon Graphics
    Memory: 1.39 GB / 15.87 GB
Binaries:
    Node: 16.15.0 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.22.19 - ~\AppData\Roaming\npm\yarn.CMD
    npm: 8.10.0 - C:\Program Files\nodejs\npm.CMD
    Watchman: Not Found
SDKs:
    Android SDK: Not Found
    Windows SDK:
    AllowDevelopmentWithoutDevLicense: Enabled
    Versions: 10.0.19041.0
IDEs:
    Android Studio: Version 2021.1.0.0 AI-211.7628.21.2111.8309675
    Visual Studio: 17.1.32414.318 (Visual Studio Community 2022)
    Languages:
    Java: 11.0.12
npmPackages:
    @react-native-community/cli: Not Found
    react: 18.1.0 = 18.1.0
    react-native: 0.70.6 = 0.70.6
    react-native-windows: Not Found
    npmGlobalPackages:
    react-native: Not Found

Steps to reproduce
Download from the repo provided below
Install the packages
And run the command: npx react-native run-android (Only configured for android)
Snack, code example, screenshot, or link to a repository
https://github.com/koen1711/react-native-ble-scala/tree/unstable

I couldn't find anything on the topic, and I am expecting no error.


来源: stackexchange

问:
How to get size of a streaming AVPlayerLayer video?

This is how I get a video view.

```<code>func getVideoView(videoURL: String, bounds: CGRect, frame: CGRect) -> UIView? {
        var asset: AVURLAsset?
        asset = AVURLAsset(url: url)
        let item = AVPlayerItem(asset: asset)
        self.player?.removeAllItems()
        self.player = AVQueuePlayer(playerItem: item)

        self.playerLayer = AVPlayerLayer(player: player)
        self.playerLooper = AVPlayerLooper(player: player!, templateItem: item)

        self.playerLayer?.frame = bounds
        self.playerLayer?.videoGravity = .resizeAspect
        let playerView = UIView(frame: frame)
        playerView.layer.addSublayer(self.playerLayer!)
        let aspectRatio = playerLayer?.videoRect.size.height ?? 1 / (playerLayer?.videoRect.size.width ?? 1)

        playerView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            playerView.heightAnchor.constraint(equalTo: playerView.widthAnchor, multiplier: aspectRatio)
        ])
        player?.volume = 0
        player?.play()
        return playerView
    }
</code>```

I get nan (not a number) when I try to calculate the aspect ratio because the video hasn't loaded yet. How can I get the real size of the video?

ContentLicense: CC BY-SA 4.0

Body:
This is how I get a video view.

func getVideoView(videoURL: String, bounds: CGRect, frame: CGRect) -> UIView? {
        var asset: AVURLAsset?
        asset = AVURLAsset(url: url)
        let item = AVPlayerItem(asset: asset)
        self.player?.removeAllItems()
        self.player = AVQueuePlayer(playerItem: item)

        self.playerLayer = AVPlayerLayer(player: player)
        self.playerLooper = AVPlayerLooper(player: player!, templateItem: item)

        self.playerLayer?.frame = bounds
        self.playerLayer?.videoGravity = .resizeAspect
        let playerView = UIView(frame: frame)
        playerView.layer.addSublayer(self.playerLayer!)
        let aspectRatio = playerLayer?.videoRect.size.height ?? 1 / (playerLayer?.videoRect.size.width ?? 1)

        playerView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            playerView.heightAnchor.constraint(equalTo: playerView.widthAnchor, multiplier: aspectRatio)
        ])
        player?.volume = 0
        player?.play()
        return playerView
    }

I get nan (not a number) when I try to calculate the aspect ratio because the video hasn't loaded yet. How can I get the real size of the video?


问:
How to do hyperparameter tuning in reinforcement learning?
Currently I am learning Proximal Policy Optimization(PPO), an algorithm of deep reinforcement learning, by following the tutorials from Huggingface(https://huggingface.co/blog/deep-rl-ppo). They have the tutorial code (https://github.com/huggingface/deep-rl-class/tree/main/unit8) and I compete for the leaderboard of LunarLander(https://huggingface.co/spaces/huggingface-projects/Deep-Reinforcement-Learning-Leaderboard) task as well. However the performance of the agent highly related to the hyperparameter tuning and reward shaping, are there good tools that i can easily tune parameters automatically?

Not tried any package yet.


问:
How would I create and if/else based on whether a DOM variable is visible or not visible?
I'm creating a puppeteer script and occasionally an "Accept Cookies" window will pop up depending on which proxy I'm using and I have a function that will press the accept button when that window pops up, but occasionally the window won't pop up and I was wondering how would I write an if/else statement to have a handling for whether the window will be visible or not. For example if cookies is visible => clicks accept | else if cookie isn't visible => ignore. I had one written up as if (cookies == true) => function | else if (cookies == null) => move on, but it didn't work as I thought. Does anyone have any ideas?</p>
```<code>const acceptCookies = `button[class="ncss-btn-primary-dark pt3-sm pb3-sm pt2-lg pb2-lg ta-sm-c u-full-width"]`

    await page.waitForSelector(acceptCookies, { visible: true });
        await Promise.all([
            page.click(acceptCookies),
            page.waitForNavigation()
        ]);

    await page.waitForTimeout( 2500 );
</code>```

Body:
I'm creating a puppeteer script and occasionally an "Accept Cookies" window will pop up depending on which proxy I'm using and I have a function that will press the accept button when that window pops up, but occasionally the window won't pop up and I was wondering how would I write an if/else statement to have a handling for whether the window will be visible or not. For example if cookies is visible => clicks accept | else if cookie isn't visible => ignore. I had one written up as if (cookies == true) => function | else if (cookies == null) => move on, but it didn't work as I thought. Does anyone have any ideas?

const acceptCookies = `button[class="ncss-btn-primary-dark pt3-sm pb3-sm pt2-lg pb2-lg ta-sm-c u-full-width"]`

    await page.waitForSelector(acceptCookies, { visible: true });
        await Promise.all([
            page.click(acceptCookies),
            page.waitForNavigation()
        ]);

    await page.waitForTimeout( 2500 );


问:
How can i backup my database with lashes?
Hello i wish someone can help me it's my presentation tomorrow i would like to ask why does my values does not have lashes? ``` when i backup my database in php? i'm using codeigniter can someone please help me whenever i back up it it turns</p>
```INSERT INTO `discount` (`id`, `name`, `discount_percent`, `active`) VALUES (3, Student, 10, 1);
```
<p>and it's giving me an error i think he want the value have lashes like this</p>
```INSERT INTO `discount` (`id`, `name`, `discount_percent`, `active`) VALUES ('3', 'Student', '10', '1');`
```
<p>i tried the first one in my localhost but failed and the second one with lashes is successful so how can i backup with lashes?</p>
<p>my code is:</p>
```public function create()
{
    // Load the DB utility class
    $this->load->dbutil();

    $test = date('YmdS-His');
    // Backup your entire database and assign it to a variable
    $config = array (
        'format' => 'zip', // gzip, zip, txt
        'filename' => 'bubblebee_'.$test.'_db.sql', // File name - NEEDED ONLY WITH ZIP FILES
        'add_drop' => TRUE, // Whether to add DROP TABLE statements to backup file
        'add_insert' => TRUE, // Whether to add INSERT data to backup file
        'newline' => "\n", // Newline character used in backup file
        'foreign_key_checks' => FALSE,
    );

   $backup =& $this->dbutil->backup($config);
   $db_name ='bubblebee_'.$test.'.zip';
   $this->load->helper('download');
   force_download($db_name, $backup);
}
```

Body:
Hello i wish someone can help me it's my presentation tomorrow i would like to ask why does my values does not have lashes? ``` when i backup my database in php? i'm using codeigniter can someone please help me whenever i back up it it turns

INSERT INTO `discount` (`id`, `name`, `discount_percent`, `active`) VALUES (3, Student, 10, 1);

and it's giving me an error i think he want the value have lashes like this

INSERT INTO `discount` (`id`, `name`, `discount_percent`, `active`) VALUES ('3', 'Student', '10', '1');`

i tried the first one in my localhost but failed and the second one with lashes is successful so how can i backup with lashes?

my code is:

public function create()
{
    // Load the DB utility class
    $this->load->dbutil();

    $test = date('YmdS-His');
    // Backup your entire database and assign it to a variable
    $config = array (
        'format' => 'zip', // gzip, zip, txt
        'filename' => 'bubblebee_'.$test.'_db.sql', // File name - NEEDED ONLY WITH ZIP FILES
        'add_drop' => TRUE, // Whether to add DROP TABLE statements to backup file
        'add_insert' => TRUE, // Whether to add INSERT data to backup file
        'newline' => "\n", // Newline character used in backup file
        'foreign_key_checks' => FALSE,
    );

   $backup =& $this->dbutil->backup($config);
   $db_name ='bubblebee_'.$test.'.zip';
   $this->load->helper('download');
   force_download($db_name, $backup);
}


问:
PyWebIO with HTTPS
I'm trying to deploy a very simple PyWebIO Application in my local network, but I'm also trying to make it available via HTTPS, so that the browser does not "complain" about it being insecure.

What is the easiest way to set up a PyWebIO Application with HTTPS?

I have been trying to pass tornados ssl_options=SSLContext like this:
pywebio.start_server(hello_world, ssl_options=ctx, port=1337, debug=True) but it didn't do the trick for me.

Title: PyWebIO with HTTPS


问:
Django Admin Button: How to pass values from many-to-many through a button to a function?
New to programming, Python, and Django. I've written a standalone function that works well enough that generates a schedule for a tennis doubles league using a list of players, the number of courts available, and a duration, which right now I just print out as a CSV and send out to the league. My goal is to create an admin portal that generates the schedule based on league and player information created in an admin portal and ultimately have that schedule stored in a SQL db and ultimately accessed via a public portal. My immediate issue is that I'm unable to figure out how to pass (or print for that matter) the list of players in my league session. Additionally, I'm not sure exactly how to pass the required information from my admin site through the button to my function.

Here's a screenshot of my LeagueSession admin page :
as you can see, I've created a button and am printing some of the data I need. I can't get the playersinsession to print. Ultimately I need to pass this as a list, I think. So while printing this list would be a great start, I also need help with passing all this info through the button to my scheduler function. Thank you!!!

custom_change_form.html:

{% extends 'admin/change_form.html' %}
{% block submit_buttons_bottom %}
{{ block.super }}

    <input type="submit" value="Generate Schedule" name="_make-unique">

    Session ID: {{ original.id }}

    Players in session: {{ original.playersinsession }}

    Number of courts: {{ original.numberofcourts }}

    Duration: {{ original.duration }}

{% endblock %}
```
<p>models.py:</p>
<pre class="lang-py prettyprint-override"><code>from django.db import models
from django.contrib import admin

# Create your models here.
class League(models.Model):
    name = models.CharField(max_length=64)
    type = models.CharField(max_length=15)

    def __str__(self):
        return f"{self.id}: {self.name} {self.type} League"

class Player(models.Model):
    first = models.CharField(max_length=64)
    last = models.CharField(max_length=64)
    LeagueSession = models.ManyToManyField('LeagueSession', blank=True, related_name="players")

    def __str__(self):
        return f"{self.first} {self.last}"

class LeagueSession(models.Model):
    leagueid = models.ForeignKey(League, on_delete=models.CASCADE, related_name="leagues")
    startdate = models.DateField()
    enddate = models.DateField()
    duration = models.IntegerField()
    numberofplayers = models.IntegerField()
    numberofcourts = models.IntegerField()
    playersinsession = models.ManyToManyField(Player, blank=True, related_name="sessions")

    def __str__(self):
        return f"{self.id} {self.leagueid.name}: {self.startdate} to {self.enddate}"
</code>```

views.py:

from django import forms
from django.shortcuts import render
from django.http import HttpResponse
import itertools
import random
import pandas as pd
from .models import League, LeagueSession, Player

# Create your views here.

class NewTaskForm(forms.Form): #this was being used before I realized it made more sense for the form/button to be on the admin site rather than the public facing site
    playersform = forms.CharField(label="List of Players")
    daysform = forms.IntegerField(label="Number of Days")
    courtsform = forms.IntegerField(label="Number of Courts")

def leagues(request): #this is just a test page to print from my models
    return render(request, "scheduler/leagues.html", {
        "leagues": League.objects.all(),
        "sessions": LeagueSession.objects.all(),
        "players": Player.objects.all()
    })

def scheduler(request): #this has not been refactored yet from when I was passing data via the NewTaskForm form; I need to fix the button first
    if request.method == 'POST':
        form = NewTaskForm(request.POST)
        if form.is_valid():
            players = form.cleaned_data["playersform"]
            num_days = form.cleaned_data["daysform"]
            print(num_days)
            #print(players)
            #num_days = 10
            players = ['Novak Djokovic','Carlos Alcaraz','John McEnroe','Rafael Nadal','Andy Murray','Roger Federer','Ivan Lendl','Andre Agassi','Pete Sampras','Daniil Medvedev','Jay Leno']
            num_courts = 2 #passing through how many days the league will have matches played on, the players names, and how many courts are available for simultaneous play
            player_combinations = [] #create function-level variable to hold all player_combinations that we will use to hold player combinations and eliminate those that have already played together for subsequent weeks
            schedule = [] #create function-level variable to hold the list of tuples that will hold the final schedule for the league
            player_combinations = list(itertools.combinations(players, 2)) #generate original list of all player combinations
            player_match_count = {} #empty dict to count how many times each player has played as the schedule is generated
            for x in range(len(players)): #looping through the dictionary to create a key:value pair for each player in the league
                player_match_count[players[x]] = 0 #filling that dictionary set to 0 for each player to track how many matches they've each played
            for days in range(num_days): #need to loop for each day's worth of matches
                matches = [] #creating an empty list for each day to hold all the matches created for all courts
                day_combinations = player_combinations.copy() #need a new list that can be modified within the courts for loop so players on court 1 can be removed from the list so they're not eligible to be put on future courts in that week
                for courts in range(num_courts): #looping through the courts to create a match on each court with unique players
                    low_player_count = min(player_match_count, key=lambda x: player_match_count[x]) #for next implementation, not currently used, but will start pulling players that have played the least matches instead of pulling random combinations. Also considering sorting player_combinations each week to put the least-played combinations first, then I wouldn't have to ever remove teams from the list, just re-sort instead.
                    print(low_player_count) #print for testing
                    team1 = random.choice(day_combinations) #assigning a random combination of 2 players to be team1. FUTURE: Change this to use low_player_count instead of random
                    playera, playerb = team1 #extracting the players from team 1 into their own variable... probably a cleaner way to identify the players without creating 2 new variables (team1[0]?)
                    player_match_count[playera] += 1 #incrementing the match count for player a
                    print(playera, player_match_count[playera]) #print for testing
                    player_match_count[playerb] += 1 #incrementing the match count for player b
                    print(playerb, player_match_count[playerb]) #print for testing
                    player_combinations.remove(team1) #removing the team1 combination from the overall player_combinations list since we do not want players to play with the same partner more than once. FUTURE: this causes the program to fail frequently especially if the duration of the league is longer since this requirement is not always possible. Need a way to reset the player_combinations when there is an error: IndexError: list index out of range.
                    day_combinations = [x for x in day_combinations if (playera not in x and playerb not in x)] #list comprehension to filter out players a and b so they can't get selected again for the other teams and courts
                    low_player_count = min(player_match_count, key=lambda x: player_match_count[x]) #for next implementation, not currently used, but will start pulling players that have played the least matches instead of pulling random combinations
                    print(low_player_count) #print for testing
                    team2 = random.choice(day_combinations) #assigning a random combination of 2 players to be team2. FUTURE: Change this to use low_player_count instead of random
                    playerc, playerd = team2 #extracting the players from team 2 into their own variable... probably a cleaner way to identify the players without creating 2 new variables (team2[0]?)
                    player_match_count[playerc] += 1 #incrementing the match count for player c
                    print(playerc, player_match_count[playerc]) #print for testing
                    player_match_count[playerd] += 1 #incrementing the match count for player d
                    print(playerd, player_match_count[playerd]) #print for testing
                    print(player_match_count) #print for testing
                    player_combinations.remove(team2) #removing the team2 combination from the overall player_combinations list since we do not want players to play with the same partner more than once. FUTURE: this causes the program to fail frequently especially if the duration of the league is longer since this requirement is not always possible. Need a way to reset the player_combinations when there is an error: IndexError: list index out of range.
                    day_combinations = [x for x in day_combinations if (playerc not in x and playerd not in x)] #list comprehension to filter out players c and d so they can't get selected again for the other teams and courts
                    daymatches = [team1, team2] #grouping the teams up to symbolize a match on a court. I probably don't need a new list here, and if I keep it, it should probably be renamed to courtmatches.
                    matches.append(daymatches) #appending the team1 vs. team2 match to the matches list for the whole day. Maybe I should rename this to daymatches after I rename daymatches to courtmatches.
                bye = [x for x in players if x not in itertools.chain.from_iterable(itertools.chain.from_iterable(matches))] #filtering out the players who are playing that week from the overall players list to get back who is on bye that week. Ugly but it works, not sure why I have to nest the chain functions.
                matches.append(bye) #new line to append the byes to matches first before appending it all to schedule
                schedule.append(matches) #putting all of the court matches we just created into the overall league schedule
                #schedule.append(bye) #adding the players on bye right after that day's matches with the intention of displaying them in their own column
            print(player_match_count) #print for testing

            print(player_match_count) #print for testing
            print(player_match_count.values()) #print for testing

        # Create a dataframe from the schedule

            df = pd.DataFrame(schedule, columns=['Court 1','Court 2','Byes']) #Dataframe to show the schedule with the weeks as the index and courts/byes as columns.
            df.index += 1 # Add 1 to the index to make the weeks start at 1
            dfhtml = df.to_html()
            print(dfhtml)
            #df.to_csv('federer.csv')
            #df['Court 1'] = df['Court 1'].str.replace('\W','', regex=True)
            return render(request, "scheduler/index.html",{
                'schedule': dfhtml,
                'form': NewTaskForm()

        })
    return render(request, "scheduler/index.html",{
        'form': NewTaskForm()
    })
```

Body:
New to programming, Python, and Django. I've written a standalone function that works well enough that generates a schedule for a tennis doubles league using a list of players, the number of courts available, and a duration, which right now I just print out as a CSV and send out to the league. My goal is to create an admin portal that generates the schedule based on league and player information created in an admin portal and ultimately have that schedule stored in a SQL db and ultimately accessed via a public portal. My immediate issue is that I'm unable to figure out how to pass (or print for that matter) the list of players in my league session. Additionally, I'm not sure exactly how to pass the required information from my admin site through the button to my function.

Here's a screenshot of my LeagueSession admin page :
as you can see, I've created a button and am printing some of the data I need. I can't get the playersinsession to print. Ultimately I need to pass this as a list, I think. So while printing this list would be a great start, I also need help with passing all this info through the button to my scheduler function. Thank you!!!

custom_change_form.html:

{% extends 'admin/change_form.html' %}
{% block submit_buttons_bottom %}
{{ block.super }}

    <input type="submit" value="Generate Schedule" name="_make-unique">

    Session ID: {{ original.id }}

    Players in session: {{ original.playersinsession }}

    Number of courts: {{ original.numberofcourts }}

    Duration: {{ original.duration }}

{% endblock %}

models.py:

from django.db import models
from django.contrib import admin

# Create your models here.
class League(models.Model):
    name = models.CharField(max_length=64)
    type = models.CharField(max_length=15)

    def __str__(self):
        return f"{self.id}: {self.name} {self.type} League"

class Player(models.Model):
    first = models.CharField(max_length=64)
    last = models.CharField(max_length=64)
    LeagueSession = models.ManyToManyField('LeagueSession', blank=True, related_name="players")

    def __str__(self):
        return f"{self.first} {self.last}"

class LeagueSession(models.Model):
    leagueid = models.ForeignKey(League, on_delete=models.CASCADE, related_name="leagues")
    startdate = models.DateField()
    enddate = models.DateField()
    duration = models.IntegerField()
    numberofplayers = models.IntegerField()
    numberofcourts = models.IntegerField()
    playersinsession = models.ManyToManyField(Player, blank=True, related_name="sessions")

    def __str__(self):
        return f"{self.id} {self.leagueid.name}: {self.startdate} to {self.enddate}"

views.py:

from django import forms
from django.shortcuts import render
from django.http import HttpResponse
import itertools
import random
import pandas as pd
from .models import League, LeagueSession, Player

# Create your views here.

class NewTaskForm(forms.Form): #this was being used before I realized it made more sense for the form/button to be on the admin site rather than the public facing site
    playersform = forms.CharField(label="List of Players")
    daysform = forms.IntegerField(label="Number of Days")
    courtsform = forms.IntegerField(label="Number of Courts")

def leagues(request): #this is just a test page to print from my models
    return render(request, "scheduler/leagues.html", {
        "leagues": League.objects.all(),
        "sessions": LeagueSession.objects.all(),
        "players": Player.objects.all()
    })

def scheduler(request): #this has not been refactored yet from when I was passing data via the NewTaskForm form; I need to fix the button first
    if request.method == 'POST':
        form = NewTaskForm(request.POST)
        if form.is_valid():
            players = form.cleaned_data["playersform"]
            num_days = form.cleaned_data["daysform"]
            print(num_days)
            #print(players)
            #num_days = 10
            players = ['Novak Djokovic','Carlos Alcaraz','John McEnroe','Rafael Nadal','Andy Murray','Roger Federer','Ivan Lendl','Andre Agassi','Pete Sampras','Daniil Medvedev','Jay Leno']
            num_courts = 2 #passing through how many days the league will have matches played on, the players names, and how many courts are available for simultaneous play
            player_combinations = [] #create function-level variable to hold all player_combinations that we will use to hold player combinations and eliminate those that have already played together for subsequent weeks
            schedule = [] #create function-level variable to hold the list of tuples that will hold the final schedule for the league
            player_combinations = list(itertools.combinations(players, 2)) #generate original list of all player combinations
            player_match_count = {} #empty dict to count how many times each player has played as the schedule is generated
            for x in range(len(players)): #looping through the dictionary to create a key:value pair for each player in the league
                player_match_count[players[x]] = 0 #filling that dictionary set to 0 for each player to track how many matches they've each played
            for days in range(num_days): #need to loop for each day's worth of matches
                matches = [] #creating an empty list for each day to hold all the matches created for all courts
                day_combinations = player_combinations.copy() #need a new list that can be modified within the courts for loop so players on court 1 can be removed from the list so they're not eligible to be put on future courts in that week
                for courts in range(num_courts): #looping through the courts to create a match on each court with unique players
                    low_player_count = min(player_match_count, key=lambda x: player_match_count[x]) #for next implementation, not currently used, but will start pulling players that have played the least matches instead of pulling random combinations. Also considering sorting player_combinations each week to put the least-played combinations first, then I wouldn't have to ever remove teams from the list, just re-sort instead.
                    print(low_player_count) #print for testing
                    team1 = random.choice(day_combinations) #assigning a random combination of 2 players to be team1. FUTURE: Change this to use low_player_count instead of random
                    playera, playerb = team1 #extracting the players from team 1 into their own variable... probably a cleaner way to identify the players without creating 2 new variables (team1[0]?)
                    player_match_count[playera] += 1 #incrementing the match count for player a
                    print(playera, player_match_count[playera]) #print for testing
                    player_match_count[playerb] += 1 #incrementing the match count for player b
                    print(playerb, player_match_count[playerb]) #print for testing
                    player_combinations.remove(team1) #removing the team1 combination from the overall player_combinations list since we do not want players to play with the same partner more than once. FUTURE: this causes the program to fail frequently especially if the duration of the league is longer since this requirement is not always possible. Need a way to reset the player_combinations when there is an error: IndexError: list index out of range.
                    day_combinations = [x for x in day_combinations if (playera not in x and playerb not in x)] #list comprehension to filter out players a and b so they can't get selected again for the other teams and courts
                    low_player_count = min(player_match_count, key=lambda x: player_match_count[x]) #for next implementation, not currently used, but will start pulling players that have played the least matches instead of pulling random combinations
                    print(low_player_count) #print for testing
                    team2 = random.choice(day_combinations) #assigning a random combination of 2 players to be team2. FUTURE: Change this to use low_player_count instead of random
                    playerc, playerd = team2 #extracting the players from team 2 into their own variable... probably a cleaner way to identify the players without creating 2 new variables (team2[0]?)
                    player_match_count[playerc] += 1 #incrementing the match count for player c
                    print(playerc, player_match_count[playerc]) #print for testing
                    player_match_count[playerd] += 1 #incrementing the match count for player d
                    print(playerd, player_match_count[playerd]) #print for testing
                    print(player_match_count) #print for testing
                    player_combinations.remove(team2) #removing the team2 combination from the overall player_combinations list since we do not want players to play with the same partner more than once. FUTURE: this causes the program to fail frequently especially if the duration of the league is longer since this requirement is not always possible. Need a way to reset the player_combinations when there is an error: IndexError: list index out of range.
                    day_combinations = [x for x in day_combinations if (playerc not in x and playerd not in x)] #list comprehension to filter out players c and d so they can't get selected again for the other teams and courts
                    daymatches = [team1, team2] #grouping the teams up to symbolize a match on a court. I probably don't need a new list here, and if I keep it, it should probably be renamed to courtmatches.
                    matches.append(daymatches) #appending the team1 vs. team2 match to the matches list for the whole day. Maybe I should rename this to daymatches after I rename daymatches to courtmatches.
                bye = [x for x in players if x not in itertools.chain.from_iterable(itertools.chain.from_iterable(matches))] #filtering out the players who are playing that week from the overall players list to get back who is on bye that week. Ugly but it works, not sure why I have to nest the chain functions.
                matches.append(bye) #new line to append the byes to matches first before appending it all to schedule
                schedule.append(matches) #putting all of the court matches we just created into the overall league schedule
                #schedule.append(bye) #adding the players on bye right after that day's matches with the intention of displaying them in their own column
            print(player_match_count) #print for testing

            print(player_match_count) #print for testing
            print(player_match_count.values()) #print for testing

        # Create a dataframe from the schedule

            df = pd.DataFrame(schedule, columns=['Court 1','Court 2','Byes']) #Dataframe to show the schedule with the weeks as the index and courts/byes as columns.
            df.index += 1 # Add 1 to the index to make the weeks start at 1
            dfhtml = df.to_html()
            print(dfhtml)
            #df.to_csv('federer.csv')
            #df['Court 1'] = df['Court 1'].str.replace('\W','', regex=True)
            return render(request, "scheduler/index.html",{
                'schedule': dfhtml,
                'form': NewTaskForm()

        })
    return render(request, "scheduler/index.html",{
        'form': NewTaskForm()
    })


问:
Problem with a model and DataAttribute [Required] used even if not present on property
I have this model :

```<code>using System.ComponentModel.DataAnnotations;

namespace Core.Domain.Models.Contracts.V1._0
{
    public class Body
    {
        [StringLength(10)]
        public string field1 { get; set; }

        [StringLength(20)]
        public string field2 { get; set; }

        public string field3 { get; set; }

        [Required]
        [StringLength(3, MinimumLength = 3)]
        public string field4 { get; set; }
    }
}
</code>```

So far so good, problem is when I check model throughout reflection, all fields are flagued as required even if not in the model.
Here result of the analasys :

```<code>    Field: <field1>, Attribut de données: System.ComponentModel.DataAnnotations.StringLengthAttribute
    Field: <field1>, Attribut de données: System.ComponentModel.DataAnnotations.RequiredAttribute

    Field: <field2>, Attribut de données: System.ComponentModel.DataAnnotations.StringLengthAttribute
    Field: <field2>, Attribut de données: System.ComponentModel.DataAnnotations.RequiredAttribute

    Field: <field3>, Attribut de données: System.ComponentModel.DataAnnotations.StringLengthAttribute
    Field: <field3>, Attribut de données: System.ComponentModel.DataAnnotations.RequiredAttribute

    Field: <field4>, Attribut de données: System.ComponentModel.DataAnnotations.RequiredAttribute
    Field: <field4>, Attribut de données: System.ComponentModel.DataAnnotations.StringLengthAttribute
</code>```

and of course, if I try to validate model but not passing field1 or field2, I came out with a validation error

Of course, question is why?

Body:
I have this model :

using System.ComponentModel.DataAnnotations;

namespace Core.Domain.Models.Contracts.V1._0
{
    public class Body
    {
        [StringLength(10)]
        public string field1 { get; set; }

        [StringLength(20)]
        public string field2 { get; set; }

        public string field3 { get; set; }

        [Required]
        [StringLength(3, MinimumLength = 3)]
        public string field4 { get; set; }
    }
}

So far so good, problem is when I check model throughout reflection, all fields are flagued as required even if not in the model.
Here result of the analasys :

    Field: <field1>, Attribut de données: System.ComponentModel.DataAnnotations.StringLengthAttribute
    Field: <field1>, Attribut de données: System.ComponentModel.DataAnnotations.RequiredAttribute

    Field: <field2>, Attribut de données: System.ComponentModel.DataAnnotations.StringLengthAttribute
    Field: <field2>, Attribut de données: System.ComponentModel.DataAnnotations.RequiredAttribute

    Field: <field3>, Attribut de données: System.ComponentModel.DataAnnotations.StringLengthAttribute
    Field: <field3>, Attribut de données: System.ComponentModel.DataAnnotations.RequiredAttribute

    Field: <field4>, Attribut de données: System.ComponentModel.DataAnnotations.RequiredAttribute
    Field: <field4>, Attribut de données: System.ComponentModel.DataAnnotations.StringLengthAttribute

and of course, if I try to validate model but not passing field1 or field2, I came out with a validation error

Of course, question is why?


问:
Why is the first item doubled in ASP.NET CORE MVC application jquery .each loop?
I am develpoing ASP.NET MVC application where I have defined PartialView like this:

```<code><div class="editorRow">
<span>Name: </span> @Html.EditorFor(m => m.Name)
</div>
</code>```

With a press of a button user can add such views to collection:

```<code><div id="editorRows">
@foreach (var item in Model.Children)
{
<partial name="_myPartial" model="item" />
}
</div>
<a id="addItem" asp-action="BlankSentence" asp-controller="Home">Add Row...</a> <br />
</code>```

These items(information that is in the PartialViews) are then to be sent back to controller with ajax function, here is a small section of the script:

```<code>var products = [];
$(".editorRow").each(function(index, element) {
      let inputEl = element.querySelector("input[name='Name']");
      products .push({ Name: inputEl.value });
});
</code>```

Problem is that the resulting products array always contain one item more then user has added to editorRows collection. First item is doubled. Why is it so? I know there are similar posts here on SO, but nothing seems to solve this particular issue.

Body:
I am develpoing ASP.NET MVC application where I have defined PartialView like this:

Name:  @Html.EditorFor(m => m.Name)

With a press of a button user can add such views to collection:

@foreach (var item in Model.Children)
{
<partial name="_myPartial" model="item" />
}

Add Row...

These items(information that is in the PartialViews) are then to be sent back to controller with ajax function, here is a small section of the script:

var products = [];
$(".editorRow").each(function(index, element) {
      let inputEl = element.querySelector("input[name='Name']");
      products .push({ Name: inputEl.value });
});

Problem is that the resulting products array always contain one item more then user has added to editorRows collection. First item is doubled. Why is it so? I know there are similar posts here on SO, but nothing seems to solve this particular issue.


问:
Is it possible to disable dependency resolution in YARN while yarn upgrade
I have a custom dependency (my own package that is in the same monorepo and was installed with yarn add <path-to-folder>). When I amend my custom package, build it and then perform yarn upgrade <my-custom-package-name> I always need to wait until yarn resolves all the dependencies. I need to optimize the time that I need to wait until yarn upgrade will finish.

Is it possible to somehow disable that dependency resolution when updating that package so that it will be faster?

If not possible with Yarn, is it possible with NPM?


问:
CronJob for mysqldump then delete files and then copy the files and then delete again
I need a cronjob where I need 4 following functions.

Step1: mysqldump

mysqldump -h HOSTNAME -uroot -proot --all-databases >
backup/dump_$(date "+%d-%m-%Y_%H:%M:%S").sql

Step2: delete sqldump files when they are older than 14 days

find /usr/bin/find /backup/*.sql -mtime +14 -delete;

Step3: push this all .sql mysqldump files which left after step 2 on another server.

Step4: like Step2 but this time on the server where I pushed the .sql files.

I need it like this because, my cronjob is running in Kubernetes Cluster.
The Server with the database is not in the Kubernetes Cluster and the Server where I need to push the .sql files is not in Kubernetes Cluster too. I already rollout the cronjob in Kubernetes but I need the commands to do what I want.

I hope someone can help me.


问:
calling API inside 'getStaticProps' in next-js gives not understandable result but same API inside useEffect has no problem
I am using next js with typescript. I am trying to call an API that is developed in .net core 7 and deployed on azure. When I call the API inside useEffect, the console the result is as follows:

and this is the API call inside useEffect:

```<code>const getPosts = async () => {
    const result = await axios.get(
      "https://abc/api/v1/public/get-articles"
    );
    console.log(result);
  };
  useEffect(() => {
    getPosts();
  }, []);
</code>```

But when I call the same API inside getStaticProps I get the following result:

here is the data part of the response:

Here is the code that is written inside getStaticProps:

```<code>  const result = await axios.get(
    "https://abc/api/v1/public/get-articles"
  );
  console.log("Response: ", result);
</code>```

It is same code as inside useEffect.

Body:
I am using next js with typescript. I am trying to call an API that is developed in .net core 7 and deployed on azure. When I call the API inside useEffect, the console the result is as follows:

and this is the API call inside useEffect:

const getPosts = async () => {
    const result = await axios.get(
      "https://abc/api/v1/public/get-articles"
    );
    console.log(result);
  };
  useEffect(() => {
    getPosts();
  }, []);

But when I call the same API inside getStaticProps I get the following result:

here is the data part of the response:

Here is the code that is written inside getStaticProps:

  const result = await axios.get(
    "https://abc/api/v1/public/get-articles"
  );
  console.log("Response: ", result);

It is same code as inside useEffect.


问:
How to remove space for files in directory
I have these 2 space files in the below directory and want to remove space for these filenames

/home/sterlingadmin/

```<code>-rw-rw-r-- 1 sterlingadmin sterlingadmin  99 Jan 3 14:32 output test.txt
-rw-rw-r-- 1 sterlingadmin sterlingadmin  24 Dec 4 10:00 space test.txt
</code>```

I try to use below find command to remove space for the files but its not reflecting for the      files

[sterlingadmin@$

find -name "* *" |tr -d "[:blank:]"

```<code>    ./outputtest.txt
    ./delspace.txt
</code>```

[sterlingadmin@$

ls -lrt

```<code>    -rw-rw-r-- 1 sterlingadmin sterlingadmin  99 Jan 3 14:32 output test.txt
    -rw-rw-r-- 1 sterlingadmin sterlingadmin  24 Dec 4 10:00 space test.txt'

Please advise if any solution for this issue. thank you.
</code>```

Body:
I have these 2 space files in the below directory and want to remove space for these filenames

/home/sterlingadmin/

-rw-rw-r-- 1 sterlingadmin sterlingadmin  99 Jan 3 14:32 output test.txt
-rw-rw-r-- 1 sterlingadmin sterlingadmin  24 Dec 4 10:00 space test.txt

I try to use below find command to remove space for the files but its not reflecting for the      files

[sterlingadmin@$

find -name "* *" |tr -d "[:blank:]"

    ./outputtest.txt
    ./delspace.txt

[sterlingadmin@$

ls -lrt

    -rw-rw-r-- 1 sterlingadmin sterlingadmin  99 Jan 3 14:32 output test.txt
    -rw-rw-r-- 1 sterlingadmin sterlingadmin  24 Dec 4 10:00 space test.txt'

Please advise if any solution for this issue. thank you.


问:
Cannot read properties of undefined (reading 'map') in React 18
I'm trying to show lists of objects such as types and brands that I have in DyeStore my react app and after using map my app crashes but vs code doesn't tell about errors.

The following error occurs in these components:

```<code>const BrandBar = observer(() => {
    const {dye} = useContext(Context)
    return (
        <Form className='d-flex'>
            {dye.Brands.map(brand=>
                <Card key={brand.id} className="mt-2" onClick={()=> dye.SetSelectedBrand(brand)} border={brand.id === dye.SetSelectedBrand.Id ? 'danger' : 'light'} style={{cursor:'poiinter'}}>
                    {brand.name}
                </Card>
                )}
        </Form>
      );
  }
)
</code>```
```<code>const TypeBar = observer(() => {
    const {dye} = useContext(Context)
    return (
        <ListGroup>
            {dye.Types.map( type =>
                <ListGroup.Item
                    style={{cursor: 'pointer'}}
                    active = {type.id === dye.SetSelectedType.id }
                    onClick={() => dye.SetSelectedType(type)}
                    key={type.id}>

                </ListGroup.Item>)}
        </ListGroup>
      );
  }
)
</code>```

This is the class where I store my brands and types arrays.

```<code>import { makeAutoObservable } from "mobx"

export default class DyeStore{
    constructor(){
        this._Types = [
            {id:1,name:'Акриловая'}
        ]
        this._Brands = [
            {id:1,name:'Самсунг'}
        ]
        this._Dyes = [
            {id:1,name:'Самсунг',price: 2400,rating:5}
        ]
        this._SelectedType = {}
        this._SelectedBrand = {}
        makeAutoObservable(this)
    }
}
</code>```

I also have setters and getters for DyeStore:

What errors I got:

I was trying to resolve this problem myself but most of the answers were not in the theme so.

Body:
I'm trying to show lists of objects such as types and brands that I have in DyeStore my react app and after using map my app crashes but vs code doesn't tell about errors.

The following error occurs in these components:

const BrandBar = observer(() => {
    const {dye} = useContext(Context)
    return (
        <Form className='d-flex'>
            {dye.Brands.map(brand=>
                <Card key={brand.id} className="mt-2" onClick={()=> dye.SetSelectedBrand(brand)} border={brand.id === dye.SetSelectedBrand.Id ? 'danger' : 'light'} style={{cursor:'poiinter'}}>
                    {brand.name}
                </Card>
                )}
        </Form>
      );
  }
)

const TypeBar = observer(() => {
    const {dye} = useContext(Context)
    return (
        <ListGroup>
            {dye.Types.map( type =>
                <ListGroup.Item
                    style={{cursor: 'pointer'}}
                    active = {type.id === dye.SetSelectedType.id }
                    onClick={() => dye.SetSelectedType(type)}
                    key={type.id}>

                </ListGroup.Item>)}
        </ListGroup>
      );
  }
)

This is the class where I store my brands and types arrays.

import { makeAutoObservable } from "mobx"

export default class DyeStore{
    constructor(){
        this._Types = [
            {id:1,name:'Акриловая'}
        ]
        this._Brands = [
            {id:1,name:'Самсунг'}
        ]
        this._Dyes = [
            {id:1,name:'Самсунг',price: 2400,rating:5}
        ]
        this._SelectedType = {}
        this._SelectedBrand = {}
        makeAutoObservable(this)
    }
}

I also have setters and getters for DyeStore:

What errors I got:

I was trying to resolve this problem myself but most of the answers were not in the theme so.


问:
Using the analyzer package, is it possible to create an instance of a DartType representing a would-be generated code?
While using the analyzer package, I was wondering if it was possible to create an instance of its DartType object.

The issue I'm facing is, the analyzer output doesn't give me a valid DartType for a given class because that class has yet to exist (it is not yet generated by a code-generator).

I can work around not using DartType directly and instead make some copycat class. But that adds a lot of complexity. So I'd like to be able to create a DartType representing the would-be generated class.

I've looked into the TypeSytem/TypeProvider objects which seem to object type-related utilities but didn't find anything I wanted.

Is that possible?


问:
Excel coding Sheets(1).Range("A11").EntireRow.Insert
I am trying to write some code that will insert a new line on Worksheet 1 whenever a new worksheet is copied. I would also like the code to make cells on the new line reference certain cells from the newly copied sheet.

The problem I have is that my code is inserting 3 lines instead of 1 and the cell D11 only shows gets the text copied from Sheet2 instead of being equal.

Hope that all makes sense. Can anyone point me in the right direction here?

Here is my code so far:

```<code>Private Sub Workbook_SheetActivate(ByVal Sh As Object)
  Sheets(1).Range("A11").EntireRow.Insert
  Sheets(1).Range("D11").Formula = Sheets(2).Range("C10")
End Sub
</code>```

Body:
I am trying to write some code that will insert a new line on Worksheet 1 whenever a new worksheet is copied. I would also like the code to make cells on the new line reference certain cells from the newly copied sheet.

The problem I have is that my code is inserting 3 lines instead of 1 and the cell D11 only shows gets the text copied from Sheet2 instead of being equal.

Hope that all makes sense. Can anyone point me in the right direction here?

Here is my code so far:

Private Sub Workbook_SheetActivate(ByVal Sh As Object)
  Sheets(1).Range("A11").EntireRow.Insert
  Sheets(1).Range("D11").Formula = Sheets(2).Range("C10")
End Sub


问:
How to delay an action (download) in until d3.js has finished re-rendering based on a change in state?
I am using a simple library to download/capture my d3 svg output as other image formats. For the most part, works great, he issue is, sometimes my image will need to redraw a change just before being downloaded, and this sometimes causes it to interrupt the rendering and capture some strange transitional state of the image. For example, I update the image to a new resolution, and it is interrupted, and stuck like this, not completing the redraw and also downloads as shown.

Is there a way using d3/react to delay any further actions until the image has finished re-drawing? The only success I had so far was adding an arbitrary delay before the download step starts, but this is not reliable when it comes to different speed connections/processing power etc. so would much prefer a different approach.

Any help will be appreciated!


问:
localStorage.getItem is not working on nextjs, using redux and material ui
i am trying to save user settings, [dark mode/ light mode] on local storage using redux on nextjs
I can save the data on the local storage but i can't pull the data into the initialSatte. here is my code

```<code>import { createSlice } from "@reduxjs/toolkit";
import Cookies from "js-cookie";

const getFromLocalStorage = (key: string) => {
  if (!key || typeof window === "undefined") {
    return "";
  }
  try {
    // @ts-ignore
    return JSON.parse(localStorage.getItem(key)) || {};
  } catch (error) {
    return {};
  }
};

export const uiSettings = createSlice({
  name: "uiSettings",
  initialState: {
    theme: getFromLocalStorage("uiSettings")?.theme || "dark",
  },
  reducers: {
    themeSwitch: (state, action) => {
      state.theme = action.payload;
      window.localStorage.setItem(
        "uiSettings",
        JSON.stringify({
          theme: action.payload,
        })
      );
    },
  },
  extraReducers: (builder) => {},
});

export const uiSettingsReducer = uiSettings.reducer;
export const { themeSwitch } = uiSettings.actions;
</code>```

i tried alot of ways to solve it but it didn't work.

Body:
i am trying to save user settings, [dark mode/ light mode] on local storage using redux on nextjs
I can save the data on the local storage but i can't pull the data into the initialSatte. here is my code

import { createSlice } from "@reduxjs/toolkit";
import Cookies from "js-cookie";

const getFromLocalStorage = (key: string) => {
  if (!key || typeof window === "undefined") {
    return "";
  }
  try {
    // @ts-ignore
    return JSON.parse(localStorage.getItem(key)) || {};
  } catch (error) {
    return {};
  }
};

export const uiSettings = createSlice({
  name: "uiSettings",
  initialState: {
    theme: getFromLocalStorage("uiSettings")?.theme || "dark",
  },
  reducers: {
    themeSwitch: (state, action) => {
      state.theme = action.payload;
      window.localStorage.setItem(
        "uiSettings",
        JSON.stringify({
          theme: action.payload,
        })
      );
    },
  },
  extraReducers: (builder) => {},
});

export const uiSettingsReducer = uiSettings.reducer;
export const { themeSwitch } = uiSettings.actions;

i tried alot of ways to solve it but it didn't work.


问:
Gutenberg - default parameter in JSON
When I try to access a value that has not been edited by the user I get an error as the parameter does not exist unless edited in the Gutenberg editor. I would like the parameter to be saved even if it's the default. Is that possible. As a workaround I declare the default value both in Javascript and in Php like below which is not ideal. Hope someone can help!

$formLink = isset($block['attrs']['link']) ? $block['attrs']['link'] : 'Default value';
```

Title: Gutenberg - default parameter in JSON


问:
Embedded PDF from base64 string is empty
I have a JPEG picture, exported from a PhotoShop PSD, not to big but ~2MB

When I want this picture as a background image with this CSS:

```<code>body{
    background-color: green;
    background-image: url("url");
    background-size: 100%;
    background-repeat: no-repeat;
    background-position: top center;
}
</code>```

and then embed it in my website with

```<code><object width="100%" height="100%" data="data:application/pdf;base64,'myBase64string'" type="application/pdf">'
    <embed src="data:application/pdf;base64,'myBase64string'" type="application/pdf" />
</object>
</code>```

the resulting object is empty, no errors in the console.
Although when I fill it in in https://base64.guru/converter/decode/pdf I get a valid PDF containing what I expect.

Unfortunately the customer won't let me share the actual picture, but when I downgrade the quality to 80% using PhotoShop, the size drops to ~1MB and it does work.

Anybody got any insights?

Body:
I have a JPEG picture, exported from a PhotoShop PSD, not to big but ~2MB

When I want this picture as a background image with this CSS:

body{
    background-color: green;
    background-image: url("url");
    background-size: 100%;
    background-repeat: no-repeat;
    background-position: top center;
}

and then embed it in my website with

<object width="100%" height="100%" data="data:application/pdf;base64,'myBase64string'" type="application/pdf">'
    <embed src="data:application/pdf;base64,'myBase64string'" type="application/pdf" />
</object>

the resulting object is empty, no errors in the console.
Although when I fill it in in https://base64.guru/converter/decode/pdf I get a valid PDF containing what I expect.

Unfortunately the customer won't let me share the actual picture, but when I downgrade the quality to 80% using PhotoShop, the size drops to ~1MB and it does work.

Anybody got any insights?


问:
python-docx(verion 0.8.11) Inline Picture
Am using windows 10 and python-docx(verion 0.8.11). How do I add_picture and implement Textwrap format = "square"?
2) Can we insert floating Picture?

Tried this...

```<code>    from docx import Document
    document = Document()
    # Add a picture to the document
    picture = document.add_picture('picture1.png')
    # Set the text wrap type to 'square'

    picture.text_wrap = True

    # Save the document
    document.save('document06Jan.docx')
</code>```

No Errors but, picture wrapFormat is still InLine with Text

Body:
Am using windows 10 and python-docx(verion 0.8.11). How do I add_picture and implement Textwrap format = "square"?
2) Can we insert floating Picture?

Tried this...

    from docx import Document
    document = Document()
    # Add a picture to the document
    picture = document.add_picture('picture1.png')
    # Set the text wrap type to 'square'

    picture.text_wrap = True

    # Save the document
    document.save('document06Jan.docx')

No Errors but, picture wrapFormat is still InLine with Text


问:
How to download SSL certificate from a LDAP Server using java ? and establish SSL connection using LDAPS?
I am trying to write a program for connecting LDAP server using java code..
Connection Type - SSL

I am getting SSLHandshakeException which says I will have to use 'server certificate' to establish ssl connection -
javax.naming.CommunicationException: :636 [Root exception is javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target]

Could anyone please suggest how to download SSL certificate from the server using java code and then use that certificate while connecting to LDAP ?

Here are the solutions i have tried, but i did not work -
How to read a Certificate attribute (caCertificate) from LDAP server (Java)?

How to make a call, via Java, with ssl and certificate to an ldap (AD)?

NOTE - I cannot override functionality of certificate verification/validation using custom socket factory


问:
hi! I encountered a problem while using models from keras , but I got the errors
```<code>from keras import models
my_mnist_model = models.load_model(modelpath)

error:
No module named 'keras.utils.generic_utils'
</code>```

I've tried installing keras==2.2.4
but it still didn't work

Body:
from keras import models
my_mnist_model = models.load_model(modelpath)

error:
No module named 'keras.utils.generic_utils'

I've tried installing keras==2.2.4
but it still didn't work


问:
Django Templates - Add Selection boxes for Search Results
Not sure how to begin programming a change to my results template/screen...

I have a search that users can use, it returns results from two related models with pagination.  This works fine.

Users wondered if I could add a selection box for each returned entry.

If they selected 1 or more entries - then they could then push an export button, and all selected entries would be saved into a file with all fields listed in csv format.

The more I think about it I think I would need a completely different results template without pagination, just because I need to pass the query set to something to print this out, but only want the ones that were selected...

Anyone done anything like this?

Not really sure if any will have an answer but figured I would put it out there.

Thanks.


问:
Github Actions not accessing download from Newspaper3k
I've been trying to use Github Actions to run a python script. Everything seems to run fine, except a specific function that uses the Newspaper3k package. The article appears to download fine (article.html works ok), but Article.parse() does not work. This works fine on my local server, but not in Github. Is this related to being able to access file locations, that are different on Github? It's a private repository, in case that makes a difference.

My yaml script is as follows:

```<code>build:
  runs-on: ubuntu-latest

  steps:
    - name: checkout repo content
      uses: actions/checkout@v3 # checkout the repository content to github runner.
    - name: setup python
      uses: actions/setup-python@v4
      with:
        python-version: '3.10' #install the python needed
        cache: 'pip'

    - name: install python packages
      run: |
        if [ -f requirements.txt ]; then pip install -r requirements.txt; fi

    - name: execute py script # run file
      env:
        WORDPRESS_USER: ${{ secrets.WORDPRESS_USER }}
        WORDPRESS_PASSWORD: ${{ secrets.WORDPRESS_PASSWORD }}
      run: |
        python main.py
</code>```

The function in question is provided below:

```<code>def generate_article_summary(supplied_links):
    summary_list = ""
    for news_article in supplied_links[:5]:
        try:
            url = news_article
            article = Article(url, config=config)
            article.download()
            article.parse()
            article.nlp()
        except:
            summary_list = summary_list + "\n"
            pass

        summary_list = summary_list + "\n" + article.summary

    return summary_list
</code>```

Any help would be much appreciated.

Body:
I've been trying to use Github Actions to run a python script. Everything seems to run fine, except a specific function that uses the Newspaper3k package. The article appears to download fine (article.html works ok), but Article.parse() does not work. This works fine on my local server, but not in Github. Is this related to being able to access file locations, that are different on Github? It's a private repository, in case that makes a difference.

My yaml script is as follows:

build:
  runs-on: ubuntu-latest

  steps:
    - name: checkout repo content
      uses: actions/checkout@v3 # checkout the repository content to github runner.
    - name: setup python
      uses: actions/setup-python@v4
      with:
        python-version: '3.10' #install the python needed
        cache: 'pip'

    - name: install python packages
      run: |
        if [ -f requirements.txt ]; then pip install -r requirements.txt; fi

    - name: execute py script # run file
      env:
        WORDPRESS_USER: ${{ secrets.WORDPRESS_USER }}
        WORDPRESS_PASSWORD: ${{ secrets.WORDPRESS_PASSWORD }}
      run: |
        python main.py

The function in question is provided below:

def generate_article_summary(supplied_links):
    summary_list = ""
    for news_article in supplied_links[:5]:
        try:
            url = news_article
            article = Article(url, config=config)
            article.download()
            article.parse()
            article.nlp()
        except:
            summary_list = summary_list + "\n"
            pass

        summary_list = summary_list + "\n" + article.summary

    return summary_list

Any help would be much appreciated.


问:
GitHub Actions - Trigger workflow from projects (v2)
I'm trying to create a GitHub action/workflow that will close an Issue when it's State field is set to "Done", but looking at the documentation it appears there are only triggers for the classic projects. Is this correct, are there no triggers for projects v2, or am I missing something?


问:
FFMPEG Kit issue in Banuba Video SDK : "FFmpegKit failed to start on brand"
I am trying to integrate Banuba Video Editor sdk in flutter.

The issue i am facing is as below

Banuba sdk works with native code for Android in Flutter

So Banuba requires FFMPEG dependency to define in Native Android

And I am already using 'ffmpeg_kit_flutter' plugin for flutter.

So both the FFMPEG kits are conflicted and some of the functions are not found. due to that I am receiving the below error.

When the app is launched I am receiving this Crash as mentioned

```<code>**java.lang.Error: FFmpegKit failed to start on brand: google, model: sdk_gphone_x86, device: generic_x86_arm, api level: 30, abis: x86 armeabi-v7a armeabi, 32bit abis: x86 armeabi-v7a armeabi, 64bit abis: .
**  at com.arthenica.ffmpegkit.NativeLoader.loadLibrary(NativeLoader.java:50)
    at com.arthenica.ffmpegkit.NativeLoader.loadFFmpegKit(NativeLoader.java:189)
    at com.arthenica.ffmpegkit.FFmpegKitConfig.<clinit>(FFmpegKitConfig.java:145)
    at com.arthenica.ffmpegkit.FFmpegKitConfig.enableFFmpegSessionCompleteCallback(FFmpegKitConfig.java:864)
    at com.arthenica.ffmpegkit.flutter.FFmpegKitFlutterPlugin.registerGlobalCallbacks(FFmpegKitFlutterPlugin.java:168)
    at com.arthenica.ffmpegkit.flutter.FFmpegKitFlutterPlugin.init(FFmpegKitFlutterPlugin.java:652)
    at com.arthenica.ffmpegkit.flutter.FFmpegKitFlutterPlugin.onAttachedToActivity(FFmpegKitFlutterPlugin.java:198)
    at io.flutter.embedding.engine.FlutterEngineConnectionRegistry.attachToActivityInternal(FlutterEngineConnectionRegistry.java:351)
    at io.flutter.embedding.engine.FlutterEngineConnectionRegistry.attachToActivity(FlutterEngineConnectionRegistry.java:324)
    at io.flutter.embedding.android.FlutterActivityAndFragmentDelegate.onAttach(FlutterActivityAndFragmentDelegate.java:194)
    at io.flutter.embedding.android.FlutterActivity.onCreate(FlutterActivity.java:498)
    at com.sound.it.MainActivity.onCreate(MainActivity.kt:43)
    at android.app.Activity.performCreate(Activity.java:8000)
    at android.app.Activity.performCreate(Activity.java:7984)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:223)
    at android.app.ActivityThread.main(ActivityThread.java:7656)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
**Caused by: java.lang.UnsatisfiedLinkError: dlopen failed: cannot locate symbol "av_log_default_callback" referenced by "/data/app/~~umF3qlB9U53L4peU9nKYuQ==/com.sound.it-agqiFlNmMe17AHMK5gYIHw==/lib/x86/libffmpegkit.so"...**
    at java.lang.Runtime.loadLibrary0(Runtime.java:1087)
    at java.lang.Runtime.loadLibrary0(Runtime.java:1008)
    at java.lang.System.loadLibrary(System.java:1664)
    at com.arthenica.ffmpegkit.NativeLoader.loadLibrary(NativeLoader.java:48)
</code>```

Looking for the solutions

Body:
I am trying to integrate Banuba Video Editor sdk in flutter.

The issue i am facing is as below

Banuba sdk works with native code for Android in Flutter

So Banuba requires FFMPEG dependency to define in Native Android

And I am already using 'ffmpeg_kit_flutter' plugin for flutter.

So both the FFMPEG kits are conflicted and some of the functions are not found. due to that I am receiving the below error.

When the app is launched I am receiving this Crash as mentioned

**java.lang.Error: FFmpegKit failed to start on brand: google, model: sdk_gphone_x86, device: generic_x86_arm, api level: 30, abis: x86 armeabi-v7a armeabi, 32bit abis: x86 armeabi-v7a armeabi, 64bit abis: .
**  at com.arthenica.ffmpegkit.NativeLoader.loadLibrary(NativeLoader.java:50)
    at com.arthenica.ffmpegkit.NativeLoader.loadFFmpegKit(NativeLoader.java:189)
    at com.arthenica.ffmpegkit.FFmpegKitConfig.<clinit>(FFmpegKitConfig.java:145)
    at com.arthenica.ffmpegkit.FFmpegKitConfig.enableFFmpegSessionCompleteCallback(FFmpegKitConfig.java:864)
    at com.arthenica.ffmpegkit.flutter.FFmpegKitFlutterPlugin.registerGlobalCallbacks(FFmpegKitFlutterPlugin.java:168)
    at com.arthenica.ffmpegkit.flutter.FFmpegKitFlutterPlugin.init(FFmpegKitFlutterPlugin.java:652)
    at com.arthenica.ffmpegkit.flutter.FFmpegKitFlutterPlugin.onAttachedToActivity(FFmpegKitFlutterPlugin.java:198)
    at io.flutter.embedding.engine.FlutterEngineConnectionRegistry.attachToActivityInternal(FlutterEngineConnectionRegistry.java:351)
    at io.flutter.embedding.engine.FlutterEngineConnectionRegistry.attachToActivity(FlutterEngineConnectionRegistry.java:324)
    at io.flutter.embedding.android.FlutterActivityAndFragmentDelegate.onAttach(FlutterActivityAndFragmentDelegate.java:194)
    at io.flutter.embedding.android.FlutterActivity.onCreate(FlutterActivity.java:498)
    at com.sound.it.MainActivity.onCreate(MainActivity.kt:43)
    at android.app.Activity.performCreate(Activity.java:8000)
    at android.app.Activity.performCreate(Activity.java:7984)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:223)
    at android.app.ActivityThread.main(ActivityThread.java:7656)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
**Caused by: java.lang.UnsatisfiedLinkError: dlopen failed: cannot locate symbol "av_log_default_callback" referenced by "/data/app/~~umF3qlB9U53L4peU9nKYuQ==/com.sound.it-agqiFlNmMe17AHMK5gYIHw==/lib/x86/libffmpegkit.so"...**
    at java.lang.Runtime.loadLibrary0(Runtime.java:1087)
    at java.lang.Runtime.loadLibrary0(Runtime.java:1008)
    at java.lang.System.loadLibrary(System.java:1664)
    at com.arthenica.ffmpegkit.NativeLoader.loadLibrary(NativeLoader.java:48)

Looking for the solutions


问:
MediaWiki Extension with Webpack and TypeScript fails to load mw (mw.util)
I'm not a frontend developer. Until a few days ago I haven't tried npm, webpack and typescript. But now (somehow) everything builds (you can find the code here).

But when I upload the extension (before the migration to TS it worked) and try to use it in MediaWiki I get an annoying message (annoying because I've spent a couple of weeks fighting in this world)

```<code>app.ts:378 Uncaught ReferenceError: mw is not defined
    at MyClass.loadWikiArticlesAjax (app.ts:378:18)
    at MyClass.initialize (app.ts:22:17)
    at new MyClass (app.ts:18:17)
    at ./includes/js/app.ts (app.ts:445:1)
    at __webpack_require__ (bootstrap:19:1)
    at startup:4:1
    at startup:4:1
loadWikiArticlesAjax @ app.ts:378
initialize @ app.ts:22
MyClass @ app.ts:18
./includes/js/app.ts @ app.ts:445
__webpack_require__ @ bootstrap:19
(anonymous) @ startup:4
(anonymous) @ startup:4
app.ts:391 Uncaught TypeError: Cannot read properties of undefined (reading 'query')
    at Object.success (app.ts:391:47)
    at fire (jquery.js?7e265:3500:31)
    at Object.fireWith [as resolveWith] (jquery.js?7e265:3630:7)
    at done (jquery.js?7e265:9822:14)
    at XMLHttpRequest.<anonymous> (jquery.js?7e265:10083:9)
</code>```

Any hint?

Body:
I'm not a frontend developer. Until a few days ago I haven't tried npm, webpack and typescript. But now (somehow) everything builds (you can find the code here).

But when I upload the extension (before the migration to TS it worked) and try to use it in MediaWiki I get an annoying message (annoying because I've spent a couple of weeks fighting in this world)

app.ts:378 Uncaught ReferenceError: mw is not defined
    at MyClass.loadWikiArticlesAjax (app.ts:378:18)
    at MyClass.initialize (app.ts:22:17)
    at new MyClass (app.ts:18:17)
    at ./includes/js/app.ts (app.ts:445:1)
    at __webpack_require__ (bootstrap:19:1)
    at startup:4:1
    at startup:4:1
loadWikiArticlesAjax @ app.ts:378
initialize @ app.ts:22
MyClass @ app.ts:18
./includes/js/app.ts @ app.ts:445
__webpack_require__ @ bootstrap:19
(anonymous) @ startup:4
(anonymous) @ startup:4
app.ts:391 Uncaught TypeError: Cannot read properties of undefined (reading 'query')
    at Object.success (app.ts:391:47)
    at fire (jquery.js?7e265:3500:31)
    at Object.fireWith [as resolveWith] (jquery.js?7e265:3630:7)
    at done (jquery.js?7e265:9822:14)
    at XMLHttpRequest.<anonymous> (jquery.js?7e265:10083:9)

Any hint?


问:
How to measure the time of individual function calls in a large R project?
I have a somewhat large R project and would like to identify performance bottlenecks by measuring how long the individual functions take to execute. I know of tools like microbenchmark for checking individual lines of code.

Is it possible to have a tool track the execution times of the individually called functions and then report the results at the end?

In practice, the idea would be that I have a script.R

```<code>plot(cars)
plot(cars + 1)
</code>```

and after running the "benchmark tool" over it, get a result that looks something like this:

```<code>plot(cars): 0.1s
plot(cars + 1): 0.1s
</code>```

How would I go about achieving something like this?

Body:
I have a somewhat large R project and would like to identify performance bottlenecks by measuring how long the individual functions take to execute. I know of tools like microbenchmark for checking individual lines of code.

Is it possible to have a tool track the execution times of the individually called functions and then report the results at the end?

In practice, the idea would be that I have a script.R

plot(cars)
plot(cars + 1)

and after running the "benchmark tool" over it, get a result that looks something like this:

plot(cars): 0.1s
plot(cars + 1): 0.1s

How would I go about achieving something like this?


问:
Displaying all images from a WordPress post (including media library)
With this function, I'm getting only those images that I uploaded using the upload button in the post section.
But, if I add an image from the media library it's now showing. I want to show all the images from the post.

How can I show all my images from the post?

```<code>$attachments = get_children(array('post_parent' => $post->ID,
              'post_status' => 'inherit',
              'post_type' => 'attachment',
              'post_mime_type' => 'image',
              'order' => 'ASC',
              'orderby' => 'menu_order ID'));

              foreach($attachments as $att_id => $attachment) {
                $full_img_url = wp_get_attachment_url($attachment->ID);
                echo wp_get_attachment_image($attachment->ID, 'full');

              }
</code>```

Body:
With this function, I'm getting only those images that I uploaded using the upload button in the post section.
But, if I add an image from the media library it's now showing. I want to show all the images from the post.

How can I show all my images from the post?

$attachments = get_children(array('post_parent' => $post->ID,
              'post_status' => 'inherit',
              'post_type' => 'attachment',
              'post_mime_type' => 'image',
              'order' => 'ASC',
              'orderby' => 'menu_order ID'));

              foreach($attachments as $att_id => $attachment) {
                $full_img_url = wp_get_attachment_url($attachment->ID);
                echo wp_get_attachment_image($attachment->ID, 'full');

              }


问:
Initialising Firebase in Flutter while using an entry point
I'm working on two native iOS and Android applications, to which I'm integrating some new Flutter pages.

I'm trying to integrate Firebase Analytics and Crashlytics in both the native apps and the Flutter module, but trying to do this, I'm only getting a black screen, with no real useful output in Logcat (so far I only tried to do it on Android).

Here is how I'm opening the initial Flutter page in Android:

```<code>@pragma('vm:entry-point')
void home() {
  WidgetsFlutterBinding.ensureInitialized();

  runApp(const ProviderScope(child: MyApp(screenName: ScreenNames.home)));
}
</code>```

Which works as expected. But after I'm adding the Firebase initialisation code:

```<code>@pragma('vm:entry-point')
void home() async {
  WidgetsFlutterBinding.ensureInitialized();

  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );

  FlutterError.onError = (errorDetails) {
    FirebaseCrashlytics.instance.recordFlutterFatalError(errorDetails);
  };
  // Pass all uncaught asynchronous errors that aren't handled by the Flutter framework to Crashlytics
  PlatformDispatcher.instance.onError = (error, stack) {
    FirebaseCrashlytics.instance.recordError(error, stack, fatal: true);
    return true;
  };

  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
  ]);

  runApp(const ProviderScope(child: MyApp(screenName: ScreenNames.home)));
}
</code>```

The Flutter screen no longer opens, and I can only see a black screen. The output from Logcat suggests that the Firebase initialisation is succesfull:

```<code>2023-01-06 16:39:01.814 12265-12265 FirebaseApp             mypackagename            I  Device unlocked: initializing all Firebase APIs for app [DEFAULT]
2023-01-06 16:39:01.824 12265-12265 FirebaseCrashlytics     mypackagename          I  Initializing Firebase Crashlytics 18.3.2 for mypackagename
2023-01-06 16:39:01.828 12265-12265 FirebaseCrashlytics     mypackagename            D  Crashlytics automatic data collection ENABLED by API.
2023-01-06 16:39:01.829 12265-12265 FirebaseCrashlytics     mypackagename            D  AnalyticsConnector now available.
2023-01-06 16:39:01.830 12265-12265 FirebaseCrashlytics     mypackagename            D  Registered Firebase Analytics listener.
2023-01-06 16:39:01.832 12265-12265 FirebaseCrashlytics     mypackagename            D  Mapping file ID is: someMappingFileId
2023-01-06 16:39:01.834 12265-12265 FirebaseCrashlytics     mypackagename          D  Checking for cached settings...
2023-01-06 16:39:01.836 12265-12265 FirebaseCrashlytics     mypackagename            D  Loaded cached settings: {"settings_version":3,"cache_duration":86400,"features":{"collect_logged_exceptions":true,"collect_reports":true,"collect_analytics":false,"prompt_enabled":false,"push_enabled":false,"firebase_crashlytics_enabled":false,"collect_anrs":true,"collect_metric_kit":false,"collect_build_ids":false},"app":{"status":"activated","update_required":false,"report_upload_variant":2,"native_report_upload_variant":2},"fabric":{"org_id":"someorgId","bundle_id":"mypackagename"},"on_demand_upload_rate_per_minute":10,"on_demand_backoff_base":1.2,"on_demand_backoff_step_duration_seconds":60,"app_quality":{"sessions_enabled":true,"sampling_rate":1,"session_timeout_seconds":1800},"expires_at":1673102189561}
2023-01-06 16:39:01.837 12265-12336 FirebaseCrashlytics     mypackagename            D  Crashlytics automatic data collection ENABLED by API.
2023-01-06 16:39:01.838 12265-12338 SchedPolicy             mypackagename            E  Failed to find cgroup for tid 12265
2023-01-06 16:39:01.840 12265-12336 FirebaseCrashlytics     mypackagename            D  Requesting settings from https://firebase-settings.crashlytics.com/spi/v2/platforms/android/gmp/1:1091409783486:android:e60a7b7bc280c8c9cc4cef/settings
2023-01-06 16:39:01.842 12265-12333 DynamiteModule          mypackagename            I  Considering local module com.google.android.gms.measurement.dynamite:86 and remote module com.google.android.gms.measurement.dynamite:87
2023-01-06 16:39:01.842 12265-12333 DynamiteModule          mypackagename          I  Selected remote version of com.google.android.gms.measurement.dynamite, version >= 87
2023-01-06 16:39:01.842 12265-12333 DynamiteModule          mypackagename            V  Dynamite loader version >= 2, using loadModule2NoCrashUtils
2023-01-06 16:39:01.848 12265-12346 SchedPolicy             mypackagename            E  Failed to find cgroup for tid 12265
2023-01-06 16:39:01.852 12265-12333 System                  mypackagename            W  ClassLoader referenced unknown path:
2023-01-06 16:39:01.852 12265-12265 FirebaseCrashlytics     mypackagename          D  Successfully configured exception handler.
2023-01-06 16:39:01.852 12265-12333 nativeloader            mypackagename          D  Configuring classloader-namespace for other apk . target_sdk_version=33, uses_libraries=, library_path=/data/app/~~U0hLgIs67w1iQqA7O5Bnyw==/com.google.android.gms-ckaJ-vfKjVAfHgdmjaEzYw==/lib/arm64:/data/app/~~U0hLgIs67w1iQqA7O5Bnyw==/com.google.android.gms-ckaJ-vfKjVAfHgdmjaEzYw==/base.apk!/lib/arm64-v8a, permitted_path=/data:/mnt/expand:/data/user/0/com.google.android.gms
2023-01-06 16:39:01.852 12265-12265 FirebaseInitProvider    mypackagename            I  FirebaseApp initialization successful
2023-01-06 16:39:01.853 12265-12335 FirebaseCrashlytics     mypackagename            D  Opening a new session with ID someID
</code>```

Any help is appreciated on how I can further debug and solve this issue.

Body:
I'm working on two native iOS and Android applications, to which I'm integrating some new Flutter pages.

I'm trying to integrate Firebase Analytics and Crashlytics in both the native apps and the Flutter module, but trying to do this, I'm only getting a black screen, with no real useful output in Logcat (so far I only tried to do it on Android).

Here is how I'm opening the initial Flutter page in Android:

@pragma('vm:entry-point')
void home() {
  WidgetsFlutterBinding.ensureInitialized();

  runApp(const ProviderScope(child: MyApp(screenName: ScreenNames.home)));
}

Which works as expected. But after I'm adding the Firebase initialisation code:

@pragma('vm:entry-point')
void home() async {
  WidgetsFlutterBinding.ensureInitialized();

  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );

  FlutterError.onError = (errorDetails) {
    FirebaseCrashlytics.instance.recordFlutterFatalError(errorDetails);
  };
  // Pass all uncaught asynchronous errors that aren't handled by the Flutter framework to Crashlytics
  PlatformDispatcher.instance.onError = (error, stack) {
    FirebaseCrashlytics.instance.recordError(error, stack, fatal: true);
    return true;
  };

  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
  ]);

  runApp(const ProviderScope(child: MyApp(screenName: ScreenNames.home)));
}

The Flutter screen no longer opens, and I can only see a black screen. The output from Logcat suggests that the Firebase initialisation is succesfull:

2023-01-06 16:39:01.814 12265-12265 FirebaseApp             mypackagename            I  Device unlocked: initializing all Firebase APIs for app [DEFAULT]
2023-01-06 16:39:01.824 12265-12265 FirebaseCrashlytics     mypackagename          I  Initializing Firebase Crashlytics 18.3.2 for mypackagename
2023-01-06 16:39:01.828 12265-12265 FirebaseCrashlytics     mypackagename            D  Crashlytics automatic data collection ENABLED by API.
2023-01-06 16:39:01.829 12265-12265 FirebaseCrashlytics     mypackagename            D  AnalyticsConnector now available.
2023-01-06 16:39:01.830 12265-12265 FirebaseCrashlytics     mypackagename            D  Registered Firebase Analytics listener.
2023-01-06 16:39:01.832 12265-12265 FirebaseCrashlytics     mypackagename            D  Mapping file ID is: someMappingFileId
2023-01-06 16:39:01.834 12265-12265 FirebaseCrashlytics     mypackagename          D  Checking for cached settings...
2023-01-06 16:39:01.836 12265-12265 FirebaseCrashlytics     mypackagename            D  Loaded cached settings: {"settings_version":3,"cache_duration":86400,"features":{"collect_logged_exceptions":true,"collect_reports":true,"collect_analytics":false,"prompt_enabled":false,"push_enabled":false,"firebase_crashlytics_enabled":false,"collect_anrs":true,"collect_metric_kit":false,"collect_build_ids":false},"app":{"status":"activated","update_required":false,"report_upload_variant":2,"native_report_upload_variant":2},"fabric":{"org_id":"someorgId","bundle_id":"mypackagename"},"on_demand_upload_rate_per_minute":10,"on_demand_backoff_base":1.2,"on_demand_backoff_step_duration_seconds":60,"app_quality":{"sessions_enabled":true,"sampling_rate":1,"session_timeout_seconds":1800},"expires_at":1673102189561}
2023-01-06 16:39:01.837 12265-12336 FirebaseCrashlytics     mypackagename            D  Crashlytics automatic data collection ENABLED by API.
2023-01-06 16:39:01.838 12265-12338 SchedPolicy             mypackagename            E  Failed to find cgroup for tid 12265
2023-01-06 16:39:01.840 12265-12336 FirebaseCrashlytics     mypackagename            D  Requesting settings from https://firebase-settings.crashlytics.com/spi/v2/platforms/android/gmp/1:1091409783486:android:e60a7b7bc280c8c9cc4cef/settings
2023-01-06 16:39:01.842 12265-12333 DynamiteModule          mypackagename            I  Considering local module com.google.android.gms.measurement.dynamite:86 and remote module com.google.android.gms.measurement.dynamite:87
2023-01-06 16:39:01.842 12265-12333 DynamiteModule          mypackagename          I  Selected remote version of com.google.android.gms.measurement.dynamite, version >= 87
2023-01-06 16:39:01.842 12265-12333 DynamiteModule          mypackagename            V  Dynamite loader version >= 2, using loadModule2NoCrashUtils
2023-01-06 16:39:01.848 12265-12346 SchedPolicy             mypackagename            E  Failed to find cgroup for tid 12265
2023-01-06 16:39:01.852 12265-12333 System                  mypackagename            W  ClassLoader referenced unknown path:
2023-01-06 16:39:01.852 12265-12265 FirebaseCrashlytics     mypackagename          D  Successfully configured exception handler.
2023-01-06 16:39:01.852 12265-12333 nativeloader            mypackagename          D  Configuring classloader-namespace for other apk . target_sdk_version=33, uses_libraries=, library_path=/data/app/~~U0hLgIs67w1iQqA7O5Bnyw==/com.google.android.gms-ckaJ-vfKjVAfHgdmjaEzYw==/lib/arm64:/data/app/~~U0hLgIs67w1iQqA7O5Bnyw==/com.google.android.gms-ckaJ-vfKjVAfHgdmjaEzYw==/base.apk!/lib/arm64-v8a, permitted_path=/data:/mnt/expand:/data/user/0/com.google.android.gms
2023-01-06 16:39:01.852 12265-12265 FirebaseInitProvider    mypackagename            I  FirebaseApp initialization successful
2023-01-06 16:39:01.853 12265-12335 FirebaseCrashlytics     mypackagename            D  Opening a new session with ID someID

Any help is appreciated on how I can further debug and solve this issue.


问:
Accuracy Estimation under Keras and Pytorch
```<code>Pytorch:
trainset = torchvision.datasets.MNIST(
    root='./data', train=True, download=True, transform=transforms.Compose([
    transforms.ToTensor()]))
trainloader = torch.utils.data.DataLoader(
    trainset, batch_size=128, shuffle=True, num_workers=1)

testset = torchvision.datasets.MNIST(
    root='./data', train=False, download=True, transform=transforms.Compose([
    transforms.ToTensor()]))
testloader = torch.utils.data.DataLoader(
    testset, batch_size=100, shuffle=False, num_workers=1)

Keras:
(_, _), (x_test, y_test) = mnist.load_data()
x_test = x_test.astype('float32') / 255.0
</code>```

I trained a LeNet5 model with MNIST under Pytorch and used pytorch2keras to tranfer it to a Keras model. But I found that the accuracy of the Keras model is only about 10% while the Pytorch model's accuracy is close to 100%. VGG16 models trained with CIFAR10 didn't show a similar situation. For consistency, no additional processing is performed on the data in either framework.

The accuracy of the model should not change even after the conversion of the format. Is it because the datasets loaded in two frameworks are completely different?

Body:
Pytorch:
trainset = torchvision.datasets.MNIST(
    root='./data', train=True, download=True, transform=transforms.Compose([
    transforms.ToTensor()]))
trainloader = torch.utils.data.DataLoader(
    trainset, batch_size=128, shuffle=True, num_workers=1)

testset = torchvision.datasets.MNIST(
    root='./data', train=False, download=True, transform=transforms.Compose([
    transforms.ToTensor()]))
testloader = torch.utils.data.DataLoader(
    testset, batch_size=100, shuffle=False, num_workers=1)

Keras:
(_, _), (x_test, y_test) = mnist.load_data()
x_test = x_test.astype('float32') / 255.0

I trained a LeNet5 model with MNIST under Pytorch and used pytorch2keras to tranfer it to a Keras model. But I found that the accuracy of the Keras model is only about 10% while the Pytorch model's accuracy is close to 100%. VGG16 models trained with CIFAR10 didn't show a similar situation. For consistency, no additional processing is performed on the data in either framework.

The accuracy of the model should not change even after the conversion of the format. Is it because the datasets loaded in two frameworks are completely different?


问:
How to preserve colours when colour metadata is "unknown"
I often need to scale up many files with unknown color metadata (probably because FFmpeg itself was dropping that metadata until very recently):

```<code>$ ffprobe -v error -show_streams "input.mp4" | grep color

color_range=tv
color_space=unknown
color_transfer=unknown
color_primaries=unknown
</code>```

No matter what I do to try and preserve the colours in these files, nothing works to prevent the colours from shifting, usually coming out darker than the input.

I've already tried:

Setting all four color metadata options (-colorspace, -color_trc, -color_primaries, -color_range) to all of their possible values for PAL, NTSC and HD inputs (bt470bg, smpte170m and bt709 respectively)

Automatically converting the colorspace as part of the scale by adding in_color_matrix=auto:out_color_matrix=<COLORSPACE>, where  is either bt470, smpte170m or bt709

Explicitly converting the colorspace as part of the scale by adding in_color_matrix=<COLORSPACE>:out_color_matrix=bt709, where  is either bt470, smpte170m or bt709

After all of this, I'm still left none the wiser as to how the hell colour works in FFmpeg and what I'm meant to be doing just to get my colour to look as it does in the original input.

Here is the (simplified) FFmpeg command that I'm running as part of a larger script, most of which is probably irrelevant to the issue but which I've included in case it isn't:

```<code>ffmpeg -y -hide_banner \
-i "input.webm" -i "outro.mp4" -loop 1 -i "watermark.png" \
-movflags +faststart+write_colr \
-filter_complex \
"color=black:16x16:d=780[base];
[0:v]scale=1922:'max(1080,ih)':flags=lanczos:in_color_matrix=auto:out_color_matrix=bt709[v0];
[1:v]scale=1922:'max(1080,ih)':flags=lanczos,fade=in:st=0:d=2:alpha=1[v1];
[2:v]lut=a=val*0.7,fade=in:st=15:d=3:alpha=1,fade=out:st=775:d=3:alpha=1[v2];
[base][v0]scale2ref[base][v0];
[base][v0]overlay[tmp];
[tmp][v1]overlay,setsar=1[tmp2];
[v2][tmp2]scale2ref=w=oh*mdar:h=ih*0.07[watermark_scaled][video]
[video][watermark_scaled]overlay=80:50:shortest=1:format=rgb[outv];
[0:a]afade=out:st=778:d=2[0a];
[0a][1:a]concat=n=2:v=0:a=1[outa]" \
-map "[outv]" -map "[outa]" -c:v libx264 -crf 15 -c:a libopus \
-pix_fmt yuv420p -colorspace bt709 -color_trc bt709 -color_primaries bt709 -color_range tv "output.mp4"
</code>```

Body:
I often need to scale up many files with unknown color metadata (probably because FFmpeg itself was dropping that metadata until very recently):

$ ffprobe -v error -show_streams "input.mp4" | grep color

color_range=tv
color_space=unknown
color_transfer=unknown
color_primaries=unknown

No matter what I do to try and preserve the colours in these files, nothing works to prevent the colours from shifting, usually coming out darker than the input.

I've already tried:

Setting all four color metadata options (-colorspace, -color_trc, -color_primaries, -color_range) to all of their possible values for PAL, NTSC and HD inputs (bt470bg, smpte170m and bt709 respectively)

Automatically converting the colorspace as part of the scale by adding in_color_matrix=auto:out_color_matrix=<COLORSPACE>, where  is either bt470, smpte170m or bt709

Explicitly converting the colorspace as part of the scale by adding in_color_matrix=<COLORSPACE>:out_color_matrix=bt709, where  is either bt470, smpte170m or bt709

After all of this, I'm still left none the wiser as to how the hell colour works in FFmpeg and what I'm meant to be doing just to get my colour to look as it does in the original input.

Here is the (simplified) FFmpeg command that I'm running as part of a larger script, most of which is probably irrelevant to the issue but which I've included in case it isn't:

ffmpeg -y -hide_banner \
-i "input.webm" -i "outro.mp4" -loop 1 -i "watermark.png" \
-movflags +faststart+write_colr \
-filter_complex \
"color=black:16x16:d=780[base];
[0:v]scale=1922:'max(1080,ih)':flags=lanczos:in_color_matrix=auto:out_color_matrix=bt709[v0];
[1:v]scale=1922:'max(1080,ih)':flags=lanczos,fade=in:st=0:d=2:alpha=1[v1];
[2:v]lut=a=val*0.7,fade=in:st=15:d=3:alpha=1,fade=out:st=775:d=3:alpha=1[v2];
[base][v0]scale2ref[base][v0];
[base][v0]overlay[tmp];
[tmp][v1]overlay,setsar=1[tmp2];
[v2][tmp2]scale2ref=w=oh*mdar:h=ih*0.07[watermark_scaled][video]
[video][watermark_scaled]overlay=80:50:shortest=1:format=rgb[outv];
[0:a]afade=out:st=778:d=2[0a];
[0a][1:a]concat=n=2:v=0:a=1[outa]" \
-map "[outv]" -map "[outa]" -c:v libx264 -crf 15 -c:a libopus \
-pix_fmt yuv420p -colorspace bt709 -color_trc bt709 -color_primaries bt709 -color_range tv "output.mp4"


问:
How can I manually add a legend to my line plot? (error message "scale for 'y' is already present")
I have produced a line plot to compare results under three conditions. These were all under separate dataframes. Here is the code for the plot:

```<code>ggplot()+
  geom_line(data = linedatac1data, aes(x=time, y=c1y), size=1.2, colour=rgb(0.6,0.9,0.9))+
  geom_line(data = linedatac2data, aes(x=time, y=c2y), size=1.2, colour=rgb(0.9,0,0.9))+
  geom_line(data = linedataidata, aes(x=time, y=Iy), size=1.2, colour=rgb(0,0.5,0.5))+
  xlim(-350,1500)+
  ylim(-2.6e-23,3.1e-23)+
  theme_light()+
  scale_y_continuous(breaks = c(-2e-23, -1e-23, 0, 1e-23, 2e-23, 3e-23))+
  ggtitle("Changes in Mean Theta Power Across Conditions")+
  xlab("Time (ms)")+
  ylab("Mean theta power ( mV^2)")
</code>```

I would like to manually produce a key matching the names of each condition (C1, C2, and I) are matched to their corresponding RGBs.

I attempted to do this by adding the following code:

```<code>  scale_colour_manual("",
                      breaks = c("Single control", "Double control", "Inhibition"),
                      values = c("Single control"=rgb(0.6,0.9,0.9), "Double control"=rgb(0.9,0,0.9), "Inhibition"=rgb(0,0.5,0.5)))
</code>```

However, I am met with an error message which reads:
"Scale for 'y' is already present. Adding another scale for 'y', which will replace the existing   scale."

Any help would be much appreciated. Thanks!

Body:
I have produced a line plot to compare results under three conditions. These were all under separate dataframes. Here is the code for the plot:

ggplot()+
  geom_line(data = linedatac1data, aes(x=time, y=c1y), size=1.2, colour=rgb(0.6,0.9,0.9))+
  geom_line(data = linedatac2data, aes(x=time, y=c2y), size=1.2, colour=rgb(0.9,0,0.9))+
  geom_line(data = linedataidata, aes(x=time, y=Iy), size=1.2, colour=rgb(0,0.5,0.5))+
  xlim(-350,1500)+
  ylim(-2.6e-23,3.1e-23)+
  theme_light()+
  scale_y_continuous(breaks = c(-2e-23, -1e-23, 0, 1e-23, 2e-23, 3e-23))+
  ggtitle("Changes in Mean Theta Power Across Conditions")+
  xlab("Time (ms)")+
  ylab("Mean theta power ( mV^2)")

I would like to manually produce a key matching the names of each condition (C1, C2, and I) are matched to their corresponding RGBs.

I attempted to do this by adding the following code:

  scale_colour_manual("",
                      breaks = c("Single control", "Double control", "Inhibition"),
                      values = c("Single control"=rgb(0.6,0.9,0.9), "Double control"=rgb(0.9,0,0.9), "Inhibition"=rgb(0,0.5,0.5)))

However, I am met with an error message which reads:
"Scale for 'y' is already present. Adding another scale for 'y', which will replace the existing   scale."

Any help would be much appreciated. Thanks!