Untitled

From Sole Pheasant, 1 Week ago, written in Plain Text, viewed 4 times. This paste will bite the big one in 2 Weeks.
URL https://paste.afonso.co/view/d103bc6e Embed
Download Paste or View Raw
  1. # -*- encoding: utf-8 -*-
  2. clr.AddReference("System.IO")
  3. from System.IO import *
  4.  
  5. clr.AddReference("SpreadsheetLight")
  6. from SpreadsheetLight import SLDocument
  7. from datetime import datetime
  8. from collections import defaultdict
  9.  
  10.  
  11. class PadelHelper:
  12.     def __init__(self):
  13.         pass
  14.  
  15.     def GetPlayers(self, team):
  16.         backhand = None
  17.         drive = None
  18.  
  19.         for player in team.InPlay:
  20.             if player.Function.ToString() == "Backhand":
  21.                 backhand = player
  22.             elif player.Function.ToString() == "Drive":
  23.                 drive = player
  24.  
  25.         if not backhand:
  26.             Core.StatusManager.Add(team.ShortName + " doesn't have Backhand player")
  27.         if not drive:
  28.             Core.StatusManager.Add(team.ShortName + " doesn't have Drive player")
  29.  
  30.         if not backhand or not drive:
  31.             return None, None
  32.         else:
  33.             return backhand, drive
  34.  
  35.     def GetCountryFlag(self, countryInitials):
  36.         filePath = ProjectSettings["ImagesFolderPath"] + "\\Flags\\" + countryInitials + ".png"
  37.  
  38.         if not File.Exists(filePath):
  39.             return ProjectSettings["ImagesFolderPath"] + "\\empty.png"
  40.         return filePath.Replace("\\", "/")
  41.  
  42.     def GetSponsors(self, projectSettings, folder, sponsorNumber, render=""):
  43.         filePath = projectSettings["ImagesFolderPath"] + "\\Sponsors\\" + folder + "\\"
  44.  
  45.         if render == "GLOBAL":
  46.             filePath = projectSettings["ImagesFolderPath"] + "\\Sponsors\\" + folder + "\\GLOBAL\\"
  47.         if render == "RESTRICTED":
  48.             filePath = projectSettings["ImagesFolderPath"] + "\\Sponsors\\" + folder + "\\RESTRICTED\\"
  49.  
  50.         if not Directory.Exists(filePath):
  51.             return (False, "", "Directory '{}' does not exist".format(filePath))
  52.  
  53.         files = Directory.GetFiles(filePath)
  54.  
  55.         for f in files:
  56.             fileName = Path.GetFileName(f)
  57.             if fileName.startswith(sponsorNumber):
  58.                 return (True, f, "")
  59.  
  60.         return (False, "", "Image with number '{}' not found in folder '{}'".format(sponsorNumber, filePath))
  61.  
  62.     def GetTournamentBadge(self):
  63.         filePath = ProjectSettings["ImagesFolderPath"] + "\\CompetitionBadges\\competition_badge_worldChamp.png"
  64.  
  65.         if not File.Exists(filePath):
  66.             return ProjectSettings["ImagesFolderPath"] + "\\empty.png"
  67.         return filePath.Replace("\\", "/")
  68.  
  69.     def GetTournamenticon(self):
  70.         filePath = ProjectSettings["ImagesFolderPath"] + "\\CompetitionBadges\\competitionlogo_World.png"
  71.  
  72.         if not File.Exists(filePath):
  73.             return ProjectSettings["ImagesFolderPath"] + "\\empty.png"
  74.         return filePath.Replace("\\", "/")
  75.  
  76.     def GetTimelineSponsor(self):
  77.         filePath = ProjectSettings["ImagesFolderPath"] + "\\Sponsors_Timeline\\sponsorTimeline.png"
  78.  
  79.         if not File.Exists(filePath):
  80.             return ProjectSettings["ImagesFolderPath"] + "\\empty.png"
  81.         return filePath.Replace("\\", "/")
  82.        
  83.     def GetTimelineCompetitionLogo(self):
  84.         filePath = ProjectSettings["ImagesFolderPath"] + "\\vaz.png"
  85.  
  86.         if not File.Exists(filePath):
  87.             return ProjectSettings["ImagesFolderPath"] + "\\empty.png"
  88.         return filePath.Replace("\\", "/")
  89.  
  90.     def GetSponsor(self):
  91.         filePath = ProjectSettings["ImagesFolderPath"] + "\\Sponsors\\sponsor.png"
  92.  
  93.         if not File.Exists(filePath):
  94.             return ProjectSettings["ImagesFolderPath"] + "\\empty.png"
  95.         return filePath.Replace("\\", "/")
  96.  
  97.     def GetOnlineSponsor(self):
  98.         filePath = ProjectSettings["ImagesFolderPath"] + "\\Sponsors\\sponsor_online.png"
  99.  
  100.         if not File.Exists(filePath):
  101.             return ProjectSettings["ImagesFolderPath"] + "\\empty.png"
  102.         return filePath.Replace("\\", "/")
  103.  
  104.     def GetPhoto(self, officialname):
  105.         filePath = ProjectSettings["ImagesFolderPath"] + "\\Photos\\" + officialname + ".webp"
  106.  
  107.         if not File.Exists(filePath):
  108.                         filePath = ProjectSettings["ImagesFolderPath"] + "\\Photos\\" + officialname + ".png"
  109.                         if not File.Exists(filePath):
  110.                                 return ProjectSettings["ImagesFolderPath"] + "\\empty.png"
  111.         return filePath.Replace("\\", "/")
  112.  
  113.     def GetPhotoTeam(self, officialname, teamFolder):
  114.         imagesFolder = ProjectSettings["ImagesFolderPath"]
  115.         folderPath = imagesFolder + "\\Photos\\" + teamFolder
  116.         filePath = folderPath + "\\" + officialname + ".webp"
  117.         logPath = Path.GetTempPath() + "PadelHelper_photos.log"
  118.  
  119.         try:
  120.             logText = "GetPhotoTeam | name={0} | teamFolder={1} | imagesFolder={2} | candidate={3} | exists={4}".format(
  121.                 officialname,
  122.                 teamFolder,
  123.                 imagesFolder,
  124.                 filePath,
  125.                 File.Exists(filePath)
  126.             )
  127.  
  128.             if Directory.Exists(folderPath):
  129.                 fileNames = [Path.GetFileName(f) for f in Directory.GetFiles(folderPath)]
  130.                 logText += " | folderFiles=" + ", ".join(fileNames)
  131.             else:
  132.                 logText += " | folderExists=False"
  133.  
  134.             File.AppendAllText(logPath, logText + "\r\n")
  135.         except Exception as ex:
  136.             File.AppendAllText(logPath, "GetPhotoTeam logging error: " + str(ex) + "\r\n")
  137.  
  138.         if not File.Exists(filePath):
  139.             return imagesFolder + "\\empty.png"
  140.  
  141.         return filePath.Replace("\\", "/")
  142.     def GetIcon(self, refname):
  143.         dirPath = ProjectSettings["ImagesFolderPath"] + "\\Icons\\"
  144.         filePath = Path.Combine(dirPath, refname + ".png")
  145.  
  146.         if not File.Exists(filePath):
  147.             dirPath = ProjectSettings["ImagesFolderPath"] + "\\"
  148.             filePath = Path.Combine(dirPath, "empty.png")
  149.         return filePath.Replace("\\", "/")
  150.  
  151.     def GetAdvert(self, refname, engine):
  152.         filePath = ProjectSettings["ImagesFolderPath"] + "\\Adverts\\" + engine + "\\" + refname + ".png"
  153.  
  154.         if not File.Exists(filePath):
  155.             return False, ProjectSettings["ImagesFolderPath"] + "\\empty.png"
  156.  
  157.         return True, filePath.Replace("\\", "/")
  158.  
  159.     def GetVirtual(self, refname, engine):
  160.         filePath = ProjectSettings["ImagesFolderPath"] + "\\Virtuals\\" + engine + "\\" + refname + ".png"
  161.  
  162.         if not File.Exists(filePath):
  163.             return False, ProjectSettings["ImagesFolderPath"] + "\\empty.png"
  164.  
  165.         return True, filePath.Replace("\\", "/")
  166.  
  167.     def GetSceneName(self, sceneFullName):
  168.         last_slash_index = sceneFullName.rfind("/")
  169.  
  170.         if last_slash_index != -1:
  171.             text_after_last_slash = sceneFullName[last_slash_index + 1:]
  172.         else:
  173.             text_after_last_slash = sceneFullName
  174.  
  175.         return text_after_last_slash
  176.  
  177.     def GetBanner(self, refname, engine):
  178.         filePath = ProjectSettings["ImagesFolderPath"] + "\\Banners\\" + engine + "\\" + refname + ".png"
  179.  
  180.         if not File.Exists(filePath):
  181.             return False, ProjectSettings["ImagesFolderPath"] + "\\empty.png"
  182.  
  183.         return True, filePath.Replace("\\", "/")
  184.  
  185.     def GetSpecial(self, refname, engine):
  186.         filePath = ProjectSettings["ImagesFolderPath"] + "\\Special_Scenes\\" + engine + "\\" + refname + ".png"
  187.  
  188.         if not File.Exists(filePath):
  189.             return False, ProjectSettings["ImagesFolderPath"] + "\\empty.png"
  190.  
  191.         return True, filePath.Replace("\\", "/")
  192.  
  193.     def GetCountryNameAndInitials(self, verify=False):
  194.         homeCountry = ActiveObjects.HomeTeam.Attributes["COUNTRY"].Value if ActiveObjects.HomeTeam.Attributes["COUNTRY"] else ""
  195.         awayCountry = ActiveObjects.AwayTeam.Attributes["COUNTRY"].Value if ActiveObjects.AwayTeam.Attributes["COUNTRY"] else ""
  196.         homeCountryInitials = ActiveObjects.HomeTeam.Attributes["COUNTRY INITIALS"].Value if ActiveObjects.HomeTeam.Attributes["COUNTRY INITIALS"] else ""
  197.         awayCountryInitials = ActiveObjects.AwayTeam.Attributes["COUNTRY INITIALS"].Value if ActiveObjects.AwayTeam.Attributes["COUNTRY INITIALS"] else ""
  198.  
  199.         if verify:
  200.             verifyCountry = []
  201.  
  202.             if not homeCountry:
  203.                 verifyCountry.append("#Please Fill Home Country parameter")
  204.  
  205.             if not awayCountry:
  206.                 verifyCountry.append("#Please Fill Away Country parameter")
  207.  
  208.             if not homeCountryInitials:
  209.                 verifyCountry.append("#Please Fill Home Country Initials parameter")
  210.  
  211.             if not awayCountryInitials:
  212.                 verifyCountry.append("#Please Fill Away Country Initials parameter")
  213.  
  214.             if len(verifyCountry) > 0:
  215.                 Core.StatusManager.Add("\n".join(verifyCountry))
  216.                 return False
  217.             else:
  218.                 return True
  219.  
  220.         return (homeCountry, homeCountryInitials, awayCountry, awayCountryInitials)
  221.  
  222.     def GetStandingsXlsxData(self, type):
  223.         group = Globals["frmController"].Controls["cmbGroup"].Text
  224.         filePath = ProjectSettings["Excels Path"] + "\\PadelGames.xlsx"
  225.         sheet = "%s_Group_%s" % (type, group)
  226.  
  227.         ws = SLDocument(filePath, sheet)
  228.         NRows = ws.GetWorksheetStatistics().EndRowIndex - 1
  229.  
  230.         matches = []
  231.  
  232.         # =====================================================
  233.         # FUNCAO AUXILIAR PARA CONVERTER VALORES NUMERICOS
  234.         # =====================================================
  235.         def safeInt(value, default=0):
  236.             try:
  237.                 value = str(value).strip()
  238.                 if value == "":
  239.                     return default
  240.                 return int(value)
  241.             except:
  242.                 return default
  243.  
  244.         # =====================================================
  245.         # LER OS JOGOS DO EXCEL
  246.         # =====================================================
  247.         for i in range(NRows):
  248.             if ws.GetCellValueAsString(i + 2, 1):
  249.                 confronto = ws.GetCellValueAsString(i + 2, 1).Trim()
  250.                 game = ws.GetCellValueAsString(i + 2, 2).ToString()
  251.                 hometeam = ws.GetCellValueAsString(i + 2, 3).Trim()
  252.                 hometeamInitials = ws.GetCellValueAsString(i + 2, 4).Trim()
  253.  
  254.                 hometeamSetsWin = ws.GetCellValueAsString(i + 2, 5).Trim()
  255.  
  256.                 orderHomeRaw = ws.GetCellValueAsString(i + 2, 6).Trim()
  257.                 orderAwayRaw = ws.GetCellValueAsString(i + 2, 7).Trim()
  258.  
  259.                 awayteamSetsWin = ws.GetCellValueAsString(i + 2, 8).Trim()
  260.                 awayteam = ws.GetCellValueAsString(i + 2, 9).Trim()
  261.                 awayteamInitials = ws.GetCellValueAsString(i + 2, 10).Trim()
  262.  
  263.                 homeParticipants = ws.GetCellValueAsString(i + 2, 11).Trim().split("|")
  264.                 awayParticipants = ws.GetCellValueAsString(i + 2, 12).Trim().split("|")
  265.  
  266.                 # Converter ordens manuais para numeros
  267.                 orderHome = None
  268.                 orderAway = None
  269.  
  270.                 if orderHomeRaw != "":
  271.                     try:
  272.                         orderHome = int(orderHomeRaw)
  273.                     except:
  274.                         orderHome = None
  275.  
  276.                 if orderAwayRaw != "":
  277.                     try:
  278.                         orderAway = int(orderAwayRaw)
  279.                     except:
  280.                         orderAway = None
  281.  
  282.                 # Converter sets vazios para zero
  283.                 homeSetsValue = safeInt(hometeamSetsWin)
  284.                 awaySetsValue = safeInt(awayteamSetsWin)
  285.  
  286.                 # Determinar vencedor do jogo
  287.                 confrontoWin = None
  288.  
  289.                 if homeSetsValue > awaySetsValue and homeSetsValue >= 2:
  290.                     confrontoWin = hometeam
  291.                 elif awaySetsValue > homeSetsValue and awaySetsValue >= 2:
  292.                     confrontoWin = awayteam
  293.  
  294.                 matches.append([
  295.                     confronto,
  296.                     game,
  297.                     hometeam,
  298.                     hometeamInitials,
  299.                     homeSetsValue,
  300.                     awayteam,
  301.                     awaySetsValue,
  302.                     awayteamInitials,
  303.                     confrontoWin,
  304.                     homeParticipants,
  305.                     awayParticipants,
  306.                     orderHome,
  307.                     orderAway
  308.                 ])
  309.  
  310.         # =====================================================
  311.         # ESTRUTURA DE DADOS DAS ESTATISTICAS
  312.         # =====================================================
  313.         stats = defaultdict(lambda: {
  314.             'initials': None,
  315.             'sets_won': 0,
  316.             'sets_lost': 0,
  317.             'matches_won': 0,
  318.             'matches_lost': 0,
  319.             'points': 0,
  320.             'games_played': 0,
  321.             'home_participants': None,
  322.             'away_participants': None,
  323.             'order': None
  324.         })
  325.  
  326.         # =====================================================
  327.         # AGRUPAR OS JOGOS POR CONFRONTO
  328.         # =====================================================
  329.         confrontos = defaultdict(list)
  330.  
  331.         for match in matches:
  332.             confronto = match[0]
  333.             confrontos[confronto].append(match)
  334.  
  335.         # =====================================================
  336.         # PROCESSAR CADA CONFRONTO
  337.         # =====================================================
  338.         for confronto, games in confrontos.items():
  339.  
  340.             for game in games:
  341.                 (
  342.                     _,
  343.                     date_str,
  344.                     home_team,
  345.                     home_initials,
  346.                     home_sets,
  347.                     away_team,
  348.                     away_sets,
  349.                     away_initials,
  350.                     winner,
  351.                     homeParticipants,
  352.                     awayParticipants,
  353.                     orderHome,
  354.                     orderAway
  355.                 ) = game
  356.  
  357.                 # Garantir que os sets sao sempre numeros
  358.                 home_sets = safeInt(home_sets)
  359.                 away_sets = safeInt(away_sets)
  360.  
  361.                 stats[home_team]['home_participants'] = homeParticipants
  362.                 stats[away_team]['away_participants'] = awayParticipants
  363.  
  364.                 stats[home_team]['initials'] = home_initials
  365.                 stats[away_team]['initials'] = away_initials
  366.  
  367.                 # Guardar a ordem manual, quando existe
  368.                 if orderHome is not None:
  369.                     stats[home_team]['order'] = orderHome
  370.  
  371.                 if orderAway is not None:
  372.                     stats[away_team]['order'] = orderAway
  373.  
  374.                 # Atualizar jogos jogados
  375.                 if home_sets > 0 or away_sets > 0:
  376.                     stats[home_team]['games_played'] += 1
  377.                     stats[away_team]['games_played'] += 1
  378.  
  379.                 # Atualizar sets ganhos e perdidos
  380.                 stats[home_team]['sets_won'] += home_sets
  381.                 stats[home_team]['sets_lost'] += away_sets
  382.  
  383.                 stats[away_team]['sets_won'] += away_sets
  384.                 stats[away_team]['sets_lost'] += home_sets
  385.  
  386.                 # =================================================
  387.                 # ATUALIZAR PARTIDAS GANHAS, PERDIDAS E PONTOS
  388.                 # VITORIA = 2 PONTOS
  389.                 # DERROTA = 1 PONTO
  390.                 # =================================================
  391.                 if winner is not None:
  392.                     if winner == home_team:
  393.                         stats[home_team]['matches_won'] += 1
  394.                         stats[away_team]['matches_lost'] += 1
  395.  
  396.                         stats[home_team]['points'] += 2
  397.                         stats[away_team]['points'] += 1
  398.  
  399.                     elif winner == away_team:
  400.                         stats[away_team]['matches_won'] += 1
  401.                         stats[home_team]['matches_lost'] += 1
  402.  
  403.                         stats[away_team]['points'] += 2
  404.                         stats[home_team]['points'] += 1
  405.  
  406.         # =====================================================
  407.         # VERIFICAR SE TODAS AS EQUIPAS TEM ORDEM MANUAL
  408.         # =====================================================
  409.         hasOrder = True
  410.  
  411.         for team, stat in stats.items():
  412.             if stat['order'] is None or stat['order'] <= 0:
  413.                 hasOrder = False
  414.                 break
  415.  
  416.         # =====================================================
  417.         # ORDENAR A CLASSIFICACAO
  418.         # =====================================================
  419.         if hasOrder:
  420.             sorted_stats = sorted(
  421.                 stats.items(),
  422.                 key=lambda x: x[1]['order']
  423.             )
  424.  
  425.         else:
  426.             sorted_stats = sorted(
  427.                 stats.items(),
  428.                 key=lambda x: (
  429.                     x[1]['points'],
  430.                     x[1]['matches_won'],
  431.                     x[1]['sets_won'] - x[1]['sets_lost'],
  432.                     x[1]['sets_won']
  433.                 ),
  434.                 reverse=True
  435.             )
  436.  
  437.         return sorted_stats, confrontos
  438.  
  439.  
  440. def Run():
  441.     Globals["PadelHelper"] = PadelHelper()

Reply to "Untitled"

Here you can reply to the paste above