问:
Data not being appended to list in my python code
I am having trouble rendering the topsport data in my HTML template. From what i can see the topsport_h2h_today data is not being collected and added to games = []

I cant figure out what is wrong. any ideas? The entain, unibet and bluebet work fine.

```<code># Initialize empty list of games
            games = []

            # Iterate through NBA games for today's games
            for game in entain_h2h_today:

                # Initialize empty dictionary for current game
                game_dict = {}

                # Add home and away teams to game_dict
                game_dict['home_team'] = game['home_team']
                game_dict['away_team'] = game['away_team']

                # Add Entain odds to game_dict
                game_dict['entain'] = {
                    'home_odds': game['home_team_h2h_odds'],
                    'away_odds': game['away_team_h2h_odds'],
                }

                # Iterate through Topsport games for today's games
                for topsport_game in topsport_h2h_today:
                    if topsport_game['home_team'] == game['home_team'] and topsport_game['away_team'] == game[
                        'away_team']:
                        game_dict['topsport'] = {
                            'home_odds': topsport_game['home_team_h2h_odds'],
                            'away_odds': topsport_game['away_team_h2h_odds'],
                        }

                # Iterate through Unibet games for today's games
                for unibet_game in unibet_h2h_today:
                    if unibet_game['home_team'] == game['home_team'] and unibet_game['away_team'] == game['away_team']:
                        game_dict['unibet'] = {
                            'home_odds': unibet_game['home_team_h2h_odds'],
                            'away_odds': unibet_game['away_team_h2h_odds'],
                        }
                        print('unibet game:', unibet_game)

                # Iterate through Bluebet games for today's games
                for bluebet_game in bluebet_h2h_today:
                    if bluebet_game['home_team'] == game['home_team'] and bluebet_game['away_team'] == game[
                        'away_team']:
                        game_dict['bluebet'] = {
                            'home_odds': bluebet_game['home_team_h2h_odds'],
                            'away_odds': bluebet_game['away_team_h2h_odds'],
                        }
                        print('bluebet game:', bluebet_game)

                # Append the game_dict to the games list
                games.append(game_dict)

            # Define the context dictionary
            context = {
                    'games': games,
                }
</code>```

this is the data in topsport_h2h_today when i print it out

[{'home_team': 'New York Knicks', 'away_team': 'Charlotte Hornets', 'home_team_h2h_odds': '1.6300', 'away_team_h2h_odds': '2.3100', 'name': 'TopSport'}, {'home_team': 'Toronto Raptors', 'away_team': 'Orlando Magic', 'home_team_h2h_odds': '1.2600', 'away_team_h2h_odds': '3.9500', 'name': 'TopSport'}, {'home_team': 'Los Angeles Lakers', 'away_team': 'Philadelphia 76ers', 'home_team_h2h_odds': '2.5500', 'away_team_h2h_odds': '1.5300', 'name': 'TopSport'}, {'home_team': 'Atlanta Hawks', 'away_team': 'Brooklyn Nets', 'home_team_h2h_odds': '3.4000', 'away_team_h2h_odds': '1.3200', 'name': 'TopSport'}, {'home_team': 'Milwaukee Bucks', 'away_team': 'Dallas Mavericks', 'home_team_h2h_odds': '1.9000', 'away_team_h2h_odds': '1.9200', 'name': 'TopSport'}, {'home_team': 'Detroit Pistons', 'away_team': 'Memphis Grizzlies', 'home_team_h2h_odds': '5.4000', 'away_team_h2h_odds': '1.1600', 'name': 'TopSport'}, {'home_team': 'Phoenix Suns', 'away_team': 'New Orleans Pelicans', 'home_team_h2h_odds': '1.8600', 'away_team_h2h_odds': '1.9800', 'name': 'TopSport'}, {'home_team': 'Washington Wizards', 'away_team': 'Indiana Pacers', 'home_team_h2h_odds': '2.3200', 'away_team_h2h_odds': '1.5900', 'name': 'TopSport'}, {'home_team': 'Sacramento Kings', 'away_team': 'Cleveland Cavaliers', 'home_team_h2h_odds': '2.2600', 'away_team_h2h_odds': '1.6200', 'name': 'TopSport'}, {'home_team': 'Minnesota Timberwolves', 'away_team': 'Utah Jazz', 'home_team_h2h_odds': '1.9200', 'away_team_h2h_odds': '1.9000', 'name': 'TopSport'}, {'home_team': 'San Antonio Spurs', 'away_team': 'Miami Heat', 'home_team_h2h_odds': '0.0000', 'away_team_h2h_odds': '0.0000', 'name': 'TopSport'}, {'home_team': 'Los Angeles Clippers', 'away_team': 'Washington Wizards', 'home_team_h2h_odds': '0.0000', 'away_team_h2h_odds': '0.0000', 'name': 'TopSport'}, {'home_team': 'Dallas Mavericks', 'away_team': 'Chicago Bulls', 'home_team_h2h_odds': '0.0000', 'away_team_h2h_odds': '0.0000', 'name': 'TopSport'}, {'home_team': 'Boston Celtics', 'away_team': 'Golden State Warriors', 'home_team_h2h_odds': '0.0000', 'away_team_h2h_odds': '0.0000', 'name': 'TopSport'}, {'home_team': 'Minnesota Timberwolves', 'away_team': 'Portland Trail Blazers', 'home_team_h2h_odds': '0.0000', 'away_team_h2h_odds': '0.0000', 'name': 'TopSport'}]

this is the full views.py (its a django project)

```<code>def basketball_nba(request):
    ############################################################################
    # ENTAIN (NEDS/LADBROKES)
    ############################################################################

    # Query firestore database for NBA games
    nba_events = db.collection('entain_au').document('basketball_nba').collection('event_odds').stream()
    event_info_entain = [doc.to_dict() for doc in nba_events]

    # print(event_info)

    # List of NBA games today win odds data
    entain_h2h_today = []
    entain_h2h_tomorrow = []

    # Iterate through NBA games json for today's games to get win odds data
    for event in event_info_entain:
        try:
            if event['event_odds']['Event']['Markets']:
                for market in event['event_odds']['Event']['Markets']:
                    if market['Name'] == 'Head To Head':
                        home_team = None
                        home_team_h2h_odds = None
                        away_team = None
                        away_team_h2h_odds = None
                        for team in market['Selections']:
                            if team['Role'] == 'Home':
                                home_team = team['Name']
                                home_team_h2h_odds = team['WinPrice']
                            elif team['Role'] == 'Away':
                                away_team = team['Name']
                                away_team_h2h_odds = team['WinPrice']

                        entain_h2h_today.append({
                            'home_team': home_team,
                            'home_team_h2h_odds': home_team_h2h_odds,
                            'away_team': away_team,
                            'away_team_h2h_odds': away_team_h2h_odds,
                            'name': 'Entain'
                        })
        except KeyError:
            pass
            # print('Error parsing:', event)  # Log error

            # Iterate through NBA games json for tomorrow's games to get win odds data
            for event in event_info_entain:
                try:
                    if event['event_odds']['Event']['Markets']:
                        for market in event['event_odds']['Event']['Markets']:
                            if market['Name'] == 'Head To Head':
                                home_team = None
                                home_team_h2h_odds = None
                                away_team = None
                                away_team_h2h_odds = None
                                for team in market['Selections']:
                                    if team['Role'] == 'Home':
                                        home_team = team['Name']
                                        home_team_h2h_odds = team['WinPrice']
                                    elif team['Role'] == 'Away':
                                        away_team = team['Name']
                                        away_team_h2h_odds = team['WinPrice']

                                entain_h2h_tomorrow.append(
                                    {'home_team': home_team,
                                     'home_team_h2h_odds': home_team_h2h_odds,
                                     'away_team': away_team,
                                     'away_team_h2h_odds': away_team_h2h_odds,
                                     'name': 'Entain'})
                except KeyError:
                    pass
                    # print(entain_h2h_today)
                    # print('Error parsing:', event)  # Log error

            ############################################################################
            # UNIBET
            ############################################################################

            # Query firestore database for NBA games
            nba_events_unibet = db.collection('unibet_au').document('basketball_nba').collection('event_odds').stream()

            # Convert the nba_events generator object to a list
            nba_events_list = list(nba_events_unibet)

            # Print the number of events in the nba_events_list variable
            print(len(nba_events_list))

            # Parse event data
            event_info = [doc.to_dict() for doc in nba_events_list]
            # print(event_info)

            # List of NBA games today win odds data
            unibet_h2h_today = []
            # List of NBA games tomorrow win odds data
            unibet_h2h_tomorrow = []

            # Set the market type you are looking for
            market_type = "Head To Head - Including Overtime"

            # Use a list comprehension to extract the data for each event
            h2h_data = [{"game": event['event_odds']['events'][0]['name'],
                         "market_type": bet_offer['criterion']['label'],
                         "home_team": bet_offer['outcomes'][0]['englishLabel'],
                         "home_team_h2h_odds": bet_offer['outcomes'][0]['odds'],
                         "away_team": bet_offer['outcomes'][1]['englishLabel'],
                         "away_team_h2h_odds": bet_offer['outcomes'][1]['odds'],
                         }
                        for event in event_info
                        for bet_offer in event['event_odds']['betOffers']
                        if bet_offer['criterion']['label'] == market_type]

            # Filter & print the h2h_data list
            for win_odds in h2h_data:
                game = win_odds['game']
                home_team = win_odds['home_team']
                home_team_h2h_odds = win_odds['home_team_h2h_odds'] / 1000
                away_team = win_odds['away_team']
                away_team_h2h_odds = win_odds['away_team_h2h_odds'] / 1000
                unibet_h2h_today.append({
                    "game": game,
                    "home_team": home_team,
                    "home_team_h2h_odds": home_team_h2h_odds,
                    "away_team": away_team,
                    "away_team_h2h_odds": away_team_h2h_odds,
                    "name": "Unibet"
                })
                # print('today:', unibet_h2h_today)
                unibet_h2h_tomorrow.append({
                    "game": game,
                    "home_team": home_team,
                    "home_team_h2h_odds": home_team_h2h_odds,
                    "away_team": away_team,
                    "away_team_h2h_odds": away_team_h2h_odds,
                    "name": "Unibet"
                })
                # print('tomorrow:', unibet_h2h_tomorrow)

            ############################################################################
            # BLUEBET
            ############################################################################

            # Query firestore database for NBA games
            nba_events_bluebet = db.collection('bluebet_au').document('basketball_nba').collection(
                'event_odds').stream()

            # Convert the nba_events generator object to a list
            nba_events_list = list(nba_events_bluebet)

            # Print the number of events in the nba_events_list variable
            print(len(nba_events_list))

            bluebet_h2h_today = []

            # Iterate through the list of events and add the data to the dictionary
            for event in nba_events_list:
                bluebet_h2h_today.append({
                    "home_team": event.to_dict()["home_team"],
                    "home_team_h2h_odds": event.to_dict()["home_team_h2h_odds"],
                    "away_team": event.to_dict()["away_team"],
                    "away_team_h2h_odds": event.to_dict()["away_team_h2h_odds"],
                    "event_title": event.to_dict()["event_title"],
                    "start_time": event.to_dict()["start_time"],
                })

            ############################################################################
            # TOPSPORT
            ############################################################################

            # Query firestore database for NBA games
            nba_events_topsport = db.collection('topsport_au').document('basketball_nba').collection('event_odds').stream()

            # Convert the nba_events generator object to a list
            nba_events_list = list(nba_events_topsport)

            # Print the number of events in the nba_events_list variable
            print(len(nba_events_list))

            topsport_h2h_today = []

            # Iterate over the nba_events_list and access the data for each event
            for event in nba_events_list:
                event_data = event.to_dict()

                topsport_h2h_today.append({
                    'home_team': event_data['event_odds']['home_team'],
                    'away_team': event_data['event_odds']['away_team'],
                    'home_team_h2h_odds': event_data['event_odds']['home_team_h2h_odds'],
                    'away_team_h2h_odds': event_data['event_odds']['away_team_h2h_odds'],
                    'name': 'TopSport',
                })

            # Print the topsport_h2h_today list
            print(topsport_h2h_today)

            # Initialize empty list of games
            games = []

            # Iterate through NBA games for today's games
            for game in entain_h2h_today:

                # Initialize empty dictionary for current game
                game_dict = {}

                # Add home and away teams to game_dict
                game_dict['home_team'] = game['home_team']
                game_dict['away_team'] = game['away_team']

                # Add Entain odds to game_dict
                game_dict['entain'] = {
                    'home_odds': game['home_team_h2h_odds'],
                    'away_odds': game['away_team_h2h_odds'],
                }

                # Iterate through Topsport games for today's games
                for topsport_game in topsport_h2h_today:
                    if topsport_game['home_team'] == game['home_team'] and topsport_game['away_team'] == game[
                        'away_team']:
                        game_dict['topsport'] = {
                            'home_odds': topsport_game['home_team_h2h_odds'],
                            'away_odds': topsport_game['away_team_h2h_odds'],
                        }

                # Iterate through Unibet games for today's games
                for unibet_game in unibet_h2h_today:
                    if unibet_game['home_team'] == game['home_team'] and unibet_game['away_team'] == game['away_team']:
                        game_dict['unibet'] = {
                            'home_odds': unibet_game['home_team_h2h_odds'],
                            'away_odds': unibet_game['away_team_h2h_odds'],
                        }
                        # print('unibet game:', unibet_game)

                # Iterate through Bluebet games for today's games
                for bluebet_game in bluebet_h2h_today:
                    if bluebet_game['home_team'] == game['home_team'] and bluebet_game['away_team'] == game[
                        'away_team']:
                        game_dict['bluebet'] = {
                            'home_odds': bluebet_game['home_team_h2h_odds'],
                            'away_odds': bluebet_game['away_team_h2h_odds'],
                        }
                        # print('bluebet game:', bluebet_game)

                # Append the game_dict to the games list
                games.append(game_dict)

            # Define the context dictionary
            context = {
                    'games': games,
                }

            # print(games)

            # Pass the context dictionary to the `render` function
            return render(request, 'nba.html', context=context)
</code>```

Body:
I am having trouble rendering the topsport data in my HTML template. From what i can see the topsport_h2h_today data is not being collected and added to games = []

I cant figure out what is wrong. any ideas? The entain, unibet and bluebet work fine.

# Initialize empty list of games
            games = []

            # Iterate through NBA games for today's games
            for game in entain_h2h_today:

                # Initialize empty dictionary for current game
                game_dict = {}

                # Add home and away teams to game_dict
                game_dict['home_team'] = game['home_team']
                game_dict['away_team'] = game['away_team']

                # Add Entain odds to game_dict
                game_dict['entain'] = {
                    'home_odds': game['home_team_h2h_odds'],
                    'away_odds': game['away_team_h2h_odds'],
                }

                # Iterate through Topsport games for today's games
                for topsport_game in topsport_h2h_today:
                    if topsport_game['home_team'] == game['home_team'] and topsport_game['away_team'] == game[
                        'away_team']:
                        game_dict['topsport'] = {
                            'home_odds': topsport_game['home_team_h2h_odds'],
                            'away_odds': topsport_game['away_team_h2h_odds'],
                        }

                # Iterate through Unibet games for today's games
                for unibet_game in unibet_h2h_today:
                    if unibet_game['home_team'] == game['home_team'] and unibet_game['away_team'] == game['away_team']:
                        game_dict['unibet'] = {
                            'home_odds': unibet_game['home_team_h2h_odds'],
                            'away_odds': unibet_game['away_team_h2h_odds'],
                        }
                        print('unibet game:', unibet_game)

                # Iterate through Bluebet games for today's games
                for bluebet_game in bluebet_h2h_today:
                    if bluebet_game['home_team'] == game['home_team'] and bluebet_game['away_team'] == game[
                        'away_team']:
                        game_dict['bluebet'] = {
                            'home_odds': bluebet_game['home_team_h2h_odds'],
                            'away_odds': bluebet_game['away_team_h2h_odds'],
                        }
                        print('bluebet game:', bluebet_game)

                # Append the game_dict to the games list
                games.append(game_dict)

            # Define the context dictionary
            context = {
                    'games': games,
                }

this is the data in topsport_h2h_today when i print it out

[{'home_team': 'New York Knicks', 'away_team': 'Charlotte Hornets', 'home_team_h2h_odds': '1.6300', 'away_team_h2h_odds': '2.3100', 'name': 'TopSport'}, {'home_team': 'Toronto Raptors', 'away_team': 'Orlando Magic', 'home_team_h2h_odds': '1.2600', 'away_team_h2h_odds': '3.9500', 'name': 'TopSport'}, {'home_team': 'Los Angeles Lakers', 'away_team': 'Philadelphia 76ers', 'home_team_h2h_odds': '2.5500', 'away_team_h2h_odds': '1.5300', 'name': 'TopSport'}, {'home_team': 'Atlanta Hawks', 'away_team': 'Brooklyn Nets', 'home_team_h2h_odds': '3.4000', 'away_team_h2h_odds': '1.3200', 'name': 'TopSport'}, {'home_team': 'Milwaukee Bucks', 'away_team': 'Dallas Mavericks', 'home_team_h2h_odds': '1.9000', 'away_team_h2h_odds': '1.9200', 'name': 'TopSport'}, {'home_team': 'Detroit Pistons', 'away_team': 'Memphis Grizzlies', 'home_team_h2h_odds': '5.4000', 'away_team_h2h_odds': '1.1600', 'name': 'TopSport'}, {'home_team': 'Phoenix Suns', 'away_team': 'New Orleans Pelicans', 'home_team_h2h_odds': '1.8600', 'away_team_h2h_odds': '1.9800', 'name': 'TopSport'}, {'home_team': 'Washington Wizards', 'away_team': 'Indiana Pacers', 'home_team_h2h_odds': '2.3200', 'away_team_h2h_odds': '1.5900', 'name': 'TopSport'}, {'home_team': 'Sacramento Kings', 'away_team': 'Cleveland Cavaliers', 'home_team_h2h_odds': '2.2600', 'away_team_h2h_odds': '1.6200', 'name': 'TopSport'}, {'home_team': 'Minnesota Timberwolves', 'away_team': 'Utah Jazz', 'home_team_h2h_odds': '1.9200', 'away_team_h2h_odds': '1.9000', 'name': 'TopSport'}, {'home_team': 'San Antonio Spurs', 'away_team': 'Miami Heat', 'home_team_h2h_odds': '0.0000', 'away_team_h2h_odds': '0.0000', 'name': 'TopSport'}, {'home_team': 'Los Angeles Clippers', 'away_team': 'Washington Wizards', 'home_team_h2h_odds': '0.0000', 'away_team_h2h_odds': '0.0000', 'name': 'TopSport'}, {'home_team': 'Dallas Mavericks', 'away_team': 'Chicago Bulls', 'home_team_h2h_odds': '0.0000', 'away_team_h2h_odds': '0.0000', 'name': 'TopSport'}, {'home_team': 'Boston Celtics', 'away_team': 'Golden State Warriors', 'home_team_h2h_odds': '0.0000', 'away_team_h2h_odds': '0.0000', 'name': 'TopSport'}, {'home_team': 'Minnesota Timberwolves', 'away_team': 'Portland Trail Blazers', 'home_team_h2h_odds': '0.0000', 'away_team_h2h_odds': '0.0000', 'name': 'TopSport'}]

this is the full views.py (its a django project)

def basketball_nba(request):
    ############################################################################
    # ENTAIN (NEDS/LADBROKES)
    ############################################################################

    # Query firestore database for NBA games
    nba_events = db.collection('entain_au').document('basketball_nba').collection('event_odds').stream()
    event_info_entain = [doc.to_dict() for doc in nba_events]

    # print(event_info)

    # List of NBA games today win odds data
    entain_h2h_today = []
    entain_h2h_tomorrow = []

    # Iterate through NBA games json for today's games to get win odds data
    for event in event_info_entain:
        try:
            if event['event_odds']['Event']['Markets']:
                for market in event['event_odds']['Event']['Markets']:
                    if market['Name'] == 'Head To Head':
                        home_team = None
                        home_team_h2h_odds = None
                        away_team = None
                        away_team_h2h_odds = None
                        for team in market['Selections']:
                            if team['Role'] == 'Home':
                                home_team = team['Name']
                                home_team_h2h_odds = team['WinPrice']
                            elif team['Role'] == 'Away':
                                away_team = team['Name']
                                away_team_h2h_odds = team['WinPrice']

                        entain_h2h_today.append({
                            'home_team': home_team,
                            'home_team_h2h_odds': home_team_h2h_odds,
                            'away_team': away_team,
                            'away_team_h2h_odds': away_team_h2h_odds,
                            'name': 'Entain'
                        })
        except KeyError:
            pass
            # print('Error parsing:', event)  # Log error

            # Iterate through NBA games json for tomorrow's games to get win odds data
            for event in event_info_entain:
                try:
                    if event['event_odds']['Event']['Markets']:
                        for market in event['event_odds']['Event']['Markets']:
                            if market['Name'] == 'Head To Head':
                                home_team = None
                                home_team_h2h_odds = None
                                away_team = None
                                away_team_h2h_odds = None
                                for team in market['Selections']:
                                    if team['Role'] == 'Home':
                                        home_team = team['Name']
                                        home_team_h2h_odds = team['WinPrice']
                                    elif team['Role'] == 'Away':
                                        away_team = team['Name']
                                        away_team_h2h_odds = team['WinPrice']

                                entain_h2h_tomorrow.append(
                                    {'home_team': home_team,
                                     'home_team_h2h_odds': home_team_h2h_odds,
                                     'away_team': away_team,
                                     'away_team_h2h_odds': away_team_h2h_odds,
                                     'name': 'Entain'})
                except KeyError:
                    pass
                    # print(entain_h2h_today)
                    # print('Error parsing:', event)  # Log error

            ############################################################################
            # UNIBET
            ############################################################################

            # Query firestore database for NBA games
            nba_events_unibet = db.collection('unibet_au').document('basketball_nba').collection('event_odds').stream()

            # Convert the nba_events generator object to a list
            nba_events_list = list(nba_events_unibet)

            # Print the number of events in the nba_events_list variable
            print(len(nba_events_list))

            # Parse event data
            event_info = [doc.to_dict() for doc in nba_events_list]
            # print(event_info)

            # List of NBA games today win odds data
            unibet_h2h_today = []
            # List of NBA games tomorrow win odds data
            unibet_h2h_tomorrow = []

            # Set the market type you are looking for
            market_type = "Head To Head - Including Overtime"

            # Use a list comprehension to extract the data for each event
            h2h_data = [{"game": event['event_odds']['events'][0]['name'],
                         "market_type": bet_offer['criterion']['label'],
                         "home_team": bet_offer['outcomes'][0]['englishLabel'],
                         "home_team_h2h_odds": bet_offer['outcomes'][0]['odds'],
                         "away_team": bet_offer['outcomes'][1]['englishLabel'],
                         "away_team_h2h_odds": bet_offer['outcomes'][1]['odds'],
                         }
                        for event in event_info
                        for bet_offer in event['event_odds']['betOffers']
                        if bet_offer['criterion']['label'] == market_type]

            # Filter & print the h2h_data list
            for win_odds in h2h_data:
                game = win_odds['game']
                home_team = win_odds['home_team']
                home_team_h2h_odds = win_odds['home_team_h2h_odds'] / 1000
                away_team = win_odds['away_team']
                away_team_h2h_odds = win_odds['away_team_h2h_odds'] / 1000
                unibet_h2h_today.append({
                    "game": game,
                    "home_team": home_team,
                    "home_team_h2h_odds": home_team_h2h_odds,
                    "away_team": away_team,
                    "away_team_h2h_odds": away_team_h2h_odds,
                    "name": "Unibet"
                })
                # print('today:', unibet_h2h_today)
                unibet_h2h_tomorrow.append({
                    "game": game,
                    "home_team": home_team,
                    "home_team_h2h_odds": home_team_h2h_odds,
                    "away_team": away_team,
                    "away_team_h2h_odds": away_team_h2h_odds,
                    "name": "Unibet"
                })
                # print('tomorrow:', unibet_h2h_tomorrow)

            ############################################################################
            # BLUEBET
            ############################################################################

            # Query firestore database for NBA games
            nba_events_bluebet = db.collection('bluebet_au').document('basketball_nba').collection(
                'event_odds').stream()

            # Convert the nba_events generator object to a list
            nba_events_list = list(nba_events_bluebet)

            # Print the number of events in the nba_events_list variable
            print(len(nba_events_list))

            bluebet_h2h_today = []

            # Iterate through the list of events and add the data to the dictionary
            for event in nba_events_list:
                bluebet_h2h_today.append({
                    "home_team": event.to_dict()["home_team"],
                    "home_team_h2h_odds": event.to_dict()["home_team_h2h_odds"],
                    "away_team": event.to_dict()["away_team"],
                    "away_team_h2h_odds": event.to_dict()["away_team_h2h_odds"],
                    "event_title": event.to_dict()["event_title"],
                    "start_time": event.to_dict()["start_time"],
                })

            ############################################################################
            # TOPSPORT
            ############################################################################

            # Query firestore database for NBA games
            nba_events_topsport = db.collection('topsport_au').document('basketball_nba').collection('event_odds').stream()

            # Convert the nba_events generator object to a list
            nba_events_list = list(nba_events_topsport)

            # Print the number of events in the nba_events_list variable
            print(len(nba_events_list))

            topsport_h2h_today = []

            # Iterate over the nba_events_list and access the data for each event
            for event in nba_events_list:
                event_data = event.to_dict()

                topsport_h2h_today.append({
                    'home_team': event_data['event_odds']['home_team'],
                    'away_team': event_data['event_odds']['away_team'],
                    'home_team_h2h_odds': event_data['event_odds']['home_team_h2h_odds'],
                    'away_team_h2h_odds': event_data['event_odds']['away_team_h2h_odds'],
                    'name': 'TopSport',
                })

            # Print the topsport_h2h_today list
            print(topsport_h2h_today)

            # Initialize empty list of games
            games = []

            # Iterate through NBA games for today's games
            for game in entain_h2h_today:

                # Initialize empty dictionary for current game
                game_dict = {}

                # Add home and away teams to game_dict
                game_dict['home_team'] = game['home_team']
                game_dict['away_team'] = game['away_team']

                # Add Entain odds to game_dict
                game_dict['entain'] = {
                    'home_odds': game['home_team_h2h_odds'],
                    'away_odds': game['away_team_h2h_odds'],
                }

                # Iterate through Topsport games for today's games
                for topsport_game in topsport_h2h_today:
                    if topsport_game['home_team'] == game['home_team'] and topsport_game['away_team'] == game[
                        'away_team']:
                        game_dict['topsport'] = {
                            'home_odds': topsport_game['home_team_h2h_odds'],
                            'away_odds': topsport_game['away_team_h2h_odds'],
                        }

                # Iterate through Unibet games for today's games
                for unibet_game in unibet_h2h_today:
                    if unibet_game['home_team'] == game['home_team'] and unibet_game['away_team'] == game['away_team']:
                        game_dict['unibet'] = {
                            'home_odds': unibet_game['home_team_h2h_odds'],
                            'away_odds': unibet_game['away_team_h2h_odds'],
                        }
                        # print('unibet game:', unibet_game)

                # Iterate through Bluebet games for today's games
                for bluebet_game in bluebet_h2h_today:
                    if bluebet_game['home_team'] == game['home_team'] and bluebet_game['away_team'] == game[
                        'away_team']:
                        game_dict['bluebet'] = {
                            'home_odds': bluebet_game['home_team_h2h_odds'],
                            'away_odds': bluebet_game['away_team_h2h_odds'],
                        }
                        # print('bluebet game:', bluebet_game)

                # Append the game_dict to the games list
                games.append(game_dict)

            # Define the context dictionary
            context = {
                    'games': games,
                }

            # print(games)

            # Pass the context dictionary to the `render` function
            return render(request, 'nba.html', context=context)


来源: stackexchange

问:
Rename a base64 encoded image on download
I have the following code to display an image - without going into details about why I am not just using the image name.

```<code><?php
$data = base64_encode(file_get_contents('example.png'));
$info = getimagesize('example.png');
$image = sprintf('data:%s;base64,%s', $info['mime'], $data);
?>

<img src="<?php echo $image; ?>" download='final-image.png' />
</code>```

It works as expected displaying the image.

However when someone right-clicks the image, in FireFox it wants to save it as (scriptname).png and Chrome wants to save it as download.png.

I can't use header() as headers are already being sent.

Is there any way to force a filename that works across browsers?

ContentLicense: CC BY-SA 4.0

Body:
I have the following code to display an image - without going into details about why I am not just using the image name.

<?php
$data = base64_encode(file_get_contents('example.png'));
$info = getimagesize('example.png');
$image = sprintf('data:%s;base64,%s', $info['mime'], $data);
?>

<img src="<?php echo $image; ?>" download='final-image.png' />

It works as expected displaying the image.

However when someone right-clicks the image, in FireFox it wants to save it as (scriptname).png and Chrome wants to save it as download.png.

I can't use header() as headers are already being sent.

Is there any way to force a filename that works across browsers?


问:
XAMPP Error - InnoDB: Operating system error number 3 in a file operation
Generally server works fine without any issues. But recently after opening my XAMPP and got this on morning

```<code>2022-12-10  9:55:29 0 [Note] InnoDB: Mutexes and rw_locks use Windows interlocked functions
2022-12-10  9:55:29 0 [Note] InnoDB: Uses event mutexes
2022-12-10  9:55:29 0 [Note] InnoDB: Compressed tables use zlib 1.2.11 2022-12-10  9:55:29 0 [Note] InnoDB: Number of pools: 1
2022-12-10  9:55:29 0 [Note] InnoDB: Using SSE2 crc32 instructions
2022-12-10  9:55:29 0 [Note] InnoDB: Initializing buffer pool, total size = 16M, instances = 1, chunk size = 16M
2022-12-10  9:55:29 0 [Note] InnoDB: Completed initialization of buffer pool
2022-12-10  9:55:29 0 [ERROR] InnoDB: Operating system error number 3 in a file operation.
2022-12-10  9:55:29 0 [ERROR] InnoDB: The error means the system cannot find the path specified.
2022-12-10  9:55:29 0 [ERROR] InnoDB: If you are installing InnoDB, remember that you must create directories yourself, InnoDB does not create them.
2022-12-10  9:55:29 0 [ERROR] InnoDB: Cannot open datafile for read-only: '.\nbc_db2022@002e1\ja_usermeta.ibd' OS error: 203
2022-12-10  9:55:29 0 [ERROR] InnoDB: Operating system error number 203 in a file operation.
2022-12-10  9:55:29 0 [Note] InnoDB: Some operating system error numbers are described at https://mariadb.com/kb/en/library/operating-system-error-codes/
2022-12-10  9:55:29 0 [ERROR] InnoDB: Could not find a valid tablespace file for ``nbc_db2022.1`.`ja_usermeta\`\`.
Please refer to https://mariadb.com/kb/en/innodb-data-dictionary-troubleshooting/ for how to resolve the issue.
2022-12-10  9:55:29 0 [Warning\] InnoDB: Ignoring tablespace for `nbc_db2022.1`.`ja_usermeta` because it could not be opened.
2022-12-10  9:55:29 0 \[ERROR\] InnoDB: Operating system error number 3 in a file operation.
2022-12-10  9:55:29 0 \[ERROR\] InnoDB: The error means the system cannot find the path specified.
2022-12-10  9:55:29 0 \[ERROR\] InnoDB: If you are installing InnoDB, remember that you must create directories yourself, InnoDB does not create them.
2022-12-10  9:55:29 0 \[ERROR\] InnoDB: Cannot open datafile for read-only: '.\\nbc_db2022@002e1\\wp_commentmeta.ibd' OS error: 203
2022-12-10  9:55:29 0 \[ERROR\] InnoDB: Operating system error number 203 in a file operation.
2022-12-10  9:55:29 0 \[Note\] InnoDB: Some operating system error numbers are described at https://mariadb.com/kb/en/library/operating-system-error-codes/%60
\
</code>```

I have already tried switching ports in PHPMyAdmin and MySQL also deleted aria_log files. I'm using Windows 11 Version 22H2

Body:
Generally server works fine without any issues. But recently after opening my XAMPP and got this on morning

2022-12-10  9:55:29 0 [Note] InnoDB: Mutexes and rw_locks use Windows interlocked functions
2022-12-10  9:55:29 0 [Note] InnoDB: Uses event mutexes
2022-12-10  9:55:29 0 [Note] InnoDB: Compressed tables use zlib 1.2.11 2022-12-10  9:55:29 0 [Note] InnoDB: Number of pools: 1
2022-12-10  9:55:29 0 [Note] InnoDB: Using SSE2 crc32 instructions
2022-12-10  9:55:29 0 [Note] InnoDB: Initializing buffer pool, total size = 16M, instances = 1, chunk size = 16M
2022-12-10  9:55:29 0 [Note] InnoDB: Completed initialization of buffer pool
2022-12-10  9:55:29 0 [ERROR] InnoDB: Operating system error number 3 in a file operation.
2022-12-10  9:55:29 0 [ERROR] InnoDB: The error means the system cannot find the path specified.
2022-12-10  9:55:29 0 [ERROR] InnoDB: If you are installing InnoDB, remember that you must create directories yourself, InnoDB does not create them.
2022-12-10  9:55:29 0 [ERROR] InnoDB: Cannot open datafile for read-only: '.\nbc_db2022@002e1\ja_usermeta.ibd' OS error: 203
2022-12-10  9:55:29 0 [ERROR] InnoDB: Operating system error number 203 in a file operation.
2022-12-10  9:55:29 0 [Note] InnoDB: Some operating system error numbers are described at https://mariadb.com/kb/en/library/operating-system-error-codes/
2022-12-10  9:55:29 0 [ERROR] InnoDB: Could not find a valid tablespace file for ``nbc_db2022.1`.`ja_usermeta\`\`.
Please refer to https://mariadb.com/kb/en/innodb-data-dictionary-troubleshooting/ for how to resolve the issue.
2022-12-10  9:55:29 0 [Warning\] InnoDB: Ignoring tablespace for `nbc_db2022.1`.`ja_usermeta` because it could not be opened.
2022-12-10  9:55:29 0 \[ERROR\] InnoDB: Operating system error number 3 in a file operation.
2022-12-10  9:55:29 0 \[ERROR\] InnoDB: The error means the system cannot find the path specified.
2022-12-10  9:55:29 0 \[ERROR\] InnoDB: If you are installing InnoDB, remember that you must create directories yourself, InnoDB does not create them.
2022-12-10  9:55:29 0 \[ERROR\] InnoDB: Cannot open datafile for read-only: '.\\nbc_db2022@002e1\\wp_commentmeta.ibd' OS error: 203
2022-12-10  9:55:29 0 \[ERROR\] InnoDB: Operating system error number 203 in a file operation.
2022-12-10  9:55:29 0 \[Note\] InnoDB: Some operating system error numbers are described at https://mariadb.com/kb/en/library/operating-system-error-codes/%60
\

I have already tried switching ports in PHPMyAdmin and MySQL also deleted aria_log files. I'm using Windows 11 Version 22H2


问:
Is there a way to display data from an extension?
I am having some trouble displaying data that is inside an extension.

Here is some sample data:

```<code>[Evvie.Course(AddressInfo: Evvie.AddressInfo(Title: "Commerce Street", Latitude: 30.78049027304715, Longitude: -91.37567342143757)),
Evvie.Course(AddressInfo: Evvie.AddressInfo(Title: "Electrify America (Target)", Latitude: 45.80593414847252, Longitude: -108.47424014718615)),
Evvie.Course(AddressInfo: Evvie.AddressInfo(Title: "29247 ", Latitude: 34.439655548047284, Longitude: -80.19629017657348))]
</code>```

And here are how my things are defined:

```<code>struct Course: Hashable, Codable {
    let AddressInfo: AddressInfo
}

struct AddressInfo: Hashable, Codable {
    let Title: String
    let Latitude: Double
    let Longitude: Double

}
extension AddressInfo {
    var coordinate:CLLocationCoordinate2D? {
        let coordinate = CLLocationCoordinate2D(latitude: Latitude, longitude: Longitude)
        return coordinate
    }
}
</code>```

My question is how would I be able to access something such as the coordinate? Something like this:

```<code>ForEach(viewModel.courses, id: \.self) { course in
    Text(course.AddressInfo.coordinate)
}
</code>```

Body:
I am having some trouble displaying data that is inside an extension.

Here is some sample data:

[Evvie.Course(AddressInfo: Evvie.AddressInfo(Title: "Commerce Street", Latitude: 30.78049027304715, Longitude: -91.37567342143757)),
Evvie.Course(AddressInfo: Evvie.AddressInfo(Title: "Electrify America (Target)", Latitude: 45.80593414847252, Longitude: -108.47424014718615)),
Evvie.Course(AddressInfo: Evvie.AddressInfo(Title: "29247 ", Latitude: 34.439655548047284, Longitude: -80.19629017657348))]

And here are how my things are defined:

struct Course: Hashable, Codable {
    let AddressInfo: AddressInfo
}

struct AddressInfo: Hashable, Codable {
    let Title: String
    let Latitude: Double
    let Longitude: Double

}
extension AddressInfo {
    var coordinate:CLLocationCoordinate2D? {
        let coordinate = CLLocationCoordinate2D(latitude: Latitude, longitude: Longitude)
        return coordinate
    }
}

My question is how would I be able to access something such as the coordinate? Something like this:

ForEach(viewModel.courses, id: \.self) { course in
    Text(course.AddressInfo.coordinate)
}


问:
How to make moving object bump a standing still object (Launching my object with mouse towards random position still object.)
Working on a program that consists of emoji's and you get an emoji that you can shoot, bit like Angry Birds but way more basic. At the moment the stand still emoji is falling down (increasing vertical velocity by gravity until it hits the ground). However this only happens when the main object has a greater horizontal position than the stand still object.

```<code>/**
 * Represents an emoji that can move on a window.
 */

public class Emoji{

    // Constants for all Emoji: size, position of the ground
    public static final double SIZE = 40;  // width/length of the emoji images
    public static final double GROUND = EmojiLauncher.GROUND;
    public static final double GRAVITY = 0.25;  // how much to reduce the speed each step.

    // Fields to store state of the Emoji:
    private double horizontalPos;
    private double aboveGround;
    private double hSpeed;
    private double vSpeed;
    private String name;

    // Constructor
    /**
     * Constructor
     */
     public Emoji(double x, double h, String name){
        this.horizontalPos = x;
        this.aboveGround = h;
        this.name = "emojis/"+name;

    }
    // Methods
    /**
     * Draws an emoji
     */
    public void draw(){
        UI.drawImage(this.name, this.horizontalPos, this.aboveGround , SIZE, SIZE);

    }

    /**
     * Makes emoji take a step
     */
    public void step(){

        if(this.vSpeed != 0 || this.hSpeed != 0){
            this.horizontalPos += hSpeed;
            this.aboveGround += vSpeed;
            this.vSpeed += GRAVITY;
              if(this.aboveGround > GROUND - SIZE){
          vSpeed = 0;
          hSpeed = 0;
          this.aboveGround = GROUND - SIZE;
        }
        }

    }

    /**
     *
     * Returns the height of the emoji above the floor.
     */
    public double getHeight(){
        return this.aboveGround;

    }

    /**
     *
     *
     * Returns the horizontal position
     */
    public double getX(){
        return this.horizontalPos;

    }

    /**
     * Returns the speed of the emoji
     */
    public double getSpeed(){
        return Math.hypot(hSpeed, vSpeed);

    }

    /**
     *
     * Set the horizontal and vertical speed of emoji
     */
    public void launch(double xSpeed, double ySpeed){
        this.hSpeed = xSpeed;
        this.vSpeed = ySpeed;

    }

    /**
     * return true if emoji is touching other emoji
     */
    public boolean touching(Emoji other){
        if(this.horizontalPos >= other.horizontalPos || this.aboveGround >= other.aboveGround){
            return true;
        }
        else {
            return false;
        }

    }

    /**
     * if emojis hit each other, the hit emoji starts moving
     */
    public void bump(Emoji other){
        if((this.hSpeed > 0 || vSpeed > 0) &&
        (this.horizontalPos >= other.horizontalPos && this.aboveGround >= other.aboveGround)){
            other.hSpeed = 1;
        }

    }

    /**
     * Main method
     */
    public static void main(String[] args){
        do {
            Emoji bike = new Emoji(110, 150, "bicycle.png");
            bike.draw();
            Emoji moon = new Emoji(50, 200, "moon.png");
            moon.draw();
            moon.launch(5, 0);
            UI.println("moon launched");
            for (int i=0; i<=100; i++){
                bike.step();
                moon.step();
                UI.clearGraphics();
                UI.drawLine(0, GROUND, 500, GROUND);
                bike.draw();
                moon.draw();

                if(moon.touching(bike)&& moon.getSpeed()>0){
                    moon.bump(bike);
                    UI.println(i+": moon touched and then bumped bike");
                }
                if(moon.getX() > 55 && moon.getX()<65){
                    UI.println(i+": moon has moved to the right");
                }
                if (moon.getHeight()==0){
                    UI.println(i+": moon at ground");
                }
                if (bike.getHeight()==0){
                    UI.println(i+": bike at ground");
                }
                UI.sleep(100);
                if (bike.getHeight()==0 && moon.getHeight()==0){
                    break;
                }
            }
        } while (UI.askBoolean("test again?"));
    }
    // END OF DRAFT CODE

}
</code>```

This is the emoji class
Needing help with the touching and bump methods so that the stand still emoji gets bumped more realistically and based on the speed of the emoji controlled.

this is what it looks like when run
the moon in the bottom left was my object that I shot at the angry target. They both need to stop on the ground.

I have a UI import which makes things much easier to make.

Body:
Working on a program that consists of emoji's and you get an emoji that you can shoot, bit like Angry Birds but way more basic. At the moment the stand still emoji is falling down (increasing vertical velocity by gravity until it hits the ground). However this only happens when the main object has a greater horizontal position than the stand still object.

/**
 * Represents an emoji that can move on a window.
 */

public class Emoji{

    // Constants for all Emoji: size, position of the ground
    public static final double SIZE = 40;  // width/length of the emoji images
    public static final double GROUND = EmojiLauncher.GROUND;
    public static final double GRAVITY = 0.25;  // how much to reduce the speed each step.

    // Fields to store state of the Emoji:
    private double horizontalPos;
    private double aboveGround;
    private double hSpeed;
    private double vSpeed;
    private String name;

    // Constructor
    /**
     * Constructor
     */
     public Emoji(double x, double h, String name){
        this.horizontalPos = x;
        this.aboveGround = h;
        this.name = "emojis/"+name;

    }
    // Methods
    /**
     * Draws an emoji
     */
    public void draw(){
        UI.drawImage(this.name, this.horizontalPos, this.aboveGround , SIZE, SIZE);

    }

    /**
     * Makes emoji take a step
     */
    public void step(){

        if(this.vSpeed != 0 || this.hSpeed != 0){
            this.horizontalPos += hSpeed;
            this.aboveGround += vSpeed;
            this.vSpeed += GRAVITY;
              if(this.aboveGround > GROUND - SIZE){
          vSpeed = 0;
          hSpeed = 0;
          this.aboveGround = GROUND - SIZE;
        }
        }

    }

    /**
     *
     * Returns the height of the emoji above the floor.
     */
    public double getHeight(){
        return this.aboveGround;

    }

    /**
     *
     *
     * Returns the horizontal position
     */
    public double getX(){
        return this.horizontalPos;

    }

    /**
     * Returns the speed of the emoji
     */
    public double getSpeed(){
        return Math.hypot(hSpeed, vSpeed);

    }

    /**
     *
     * Set the horizontal and vertical speed of emoji
     */
    public void launch(double xSpeed, double ySpeed){
        this.hSpeed = xSpeed;
        this.vSpeed = ySpeed;

    }

    /**
     * return true if emoji is touching other emoji
     */
    public boolean touching(Emoji other){
        if(this.horizontalPos >= other.horizontalPos || this.aboveGround >= other.aboveGround){
            return true;
        }
        else {
            return false;
        }

    }

    /**
     * if emojis hit each other, the hit emoji starts moving
     */
    public void bump(Emoji other){
        if((this.hSpeed > 0 || vSpeed > 0) &&
        (this.horizontalPos >= other.horizontalPos && this.aboveGround >= other.aboveGround)){
            other.hSpeed = 1;
        }

    }

    /**
     * Main method
     */
    public static void main(String[] args){
        do {
            Emoji bike = new Emoji(110, 150, "bicycle.png");
            bike.draw();
            Emoji moon = new Emoji(50, 200, "moon.png");
            moon.draw();
            moon.launch(5, 0);
            UI.println("moon launched");
            for (int i=0; i<=100; i++){
                bike.step();
                moon.step();
                UI.clearGraphics();
                UI.drawLine(0, GROUND, 500, GROUND);
                bike.draw();
                moon.draw();

                if(moon.touching(bike)&& moon.getSpeed()>0){
                    moon.bump(bike);
                    UI.println(i+": moon touched and then bumped bike");
                }
                if(moon.getX() > 55 && moon.getX()<65){
                    UI.println(i+": moon has moved to the right");
                }
                if (moon.getHeight()==0){
                    UI.println(i+": moon at ground");
                }
                if (bike.getHeight()==0){
                    UI.println(i+": bike at ground");
                }
                UI.sleep(100);
                if (bike.getHeight()==0 && moon.getHeight()==0){
                    break;
                }
            }
        } while (UI.askBoolean("test again?"));
    }
    // END OF DRAFT CODE

}

This is the emoji class
Needing help with the touching and bump methods so that the stand still emoji gets bumped more realistically and based on the speed of the emoji controlled.

this is what it looks like when run
the moon in the bottom left was my object that I shot at the angry target. They both need to stop on the ground.

I have a UI import which makes things much easier to make.


问:
std::enable_if fails to specialize class template while is able to specialize function template
Suppose I have a family of enums with predefined structure:

```<code>enum class A {BEGIN, a, b, c, END};
</code>```

Now I need to implement a way to get min and max values (somewhat like numeric limits) which is able to work with both standard numeric types and enums.

If I write something like following chunk of code, I get desired result:

```<code>template <typename T, typename std::enable_if_t<std::is_enum_v<T>, bool> = true>
T min() {
    return T::BEGIN;
}

template <typename T, typename std::enable_if_t<!std::is_enum_v<T>, bool> = true>
T min() {
    return std::numeric_limits<T>::min();
}
...

min<A>(); // works
</code>```

But shall I try to structure it a bit more, I immidiatelly get template redefinition errors:

```<code>template <typename T, typename std::enable_if_t<!std::is_enum_v<T>, bool> = true>
struct NumericLimits{
    static T min() { return std::numeric_limits<T>::min(); }
    static T max() { return std::numeric_limits<T>::max(); }
};

template <typename T, typename std::enable_if_t<std::is_enum_v<T>, bool> = true>
struct NumericLimits {
    static T min() { return T::BEGIN; }
    static T max() { return T::END; }
};
...
NumericLimits<A>::min(); // error

</code>```

Compiler complais of following on call:

```<code><source>:60:74: error: template non-type parameter has a different type 'typename std::enable_if_t<std::is_enum_v<T>, bool>' (aka 'typename enable_if<std::is_enum_v<T>, bool>::type') in template redeclaration
template <typename T, typename std::enable_if_t<std::is_enum_v<T>, bool> = true>
</code>```

Although I kind of have what I want with the fist approach, I'm wondering what's wrong with second? I'd expect it to work too. Why am I unable to specialize class template? Or why function template specialization is not treated as redeclaration?

Body:
Suppose I have a family of enums with predefined structure:

enum class A {BEGIN, a, b, c, END};

Now I need to implement a way to get min and max values (somewhat like numeric limits) which is able to work with both standard numeric types and enums.

If I write something like following chunk of code, I get desired result:

template <typename T, typename std::enable_if_t<std::is_enum_v<T>, bool> = true>
T min() {
    return T::BEGIN;
}

template <typename T, typename std::enable_if_t<!std::is_enum_v<T>, bool> = true>
T min() {
    return std::numeric_limits<T>::min();
}
...

min(); // works

But shall I try to structure it a bit more, I immidiatelly get template redefinition errors:

template <typename T, typename std::enable_if_t<!std::is_enum_v<T>, bool> = true>
struct NumericLimits{
    static T min() { return std::numeric_limits<T>::min(); }
    static T max() { return std::numeric_limits<T>::max(); }
};

template <typename T, typename std::enable_if_t<std::is_enum_v<T>, bool> = true>
struct NumericLimits {
    static T min() { return T::BEGIN; }
    static T max() { return T::END; }
};
...
NumericLimits::min(); // error

Compiler complais of following on call:

<source>:60:74: error: template non-type parameter has a different type 'typename std::enable_if_t<std::is_enum_v<T>, bool>' (aka 'typename enable_if<std::is_enum_v<T>, bool>::type') in template redeclaration
template <typename T, typename std::enable_if_t<std::is_enum_v<T>, bool> = true>

Although I kind of have what I want with the fist approach, I'm wondering what's wrong with second? I'd expect it to work too. Why am I unable to specialize class template? Or why function template specialization is not treated as redeclaration?


问:
How do I access svg file embedded classes from separate CSS file
I'm trying to manipulate the color of paths/groups within an svg file from a separate CSS file.

I'm using react and have imported the SVG file as a React Component which is then manipulated using CSS however I can only manipulate one section of it using fill: current color.

Here is part of my SVG file

```<code>    <g id="traps" class="neck">
        <path d="m89.87,..."/>
    </g>
    <g id="biceps" class="upperArms">
        <path d="m167.82,..."/>
        <path d="m70.91,170.86c-1.07,..."/>
    </g>
</code>```

Is there any way to access these classes/id's in order to dynamically manipulate them on my website?

Body:
I'm trying to manipulate the color of paths/groups within an svg file from a separate CSS file.

I'm using react and have imported the SVG file as a React Component which is then manipulated using CSS however I can only manipulate one section of it using fill: current color.

Here is part of my SVG file

    <g id="traps" class="neck">
        <path d="m89.87,..."/>
    </g>
    <g id="biceps" class="upperArms">
        <path d="m167.82,..."/>
        <path d="m70.91,170.86c-1.07,..."/>
    </g>

Is there any way to access these classes/id's in order to dynamically manipulate them on my website?


问:
Cucumber IntelleJ feature steps can't find stepDefinitions
I know its an annoying issue hope someone or IntelleJ itself find a solution.
There are definitions for every single steps but when I press Ctrl+Click on steps to navigate to step definitions, it doesn't work and it say no step definition create step definition.
I tried all possible and recommended ways like 'edit config' and setting the proper glue, Installing/uninstalling Substep plugin</p>


问:
Next-Auth Credential signIn() Causing Issue with Code 302
In my onSubmit handler, the resp returned from signIn is: {error: null, status: 302, ok: false, url: 'http://localhost:3000/login'}

if (resp?.ok) fails and so router.push("/"); never gets called so the page doesn't redirect. But it does set the session token.

Where is this response coming from and why is that responder setting this 302 code that can't be handled? And ultimately, how can I correct this issue with the 302 status code that's causing the error?

I was able to get it working by removing redirect: false, and adding callbackUrl: "/", inside of signIn("credentials", { but this causes a full page reload. So it's slower and looks worse, poor UX...

When I run

```<code> curl -v 'http://localhost:3001/' \                                                                                ─╯
-X POST \
-H 'content-type: application/json' \
--data '{
"query": "mutation Login { login(email: \"c@c.com\", password: \"cc\") { email password } }"}'
</code>```

I get the following response with status code 200:

```<code>Note: Unnecessary use of -X or --request, POST is already inferred.
*   Trying 127.0.0.1:3001...
* Connected to localhost (127.0.0.1) port 3001 (#0)
> POST / HTTP/1.1
> Host: localhost:3001
> User-Agent: curl/7.84.0
> Accept: */*
> content-type: application/json
> Content-Length: 95
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< X-Powered-By: Express
< Access-Control-Allow-Origin: *
< cache-control: no-store
< Content-Type: application/json; charset=utf-8
< Content-Length: 55
< ETag: W/"37-HpRnb+ujrwu8KqiIqkD9OLY/ndI"
< Date: Sat, 10 Dec 2022 21:48:04 GMT
< Connection: keep-alive
< Keep-Alive: timeout=5
<
{"data":{"login":{"email":"c@c.com","password":"cc"}}}
* Connection #0 to host localhost left intact

</code>```

So where is next-auth/signIn getting the 302 from?

full code: https://github.com/currenthandle/hackathon

In this other codebase I do the same thing, and get a 200 status code instead of 302. This one uses tRPC instead of graphQL: https://github.com/currenthandle/shopping-list/blob/main/src/pages/login.tsx#L31

src/pages/login.tsx

```<code>const Login: NextPage = () => {
  // ...
  const onSubmit = async (/*data: Schema*/) => {
    const formValues = getValues();
    try {
      const resp = await signIn("credentials", {
        id: "credentials",
        email: formValues.email,
        password: formValues.password,
        redirect: false,
      });
      if (resp?.ok) {
        router.push("/");
      } else {
        console.error("error", resp);
      }
    } catch (error) {
      console.error("error", error);
    }
  };

  return (
    <div className="flex justify-center pt-10">
      {/* ... *}
      <form
        onSubmit={handleSubmit(onSubmit)}
        className="flex w-6/12 flex-col justify-center"
      >
        {/* ... *}
      </form>
      {/* ... *}
    </div>
  );
};
export default Login;
</code>```

src/pages/api/auth/[...nextauth].ts

```<code>import NextAuth, { type NextAuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { ApolloClient, InMemoryCache, gql } from "@apollo/client";

import { env } from "../../../env/server.mjs";
import { prisma } from "../../../server/db/client";

const LOGIN_MUTATION = gql`
  mutation Login($email: String!, $password: String!) {
    login(email: $email, password: $password) {
      email
    }
  }
`;

const client = new ApolloClient({
  uri: "http://localhost:3000/api/graphql",
  cache: new InMemoryCache(),
});

export const authOptions: NextAuthOptions = {
  pages: {
    signIn: "/login",
    newUser: "/signUp",
  },
  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        email: {
          label: "Email",
          type: "email",
          placeholder: "",
        },
        password: {
          label: "Password",
          type: "password",
          placeholder: "",
        },
      },
      async authorize(credentials) {
        const resp = await client.mutate({
          mutation: LOGIN_MUTATION,
          variables: {
            email: credentials?.email,
            password: credentials?.password,
          },
        });
        const user = resp?.data?.login;
        if (user) {
          return user;
        }
        throw new Error("Invalid email or password");
      },
    }),
  ],
};

export default NextAuth(authOptions);
</code>```

src/pages/api/graphql.ts

```<code>import { ApolloServer } from "@apollo/server";
import { startServerAndCreateNextHandler } from "@as-integrations/next";
import { gql } from "graphql-tag";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

const resolvers = {
  Query: {
    hello: () => "world",
  },
  Mutation: {
    async createUser(parent, args, context, info) {
      const { email, password } = args;
      console.log("context", Object.keys(context.req));
      const user = await prisma.user.create({
        data: {
          email,
          password,
        },
      });
      return user;
    },
    async login(parent, args, context, info) {
      console.log("context", context);
      const { email, password } = args;
      const user = await prisma.user.findUnique({
        where: {
          email,
        },
      });
      console.log("user before ", user);
      if (!user) {
        throw new Error("Invalid email or password");
      }
      if (user.password !== password) {
        throw new Error("Invalid email or password");
      }
      console.log("user", user);
      return user;
    },
  },
};

const typeDefs = gql`
  type Query {
    hello: String
  }
  type Mutation {
    createUser(email: String!, password: String!): User!
    login(email: String!, password: String!): User!
  }
  type User {
    id: ID!
    email: String!
    password: String!
  }
`;

const server = new ApolloServer({
  resolvers,
  typeDefs,
});

export default startServerAndCreateNextHandler(server);
</code>```

Body:
In my onSubmit handler, the resp returned from signIn is: {error: null, status: 302, ok: false, url: 'http://localhost:3000/login'}

if (resp?.ok) fails and so router.push("/"); never gets called so the page doesn't redirect. But it does set the session token.

Where is this response coming from and why is that responder setting this 302 code that can't be handled? And ultimately, how can I correct this issue with the 302 status code that's causing the error?

I was able to get it working by removing redirect: false, and adding callbackUrl: "/", inside of signIn("credentials", { but this causes a full page reload. So it's slower and looks worse, poor UX...

When I run

 curl -v 'http://localhost:3001/' \                                                                                ─╯
-X POST \
-H 'content-type: application/json' \
--data '{
"query": "mutation Login { login(email: \"c@c.com\", password: \"cc\") { email password } }"}'

I get the following response with status code 200:

Note: Unnecessary use of -X or --request, POST is already inferred.
*   Trying 127.0.0.1:3001...
* Connected to localhost (127.0.0.1) port 3001 (#0)
> POST / HTTP/1.1
> Host: localhost:3001
> User-Agent: curl/7.84.0
> Accept: */*
> content-type: application/json
> Content-Length: 95
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< X-Powered-By: Express
< Access-Control-Allow-Origin: *
< cache-control: no-store
< Content-Type: application/json; charset=utf-8
< Content-Length: 55
< ETag: W/"37-HpRnb+ujrwu8KqiIqkD9OLY/ndI"
< Date: Sat, 10 Dec 2022 21:48:04 GMT
< Connection: keep-alive
< Keep-Alive: timeout=5
<
{"data":{"login":{"email":"c@c.com","password":"cc"}}}
* Connection #0 to host localhost left intact

So where is next-auth/signIn getting the 302 from?

full code: https://github.com/currenthandle/hackathon

In this other codebase I do the same thing, and get a 200 status code instead of 302. This one uses tRPC instead of graphQL: https://github.com/currenthandle/shopping-list/blob/main/src/pages/login.tsx#L31

src/pages/login.tsx

const Login: NextPage = () => {
  // ...
  const onSubmit = async (/*data: Schema*/) => {
    const formValues = getValues();
    try {
      const resp = await signIn("credentials", {
        id: "credentials",
        email: formValues.email,
        password: formValues.password,
        redirect: false,
      });
      if (resp?.ok) {
        router.push("/");
      } else {
        console.error("error", resp);
      }
    } catch (error) {
      console.error("error", error);
    }
  };

  return (

      {/* ... *}
      <form
        onSubmit={handleSubmit(onSubmit)}
        className="flex w-6/12 flex-col justify-center"
      >
        {/* ... *}
      </form>
      {/* ... *}

  );
};
export default Login;

src/pages/api/auth/[...nextauth].ts

import NextAuth, { type NextAuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { ApolloClient, InMemoryCache, gql } from "@apollo/client";

import { env } from "../../../env/server.mjs";
import { prisma } from "../../../server/db/client";

const LOGIN_MUTATION = gql`
  mutation Login($email: String!, $password: String!) {
    login(email: $email, password: $password) {
      email
    }
  }
`;

const client = new ApolloClient({
  uri: "http://localhost:3000/api/graphql",
  cache: new InMemoryCache(),
});

export const authOptions: NextAuthOptions = {
  pages: {
    signIn: "/login",
    newUser: "/signUp",
  },
  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        email: {
          label: "Email",
          type: "email",
          placeholder: "",
        },
        password: {
          label: "Password",
          type: "password",
          placeholder: "",
        },
      },
      async authorize(credentials) {
        const resp = await client.mutate({
          mutation: LOGIN_MUTATION,
          variables: {
            email: credentials?.email,
            password: credentials?.password,
          },
        });
        const user = resp?.data?.login;
        if (user) {
          return user;
        }
        throw new Error("Invalid email or password");
      },
    }),
  ],
};

export default NextAuth(authOptions);

src/pages/api/graphql.ts

import { ApolloServer } from "@apollo/server";
import { startServerAndCreateNextHandler } from "@as-integrations/next";
import { gql } from "graphql-tag";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

const resolvers = {
  Query: {
    hello: () => "world",
  },
  Mutation: {
    async createUser(parent, args, context, info) {
      const { email, password } = args;
      console.log("context", Object.keys(context.req));
      const user = await prisma.user.create({
        data: {
          email,
          password,
        },
      });
      return user;
    },
    async login(parent, args, context, info) {
      console.log("context", context);
      const { email, password } = args;
      const user = await prisma.user.findUnique({
        where: {
          email,
        },
      });
      console.log("user before ", user);
      if (!user) {
        throw new Error("Invalid email or password");
      }
      if (user.password !== password) {
        throw new Error("Invalid email or password");
      }
      console.log("user", user);
      return user;
    },
  },
};

const typeDefs = gql`
  type Query {
    hello: String
  }
  type Mutation {
    createUser(email: String!, password: String!): User!
    login(email: String!, password: String!): User!
  }
  type User {
    id: ID!
    email: String!
    password: String!
  }
`;

const server = new ApolloServer({
  resolvers,
  typeDefs,
});

export default startServerAndCreateNextHandler(server);


问:
How to add a callback to a form submit when AJAX is not an option (e.g., for a file download)?
I need to add a callback to a jQuery form submit that will be called after the request completes (something like .complete on an AJAX request). I know that there's this question, but there's currently nothing there that works for my needs. I have a form submit that initiates a file download, so by its very nature, I can't use an AJAX request; it has to be a form submit. Is there any way that I can get the file download and have a callback called once the request completes (whether successfully or otherwise)?

I've also investigated the possibility of wrapping the form submit in a promise; but that requires the ability to pass in success/failure callbacks in the first place.

(There's also this related question, which doesn't have an answer.)


问:
path = currentFile.rsplit('.', 1)[1].lower() Indexerror: List index out of range
I have to make a program RC5 encryption. I'm new to coding. I have finished my game, and during testing, everything works fine, but i get this error.


问:
Not able to pass around the same reference of a shared pointer
I have a singleton class A that the user interacts with. A stores shared pointers to a separate class B. And within A::doStuff(), it allows B to delete B from the vector in A that stores the shared pointers.

However, I can't seem to find a way for B to inform A about itself. In short, what A stores != what B informs A to delete from itself.

Right now I am just using std::make_shared(*this) such that the syntax matches but this creates a new instance of B which doesn't match with b in main, hence failure for A to remove it.

```<code>struct B
{
    void doStuff()
    {
        // stuff...

        // and then delete itself from A::_vec
        A::get().del(std::make_shared<B>(*this));

        // with raw ptr, I would do `A::get().del(this);
    }
};
</code>```

Here's the sample code that prints use_count to help identify whether the same object is attempted to be removed from A.

I'd expect the shared count at the end of the program to be 1, but it's 2.

```<code>class B;

class A
{
    std::vector<std::shared_ptr<B>> _vec;

    public:
    static A& get();
    void run();
    void add(std::shared_ptr<B> b);
    void del(std::shared_ptr<B> b);
};

struct B
{
    void doStuff()
    {
        // stuff...

        // and then delete itself from A::_vec
        A::get().del(std::make_shared<B>(*this));

        // A::get().del(this);  // would do this with raw pointer!
    }
};

A& A::get()
{
    static A obj;
    return obj;
}

void A::run()
{
    for (auto e : _vec)
    {
        e->doStuff();
    }
}

void A::add(std::shared_ptr<B> b)
{
    std::cout << "A::add[1] = " << b.use_count() << std::endl;
    _vec.push_back(b);
    std::cout << "A::add[2] = " << b.use_count() << std::endl;
}

void A::del(std::shared_ptr<B> b)
{
    // removing b from _vec
    std::cout << "\n_vec size1 = " << _vec.size() << std::endl;
    std::cout << "A::del[1] = " << b.use_count() << std::endl;

    _vec.erase(std::remove(_vec.begin(), _vec.end(), b), _vec.end());
    // _vec size remains 1 since "b" != what's in _vec

    std::cout << "A::del[2] = " << b.use_count() << std::endl;
    std::cout << "_vec size2 = " << _vec.size() << std::endl << std::endl;
}

int main()
{
    auto b = std::make_shared<B>();
    A::get().add(b);

    std::cout << "After add = " << b.use_count() << std::endl;

    A::get().run();

    // remains 2 since _vec.erase wasn't successful!
    std::cout << "After remove = " << b.use_count() << std::endl;
}
</code>```

Body:
I have a singleton class A that the user interacts with. A stores shared pointers to a separate class B. And within A::doStuff(), it allows B to delete B from the vector in A that stores the shared pointers.

However, I can't seem to find a way for B to inform A about itself. In short, what A stores != what B informs A to delete from itself.

Right now I am just using std::make_shared(*this) such that the syntax matches but this creates a new instance of B which doesn't match with b in main, hence failure for A to remove it.

struct B
{
    void doStuff()
    {
        // stuff...

        // and then delete itself from A::_vec
        A::get().del(std::make_shared(*this));

        // with raw ptr, I would do `A::get().del(this);
    }
};

Here's the sample code that prints use_count to help identify whether the same object is attempted to be removed from A.

I'd expect the shared count at the end of the program to be 1, but it's 2.

class B;

class A
{
    std::vector<std::shared_ptr> _vec;

    public:
    static A& get();
    void run();
    void add(std::shared_ptr b);
    void del(std::shared_ptr b);
};

struct B
{
    void doStuff()
    {
        // stuff...

        // and then delete itself from A::_vec
        A::get().del(std::make_shared(*this));

        // A::get().del(this);  // would do this with raw pointer!
    }
};

A& A::get()
{
    static A obj;
    return obj;
}

void A::run()
{
    for (auto e : _vec)
    {
        e->doStuff();
    }
}

void A::add(std::shared_ptr b)
{
    std::cout << "A::add[1] = " << b.use_count() << std::endl;
    _vec.push_back(b);
    std::cout << "A::add[2] = " << b.use_count() << std::endl;
}

void A::del(std::shared_ptr b)
{
    // removing b from _vec
    std::cout << "\n_vec size1 = " << _vec.size() << std::endl;
    std::cout << "A::del[1] = " << b.use_count() << std::endl;

    _vec.erase(std::remove(_vec.begin(), _vec.end(), b), _vec.end());
    // _vec size remains 1 since "b" != what's in _vec

    std::cout << "A::del[2] = " << b.use_count() << std::endl;
    std::cout << "_vec size2 = " << _vec.size() << std::endl << std::endl;
}

int main()
{
    auto b = std::make_shared();
    A::get().add(b);

    std::cout << "After add = " << b.use_count() << std::endl;

    A::get().run();

    // remains 2 since _vec.erase wasn't successful!
    std::cout << "After remove = " << b.use_count() << std::endl;
}


Title: Plot time series data using pandas

Body:
I am trying to plot some time series data and I have the data like below

                      0       1
0   2022-12-02 14:57:25  64.603
1   2022-12-02 14:57:56  64.610
2   2022-12-02 14:58:27  64.610
3   2022-12-02 14:58:58  64.607
4   2022-12-02 14:59:29  64.599
..                  ...     ...
716 2022-12-02 21:07:38  73.888
717 2022-12-02 21:08:09  73.887
718 2022-12-02 21:08:40  73.883
719 2022-12-02 21:09:11  73.885
720 2022-12-02 21:09:42  73.886

The code below (snippet) is plotting the x values as strings not datetime

df[0] = pd.to_datetime(df[0], format='%Y/%m/%d %H:%M:%S',errors='ignore')
fig = plt.plot(df[0], df[1])

Any ideas what is not right here?


问:
Loading dataset from external file system (https) directly into Spark dataframe
I'm trying to load a CSV dataset directly from an external file system, but I'm getting a 401 Unauthorized response whenever I call sparkContext.addFile(). Is there a way to add authorization headers to the request before adding the file? Or a better way to load a csv file as a dataframe?

This is what I'm trying now and it throws an exception when I make the addFile() call.

```<code>import org.apache.spark.SparkFiles

spark.sparkContext.addFile(urlPath)
val df = spark.read
    .option("header", true)
    .csv("file://"+SparkFiles.get(urlPath))
</code>```

Body:
I'm trying to load a CSV dataset directly from an external file system, but I'm getting a 401 Unauthorized response whenever I call sparkContext.addFile(). Is there a way to add authorization headers to the request before adding the file? Or a better way to load a csv file as a dataframe?

This is what I'm trying now and it throws an exception when I make the addFile() call.

import org.apache.spark.SparkFiles

spark.sparkContext.addFile(urlPath)
val df = spark.read
    .option("header", true)
    .csv("file://"+SparkFiles.get(urlPath))


问:
GitLab CI failing after call php in a docker composer exec command

My CI script is failing without any error message, do you guys have any idea why?

docker compose exec -T my-app-name bash -c 'php -d xdebug.mode=off ./vendor/maglnet/composer-require-checker/bin/composer-require-checker check --output=json > composer-require-check-report.json'

# I also tried variations, always with the same result.

docker compose exec -T my-app-name php -d xdebug.mode=off ./vendor/maglnet/composer-require-checker/bin/composer-require-checker check --output=json > composer-require-check-report.json

docker compose exec -T my-app-name XDEBUG_MODE=off php ./vendor/maglnet/composer-require-checker/bin/composer-require-checker check --output=json > composer-require-check-report.json

docker compose exec -T my-app-name bash -c 'php -d xdebug.mode=off ./vendor/maglnet/composer-require-checker/bin/composer-require-checker check --output=json' > composer-require-check-report.json

docker compose exec -T my-app-name bash -c 'XDEBUG_MODE=off php ./vendor/maglnet/composer-require-checker/bin/composer-require-checker check --output=json > composer-require-check-report.json'
```

As mentioned, the command is executing correctly and the file is generated at the end.

The command works well locally (and apparently works well in the runner too), I just don't know why the job is failing.

Body:
My CI script is failing without any error message, do you guys have any idea why?

docker compose exec -T my-app-name bash -c 'php -d xdebug.mode=off ./vendor/maglnet/composer-require-checker/bin/composer-require-checker check --output=json > composer-require-check-report.json'

# I also tried variations, always with the same result.

docker compose exec -T my-app-name php -d xdebug.mode=off ./vendor/maglnet/composer-require-checker/bin/composer-require-checker check --output=json > composer-require-check-report.json

docker compose exec -T my-app-name XDEBUG_MODE=off php ./vendor/maglnet/composer-require-checker/bin/composer-require-checker check --output=json > composer-require-check-report.json

docker compose exec -T my-app-name bash -c 'php -d xdebug.mode=off ./vendor/maglnet/composer-require-checker/bin/composer-require-checker check --output=json' > composer-require-check-report.json

docker compose exec -T my-app-name bash -c 'XDEBUG_MODE=off php ./vendor/maglnet/composer-require-checker/bin/composer-require-checker check --output=json > composer-require-check-report.json'

As mentioned, the command is executing correctly and the file is generated at the end.

The command works well locally (and apparently works well in the runner too), I just don't know why the job is failing.


问:
Custom control with Entry, ReturnCommand not working
I built a simple adaptation of the Entry control as follows:

```<code><?xml version="1.0" encoding="utf-8" ?>
<Grid xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
  xmlns:local="clr-namespace:B1WApp.CustomControls"
  x:Class="B1WApp.CustomControls.UI5Entry"
  x:DataType="local:UI5Entry">

<Border StrokeShape="RoundRectangle 5"
        Stroke="{StaticResource SAPFieldBackground}"
        BackgroundColor="{StaticResource SAPFieldBorderColor}"
        Padding="1"
        x:Name="OuterBorder">
    <Border StrokeShape="RoundRectangle 4"
            Stroke="{StaticResource SAPFieldBackground}"
            BackgroundColor="{StaticResource SAPFieldBackground}">
        <Entry Text="{Binding Path=Text}"
               Placeholder="{Binding Path=Placeholder}"
               PlaceholderColor="{StaticResource SAPFieldPlaceholderColor}"
               ReturnType="{Binding Path=ReturnType}"
               IsPassword="{Binding Path=IsPassword}"
               Margin="{OnPlatform Default='0', Android='0,-8,0,-8'}"
               Focused="Entry_Focused"
               Unfocused="Entry_Unfocused"
               Completed="Entry_Completed"
               ReturnCommand="{Binding Path=ReturnCommand}"/>
    </Border>
</Border>
</Grid>
</code>```

In code-behind I have:

```<code>using System.Windows.Input;

public partial class UI5Entry : Grid
{
    public UI5Entry()
    {
        InitializeComponent();

        this.BindingContext = this;
    }

// additional code omitted for brevity

    public static readonly BindableProperty ReturnCommandProperty = BindableProperty.Create(
        propertyName: nameof(ReturnCommand),
        returnType: typeof(ICommand),
        declaringType: typeof(UI5Entry),
        defaultValue: null,
        defaultBindingMode: BindingMode.OneWay);

    public ICommand ReturnCommand
    {
        get => (ICommand)GetValue(ReturnCommandProperty);
        set => SetValue(ReturnCommandProperty, value);
    }
}
</code>```

However, when I use the control, the ReturnCommand never fires. The other properties work fine, however. Am I missing something here?

```<code><customControls:UI5Entry
                ReturnType="Search"
                Placeholder="Digita/escanea # de doc."
                Text="{Binding SearchText, Mode=TwoWay}"
                ReturnCommand="{Binding SearchForBaseDocumentsCommand}"
                />
</code>```

Thanks in advance for any hints on this issue.

Best regards,

Joerg.

Body:
I built a simple adaptation of the Entry control as follows:

<?xml version="1.0" encoding="utf-8" ?>
<Grid xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
  xmlns:local="clr-namespace:B1WApp.CustomControls"
  x:Class="B1WApp.CustomControls.UI5Entry"
  x:DataType="local:UI5Entry">

<Border StrokeShape="RoundRectangle 5"
        Stroke="{StaticResource SAPFieldBackground}"
        BackgroundColor="{StaticResource SAPFieldBorderColor}"
        Padding="1"
        x:Name="OuterBorder">
    <Border StrokeShape="RoundRectangle 4"
            Stroke="{StaticResource SAPFieldBackground}"
            BackgroundColor="{StaticResource SAPFieldBackground}">
        <Entry Text="{Binding Path=Text}"
               Placeholder="{Binding Path=Placeholder}"
               PlaceholderColor="{StaticResource SAPFieldPlaceholderColor}"
               ReturnType="{Binding Path=ReturnType}"
               IsPassword="{Binding Path=IsPassword}"
               Margin="{OnPlatform Default='0', Android='0,-8,0,-8'}"
               Focused="Entry_Focused"
               Unfocused="Entry_Unfocused"
               Completed="Entry_Completed"
               ReturnCommand="{Binding Path=ReturnCommand}"/>
    </Border>
</Border>
</Grid>

In code-behind I have:

using System.Windows.Input;

public partial class UI5Entry : Grid
{
    public UI5Entry()
    {
        InitializeComponent();

        this.BindingContext = this;
    }

// additional code omitted for brevity

    public static readonly BindableProperty ReturnCommandProperty = BindableProperty.Create(
        propertyName: nameof(ReturnCommand),
        returnType: typeof(ICommand),
        declaringType: typeof(UI5Entry),
        defaultValue: null,
        defaultBindingMode: BindingMode.OneWay);

    public ICommand ReturnCommand
    {
        get => (ICommand)GetValue(ReturnCommandProperty);
        set => SetValue(ReturnCommandProperty, value);
    }
}

However, when I use the control, the ReturnCommand never fires. The other properties work fine, however. Am I missing something here?

<customControls:UI5Entry
                ReturnType="Search"
                Placeholder="Digita/escanea # de doc."
                Text="{Binding SearchText, Mode=TwoWay}"
                ReturnCommand="{Binding SearchForBaseDocumentsCommand}"
                />

Thanks in advance for any hints on this issue.

Best regards,

Joerg.


问:
Regular Expression for each password strength cases and names with spaces JavaScript
Could you help with regex in the following situation?

If the string only numbers, only lowercase char, only uppercase, or only symbols.
This is how far I got.

```<code>/[0-9]|[a-z]|[A-Z]|[!@#$%^&*)(+=._-]/
</code>```

If the string is a mixture of the two cases(either number, lowercase, uppercase, or symbols)

No idea about its regex.

If the string has at least one number, one lowercase, one uppercase, and one symbol.

```<code>/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]$/
</code>```

If regex for a string that is consisted of numbers and alphabets and can have space in the middle (neither at the start nor at the end)

```<code>/^[a-z\d\s]+$/
</code>```

This is not related to passwords. I would like it if someone could help me with case 2 and confirm the rest.
Thanks.

Body:
Could you help with regex in the following situation?

If the string only numbers, only lowercase char, only uppercase, or only symbols.
This is how far I got.

/[0-9]|[a-z]|[A-Z]|[!@#$%^&*)(+=._-]/

If the string is a mixture of the two cases(either number, lowercase, uppercase, or symbols)

No idea about its regex.

If the string has at least one number, one lowercase, one uppercase, and one symbol.

/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]$/

If regex for a string that is consisted of numbers and alphabets and can have space in the middle (neither at the start nor at the end)

/^[a-z\d\s]+$/

This is not related to passwords. I would like it if someone could help me with case 2 and confirm the rest.
Thanks.


问:
data key in useQuery
I was implementing GraphQl in React Native but I encountered a problem where while using useQuery for one exported object I did not have use the data key with the data but for the the other passed data I had to use it. Otherwise the data was undefined. Can someone please explain this working of useQuery?
I am attaching code snippet for better understanding.

```<code>const { loading, error, data } = useQuery(COUNTRY_QUERY);// Not above

const { loading2, error2, data: data2 } = useQuery(COUNTRY_CODE_QUERY); //It had to be used here
</code>```

This is the query that I typed:

```<code>export const COUNTRY_QUERY = gql`
  query CountryQuery {
    countries {
      name
    }
  }
`;

export const COUNTRY_CODE_QUERY = gql`
  query {
    country(code: "BR") {
      name
      capital
      code
      native
      emoji
      currency
    }
  }
`;

</code>```

I have tried it with different parameters but it was no use.

Title: data key in useQuery

Body:
I was implementing GraphQl in React Native but I encountered a problem where while using useQuery for one exported object I did not have use the data key with the data but for the the other passed data I had to use it. Otherwise the data was undefined. Can someone please explain this working of useQuery?
I am attaching code snippet for better understanding.

const { loading, error, data } = useQuery(COUNTRY_QUERY);// Not above

const { loading2, error2, data: data2 } = useQuery(COUNTRY_CODE_QUERY); //It had to be used here

This is the query that I typed:

export const COUNTRY_QUERY = gql`
  query CountryQuery {
    countries {
      name
    }
  }
`;

export const COUNTRY_CODE_QUERY = gql`
  query {
    country(code: "BR") {
      name
      capital
      code
      native
      emoji
      currency
    }
  }
`;

I have tried it with different parameters but it was no use.


问:
Multiprocessing makes the code slower than expected - using Cython and using vanilla Python
Got to give credit to NeuralNine video about Cython - from here I got the code.

Here I have a .pyx that contains two functions that are doing the same thing, which is given an integer amount returns a list of all the prime numbers below that number.

prime_finder_vanilla - Pure python

prime_finder_optimized - Cython

def prime_finder_vanilla(amount):
    primes = []
    found = 0
    number = 2
    while found < amount:
        for x in primes:
            if number % x == 0:
                break
        else:
            primes.append(number)
            found += 1
        number += 1
    return primes

def prime_finder_optimized(int amount):
    cdef int number, x, found
    cdef int primes[100_000]

    amount = min(amount, 100_000)
    found = 0
    number = 2
    while found < amount:
        for x in primes[:found]:
            if number % x == 0:
                break
        else:
            primes[found] = number
            found += 1

        number += 1

    return_list = [p for p in primes[:found]] # <--- ?! why not just return primes[:found] lol
    return return_list
```
<p>I've compiled the file with the command line:</p>
```python setup.py build_ext --inplace
```
<p>setup.py</p>
<pre class="lang-py prettyprint-override"><code>from setuptools import setup
from Cython.Build import cythonize

setup  (
    ext_modules=cythonize('testing_cython.pyx')
)
</code>```

Now, I did run both functions, and it really seems that the Cython implementation is faster! but what I always like to do, is build a third part method that runs these functions for a given range, and calculates the average time it took to run these functions and get more accurate statistics of how optimized it really is.

So this is my "third party optimization analysis" file:

import time
from multiprocessing import Pool

import testing_cython

def check_performance(fn, tests_amount, tests_amount_start=1_000):
    times = []

    for amount in range(tests_amount_start, tests_amount_start + tests_amount + 1):
        start = time.perf_counter()
        fn(amount)
        times.append(time.perf_counter() - start)

    return sum(times) / len(times)

if __name__ == '__main__':
    starting_time = time.perf_counter()
    pool = Pool(processes=2)
    res1 = pool.apply_async(check_performance, args=(testing_cython.prime_finder_vanilla, 300))
    # res1 = res1.get()
    res2 = pool.apply_async(check_performance, args=(testing_cython.prime_finder_optimized, 300))
    # res2 = res2.get()
    pool.close()
    pool.join()
    print(f"With multiprocessing: {time.perf_counter() - starting_time} seconds")
    # print(f"{res1=}\n{res2=}\n{res1/res2=}")

    print('-' * 30)

    starting_time = time.perf_counter()
    check_performance(testing_cython.prime_finder_vanilla, 300)
    print(f"After vanilla sequentially: {time.perf_counter() - starting_time}")
    check_performance(testing_cython.prime_finder_optimized, 300)
    print(f"Without multiprocessing: {time.perf_counter() - starting_time} seconds")

```
<p>Basically what it does is it takes any function <code>fn</code>, the amount of tests we want to do <code>tests_amount</code>, and the starting point to check the primes <code>tests_amount_start</code>, so if we give it <code>tests_amount=5</code> and leave <code>tests_amount_start</code> as it is, it will return the average runtime of: <code>fn(1000), f(1001), f(1002), f(1003), f(1004), f(1005)</code></p>
<p>Getting this result:</p>
```With multiprocessing: 5.528125900003943 seconds
------------------------------
After vanilla sequentially: 4.921810699997877
Without multiprocessing: 5.678506500000367 seconds
```

What I don't get is that simple math:

If sequentially the average running time of the vanilla is 4.9218 and the whole process sequentially took 5.678, this means that on average, the optimized version should take 5.678 - 4.921 = 0.757.

So, why is it with multiprocessing it takes 5.528 and not 4.921 - which is the running time of the heavy vanilla code? because the optimized version was running in parallel to the vanilla, it should be "included" in the total runtime... no?

What am I missing?

Body:
Got to give credit to NeuralNine video about Cython - from here I got the code.

Here I have a .pyx that contains two functions that are doing the same thing, which is given an integer amount returns a list of all the prime numbers below that number.

prime_finder_vanilla - Pure python

prime_finder_optimized - Cython

def prime_finder_vanilla(amount):
    primes = []
    found = 0
    number = 2
    while found < amount:
        for x in primes:
            if number % x == 0:
                break
        else:
            primes.append(number)
            found += 1
        number += 1
    return primes

def prime_finder_optimized(int amount):
    cdef int number, x, found
    cdef int primes[100_000]

    amount = min(amount, 100_000)
    found = 0
    number = 2
    while found < amount:
        for x in primes[:found]:
            if number % x == 0:
                break
        else:
            primes[found] = number
            found += 1

        number += 1

    return_list = [p for p in primes[:found]] # <--- ?! why not just return primes[:found] lol
    return return_list

I've compiled the file with the command line:

python setup.py build_ext --inplace

setup.py

from setuptools import setup
from Cython.Build import cythonize

setup  (
    ext_modules=cythonize('testing_cython.pyx')
)

Now, I did run both functions, and it really seems that the Cython implementation is faster! but what I always like to do, is build a third part method that runs these functions for a given range, and calculates the average time it took to run these functions and get more accurate statistics of how optimized it really is.

So this is my "third party optimization analysis" file:

import time
from multiprocessing import Pool

import testing_cython

def check_performance(fn, tests_amount, tests_amount_start=1_000):
    times = []

    for amount in range(tests_amount_start, tests_amount_start + tests_amount + 1):
        start = time.perf_counter()
        fn(amount)
        times.append(time.perf_counter() - start)

    return sum(times) / len(times)

if __name__ == '__main__':
    starting_time = time.perf_counter()
    pool = Pool(processes=2)
    res1 = pool.apply_async(check_performance, args=(testing_cython.prime_finder_vanilla, 300))
    # res1 = res1.get()
    res2 = pool.apply_async(check_performance, args=(testing_cython.prime_finder_optimized, 300))
    # res2 = res2.get()
    pool.close()
    pool.join()
    print(f"With multiprocessing: {time.perf_counter() - starting_time} seconds")
    # print(f"{res1=}\n{res2=}\n{res1/res2=}")

    print('-' * 30)

    starting_time = time.perf_counter()
    check_performance(testing_cython.prime_finder_vanilla, 300)
    print(f"After vanilla sequentially: {time.perf_counter() - starting_time}")
    check_performance(testing_cython.prime_finder_optimized, 300)
    print(f"Without multiprocessing: {time.perf_counter() - starting_time} seconds")

Basically what it does is it takes any function fn, the amount of tests we want to do tests_amount, and the starting point to check the primes tests_amount_start, so if we give it tests_amount=5 and leave tests_amount_start as it is, it will return the average runtime of: fn(1000), f(1001), f(1002), f(1003), f(1004), f(1005)

Getting this result:

With multiprocessing: 5.528125900003943 seconds
------------------------------
After vanilla sequentially: 4.921810699997877
Without multiprocessing: 5.678506500000367 seconds

What I don't get is that simple math:

If sequentially the average running time of the vanilla is 4.9218 and the whole process sequentially took 5.678, this means that on average, the optimized version should take 5.678 - 4.921 = 0.757.

So, why is it with multiprocessing it takes 5.528 and not 4.921 - which is the running time of the heavy vanilla code? because the optimized version was running in parallel to the vanilla, it should be "included" in the total runtime... no?

What am I missing?


问:
How can i order data by specific String Field
i have the following get method

```<code>  FirebaseFirestore.instance.collection('comments').limit(5)
        .orderBy('commentDate',descending: true)
        .get(const GetOptions(source: Source.server)).then((value){
          //outputs
          today
          yestrday
          oldest
          oldest
          oldest

       });
</code>```

in previous method i am sorting comments according to the latest .

one of the fields is commentOwnerId : Lx33AN0RwDEWzO7T3xQV.

Perhaps the owner of the comment is not the most recent , However, I want to show it as a priority over the rest of the documents .

```<code>  FirebaseFirestore.instance.collection('comments').limit(5)
        .orderBy('commentOwnerId ',descending: true) // here i am stack
        .orderBy('commentDate',descending: true)
        .get(const GetOptions(source: Source.server)).then((value){
          //outputs
          myComment (yesterday)
          today
          oldest
          oldest
          oldest

       });
</code>```

i notice if the commentOwnerId field is Boolean instead of string value so it work as expected
but of course i cannot use Boolean since i need to chick if it was == my id or no then descending it to true if it was mine .

How could i handle it ?

Body:
i have the following get method

  FirebaseFirestore.instance.collection('comments').limit(5)
        .orderBy('commentDate',descending: true)
        .get(const GetOptions(source: Source.server)).then((value){
          //outputs
          today
          yestrday
          oldest
          oldest
          oldest

       });

in previous method i am sorting comments according to the latest .

one of the fields is commentOwnerId : Lx33AN0RwDEWzO7T3xQV.

Perhaps the owner of the comment is not the most recent , However, I want to show it as a priority over the rest of the documents .

  FirebaseFirestore.instance.collection('comments').limit(5)
        .orderBy('commentOwnerId ',descending: true) // here i am stack
        .orderBy('commentDate',descending: true)
        .get(const GetOptions(source: Source.server)).then((value){
          //outputs
          myComment (yesterday)
          today
          oldest
          oldest
          oldest

       });

i notice if the commentOwnerId field is Boolean instead of string value so it work as expected
but of course i cannot use Boolean since i need to chick if it was == my id or no then descending it to true if it was mine .

How could i handle it ?