row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
38,849
j'ai cette page php : <?php use DB\DataBaseManager; $manager = new DataBaseManager(); $artistDB = $manager->getArtistDB(); $liste_artistes = $artistDB->findAll(); $pageSize = 10; $page = isset($_GET['page']) ? intval($_GET['page']) : 1; $offset = ($page - 1) * $pageSize; $sonDB = $manager->getSonDB(); $liste_sons = $sonDB->findAll($offset, $pageSize); $genreDB = $manager->getGenreDB(); $liste_genres = $genreDB->findAll(); $utilisateurDB = $manager->getUtilisateurDB(); $liste_utilisateurs = $utilisateurDB->findAll(); $playlistDB = $manager->getPlaylistDB(); $liste_playlists = $playlistDB->findAll(); $albumDB = $manager->getAlbumDB(); $liste_albums = $albumDB->findAll(); ?> <aside> <div class="left"> <a href="index.php?action=accueil" class="btn-retour"> <svg width="26" height="16" viewBox="0 0 26 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M8.22816 1.73682L2.00009 7.96489M2.00009 7.96489L8.22816 14.193M2.00009 7.96489H24.4211" stroke="currentColor" stroke-width="2.49123" stroke-linecap="round" stroke-linejoin="round"/> </svg> Retour application </a> <nav> <ul> <li> <a href="" id="goToMenuPrincipal"> <svg width="27" height="17" viewBox="0 0 27 17" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M1.83325 1.2085H25.1666M1.83325 8.50016H25.1666M1.83325 15.7918H25.1666" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> Menu principal </a> </li> <li> <a href="" id="goToArtistes"> <svg width="30" height="23" viewBox="0 0 30 23" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M23.9866 21.7082H26.1667C27.7775 21.7082 29.1809 20.3606 28.6692 18.8332C27.8893 16.5055 25.9706 15.0979 22.5977 14.6103M18.146 9.84388C18.5703 9.97801 19.0564 10.0415 19.6042 10.0415C22.0347 10.0415 23.25 8.7915 23.25 5.6665C23.25 2.5415 22.0347 1.2915 19.6042 1.2915C19.0564 1.2915 18.5703 1.355 18.146 1.48913M10.8542 14.4165C16.6277 14.4165 19.4474 16.1838 20.1527 19.7183C20.3689 20.8015 19.4379 21.7082 18.3333 21.7082H3.375C2.27043 21.7082 1.33943 20.8015 1.5556 19.7183C2.26098 16.1838 5.08064 14.4165 10.8542 14.4165ZM10.8542 10.0415C13.2847 10.0415 14.5 8.7915 14.5 5.6665C14.5 2.5415 13.2847 1.2915 10.8542 1.2915C8.42361 1.2915 7.20833 2.5415 7.20833 5.6665C7.20833 8.7915 8.42361 10.0415 10.8542 10.0415Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> Artistes </a> </li> <li> <a href="" id="goToSons"> <svg width="29" height="29" viewBox="0 0 29 29" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M5.75 14.5C5.75 11.2613 7.50962 8.43351 10.125 6.92059M23.25 14.2123C23.25 17.451 21.4904 20.2788 18.875 21.7917M27.625 14.5C27.625 21.7487 21.7487 27.625 14.5 27.625C7.25126 27.625 1.375 21.7487 1.375 14.5C1.375 7.25126 7.25126 1.375 14.5 1.375C21.7487 1.375 27.625 7.25126 27.625 14.5ZM17.4167 14.5C17.4167 16.1108 16.1108 17.4167 14.5 17.4167C12.8892 17.4167 11.5833 16.1108 11.5833 14.5C11.5833 12.8892 12.8892 11.5833 14.5 11.5833C16.1108 11.5833 17.4167 12.8892 17.4167 14.5Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> Sons </a> </li> <li> <a href="" id="goToGenres"> <svg width="23" height="20" viewBox="0 0 23 20" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M1.29175 7.04183H15.8751M1.29175 1.2085H15.8751M1.29175 12.8752H10.0417M15.8751 12.8752V18.7085L21.7084 15.7918L15.8751 12.8752Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> Genres </a> </li> <li> <a href="" id="goToUtilisateurs"> <svg width="23" height="27" viewBox="0 0 23 27" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M18.2405 24.7722C19.8065 24.7722 21.1404 23.4819 20.7854 21.9567C19.9025 18.1628 16.9499 16.2658 11.1519 16.2658C5.35387 16.2658 2.40129 18.1628 1.51836 21.9567C1.16341 23.4819 2.49732 24.7722 4.06329 24.7722H18.2405Z" stroke="currentColor" stroke-width="2.83544" stroke-linecap="round" stroke-linejoin="round"/> <path fill-rule="evenodd" clip-rule="evenodd" d="M11.1519 12.0127C13.9873 12.0127 15.4051 10.5949 15.4051 7.05063C15.4051 3.50633 13.9873 2.08861 11.1519 2.08861C8.31645 2.08861 6.89873 3.50633 6.89873 7.05063C6.89873 10.5949 8.31645 12.0127 11.1519 12.0127Z" stroke="currentColor" stroke-width="2.83544" stroke-linecap="round" stroke-linejoin="round"/> </svg> Utilisateurs </a> </li> <li> <a href="" id="goToPlaylists"> <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M1 3C1 1.89543 1.89543 1 3 1H4C5.10457 1 6 1.89543 6 3V4C6 5.10457 5.10457 6 4 6H3C1.89543 6 1 5.10457 1 4V3Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> <path d="M10 3C10 1.89543 10.8954 1 12 1H13C14.1046 1 15 1.89543 15 3V4C15 5.10457 14.1046 6 13 6H12C10.8954 6 10 5.10457 10 4V3Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> <path d="M1 12C1 10.8954 1.89543 10 3 10H4C5.10457 10 6 10.8954 6 12V13C6 14.1046 5.10457 15 4 15H3C1.89543 15 1 14.1046 1 13V12Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> <path d="M10 12C10 10.8954 10.8954 10 12 10H13C14.1046 10 15 10.8954 15 12V13C15 14.1046 14.1046 15 13 15H12C10.8954 15 10 14.1046 10 13V12Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> Playlists </a> </li> <li> <a href="" id="goToAlbums"> <svg width="27" height="27" viewBox="0 0 27 27" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M8.8125 21.8333C8.8125 24.1345 7.06361 26 4.90625 26C2.74889 26 1 24.1345 1 21.8333C1 19.5321 2.74889 17.6667 4.90625 17.6667C7.06361 17.6667 8.8125 19.5321 8.8125 21.8333ZM8.8125 21.8333V3.57439C8.8125 3.05949 9.20349 2.62875 9.71598 2.57906L24.9035 1.10633C25.4912 1.04934 26 1.51124 26 2.10166V20.1667M26 20.1667C26 22.4679 24.2511 24.3333 22.0938 24.3333C19.9364 24.3333 18.1875 22.4679 18.1875 20.1667C18.1875 17.8655 19.9364 16 22.0938 16C24.2511 16 26 17.8655 26 20.1667Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> Albums </a> </li> </ul> <div class="active-square" id="activeSquare"></div> </nav> <div class="actions"> <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M10 6V14M14 10H6M10 19C14.9706 19 19 14.9706 19 10C19 5.02944 14.9706 1 10 1C5.02944 1 1 5.02944 1 10C1 14.9706 5.02944 19 10 19Z" stroke="#E2FF08" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> </div> </div> </aside> <div class="right"> <!-- barre de recherche --> <div id="recherche" class="wrapper-recherche"> <div class="text-field"> <img src="/Assets/icons/search.svg" alt="user"/> <input type="text" placeholder="Ma recherche" value=""> </div> </div> <div class="container-tabs"> <main> <section id="pagePrincipale" class="page"> <header> <h2>Menu principal</h2> <svg width="29" height="29" viewBox="0 0 39 39" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M37.6118 9.82166L27.9072 14.9928C32.319 9.33028 28.353 1.28109 19.1767 0V9.98935C15.8932 3.95635 6.60488 3.25634 0.923272 9.82361L10.2961 14.8173C2.99181 14.4254 -2.30948 21.4977 1.01413 29.3226L10.8413 24.0871C6.34922 29.619 9.45097 38.5008 19.1746 39V28.1059C21.8685 34.7941 32.0717 37.0091 37.5188 29.3226L27.2966 23.8766C34.9199 25.066 42.0996 18.019 37.6118 9.82361V9.82166Z" fill="#E2FF08"/> </svg> </header> <div class="menu"> <button class="admin-content"> <svg width="29" height="29" viewBox="0 0 30 23" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M23.9866 21.7082H26.1667C27.7775 21.7082 29.1809 20.3606 28.6692 18.8332C27.8893 16.5055 25.9706 15.0979 22.5977 14.6103M18.146 9.84388C18.5703 9.97801 19.0564 10.0415 19.6042 10.0415C22.0347 10.0415 23.25 8.7915 23.25 5.6665C23.25 2.5415 22.0347 1.2915 19.6042 1.2915C19.0564 1.2915 18.5703 1.355 18.146 1.48913M10.8542 14.4165C16.6277 14.4165 19.4474 16.1838 20.1527 19.7183C20.3689 20.8015 19.4379 21.7082 18.3333 21.7082H3.375C2.27043 21.7082 1.33943 20.8015 1.5556 19.7183C2.26098 16.1838 5.08064 14.4165 10.8542 14.4165ZM10.8542 10.0415C13.2847 10.0415 14.5 8.7915 14.5 5.6665C14.5 2.5415 13.2847 1.2915 10.8542 1.2915C8.42361 1.2915 7.20833 2.5415 7.20833 5.6665C7.20833 8.7915 8.42361 10.0415 10.8542 10.0415Z" stroke="#FEFCE1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> <div class="textes"> <h3>Artistes</h3> <p>Les artistes de l'application</p> </div> </button> <button class="admin-content"> <svg width="29" height="29" viewBox="0 0 29 29" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M5.75 14.5C5.75 11.2613 7.50962 8.43351 10.125 6.92059M23.25 14.2123C23.25 17.451 21.4904 20.2788 18.875 21.7917M27.625 14.5C27.625 21.7487 21.7487 27.625 14.5 27.625C7.25126 27.625 1.375 21.7487 1.375 14.5C1.375 7.25126 7.25126 1.375 14.5 1.375C21.7487 1.375 27.625 7.25126 27.625 14.5ZM17.4167 14.5C17.4167 16.1108 16.1108 17.4167 14.5 17.4167C12.8892 17.4167 11.5833 16.1108 11.5833 14.5C11.5833 12.8892 12.8892 11.5833 14.5 11.5833C16.1108 11.5833 17.4167 12.8892 17.4167 14.5Z" stroke="#FEFCE1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> <div class="textes"> <h3>Sons</h3> <p>Les sons de l'application</p> </div> </butt> <button class="admin-content"> <svg width="29" height="29" viewBox="0 0 23 20" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M1.29175 7.04183H15.8751M1.29175 1.2085H15.8751M1.29175 12.8752H10.0417M15.8751 12.8752V18.7085L21.7084 15.7918L15.8751 12.8752Z" stroke="#FEFCE1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> <div class="textes"> <h3>Genres</h3> <p>Les genres de l'application</p> </div> </button> <button class="admin-content"> <svg width="29" height="29" viewBox="0 0 23 27" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M18.2405 24.7722C19.8065 24.7722 21.1404 23.4819 20.7854 21.9567C19.9025 18.1628 16.9499 16.2658 11.1519 16.2658C5.35387 16.2658 2.40129 18.1628 1.51836 21.9567C1.16341 23.4819 2.49732 24.7722 4.06329 24.7722H18.2405Z" stroke="#FEFCE1" stroke-width="2.83544" stroke-linecap="round" stroke-linejoin="round"/> <path fill-rule="evenodd" clip-rule="evenodd" d="M11.1519 12.0127C13.9873 12.0127 15.4051 10.5949 15.4051 7.05063C15.4051 3.50633 13.9873 2.08861 11.1519 2.08861C8.31645 2.08861 6.89873 3.50633 6.89873 7.05063C6.89873 10.5949 8.31645 12.0127 11.1519 12.0127Z" stroke="#FEFCE1" stroke-width="2.83544" stroke-linecap="round" stroke-linejoin="round"/> </svg> <div class="textes"> <h3>Utilisateurs</h3> <p>Les utilisateurs de l'application</p> </div> </button> <button class="admin-content"> <svg width="29" height="29" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M1 3C1 1.89543 1.89543 1 3 1H4C5.10457 1 6 1.89543 6 3V4C6 5.10457 5.10457 6 4 6H3C1.89543 6 1 5.10457 1 4V3Z" stroke="#FEFCE1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> <path d="M10 3C10 1.89543 10.8954 1 12 1H13C14.1046 1 15 1.89543 15 3V4C15 5.10457 14.1046 6 13 6H12C10.8954 6 10 5.10457 10 4V3Z" stroke="#FEFCE1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> <path d="M1 12C1 10.8954 1.89543 10 3 10H4C5.10457 10 6 10.8954 6 12V13C6 14.1046 5.10457 15 4 15H3C1.89543 15 1 14.1046 1 13V12Z" stroke="#FEFCE1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> <path d="M10 12C10 10.8954 10.8954 10 12 10H13C14.1046 10 15 10.8954 15 12V13C15 14.1046 14.1046 15 13 15H12C10.8954 15 10 14.1046 10 13V12Z" stroke="#FEFCE1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> <div class="textes"> <h3>Playlists</h3> <p>Les playlists de l'application</p> </div> </button> <button class="admin-content"> <svg width="18" height="17" viewBox="0 0 18 17" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M6 13.5C6 14.8807 4.88071 16 3.5 16C2.11929 16 1 14.8807 1 13.5C1 12.1193 2.11929 11 3.5 11C4.88071 11 6 12.1193 6 13.5ZM6 13.5V2.91321C6 2.39601 6.39439 1.96415 6.90946 1.91732L15.9095 1.09914C16.4951 1.0459 17 1.507 17 2.09503V12.5M17 12.5C17 13.8807 15.8807 15 14.5 15C13.1193 15 12 13.8807 12 12.5C12 11.1193 13.1193 10 14.5 10C15.8807 10 17 11.1193 17 12.5Z" stroke="#FEFCE1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> <div class="textes"> <h3>Albums</h3> <p>Les albums de l'application</p> </div> </button> </div> </section> <section id="pageArtistes" class="page"> <header> <h2>Artistes</h2> <svg width="29" height="29" viewBox="0 0 39 39" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M37.6118 9.82166L27.9072 14.9928C32.319 9.33028 28.353 1.28109 19.1767 0V9.98935C15.8932 3.95635 6.60488 3.25634 0.923272 9.82361L10.2961 14.8173C2.99181 14.4254 -2.30948 21.4977 1.01413 29.3226L10.8413 24.0871C6.34922 29.619 9.45097 38.5008 19.1746 39V28.1059C21.8685 34.7941 32.0717 37.0091 37.5188 29.3226L27.2966 23.8766C34.9199 25.066 42.0996 18.019 37.6118 9.82361V9.82166Z" fill="#E2FF08"/> </svg> </header> </section> <section id="pageSons" class="page"> <header> <h2>Sons</h2> <svg width="29" height="29" viewBox="0 0 39 39" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M37.6118 9.82166L27.9072 14.9928C32.319 9.33028 28.353 1.28109 19.1767 0V9.98935C15.8932 3.95635 6.60488 3.25634 0.923272 9.82361L10.2961 14.8173C2.99181 14.4254 -2.30948 21.4977 1.01413 29.3226L10.8413 24.0871C6.34922 29.619 9.45097 38.5008 19.1746 39V28.1059C21.8685 34.7941 32.0717 37.0091 37.5188 29.3226L27.2966 23.8766C34.9199 25.066 42.0996 18.019 37.6118 9.82361V9.82166Z" fill="#E2FF08"/> </svg> </header> </section> <section id="pageGenres" class="page"> <header> <h2>Genres</h2> <svg width="29" height="29" viewBox="0 0 39 39" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M37.6118 9.82166L27.9072 14.9928C32.319 9.33028 28.353 1.28109 19.1767 0V9.98935C15.8932 3.95635 6.60488 3.25634 0.923272 9.82361L10.2961 14.8173C2.99181 14.4254 -2.30948 21.4977 1.01413 29.3226L10.8413 24.0871C6.34922 29.619 9.45097 38.5008 19.1746 39V28.1059C21.8685 34.7941 32.0717 37.0091 37.5188 29.3226L27.2966 23.8766C34.9199 25.066 42.0996 18.019 37.6118 9.82361V9.82166Z" fill="#E2FF08"/> </svg> </header> </section> <section id="pageUtilisateurs" class="page"> <header> <h2>Utilisateurs</h2> <svg width="29" height="29" viewBox="0 0 39 39" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M37.6118 9.82166L27.9072 14.9928C32.319 9.33028 28.353 1.28109 19.1767 0V9.98935C15.8932 3.95635 6.60488 3.25634 0.923272 9.82361L10.2961 14.8173C2.99181 14.4254 -2.30948 21.4977 1.01413 29.3226L10.8413 24.0871C6.34922 29.619 9.45097 38.5008 19.1746 39V28.1059C21.8685 34.7941 32.0717 37.0091 37.5188 29.3226L27.2966 23.8766C34.9199 25.066 42.0996 18.019 37.6118 9.82361V9.82166Z" fill="#E2FF08"/> </svg> </header> </section> <section id="pagePlaylists" class="page"> <header> <h2>Playlists</h2> <svg width="29" height="29" viewBox="0 0 39 39" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M37.6118 9.82166L27.9072 14.9928C32.319 9.33028 28.353 1.28109 19.1767 0V9.98935C15.8932 3.95635 6.60488 3.25634 0.923272 9.82361L10.2961 14.8173C2.99181 14.4254 -2.30948 21.4977 1.01413 29.3226L10.8413 24.0871C6.34922 29.619 9.45097 38.5008 19.1746 39V28.1059C21.8685 34.7941 32.0717 37.0091 37.5188 29.3226L27.2966 23.8766C34.9199 25.066 42.0996 18.019 37.6118 9.82361V9.82166Z" fill="#E2FF08"/> </svg> </header> </section> <section id="pageAlbums" class="page"> <header> <h2>Albums</h2> <svg width="29" height="29" viewBox="0 0 39 39" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M37.6118 9.82166L27.9072 14.9928C32.319 9.33028 28.353 1.28109 19.1767 0V9.98935C15.8932 3.95635 6.60488 3.25634 0.923272 9.82361L10.2961 14.8173C2.99181 14.4254 -2.30948 21.4977 1.01413 29.3226L10.8413 24.0871C6.34922 29.619 9.45097 38.5008 19.1746 39V28.1059C21.8685 34.7941 32.0717 37.0091 37.5188 29.3226L27.2966 23.8766C34.9199 25.066 42.0996 18.019 37.6118 9.82361V9.82166Z" fill="#E2FF08"/> </svg> </header> </section> </main> </div> </div> ce css : @font-face { font-family: 'Kicker'; src: url('../fonts/kicker-black/KickerTrial-Black.ttf') format('truetype'); font-weight: 100; font-style: normal; } @font-face { font-family: 'Kicker'; src: url('../fonts/kicker-black/KickerTrial-BlackItalic.ttf') format('truetype'); font-weight: 100; font-style: italic; } @font-face { font-family: 'Kicker'; src: url('../fonts/kicker-bold/KickerTrial-BlackSlanted.ttf') format('truetype'); font-weight: 200; font-style: normal; } @font-face { font-family: 'PP Mori'; src: url('../fonts/pp-mori/PPMori-ExtraLight.otf') format('truetype'); font-weight: 100; font-style: normal; } @font-face { font-family: 'PP Mori'; src: url('../fonts/pp-mori/PPMori-ExtraLightItalic.otf') format('truetype'); font-weight: 100; font-style: italic; } @font-face { font-family: 'PP Mori'; src: url('../fonts/pp-mori/PPMori-Regular.otf') format('truetype'); font-weight: 200; font-style: normal; } @font-face { font-family: 'PP Mori'; src: url('../fonts/pp-mori/PPMori-RegularItalic.otf') format('truetype'); font-weight: 200; font-style: italic; } @font-face { font-family: 'PP Mori'; src: url('../fonts/pp-mori/PPMori-SemiBold.otf') format('truetype'); font-weight: 300; font-style: normal; } @font-face { font-family: 'PP Mori'; src: url('../fonts/pp-mori/PPMori-SemiBoldItalic.otf') format('truetype'); font-weight: 300; font-style: italic; } *{ margin: 0; padding: 0; box-sizing: border-box; } :root { --yellow: #E2FF08; --text-color: #FEFCE1; --text-color-secondary: #7F7E70; --background-color: #000000; --background-secondary: #070808; } body{ background-color: var(--background-color); position: relative; display: flex; justify-content: space-between; font-family: 'PP Mori', sans-serif; min-height: 100vh; max-width: 100vw; overflow:hidden; margin: 0; padding: 0; } nav { position: relative; display: flex; background-color: var(--background-secondary); border-radius: 1rem; padding: 1rem; min-height: 100%; } nav ul { display: flex; flex-direction: column; gap: 0.85rem; height: 100%; list-style: none; position: relative; padding: 0; z-index: 2; } nav ul li { list-style-type: none; width: 100%; } nav .active-square { position: absolute; width: 85%; height: 3.5rem; z-index: 0; background-color: var(--yellow); border-radius: 0.8rem; } nav ul li a { text-decoration: none; color: var(--text-color); gap: 0.7rem; height: 3.5rem; max-height: 3.5rem; display: flex; width: 15.5rem; align-items: center; white-space: nowrap; font-size: 1rem; padding: 1rem; } nav ul li a svg { position: relative; } body .left{ position: relative; width: 15rem; height: 100%; display: flex; gap: 5rem; flex-direction: column; background-color: var(--background-secondary); } body .left img{ align-self: flex-start; } .actions { position: absolute; bottom: 0; right: 0; padding: 1rem; } .actions a { text-decoration: none; font-size: 1rem; margin-left: 1rem; } .btn-retour { cursor: pointer; display: flex; gap:1rem; background-color: var(--background-secondary); border: none; padding: 1.5rem 1rem; border-radius: 1rem; color:var(--yellow); font-family: 'PP Mori'; font-weight: 300; width: 13rem; height: 4.4375rem; font-size: 0.95rem; display: flex; gap: 0.7rem; align-items: center; text-decoration: none; background-color: #0E100F; margin: 1rem 1rem; } .btn-retour a:hover{ filter: brightness(0.8); } .right { position: relative; width: 100%; height: 100%; display: flex; flex-direction: column; } #recherche { background-color: #070808; padding: 1rem 1rem; display: flex; align-items: center; margin-left: 0.7rem; } .text-field{ width: 100%; display: flex; position: relative; padding: 1.625rem 1.875rem; background-color: #070808; color: var(--text-color-secondary); } .text-field img{ height: 1.5rem; } .text-field input{ position: absolute; top: 0; left: 0; width: 100%; height: 100%; padding-left: 6rem; background-color: transparent; border: none; border-bottom: 1.5px solid var(--text-color-secondary); outline: none; color: var(--text-color-secondary); font-family: 'PP Mori'; font-weight: 300; font-size: 1.25rem; transition: all 0.2s ease-in-out; } .text-field.no-space input{ padding-left: 1rem; } .text-field input:focus{ border-bottom: 1.5px solid var(--yellow); transition: all 0.2s ease-in-out; } h2 { font-family: 'PP Mori', sans-serif; font-size: 3rem; font-weight: 300; color: var(--text-color); margin: 3rem 1rem; } header { display: flex; align-items: center; padding-left: 1.5rem } .menu { margin-top: 1rem; display: grid; grid-template-columns: repeat(3, 1fr); grid-template-rows: repeat(2, 1fr); gap: 1.5rem; } .admin-content { margin-top: 1rem; background-color: #070808; display: flex; align-items: center; justify-content: center; width: 24vw; height: 25vh; margin-left: 2rem; border-radius: 1rem; border: none; cursor: pointer; } .textes { display: flex; flex-direction: column; align-items: flex-start; margin-left: 4.5rem; } .textes h3 { margin-top: 1rem; font-family: "PP Mori"; font-weight: 300; color: #FEFCE1; font-size: 2rem; opacity: 50%; } .textes p { font-family: "PP Mori"; font-size: 0.875rem; color: #FEFCE1; opacity: 30%; margin-top: 0.5rem; } .admin-content svg { width: 5rem; height: 4.5rem; } #pagePrincipale { opacity: 1; display: block; } .page { position: absolute; opacity: 0; padding-right: 2rem; width: 100%; display: flex; gap: 1.15rem; height: 100%; } ce js : const activeSquare = document.querySelector("#activeSquare"); const goToMenuPrincipal = document.querySelector("#goToMenuPrincipal"); const goToArtistes = document.querySelector("#goToArtistes"); const goToSons = document.querySelector("#goToSons"); const goToGenres = document.querySelector("#goToGenres"); const goToUtilisateurs = document.querySelector("#goToUtilisateurs"); const goToPlaylists = document.querySelector("#goToPlaylists"); const goToAlbums = document.querySelector("#goToAlbums"); const sectionMenuPrincipal = document.querySelector("#pagePrincipale"); const sectionMenuArtistes = document.querySelector("#pageArtistes"); const sectionMenuSons = document.querySelector("#pageSons"); const sectionMenuGenres = document.querySelector("#pageGenres"); const sectionMenuUtilisateurs = document.querySelector("#pageUtilisateurs"); const sectionMenuPlaylists = document.querySelector("#pagePlaylists"); const sectionMenuAlbums = document.querySelector("#pageAlbums"); function changeCurrentMenu(e, index) { e?.preventDefault(); function clearActiveSections() { if (sectionMenuPrincipal.classList != null) sectionMenuPrincipal.classList.remove("active-section"); if (sectionMenuArtistes.classList != null) sectionMenuArtistes.classList.remove("active-section"); if (sectionMenuSons.classList != null) sectionMenuSons.classList.remove("active-section"); if (sectionMenuGenres.classList != null) sectionMenuGenres.classList.remove("active-section"); if (sectionMenuUtilisateurs.classList != null) sectionMenuUtilisateurs.classList.remove("active-section"); if (sectionMenuPlaylists.classList != null) sectionMenuPlaylists.classList.remove("active-section"); if (sectionMenuAlbums.classList != null) sectionMenuAlbums.classList.remove("active-section"); } const curSection = document.querySelector(".active-section"); let curIndex = -1; if (e) { const curSectionName = curSection.id.split("page")[1]; curIndex = curSectionName == "Principale" ? 0 : curSectionName == "Artistes" ? 1 : curSectionName == "Sons" ? 2 : curSectionName == "Genres" ? 3 : curSectionName == "Utilisateurs" ? 4 : curSectionName == "Playlists" ? 5 : 6; if (e.target.id.split("goTo")[1] == curSectionName) return; } const menuItemHeight = 3.5; const menuItemMargin = 0.85; const startPosition = 1; const position = startPosition + index * (menuItemHeight + menuItemMargin); gsap.to(activeSquare, { top: `${position}rem`, duration: 0.6, ease: "power4.out" }); const menuItems = [goToMenuPrincipal, goToArtistes, goToSons, goToGenres, goToUtilisateurs, goToPlaylists, goToAlbums]; menuItems.forEach((menuItem, i) => { gsap.to(menuItem, { color: i === index ? "#0E100F" : "#FEFCE1", duration: 0.6, ease: "power4.out" }); }); switch(index) { case 0: gsap.to(goToMenuPrincipal, {color: "#0E100F", duration: 0.6, ease:"power4.out"}); gsap.to(goToArtistes, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToSons, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToGenres, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToUtilisateurs, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToPlaylists, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToAlbums, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.fromTo(sectionMenuPrincipal, {opacity: 0, y: index < curIndex ? "-100vh" : "100vh"}, {opacity: 1, x: 0, duration: 0.6, zIndex: 1, ease:"power4.out"}); gsap.to(curSection, {opacity:0, y: index < curIndex ? "100vh" : "-100vh", duration:0.6, zIndex: -1, ease: "power4.out"}); clearActiveSections(); sectionMenuPrincipal.classList.add("active-section"); break; case 1: gsap.to(goToMenuPrincipal, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToArtistes, {color: "#0E100F", duration: 0.6, ease:"power4.out"}); gsap.to(goToSons, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToGenres, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToUtilisateurs, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToPlaylists, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToAlbums, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.fromTo(sectionMenuArtistes, {opacity: 0, y: index < curIndex ? "-100vh" : "100vh"}, {opacity: 1, x: 0, duration: 0.6, zIndex: 1, ease:"power4.out"}); gsap.to(curSection, {opacity:0, y: index < curIndex ? "100vh" : "-100vh", duration:0.6, zIndex: -1, ease: "power4.out"}); clearActiveSections(); sectionMenuArtistes.classList.add("active-section"); break; case 2: gsap.to(goToMenuPrincipal, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToArtistes, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToSons, {color: "#0E100F", duration: 0.6, ease:"power4.out"}); gsap.to(goToGenres, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToUtilisateurs, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToPlaylists, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToAlbums, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.fromTo(sectionMenuSons, {opacity: 0, y: index < curIndex ? "-100vh" : "100vh"}, {opacity: 1, x: 0, duration: 0.6, zIndex: 1, ease:"power4.out"}); gsap.to(curSection, {opacity:0, y: index < curIndex ? "100vh" : "-100vh", duration:0.6, zIndex: -1, ease: "power4.out"}); clearActiveSections(); sectionMenuSons.classList.add("active-section"); break; case 3: gsap.to(goToMenuPrincipal, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToArtistes, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToSons, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToGenres, {color: "#0E100F", duration: 0.6, ease:"power4.out"}); gsap.to(goToUtilisateurs, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToPlaylists, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToAlbums, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.fromTo(sectionMenuGenres, {opacity: 0, y: index < curIndex ? "-100vh" : "100vh"}, {opacity: 1, x: 0, duration: 0.6, zIndex: 1, ease:"power4.out"}); gsap.to(curSection, {opacity:0, y: index < curIndex ? "100vh" : "-100vh", duration:0.6, zIndex: -1, ease: "power4.out"}); clearActiveSections(); sectionMenuGenres.classList.add("active-section"); break; case 4: gsap.to(goToMenuPrincipal, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToArtistes, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToSons, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToGenres, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToUtilisateurs, {color: "#0E100F", duration: 0.6, ease:"power4.out"}); gsap.to(goToPlaylists, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToAlbums, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.fromTo(sectionMenuUtilisateurs, {opacity: 0, y: index < curIndex ? "-100vh" : "100vh"}, {opacity: 1, x: 0, duration: 0.6, zIndex: 1, ease:"power4.out"}); gsap.to(curSection, {opacity:0, y: index < curIndex ? "100vh" : "-100vh", duration:0.6, zIndex: -1, ease: "power4.out"}); clearActiveSections(); sectionMenuUtilisateurs.classList.add("active-section"); break; case 5: gsap.to(goToMenuPrincipal, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToArtistes, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToSons, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToGenres, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToUtilisateurs, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToPlaylists, {color: "#0E100F", duration: 0.6, ease:"power4.out"}); gsap.to(goToAlbums, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.fromTo(sectionMenuPlaylists, {opacity: 0, y: index < curIndex ? "-100vh" : "100vh"}, {opacity: 1, x: 0, duration: 0.6, zIndex: 1, ease:"power4.out"}); gsap.to(curSection, {opacity:0, y: index < curIndex ? "100vh" : "-100vh", duration:0.6, zIndex: -1, ease: "power4.out"}); clearActiveSections(); sectionMenuPlaylists.classList.add("active-section"); break; case 6: gsap.to(goToMenuPrincipal, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToArtistes, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToSons, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToGenres, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToUtilisateurs, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToPlaylists, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToAlbums, {color: "#0E100F", duration: 0.6, ease:"power4.out"}); gsap.fromTo(sectionMenuAlbums, {opacity: 0, y: index < curIndex ? "-100vh" : "100vh"}, {opacity: 1, x: 0, duration: 0.6, zIndex: 1, ease:"power4.out"}); gsap.to(curSection, {opacity:0, y: index < curIndex ? "100vh" : "-100vh", duration:0.6, zIndex: -1, ease: "power4.out"}); clearActiveSections(); sectionMenuAlbums.classList.add("active-section"); break; } } changeCurrentMenu(null, 0); goToMenuPrincipal.addEventListener('click', (e) => changeCurrentMenu(e,0)); goToArtistes.addEventListener('click', (e) => changeCurrentMenu(e,1)); goToSons.addEventListener('click', (e) => changeCurrentMenu(e,2)); goToGenres.addEventListener('click', (e) => changeCurrentMenu(e,3)); goToUtilisateurs.addEventListener('click', (e) => changeCurrentMenu(e,4)); goToPlaylists.addEventListener('click', (e) => changeCurrentMenu(e,5)); goToAlbums.addEventListener('click', (e) => changeCurrentMenu(e,6)); mais je ne trouve pas quelles valeurs mettre dans les transitions gsap pour que les sections de la classe page soient bien affichées à chaque transition à leur place initiale. comment faire ?
70a03bb22d3a54df3bdd93980cb7012a
{ "intermediate": 0.3754093050956726, "beginner": 0.42614346742630005, "expert": 0.19844721257686615 }
38,850
voici de l'html : <aside> <div class="left"> <a href="index.php?action=accueil" class="btn-retour"> <svg width="26" height="16" viewBox="0 0 26 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M8.22816 1.73682L2.00009 7.96489M2.00009 7.96489L8.22816 14.193M2.00009 7.96489H24.4211" stroke="currentColor" stroke-width="2.49123" stroke-linecap="round" stroke-linejoin="round"/> </svg> Retour application </a> <nav> <ul> <li> <a href="" id="goToMenuPrincipal"> <svg width="27" height="17" viewBox="0 0 27 17" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M1.83325 1.2085H25.1666M1.83325 8.50016H25.1666M1.83325 15.7918H25.1666" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> Menu principal </a> </li> <li> <a href="" id="goToArtistes"> <svg width="30" height="23" viewBox="0 0 30 23" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M23.9866 21.7082H26.1667C27.7775 21.7082 29.1809 20.3606 28.6692 18.8332C27.8893 16.5055 25.9706 15.0979 22.5977 14.6103M18.146 9.84388C18.5703 9.97801 19.0564 10.0415 19.6042 10.0415C22.0347 10.0415 23.25 8.7915 23.25 5.6665C23.25 2.5415 22.0347 1.2915 19.6042 1.2915C19.0564 1.2915 18.5703 1.355 18.146 1.48913M10.8542 14.4165C16.6277 14.4165 19.4474 16.1838 20.1527 19.7183C20.3689 20.8015 19.4379 21.7082 18.3333 21.7082H3.375C2.27043 21.7082 1.33943 20.8015 1.5556 19.7183C2.26098 16.1838 5.08064 14.4165 10.8542 14.4165ZM10.8542 10.0415C13.2847 10.0415 14.5 8.7915 14.5 5.6665C14.5 2.5415 13.2847 1.2915 10.8542 1.2915C8.42361 1.2915 7.20833 2.5415 7.20833 5.6665C7.20833 8.7915 8.42361 10.0415 10.8542 10.0415Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> Artistes </a> </li> <li> <a href="" id="goToSons"> <svg width="29" height="29" viewBox="0 0 29 29" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M5.75 14.5C5.75 11.2613 7.50962 8.43351 10.125 6.92059M23.25 14.2123C23.25 17.451 21.4904 20.2788 18.875 21.7917M27.625 14.5C27.625 21.7487 21.7487 27.625 14.5 27.625C7.25126 27.625 1.375 21.7487 1.375 14.5C1.375 7.25126 7.25126 1.375 14.5 1.375C21.7487 1.375 27.625 7.25126 27.625 14.5ZM17.4167 14.5C17.4167 16.1108 16.1108 17.4167 14.5 17.4167C12.8892 17.4167 11.5833 16.1108 11.5833 14.5C11.5833 12.8892 12.8892 11.5833 14.5 11.5833C16.1108 11.5833 17.4167 12.8892 17.4167 14.5Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> Sons </a> </li> <li> <a href="" id="goToGenres"> <svg width="23" height="20" viewBox="0 0 23 20" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M1.29175 7.04183H15.8751M1.29175 1.2085H15.8751M1.29175 12.8752H10.0417M15.8751 12.8752V18.7085L21.7084 15.7918L15.8751 12.8752Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> Genres </a> </li> <li> <a href="" id="goToUtilisateurs"> <svg width="23" height="27" viewBox="0 0 23 27" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M18.2405 24.7722C19.8065 24.7722 21.1404 23.4819 20.7854 21.9567C19.9025 18.1628 16.9499 16.2658 11.1519 16.2658C5.35387 16.2658 2.40129 18.1628 1.51836 21.9567C1.16341 23.4819 2.49732 24.7722 4.06329 24.7722H18.2405Z" stroke="currentColor" stroke-width="2.83544" stroke-linecap="round" stroke-linejoin="round"/> <path fill-rule="evenodd" clip-rule="evenodd" d="M11.1519 12.0127C13.9873 12.0127 15.4051 10.5949 15.4051 7.05063C15.4051 3.50633 13.9873 2.08861 11.1519 2.08861C8.31645 2.08861 6.89873 3.50633 6.89873 7.05063C6.89873 10.5949 8.31645 12.0127 11.1519 12.0127Z" stroke="currentColor" stroke-width="2.83544" stroke-linecap="round" stroke-linejoin="round"/> </svg> Utilisateurs </a> </li> <li> <a href="" id="goToPlaylists"> <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M1 3C1 1.89543 1.89543 1 3 1H4C5.10457 1 6 1.89543 6 3V4C6 5.10457 5.10457 6 4 6H3C1.89543 6 1 5.10457 1 4V3Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> <path d="M10 3C10 1.89543 10.8954 1 12 1H13C14.1046 1 15 1.89543 15 3V4C15 5.10457 14.1046 6 13 6H12C10.8954 6 10 5.10457 10 4V3Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> <path d="M1 12C1 10.8954 1.89543 10 3 10H4C5.10457 10 6 10.8954 6 12V13C6 14.1046 5.10457 15 4 15H3C1.89543 15 1 14.1046 1 13V12Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> <path d="M10 12C10 10.8954 10.8954 10 12 10H13C14.1046 10 15 10.8954 15 12V13C15 14.1046 14.1046 15 13 15H12C10.8954 15 10 14.1046 10 13V12Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> Playlists </a> </li> <li> <a href="" id="goToAlbums"> <svg width="27" height="27" viewBox="0 0 27 27" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M8.8125 21.8333C8.8125 24.1345 7.06361 26 4.90625 26C2.74889 26 1 24.1345 1 21.8333C1 19.5321 2.74889 17.6667 4.90625 17.6667C7.06361 17.6667 8.8125 19.5321 8.8125 21.8333ZM8.8125 21.8333V3.57439C8.8125 3.05949 9.20349 2.62875 9.71598 2.57906L24.9035 1.10633C25.4912 1.04934 26 1.51124 26 2.10166V20.1667M26 20.1667C26 22.4679 24.2511 24.3333 22.0938 24.3333C19.9364 24.3333 18.1875 22.4679 18.1875 20.1667C18.1875 17.8655 19.9364 16 22.0938 16C24.2511 16 26 17.8655 26 20.1667Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> Albums </a> </li> </ul> <div class="active-square" id="activeSquare"></div> </nav> <div class="actions"> <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M10 6V14M14 10H6M10 19C14.9706 19 19 14.9706 19 10C19 5.02944 14.9706 1 10 1C5.02944 1 1 5.02944 1 10C1 14.9706 5.02944 19 10 19Z" stroke="#E2FF08" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> </div> </div> </aside> <div class="right"> <!-- barre de recherche --> <div id="recherche" class="wrapper-recherche"> <div class="text-field"> <img src="/Assets/icons/search.svg" alt="user"/> <input type="text" placeholder="Ma recherche" value=""> </div> </div> <div class="container-tabs"> <main> <section id="pagePrincipale" class="page"> <header> <h2>Menu principal</h2> <svg width="29" height="29" viewBox="0 0 39 39" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M37.6118 9.82166L27.9072 14.9928C32.319 9.33028 28.353 1.28109 19.1767 0V9.98935C15.8932 3.95635 6.60488 3.25634 0.923272 9.82361L10.2961 14.8173C2.99181 14.4254 -2.30948 21.4977 1.01413 29.3226L10.8413 24.0871C6.34922 29.619 9.45097 38.5008 19.1746 39V28.1059C21.8685 34.7941 32.0717 37.0091 37.5188 29.3226L27.2966 23.8766C34.9199 25.066 42.0996 18.019 37.6118 9.82361V9.82166Z" fill="#E2FF08"/> </svg> </header> <div class="menu"> <button class="admin-content"> <svg width="29" height="29" viewBox="0 0 30 23" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M23.9866 21.7082H26.1667C27.7775 21.7082 29.1809 20.3606 28.6692 18.8332C27.8893 16.5055 25.9706 15.0979 22.5977 14.6103M18.146 9.84388C18.5703 9.97801 19.0564 10.0415 19.6042 10.0415C22.0347 10.0415 23.25 8.7915 23.25 5.6665C23.25 2.5415 22.0347 1.2915 19.6042 1.2915C19.0564 1.2915 18.5703 1.355 18.146 1.48913M10.8542 14.4165C16.6277 14.4165 19.4474 16.1838 20.1527 19.7183C20.3689 20.8015 19.4379 21.7082 18.3333 21.7082H3.375C2.27043 21.7082 1.33943 20.8015 1.5556 19.7183C2.26098 16.1838 5.08064 14.4165 10.8542 14.4165ZM10.8542 10.0415C13.2847 10.0415 14.5 8.7915 14.5 5.6665C14.5 2.5415 13.2847 1.2915 10.8542 1.2915C8.42361 1.2915 7.20833 2.5415 7.20833 5.6665C7.20833 8.7915 8.42361 10.0415 10.8542 10.0415Z" stroke="#FEFCE1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> <div class="textes"> <h3>Artistes</h3> <p>Les artistes de l'application</p> </div> </button> <button class="admin-content"> <svg width="29" height="29" viewBox="0 0 29 29" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M5.75 14.5C5.75 11.2613 7.50962 8.43351 10.125 6.92059M23.25 14.2123C23.25 17.451 21.4904 20.2788 18.875 21.7917M27.625 14.5C27.625 21.7487 21.7487 27.625 14.5 27.625C7.25126 27.625 1.375 21.7487 1.375 14.5C1.375 7.25126 7.25126 1.375 14.5 1.375C21.7487 1.375 27.625 7.25126 27.625 14.5ZM17.4167 14.5C17.4167 16.1108 16.1108 17.4167 14.5 17.4167C12.8892 17.4167 11.5833 16.1108 11.5833 14.5C11.5833 12.8892 12.8892 11.5833 14.5 11.5833C16.1108 11.5833 17.4167 12.8892 17.4167 14.5Z" stroke="#FEFCE1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> <div class="textes"> <h3>Sons</h3> <p>Les sons de l'application</p> </div> </butt> <button class="admin-content"> <svg width="29" height="29" viewBox="0 0 23 20" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M1.29175 7.04183H15.8751M1.29175 1.2085H15.8751M1.29175 12.8752H10.0417M15.8751 12.8752V18.7085L21.7084 15.7918L15.8751 12.8752Z" stroke="#FEFCE1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> <div class="textes"> <h3>Genres</h3> <p>Les genres de l'application</p> </div> </button> <button class="admin-content"> <svg width="29" height="29" viewBox="0 0 23 27" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M18.2405 24.7722C19.8065 24.7722 21.1404 23.4819 20.7854 21.9567C19.9025 18.1628 16.9499 16.2658 11.1519 16.2658C5.35387 16.2658 2.40129 18.1628 1.51836 21.9567C1.16341 23.4819 2.49732 24.7722 4.06329 24.7722H18.2405Z" stroke="#FEFCE1" stroke-width="2.83544" stroke-linecap="round" stroke-linejoin="round"/> <path fill-rule="evenodd" clip-rule="evenodd" d="M11.1519 12.0127C13.9873 12.0127 15.4051 10.5949 15.4051 7.05063C15.4051 3.50633 13.9873 2.08861 11.1519 2.08861C8.31645 2.08861 6.89873 3.50633 6.89873 7.05063C6.89873 10.5949 8.31645 12.0127 11.1519 12.0127Z" stroke="#FEFCE1" stroke-width="2.83544" stroke-linecap="round" stroke-linejoin="round"/> </svg> <div class="textes"> <h3>Utilisateurs</h3> <p>Les utilisateurs de l'application</p> </div> </button> <button class="admin-content"> <svg width="29" height="29" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M1 3C1 1.89543 1.89543 1 3 1H4C5.10457 1 6 1.89543 6 3V4C6 5.10457 5.10457 6 4 6H3C1.89543 6 1 5.10457 1 4V3Z" stroke="#FEFCE1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> <path d="M10 3C10 1.89543 10.8954 1 12 1H13C14.1046 1 15 1.89543 15 3V4C15 5.10457 14.1046 6 13 6H12C10.8954 6 10 5.10457 10 4V3Z" stroke="#FEFCE1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> <path d="M1 12C1 10.8954 1.89543 10 3 10H4C5.10457 10 6 10.8954 6 12V13C6 14.1046 5.10457 15 4 15H3C1.89543 15 1 14.1046 1 13V12Z" stroke="#FEFCE1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> <path d="M10 12C10 10.8954 10.8954 10 12 10H13C14.1046 10 15 10.8954 15 12V13C15 14.1046 14.1046 15 13 15H12C10.8954 15 10 14.1046 10 13V12Z" stroke="#FEFCE1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> <div class="textes"> <h3>Playlists</h3> <p>Les playlists de l'application</p> </div> </button> <button class="admin-content"> <svg width="18" height="17" viewBox="0 0 18 17" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M6 13.5C6 14.8807 4.88071 16 3.5 16C2.11929 16 1 14.8807 1 13.5C1 12.1193 2.11929 11 3.5 11C4.88071 11 6 12.1193 6 13.5ZM6 13.5V2.91321C6 2.39601 6.39439 1.96415 6.90946 1.91732L15.9095 1.09914C16.4951 1.0459 17 1.507 17 2.09503V12.5M17 12.5C17 13.8807 15.8807 15 14.5 15C13.1193 15 12 13.8807 12 12.5C12 11.1193 13.1193 10 14.5 10C15.8807 10 17 11.1193 17 12.5Z" stroke="#FEFCE1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> <div class="textes"> <h3>Albums</h3> <p>Les albums de l'application</p> </div> </button> </div> </section> <section id="pageArtistes" class="page"> <header> <h2>Artistes</h2> <svg width="29" height="29" viewBox="0 0 39 39" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M37.6118 9.82166L27.9072 14.9928C32.319 9.33028 28.353 1.28109 19.1767 0V9.98935C15.8932 3.95635 6.60488 3.25634 0.923272 9.82361L10.2961 14.8173C2.99181 14.4254 -2.30948 21.4977 1.01413 29.3226L10.8413 24.0871C6.34922 29.619 9.45097 38.5008 19.1746 39V28.1059C21.8685 34.7941 32.0717 37.0091 37.5188 29.3226L27.2966 23.8766C34.9199 25.066 42.0996 18.019 37.6118 9.82361V9.82166Z" fill="#E2FF08"/> </svg> </header> </section> <section id="pageSons" class="page"> <header> <h2>Sons</h2> <svg width="29" height="29" viewBox="0 0 39 39" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M37.6118 9.82166L27.9072 14.9928C32.319 9.33028 28.353 1.28109 19.1767 0V9.98935C15.8932 3.95635 6.60488 3.25634 0.923272 9.82361L10.2961 14.8173C2.99181 14.4254 -2.30948 21.4977 1.01413 29.3226L10.8413 24.0871C6.34922 29.619 9.45097 38.5008 19.1746 39V28.1059C21.8685 34.7941 32.0717 37.0091 37.5188 29.3226L27.2966 23.8766C34.9199 25.066 42.0996 18.019 37.6118 9.82361V9.82166Z" fill="#E2FF08"/> </svg> </header> </section> <section id="pageGenres" class="page"> <header> <h2>Genres</h2> <svg width="29" height="29" viewBox="0 0 39 39" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M37.6118 9.82166L27.9072 14.9928C32.319 9.33028 28.353 1.28109 19.1767 0V9.98935C15.8932 3.95635 6.60488 3.25634 0.923272 9.82361L10.2961 14.8173C2.99181 14.4254 -2.30948 21.4977 1.01413 29.3226L10.8413 24.0871C6.34922 29.619 9.45097 38.5008 19.1746 39V28.1059C21.8685 34.7941 32.0717 37.0091 37.5188 29.3226L27.2966 23.8766C34.9199 25.066 42.0996 18.019 37.6118 9.82361V9.82166Z" fill="#E2FF08"/> </svg> </header> </section> <section id="pageUtilisateurs" class="page"> <header> <h2>Utilisateurs</h2> <svg width="29" height="29" viewBox="0 0 39 39" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M37.6118 9.82166L27.9072 14.9928C32.319 9.33028 28.353 1.28109 19.1767 0V9.98935C15.8932 3.95635 6.60488 3.25634 0.923272 9.82361L10.2961 14.8173C2.99181 14.4254 -2.30948 21.4977 1.01413 29.3226L10.8413 24.0871C6.34922 29.619 9.45097 38.5008 19.1746 39V28.1059C21.8685 34.7941 32.0717 37.0091 37.5188 29.3226L27.2966 23.8766C34.9199 25.066 42.0996 18.019 37.6118 9.82361V9.82166Z" fill="#E2FF08"/> </svg> </header> </section> <section id="pagePlaylists" class="page"> <header> <h2>Playlists</h2> <svg width="29" height="29" viewBox="0 0 39 39" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M37.6118 9.82166L27.9072 14.9928C32.319 9.33028 28.353 1.28109 19.1767 0V9.98935C15.8932 3.95635 6.60488 3.25634 0.923272 9.82361L10.2961 14.8173C2.99181 14.4254 -2.30948 21.4977 1.01413 29.3226L10.8413 24.0871C6.34922 29.619 9.45097 38.5008 19.1746 39V28.1059C21.8685 34.7941 32.0717 37.0091 37.5188 29.3226L27.2966 23.8766C34.9199 25.066 42.0996 18.019 37.6118 9.82361V9.82166Z" fill="#E2FF08"/> </svg> </header> </section> <section id="pageAlbums" class="page"> <header> <h2>Albums</h2> <svg width="29" height="29" viewBox="0 0 39 39" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M37.6118 9.82166L27.9072 14.9928C32.319 9.33028 28.353 1.28109 19.1767 0V9.98935C15.8932 3.95635 6.60488 3.25634 0.923272 9.82361L10.2961 14.8173C2.99181 14.4254 -2.30948 21.4977 1.01413 29.3226L10.8413 24.0871C6.34922 29.619 9.45097 38.5008 19.1746 39V28.1059C21.8685 34.7941 32.0717 37.0091 37.5188 29.3226L27.2966 23.8766C34.9199 25.066 42.0996 18.019 37.6118 9.82361V9.82166Z" fill="#E2FF08"/> </svg> </header> </section> </main> </div> </div> le css qui va avec : @font-face { font-family: 'Kicker'; src: url('../fonts/kicker-black/KickerTrial-Black.ttf') format('truetype'); font-weight: 100; font-style: normal; } @font-face { font-family: 'Kicker'; src: url('../fonts/kicker-black/KickerTrial-BlackItalic.ttf') format('truetype'); font-weight: 100; font-style: italic; } @font-face { font-family: 'Kicker'; src: url('../fonts/kicker-bold/KickerTrial-BlackSlanted.ttf') format('truetype'); font-weight: 200; font-style: normal; } @font-face { font-family: 'PP Mori'; src: url('../fonts/pp-mori/PPMori-ExtraLight.otf') format('truetype'); font-weight: 100; font-style: normal; } @font-face { font-family: 'PP Mori'; src: url('../fonts/pp-mori/PPMori-ExtraLightItalic.otf') format('truetype'); font-weight: 100; font-style: italic; } @font-face { font-family: 'PP Mori'; src: url('../fonts/pp-mori/PPMori-Regular.otf') format('truetype'); font-weight: 200; font-style: normal; } @font-face { font-family: 'PP Mori'; src: url('../fonts/pp-mori/PPMori-RegularItalic.otf') format('truetype'); font-weight: 200; font-style: italic; } @font-face { font-family: 'PP Mori'; src: url('../fonts/pp-mori/PPMori-SemiBold.otf') format('truetype'); font-weight: 300; font-style: normal; } @font-face { font-family: 'PP Mori'; src: url('../fonts/pp-mori/PPMori-SemiBoldItalic.otf') format('truetype'); font-weight: 300; font-style: italic; } *{ margin: 0; padding: 0; box-sizing: border-box; } :root { --yellow: #E2FF08; --text-color: #FEFCE1; --text-color-secondary: #7F7E70; --background-color: #000000; --background-secondary: #070808; } body{ background-color: var(--background-color); position: relative; display: flex; justify-content: space-between; font-family: 'PP Mori', sans-serif; min-height: 100vh; max-width: 100vw; overflow:hidden; margin: 0; padding: 0; } nav { position: relative; display: flex; background-color: var(--background-secondary); border-radius: 1rem; padding: 1rem; min-height: 100%; } nav ul { display: flex; flex-direction: column; gap: 0.85rem; height: 100%; list-style: none; position: relative; padding: 0; z-index: 2; } nav ul li { list-style-type: none; width: 100%; } nav .active-square { position: absolute; width: 85%; height: 3.5rem; z-index: 0; background-color: var(--yellow); border-radius: 0.8rem; } nav ul li a { text-decoration: none; color: var(--text-color); gap: 0.7rem; height: 3.5rem; max-height: 3.5rem; display: flex; width: 15.5rem; align-items: center; white-space: nowrap; font-size: 1rem; padding: 1rem; } nav ul li a svg { position: relative; } body .left{ position: relative; width: 15rem; height: 100%; display: flex; gap: 5rem; flex-direction: column; background-color: var(--background-secondary); } body .left img{ align-self: flex-start; } .actions { position: absolute; bottom: 0; right: 0; padding: 1rem; } .actions a { text-decoration: none; font-size: 1rem; margin-left: 1rem; } .btn-retour { cursor: pointer; display: flex; gap:1rem; background-color: var(--background-secondary); border: none; padding: 1.5rem 1rem; border-radius: 1rem; color:var(--yellow); font-family: 'PP Mori'; font-weight: 300; width: 13rem; height: 4.4375rem; font-size: 0.95rem; display: flex; gap: 0.7rem; align-items: center; text-decoration: none; background-color: #0E100F; margin: 1rem 1rem; } .btn-retour a:hover{ filter: brightness(0.8); } .right { position: relative; width: 100%; height: 100%; display: flex; flex-direction: column; } #recherche { background-color: #070808; padding: 1rem 1rem; display: flex; align-items: center; margin-left: 0.7rem; } .text-field{ width: 100%; display: flex; position: relative; padding: 1.625rem 1.875rem; background-color: #070808; color: var(--text-color-secondary); } .text-field img{ height: 1.5rem; } .text-field input{ position: absolute; top: 0; left: 0; width: 100%; height: 100%; padding-left: 6rem; background-color: transparent; border: none; border-bottom: 1.5px solid var(--text-color-secondary); outline: none; color: var(--text-color-secondary); font-family: 'PP Mori'; font-weight: 300; font-size: 1.25rem; transition: all 0.2s ease-in-out; } .text-field.no-space input{ padding-left: 1rem; } .text-field input:focus{ border-bottom: 1.5px solid var(--yellow); transition: all 0.2s ease-in-out; } h2 { font-family: 'PP Mori', sans-serif; font-size: 3rem; font-weight: 300; color: var(--text-color); margin: 3rem 1rem; } header { display: flex; align-items: center; padding-left: 1.5rem } .menu { margin-top: 1rem; display: grid; grid-template-columns: repeat(3, 1fr); grid-template-rows: repeat(2, 1fr); gap: 1.5rem; } .admin-content { margin-top: 1rem; background-color: #070808; display: flex; align-items: center; justify-content: center; width: 24vw; height: 25vh; margin-left: 2rem; border-radius: 1rem; border: none; cursor: pointer; } .textes { display: flex; flex-direction: column; align-items: flex-start; margin-left: 4.5rem; } .textes h3 { margin-top: 1rem; font-family: "PP Mori"; font-weight: 300; color: #FEFCE1; font-size: 2rem; opacity: 50%; } .textes p { font-family: "PP Mori"; font-size: 0.875rem; color: #FEFCE1; opacity: 30%; margin-top: 0.5rem; } .admin-content svg { width: 5rem; height: 4.5rem; } #pagePrincipale { opacity: 1; display: block; } .page { position: absolute; opacity: 0; padding-right: 2rem; width: 100%; display: flex; gap: 1.15rem; height: 100%; } et du js : const activeSquare = document.querySelector("#activeSquare"); const goToMenuPrincipal = document.querySelector("#goToMenuPrincipal"); const goToArtistes = document.querySelector("#goToArtistes"); const goToSons = document.querySelector("#goToSons"); const goToGenres = document.querySelector("#goToGenres"); const goToUtilisateurs = document.querySelector("#goToUtilisateurs"); const goToPlaylists = document.querySelector("#goToPlaylists"); const goToAlbums = document.querySelector("#goToAlbums"); const sectionMenuPrincipal = document.querySelector("#pagePrincipale"); const sectionMenuArtistes = document.querySelector("#pageArtistes"); const sectionMenuSons = document.querySelector("#pageSons"); const sectionMenuGenres = document.querySelector("#pageGenres"); const sectionMenuUtilisateurs = document.querySelector("#pageUtilisateurs"); const sectionMenuPlaylists = document.querySelector("#pagePlaylists"); const sectionMenuAlbums = document.querySelector("#pageAlbums"); function changeCurrentMenu(e, index) { e?.preventDefault(); function clearActiveSections() { if (sectionMenuPrincipal.classList != null) sectionMenuPrincipal.classList.remove("active-section"); if (sectionMenuArtistes.classList != null) sectionMenuArtistes.classList.remove("active-section"); if (sectionMenuSons.classList != null) sectionMenuSons.classList.remove("active-section"); if (sectionMenuGenres.classList != null) sectionMenuGenres.classList.remove("active-section"); if (sectionMenuUtilisateurs.classList != null) sectionMenuUtilisateurs.classList.remove("active-section"); if (sectionMenuPlaylists.classList != null) sectionMenuPlaylists.classList.remove("active-section"); if (sectionMenuAlbums.classList != null) sectionMenuAlbums.classList.remove("active-section"); } const curSection = document.querySelector(".active-section"); let curIndex = -1; if (e) { const curSectionName = curSection.id.split("page")[1]; curIndex = curSectionName == "Principale" ? 0 : curSectionName == "Artistes" ? 1 : curSectionName == "Sons" ? 2 : curSectionName == "Genres" ? 3 : curSectionName == "Utilisateurs" ? 4 : curSectionName == "Playlists" ? 5 : 6; if (e.target.id.split("goTo")[1] == curSectionName) return; } const menuItemHeight = 3.5; const menuItemMargin = 0.85; const startPosition = 1; const position = startPosition + index * (menuItemHeight + menuItemMargin); gsap.to(activeSquare, { top: `${position}rem`, duration: 0.6, ease: "power4.out" }); const menuItems = [goToMenuPrincipal, goToArtistes, goToSons, goToGenres, goToUtilisateurs, goToPlaylists, goToAlbums]; menuItems.forEach((menuItem, i) => { gsap.to(menuItem, { color: i === index ? "#0E100F" : "#FEFCE1", duration: 0.6, ease: "power4.out" }); }); switch(index) { case 0: gsap.to(goToMenuPrincipal, {color: "#0E100F", duration: 0.6, ease:"power4.out"}); gsap.to(goToArtistes, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToSons, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToGenres, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToUtilisateurs, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToPlaylists, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToAlbums, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.fromTo(sectionMenuPrincipal, {opacity: 0, y: index < curIndex ? "-100vw" : "100vw"}, {opacity: 1, x: 0, duration: 0.6, zIndex: 1, ease:"power4.out"}); gsap.to(curSection, {opacity:0, y: index < curIndex ? "100vw" : "-100vw", duration:0.6, zIndex: -1, ease: "power4.out"}); clearActiveSections(); sectionMenuPrincipal.classList.add("active-section"); break; case 1: gsap.to(goToMenuPrincipal, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToArtistes, {color: "#0E100F", duration: 0.6, ease:"power4.out"}); gsap.to(goToSons, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToGenres, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToUtilisateurs, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToPlaylists, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToAlbums, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.fromTo(sectionMenuArtistes, {opacity: 0, y: index < curIndex ? "-100vw" : "100vw"}, {opacity: 1, x: 0, duration: 0.6, zIndex: 1, ease:"power4.out"}); gsap.to(curSection, {opacity:0, y: index < curIndex ? "100vw" : "-100vw", duration:0.6, zIndex: -1, ease: "power4.out"}); clearActiveSections(); sectionMenuArtistes.classList.add("active-section"); break; case 2: gsap.to(goToMenuPrincipal, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToArtistes, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToSons, {color: "#0E100F", duration: 0.6, ease:"power4.out"}); gsap.to(goToGenres, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToUtilisateurs, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToPlaylists, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToAlbums, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.fromTo(sectionMenuSons, {opacity: 0, y: index < curIndex ? "-100vw" : "100vw"}, {opacity: 1, x: 0, duration: 0.6, zIndex: 1, ease:"power4.out"}); gsap.to(curSection, {opacity:0, y: index < curIndex ? "100vw" : "-100vw", duration:0.6, zIndex: -1, ease: "power4.out"}); clearActiveSections(); sectionMenuSons.classList.add("active-section"); break; case 3: gsap.to(goToMenuPrincipal, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToArtistes, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToSons, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToGenres, {color: "#0E100F", duration: 0.6, ease:"power4.out"}); gsap.to(goToUtilisateurs, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToPlaylists, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToAlbums, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.fromTo(sectionMenuGenres, {opacity: 0, y: index < curIndex ? "-100vw" : "100vw"}, {opacity: 1, x: 0, duration: 0.6, zIndex: 1, ease:"power4.out"}); gsap.to(curSection, {opacity:0, y: index < curIndex ? "100vw" : "-100vw", duration:0.6, zIndex: -1, ease: "power4.out"}); clearActiveSections(); sectionMenuGenres.classList.add("active-section"); break; case 4: gsap.to(goToMenuPrincipal, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToArtistes, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToSons, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToGenres, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToUtilisateurs, {color: "#0E100F", duration: 0.6, ease:"power4.out"}); gsap.to(goToPlaylists, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToAlbums, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.fromTo(sectionMenuUtilisateurs, {opacity: 0, y: index < curIndex ? "-100vw" : "100vw"}, {opacity: 1, x: 0, duration: 0.6, zIndex: 1, ease:"power4.out"}); gsap.to(curSection, {opacity:0, y: index < curIndex ? "100vw" : "-100vw", duration:0.6, zIndex: -1, ease: "power4.out"}); clearActiveSections(); sectionMenuUtilisateurs.classList.add("active-section"); break; case 5: gsap.to(goToMenuPrincipal, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToArtistes, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToSons, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToGenres, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToUtilisateurs, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToPlaylists, {color: "#0E100F", duration: 0.6, ease:"power4.out"}); gsap.to(goToAlbums, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.fromTo(sectionMenuPlaylists, {opacity: 0, y: index < curIndex ? "-100vw" : "100vw"}, {opacity: 1, x: 0, duration: 0.6, zIndex: 1, ease:"power4.out"}); gsap.to(curSection, {opacity:0, y: index < curIndex ? "100vw" : "-100vw", duration:0.6, zIndex: -1, ease: "power4.out"}); clearActiveSections(); sectionMenuPlaylists.classList.add("active-section"); break; case 6: gsap.to(goToMenuPrincipal, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToArtistes, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToSons, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToGenres, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToUtilisateurs, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToPlaylists, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToAlbums, {color: "#0E100F", duration: 0.6, ease:"power4.out"}); gsap.fromTo(sectionMenuAlbums, {opacity: 0, y: index < curIndex ? "-100vw" : "100vw"}, {opacity: 1, x: 0, duration: 0.6, zIndex: 1, ease:"power4.out"}); gsap.to(curSection, {opacity:0, y: index < curIndex ? "100vw" : "-100vw", duration:0.6, zIndex: -1, ease: "power4.out"}); clearActiveSections(); sectionMenuAlbums.classList.add("active-section"); break; } } changeCurrentMenu(null, 0); goToMenuPrincipal.addEventListener('click', (e) => changeCurrentMenu(e,0)); goToArtistes.addEventListener('click', (e) => changeCurrentMenu(e,1)); goToSons.addEventListener('click', (e) => changeCurrentMenu(e,2)); goToGenres.addEventListener('click', (e) => changeCurrentMenu(e,3)); goToUtilisateurs.addEventListener('click', (e) => changeCurrentMenu(e,4)); goToPlaylists.addEventListener('click', (e) => changeCurrentMenu(e,5)); goToAlbums.addEventListener('click', (e) => changeCurrentMenu(e,6)); sans que tu modifies la logique de monde code ou quoi, j'aimerais que tu changes les valeurs des transitions gsap pour que la navbar déplace verticalement les sections, et que ces sections soient bien centrées
f0e2aea8d79cceea26bb5d72ab681c80
{ "intermediate": 0.39427080750465393, "beginner": 0.40862026810646057, "expert": 0.1971088945865631 }
38,851
Please explain what types of neural network Stable Diffusion is. Then explain in simple language how each part of Stable Diffusion work
f9fb4e9641558bb3f9fd49aca7c972a1
{ "intermediate": 0.08891284465789795, "beginner": 0.05070960521697998, "expert": 0.8603775501251221 }
38,852
spots = np.array([[2,3,4,5,6,7], # имя переменной spots по-английски значит «пятна» [3,4,5,6,7,8], [4,5,6,7,8,9], [5,6,7,8,9,10], [6,7,8,9,10,11], [7,8,9,10,11,12]]) spot_counts = {} for i in range(0, 6): for j in range(0, 6): if spots[i][j] not in spot_counts.keys(): spot_counts[spots[i][j]] = 1 else: spot_counts[spots[i][j]] += 1 обьясни как работает этот код, а именно цикл
bd6aaa420db7e3f3adcb2790f0584dd3
{ "intermediate": 0.34849902987480164, "beginner": 0.3802306354045868, "expert": 0.2712703347206116 }
38,853
Write simple diffusion neural network on Java which generates 16x16 images. Don't use external libraries. Provide two functions: train on images from "dataset/" dir and generate images and save to "output/" dir
2781ffa3cdccadf84201b088b7d5cc82
{ "intermediate": 0.3312258720397949, "beginner": 0.10935670137405396, "expert": 0.5594173669815063 }
38,854
hi
ade8ebae04247cecdd914228f4db42ea
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
38,855
i cant import import azure.ai.vision as sdk
fd0bd6c8326dec210b1bf0ea9989fd82
{ "intermediate": 0.42069050669670105, "beginner": 0.2717878520488739, "expert": 0.30752167105674744 }
38,856
Write Python script which copy png images from "input/" dir to "output/" dir with removing all duplicates
81587f2bdb4b6ba1c02544e464124e28
{ "intermediate": 0.4270631670951843, "beginner": 0.17492642998695374, "expert": 0.39801034331321716 }
38,857
can u change the folder to dynamic detect C:\Users\ADAM7\Desktop\Projects_demo\03_ocr\output like in this code can only work for 1_output only into excel... : import os import azure.ai.vision as sdk import openpyxl from openpyxl.styles import Font, PatternFill from openpyxl.utils import get_column_letter import os # Exported to environment variable, safer and more secure for sensitive information like APIs VISION_ENDPOINT = "https://e1455.cognitiveservices.azure.com/" #os.environ.get("VISION_ENDPOINT") VISION_KEY = "f854095df16b4e889476c0881b81ab44" #os.environ.get("VISION_KEY") if VISION_ENDPOINT is None or VISION_KEY is None: raise ValueError("VISION_ENDPOINT and VISION_KEY must be set in the environment") service_options = sdk.VisionServiceOptions(VISION_ENDPOINT, VISION_KEY) # Specify the paths to your local image files image_paths = [ r'C:\Users\ADAM7\Desktop\Projects_demo\03_ocr\output\1_output\01_lead_number.jpg', r'C:\Users\ADAM7\Desktop\Projects_demo\03_ocr\output\1_output\02_company.jpg', r'C:\Users\ADAM7\Desktop\Projects_demo\03_ocr\output\1_output\03_name.jpg', r'C:\Users\ADAM7\Desktop\Projects_demo\03_ocr\output\1_output\07_industry.jpg', r'C:\Users\ADAM7\Desktop\Projects_demo\03_ocr\output\1_output\08_interest.jpg', r'C:\Users\ADAM7\Desktop\Projects_demo\03_ocr\output\1_output\11_preparedBy.jpg', r'C:\Users\ADAM7\Desktop\Projects_demo\03_ocr\output\1_output\06_category_resized.jpg\06_category_resized.jpg', r'C:\Users\ADAM7\Desktop\Projects_demo\03_ocr\output\1_output\09_product_resized.jpg\09_product_resized.jpg', r'C:\Users\ADAM7\Desktop\Projects_demo\03_ocr\output\1_output\05_nameCards.jpg' ] # Specify corresponding headers headers = ["Lead Number", "Company", "Name", "Industry", "Interest", "Prepared by","Category","Product", "Etc"] # Initialize the Excel workbook and sheet excel_file_path = r'C:\Users\ADAM7\Desktop\Projects_demo\03_ocr\test.xlsx' wb = openpyxl.Workbook() sheet = wb.active # Write headers to the Excel sheet and apply formatting sheet.append(headers) # Header formatting for cell in sheet[1]: cell.font = Font(bold=True) cell.fill = PatternFill(start_color="DDDDDD", end_color="DDDDDD", fill_type="solid") # Initialize a list to store the extracted information extracted_info_list = [] # Iterate through each image path and extract information using OCR for image_path, header in zip(image_paths, headers): with open(image_path, 'rb') as image_file: image_buffer = image_file.read() image_source_buffer = sdk.ImageSourceBuffer() image_source_buffer.image_writer.write(image_buffer) vision_source = sdk.VisionSource(image_source_buffer=image_source_buffer) analysis_options = sdk.ImageAnalysisOptions() analysis_options.features = ( sdk.ImageAnalysisFeature.TEXT ) analysis_options.language = "en" analysis_options.gender_neutral_caption = False image_analyzer = sdk.ImageAnalyzer(service_options, vision_source, analysis_options) result = image_analyzer.analyze() # Extract relevant information from OCR result extracted_info = "" if result.reason == sdk.ImageAnalysisResultReason.ANALYZED and result.text is not None: for line in result.text.lines: extracted_info += line.content + " " # Append the extracted information to the list extracted_info_list.append(extracted_info) # Append the list to the Excel sheet as a single row sheet.append(extracted_info_list) # Auto-adjust column width for column in sheet.columns: max_length = 0 column = [cell for cell in column] for cell in column: try: if len(str(cell.value)) > max_length: max_length = len(cell.value) except: pass adjusted_width = (max_length + 2) sheet.column_dimensions[get_column_letter(column[0].column)].width = adjusted_width # Save the Excel file wb.save(excel_file_path) print(f"Completed. Check '{excel_file_path}' for the results.")
251f13ad38762598435a012cb4ff313d
{ "intermediate": 0.37814244627952576, "beginner": 0.3995683193206787, "expert": 0.22228921949863434 }
38,858
There is Python code for copy pictures and remove duplicates. This code doesn't work well with image hash. Please rewrite it using 90% image equation criteria import os from PIL import Image import hashlib import shutil # Define the input and output directories input_dir = 'input/' output_dir = 'output/' # Create the output directory if it does not exist if not os.path.exists(output_dir): os.makedirs(output_dir) # Helper function to calculate the hash of an image file def get_image_hash(img_path): with Image.open(img_path) as img: # Some images may have an alpha layer, convert to RGB to avoid issues image_data = img.convert('RGB').tobytes() # Create a hash of the image data return hashlib.md5(image_data).hexdigest() # Keep track of image hashes to identify duplicates image_hashes = set() for file_name in os.listdir(input_dir): if file_name.lower().endswith('.png'): # Build the full file path file_path = os.path.join(input_dir, file_name) # Calculate the image hash img_hash = get_image_hash(file_path) # If the hash is new (non-duplicate), copy the image if img_hash not in image_hashes: image_hashes.add(img_hash) dest_path = os.path.join(output_dir, file_name) shutil.copy(file_path, dest_path) print(f"Copied: {file_name}") else: print(f"Duplicate found, skipping: {file_name}") print("Finished copying images.")
f2dcdc15bad90fb9a7bc30b8acdc140c
{ "intermediate": 0.596537172794342, "beginner": 0.18203042447566986, "expert": 0.22143235802650452 }
38,859
1 ANNEXURE 1 Regulation for B.Tech, 2019 2 The A. P. J. Abdul Kalam Technological University Academic Regulations for B. Tech, 2019 This may be called the A. P. J. Abdul Kalam Technological University Academic Regulations for B. Tech, 2019. These are subject to the provisions of the APJ Abdul Kalam Technological University Act, 2015, the statutes and ordinances if any issued in the subject from time to time. It is the express understanding that these regulations are subject to the approval of the concerned statutory bodies of the University. These regulations shall be applicable for students admitted from 2019 onward. 1. Preamble R1.1 The University has the right to modify the regulations from time to time. R1.2 In all matters related to the regulations, the decision of the University and its interpretation given by the BOG shall be final and binding. 2. Admission R2.1 Admission policy, eligibility for admission and admission procedure shall be decided by the University or the competent statutory authority for admissions from time to time. R2.2 If at any time after admission, it is found that a candidate has not fulfilled any of the requirements stipulated by the University or the statutory body concerned, the Vice Chancellor may revoke the admission of the candidate and report the matter to the BOG. R2.3 No student shall be permitted, under any circumstances, to change the branch/stream to which he/she is admitted by the competent authority for admission. R2.4 A student admitted to a particular institute shall continue studying in that institute till the completion of the course, unless he/she is permitted an inter college transfer as per R9.1 to 9.12. 3. Structure of B.Tech. Program. R3.1 The duration of the B.Tech. Program shall be 4 years (8 semesters) R3.2 The maximum duration shall be six academic years spanning 12 semesters. R3.3 Every academic year shall have two semesters “1st July to 31st December (Odd semester)” and “1st January to 30th June (Even semester)”. Each semester shall have minimum of 72 working days. The vacation of the faculty and staff shall be as per the Government orders from time to time. R3.4 Every branch of the B.Tech Program shall have a curriculum and syllabi for the courses approved by the Academic Council. Syllabus for any course shall be normally modified / updated once in four years. However, innovative elective courses can be included as 3 and when required, on the recommendations of the respective Board of Studies and subject to the approval of the Academic Council. All revisions shall be based only on the recommendations of the Board of Studies concerned. R3.5 The academic programs of the University follow the credit system. The general pattern is as below: 1 Hr. Lecture (L) per week 1 credit 1 Hr. Tutorial (T) per week 1 credit 1 to 2 Hours Practical(P) per week 1 credit 3 to 4 Hours Practical(P) per week 2 credit The workload of a faculty member shall be the actual number of hours engaged by the faculty member. R3.6 The curriculum of any branch of the B.Tech. Program shall have a total of 160 academic credits and 2 additional pass/fail credits. R3.7 Every course of B. Tech. Program shall be placed in one of the nine categories as listed in table below. S. No. Category Code Breakup of Credits 1 Humanities and Social Sciences including Management courses HSMC 8 2 Basic Science courses BSC 26 3 Engineering Science courses including workshop, drawing, basics of electrical/mechanical/computer etc ESC 22 4 Professional core courses PCC 76 5 Professional Elective courses relevant to chosen specialization/branch PEC 15 6 Open subjects – Electives from other technical and /or emerging subjects ` as specified in the curriculum concerned. OEC 03 7 Project work, seminar and internship in industry or elsewhere PROJ 10 8 Mandatory Courses [Environmental Sciences, Induction training, Indian Constitution, Essence of Indian Traditional Knowledge] MC Non credit 9 Mandatory Student Activities (Pass/Fail) SA 2 Total Credits 162 4 R3.8 No semester shall have more than six lecture-based courses and two laboratory and/or drawing/seminar/project courses in the curriculum. Credit per semester shall not be less than 15 or greater than 25 and cumulative credits shall not be less than 162. R3.9 The medium of instruction shall be English. All examinations, project/seminar reports and presentations shall be in English. 4. Academic Monitoring and Student Support. R4.1 Advisory System: There shall be one Senior Faculty Advisor (SFA) for a class and a faculty advisor (FA) each for 25 to 35 students in the class. The Principal shall assign a regular faculty member with minimum five years of experience as the Senior Faculty Advisor (SFA) in discussion with the Head of Department concerned. R4.2 The documents regarding all academic and non academic matters of students under an advisory group shall be kept under the custody of Faculty Advisor/Senior Faculty Advisor. R4.3 All requests/applications from a student or parent to higher offices are to be forwarded/recommended by his/her Faculty Advisor/Senior Faculty Advisor. Students and parents shall first approach their Faculty Advisor/ Senior Faculty Advisor for all kinds of advices, clarifications and permissions on academic matters. It is the official responsibility of the institution to provide the required guidance, clarifications and advices to the students and parents strictly based on the prevailing academic regulations. R4.4 The SFA shall arrange separate or combined meetings with advisors; course faculty, Parents and students as and when required and discuss the academic progress of students under their advisory group. The Senior Faculty Advisor/ Faculty Advisor shall also offer guidance and help to solve the issues on academic and non-academic matters including personal issues of the students in their advisory group. Advisory meetings shall preferably be convened: 1. Immediately after the commencement of the semester. 2. Immediately after announcing the marks of first internal evaluation test. The internal marks, activity points earned during the semester and eligibility of attendance shall be uploaded in the University portal only after displaying the same in the department notice board at least for two working days. This is for the information and feed back of the students. Any concerns raised by the students regarding attendance and internal marks and activity points shall be looked into in the combined meetings of advisors, course faculty and the students concerned. The principal/ HoD shall ensure the proper redressal of the concerns raised by the students regarding internal assessment and attendance. The FA/SFA shall be the custodian of the minutes and action taken reports of the advisory meetings. 5 R4.5 The SFA shall get the minutes and action taken reports of advisory meetings approved by the Head of Department and the Principal. It shall be the duty of the HoD and the Principal to produce it before the University as and when required. R4.6 The FA/SFA shall keep a hard copy of the consolidated statement of attendance, activity points and internal marks of the students in their advisory group. It shall be kept with the HoD without fail for all sorts of inspections. R4.7 Regular communication with the parents of students in respect of progress in academic matters and other general issues shall be the responsibility of the Senior Faculty Advisor/ Faculty Advisor. R4.8 The Principal shall inform/forward all regulations, guide lines, communications, announcements etc issued by the University regarding student academic and other matters to the HoDs/ Senior Faculty Advisors for information and timely action. R4.9 It shall be the official responsibility of the Principal to arrange necessary orientation programmes to the HoDs, SFAs and SAs regarding student counseling, the prevailing University norms, regulations, guidelines and procedures on all academic and other University related matters. 5. Academic Auditing of affiliated institutions. R5.1 There shall be academic auditing in each affiliated college at stipulated intervals. The academic auditing shall be conducted jointly by an Internal Quality Assurance Cell (IQAC) within the college and external academic auditor(s) appointed by the University. The Internal Quality Assurance Cell (IQAC) in each college shall oversee and monitor all the academic activities including all internal evaluations and examinations. This cell shall prepare academic audit statements in the formats prescribed by the University for each semester at regular intervals. These reports shall be presented to the external academic auditor(s), who shall use it as reference for independent auditing. The external auditor(s) shall submit the final audit report to the University in the prescribed format. Academic auditing shall cover:- 1. Course delivery and adherence to the course plan, syllabus coverage, quality of question papers used for internal examinations, internal evaluation, maintenance of laboratory experimental set ups and equipments, practical assignments, mini projects and conduct of practical classes and their evaluation. 2. Co-curricular and Extra-curricular activities available for students, the monitoring mechanism of activity points to be earned by the students. 3. Academic functioning of the college encompassing students, faculty and college administration covering punctuality, attendance, discipline, academic, environment, learning ecosystem, academic accountability, academic achievements and benchmarking. 4. The audit shall also cover the quality criteria prescribed by NBA/NAAC. 6 6. Assessment R6.1 There shall be End Semester Examinations (ESE) in every semester for all courses as prescribed under the respective curriculum, except the Lab/ workshops courses for 1 & 2 semesters. The End Semester Examinations shall be conducted by the University. Semester classes shall be completed at least ten days before the commencement of the End Semester Examination. R6.2 The End Semester Examinations (ESE) shall be held twice in a year – May/June session (for even semesters) and November/December session (for odd semesters). However, the End Semester Examinations of the VII and VIII Semesters shall be conducted in both the sessions. R6.3 Candidates in each semester shall be evaluated both by Continuous Internal Evaluation (CIE) and End Semester Examinations (ESE). The ratio of Continuous Internal Evaluation (CIE) to End Semester Examinations (ESE) shall be as below : 1. Theory Courses : 1 : 2 2. Laboratory Courses : 1 : 1 3. Project : CIE only 4. Seminar : CIE only R6.4 Continuous Internal Evaluation (CIE)): The Continuous Internal Evaluation shall be on the basis of the day-to-day work, periodic tests (minimum two in a semester) and assignments (minimum two). The faculty member (s) concerned shall carry out the Continuous Internal Evaluation (CIE) for the course allotted to him/her. The CIE marks for individual subjects shall be computed by giving weightage to the following parameters unless otherwise specified in the curriculum. Course Attendance Tests Assignment/ Class work/ Course project. Theory 20% 50% 30% Drawing/ Practical 20% 40% 40% There shall be minimum two internal evaluation tests, each of 2hrs duration. Each test shall cover 50% of the syllabus and shall be for 50marks. Retest shall be permitted to the students who could not appear for the internal tests due to genuine grounds. Three days shall be utilised for conducting the internal evaluation test. Project work a. Work assessed by the project guide – 30% b. Three member Continuous Internal Evaluation Committee – 40% ( Guide shall be one member in the CIE committee) c. Final Evaluation by a three member Committee comprising of the department project coordinator, guide and an external expert. The external expert shall be an academician or from industry. The industry expert is preferred : 30% d. One third of the project credit shall be completed in VII semester and two third in VIII semester. 7 Seminar The report and the presentation shall be evaluated by a team of internal members comprising three senior faculty members based on the style of presentation, technical content, adequacy of reference, depth of knowledge and overall quality of the report. a) Attendance : 10% b) Guide : 20% c) Technical content : 30% d) Presentation : 40% The CIE marks for the attendance (20%) for each theory, practical and drawing shall be awarded in full, only if the candidate has secured 90% attendance or above in the subject. If a student has attendance for a subject below 90%, reduction in the marks for the attendance shall be made proportionally. The CIE marks obtained by the student for all subjects in a semester are to be published at least 5 days before the commencement of the University examinations. Duty leave shall be accounted for awarding the internal marks for attendance. R6.5 Students, who have completed a course but could not write the end semester examination, shall be awarded “I’ Grade, provided they meet other eligibility criteria (R6.6). They shall register (exam registration) and appear for the end semester examination at the next opportunity and earn the credits without having to register (course registration) for the course again. R6.6 The main eligibility criteria for registering to the End Semester Examination are attendance in the course and no pending disciplinary action. The minimum attendance for appearing for the End Semester Examination is 75% in each course. Students who do not meet these eligibility criteria are awarded an FE grade. R6.7 The students with FE grade shall register for the courses during the normal semesters in which the courses are offered. However, for the seventh and eighth semester FE grade students can register for the courses in the next immediate chance, if offered by their institute. R6.8 A student who does not register for all the courses listed in the curriculum for a semester shall not be eligible to enroll for the next higher semester. R6.9 The maximum number of credits a student can register (course registration) for, in a semester is limited to 08 credits in excess of the total mandatory credits allotted in the curriculum for that semester. R6.10 A student will be eligible for the award of B. Tech. Degree of the University on satisfying the following requirements: 1. Fulfilled all the curriculum requirements within the stipulated duration of the course. 2. Earned the required minimum credits as specified in the curriculum for the branch of study (R3.6 and R3.7). 3. No pending disciplinary action. 8 R6.11 Students registered for a course have to attend the course regularly and undergo the Continuous Internal Evaluation (CIE) and appear for the End Semester Examinations (ESE). Credits for the course are deemed to be earned only on getting at least a pass grade ‘P’ or better in the composite evaluation. R6.12 Pass minimum for a course shall be 40% for the End Semester Examination and 50% of CIE and ESA put together. Letter grade ‘F’ will be awarded to the student for a course if either his/her mark for the End Semester Examination (ESE) is below 40 % or the overall mark [Continuous Internal Evaluation (CIE) + End Semester Examination (ESE)] is below 50 %. R6.13 Students who received F grade in an End Semester Examination shall have to appear for the End Semester Examination at the next opportunity and earn the credits. They shall not be permitted to register for the course again. R6.14 Continuous Internal Evaluation mark percentage shall not exceed 30% over the End Semester Examination mark %. CIE marks awarded to a student shall be normalised accordingly. For example if the end semester mark % is 40, then the maximum eligible CIE mark % is 40+30 = 70 %.) R6.15 Grading is based on the overall % marks obtained by the student in a course, as given in 6.16. The grade card shall only give the grades against the courses the student has registered. Semester grade card shall give the grade for each registered course, Semester Grade Point Average (SGPA) for the semester as well as Cumulative Grade Point Average (CGPA). R6.16 Grade and Grade Points Grades Grade Point (GP) % of Total Marks obtained in the course S 10 90% and above A+ 9.0 85% and above but less than 90% A 8.5 80% and above but less than 85% B+ 8.0 75% and above but less than 80% B 7.5 70% and above but less than 75% C + 7.0 65% and above but less than 70% C 6.5 60% and above but less than 65% D 6.0 55% and above but less than 60% P (Pass) 5.5 50% and above but less than 55% F (Fail) 0 Below 50% (CIE + ESE) or Below 40 % for ESE FE 0 Failed due to lack of eligibility criteria (R6.6) I 0 Could not appear for the end semester examination but fulfills the eligibility criteria. Classification of B. Tech Degree. First Class with Distinction CGPA 8.0 and above First Class CGPA 6.5 and above Equivalent percentage mark shall be = 10 * CGPA – 2.5 9 R6.17 Minimum Cumulative Credit Requirements for Registering to Higher Semesters Semester Allotted Credits Cumulative Credits Minimum Cumulative Credits required for B. Tech Minimum Cumulative Credits required for B. Tech Lateral Enrty. First 17 17 Not Applicable Not Applicable Second 21 38 Not Insisted Not Insisted Third 22 60 Not Insisted Not Insisted Fourth 22 82 Not Insisted Not Insisted Fifth 23 105 21 Credits from S1& S2 Not Insisted Sixth 24 129 Not Insisted Not Insisted Seventh 15 144 47 Credits from S1 to S4 09 Credits from S3 to S4 Eight 16 160 Not Insisted Not Insisted R6.18 There is no provision for improving the grade. However, the student is permitted to check the answer books of the End Semester Examination after the results are declared, on payment of the prescribed fee. Any discrepancy in evaluation could be brought to the notice of the Controller of Examination, who shall initiate appropriate action as per the University Examination Manual. R.6.19 The students can apply for revaluation of the answer books of the end semester examination after the results are declared. The final mark awarded will be the better of the two marks. If the difference in marks obtained in revaluation and the original valuation is more than 15% of the maximum marks, it shall be sent for third valuation. The final mark shall then be the average of the closer of the two marks obtained in the three valuations to the advantage of the student or the mark obtained in the original valuation whichever is higher. The Controller of Examination shall examine such cases and conduct proper enquiry to see whether any of the examiners is responsible for negligent valuation of answer script and initiate suitable action as per the University Examination Manual. R6.20 Grade cards shall be made available in the student login for the registered courses, in every semester. On earning the required credits for the degree, the University will issue the final consolidated grade sheet for the B. Tech program including CGPA. R6.21 Calculation of SGPA/CGPA Semester Grade Point Average (SGPA) and Cumulative Grade Point Average (CGPA) are calculated as follows. SGPA = Σ(Ci×GPi)/ΣCi , where ‘Ci’ is the credit assigned for a course and ‘GPi’ is the grade point for that course. Summation is done for all courses specified in the curriculum of that semester. The failed and incomplete courses shall also be considered in the calculation. CGPA = Σ(Ci×GPi)/ΣCi , where ‘Ci’ is the credit assigned for a course and ‘GPi’ is the grade point for that course. Summation is done for all courses specified in the 10 curriculum up to that semester for which the ‘CGPA’ is needed. Here the failed courses shall also be accounted. CGPA for the B. Tech programme is arrived at by considering all course credits that are needed for the degree and their respective grade points. For students admitted under lateral entry scheme, credits for the first and second semester courses shall not be accounted for the calculation of CGPA. Equivalent percentage mark shall be = 10 * CGPA – 2.5 R6.22 Any act of violation of University directions, indiscipline, misbehavior, or unfair practice in examinations from the part of students, faculty members, staff, institution, management or any other source shall be viewed very seriously. It is the legal responsibility of the principal and the college management to see that the examinations are conducted strictly as per the directions of the University and as specified in the examination Manual. Malpractices in examinations observed or reported by an official employed by the University, faculty member, invigilator or anybody shall be immediately reported to the Principal. The principal shall in turn conduct a preliminary enquiry giving the student concerned a chance to explain his/her case. The Principal shall then forward the case with his/her preliminary enquiry report and remarks to the Controller of Examinations along with all related documents and evidences within two working days. The Controller of examination shall decide the course of action on the issue as per the prescribed norms in the University Examination Manual. R6.23 A student shall earn 2 credits by actively involving in co – curricular and extra – curricular activities as per the guidelines issued by the University from time to time. On getting minimum 100 activity points the student passes the course and earns the two credits which shall not be counted for the calculation of CGPA but mandatory for the award of the Degree. For the students admitted under lateral entry scheme the 2 credits shall be considered to be earned on getting 75 activity points. The students are required to keep a file containing documentary proofs of activities done by him/her attested by the Senior Faculty Advisor/ Faculty Advisor. 7. Break of Study R7.1 A student is permitted to avail break of study: i) In case of accident or serious illness needing prolonged hospitalization and rest. ii) In case the student has a bright idea and would like to initiate a start-up venture or develop a product. iii) In case of any personal reasons that need a break in study. iv) For internship leading to employment. For break of study due to illness, student shall submit all necessary medical reports together with the recommendation of the doctor treating him giving definite reasons for break of study and its duration. Before joining back, the student should submit the fitness certificate from the doctor who treated him. Students who want to initiate a start-up venture or a product development, have to 11 submit a project report, clearly indicating the purpose, action plan, technical details, funding details and future plans to the college Principal. The Principal shall evaluate the proposal by constituting an expert team consisting of a technocrat and a bank executive and take an appropriate decision based on the team’s recommendation. The break of study for the start up shall be permitted only after the 4th semester for a maximum duration of two semesters. This is however permitted only on successfully completing the courses listed out in the first two semesters. Students who require a break in study due to personal reasons shall convince the Principal on the genuine need for it by giving authentic evidence for the same. Students who require break in study for ‘internship leading to employment’ shall produce the offer letter obtained from the employer concerned. The principal shall verify the authenticity of the offer and submit his recommendation to the University sufficiently in advance for approval. Only campus placed students with an annual compensation more than 6 lakhs are eligible to avail this facility. In the semester system followed by the University, break of study for an academic year is the preferred option than break of study for a semester. The student can avail the break of study only with the prior approval of the University. The Principal shall upload the request of the student with all relevant documents to the University portal for the approval with his/her recommendations. Students shall have to rejoin on the first working day of the same semester on which he/she had started availing the break of study. 8.Attendance R8.1 Students are expected to attain 100% attendance for all courses. However, under unavoidable circumstances they are permitted to avail leave. Total leave of absence shall not exceed 25% of the academic contact hours for a course and 75% attendance is mandatory for registering to the end semester examination. On medical ground the college Principal can relax the minimum attendance requirement to 60%, to write the end semester examination. This is permitted for one or more courses registered in the semester. Principal shall keep all records which led to his decision on attendance, for verification by the Academic Auditors/ University officials. This provision is applicable only to any two semesters during the entire program period. In case of prolonged illness, break of study is permitted as per R7.1. R8.2 The Principals are authorized to grant attendance relaxation (duty leave) to the students in officially sponsored national level competitions/championships/ tournaments when called upon to do so, up to a maximum of 10%. Such students should produce the participation certificate countersigned by the University Sports Coordinator/ the Director of Physical Education in the case of sports activities and the Senior Faculty Advisor in the case of other extracurricular activities: within ten days of the event. The participation certificate thus produced shall be forwarded to the Principal with the due recommendation of the respective Head of the Department. Under any circumstances, the principal shall not consider the certificate if the overall attendance of the candidate is less than 60%. Late applications received shall not be considered on any account. The student shall get official prior permission from the University for representing the University. 12 8.3 The Principals are authorized to grant attendance relaxation (duty leave) to the students for organizing extra/ co-curricular activities, up to a maximum of 05%. Such students should produce the required documents countersigned by the University Sports Coordinator/ the Director of Physical Education in the case of sports activities and the Senior Faculty Advisor in the case of other extra/ co-curricular activities: within ten days of the events. The documents thus produced shall be forwarded to the Principal with the due recommendation of the respective Head of the Department. Under any circumstances, the principal shall not consider the documents, if the overall attendance of the candidate is less than 60%. Late applications received shall not be considered on any account. 9.Inter College Transfer R9.1 Inter college transfer shall be applicable only for regular B. Tech students. R9.2 The transfer shall be permitted just before the commencement of third semester. R9.3 The transfer shall be with effect from the first working day of the third semester. R9.4 The transfer shall be only within the sanctioned strength of the receiving college. R9.5 The following Category of students shall not be eligible for inter college transfer 1. Govt. of India Nominee. 2. Management Quota in Aided colleges. 3. Management Quota in private Self Financing Colleges 4. Students admitted under NRI/PIO quota. 5. Lateral Entry students. 6. Students admitted under TFW Scheme. 7. Students admitted in any supernumerary seats. 8. Any other category which are ineligible as per the conditions for admission prescribed by Govt. of Kerala/Govt. of India. R9.6 The transfer shall be permitted: 1. Between Govt/ Govt. Aided Colleges. 2. Between Self – Financing Colleges. (Including Govt. Controlled SFC). R9.7 Notification inviting application for inter college transfer shall be issued by the University just before the commencement of the third semester. R9.8 The candidate should fulfill the academic eligibility requirement for promotion to the third semester. R9.9 If the number of applicants is more than the vacant seats available, the transfer may be based on the Kerala Engineering Entrance Rank. R9.10 The students shall opt only one college for inter college transfer. R9.11 The selected candidates shall remit a fee of Rs 3000/- (No fee for SC/ST students) within the stipulated date to the University. However, this rule is not applicable to the students transferred to other institutes under “Shift College” University order. R9.12 The College transfer once approved by the receiving college will be final and binding on the applicant. No student will be permitted, under any circumstances, to refuse the change of college once offered. 13 10.Migration from other Universities R10.1 Migration to the University from other Universities shall be permitted only if the parent University and the APJ Abdul Kalam Technological University enters into a bipartite agreement/ MoU for this purpose. However, this condition is not applicable to the students in any of the Engineering colleges/ institutions, which, before the commencement of KTU Act remained affiliated to Universities except Deemed to be Universities in the State of Kerala. R10.2 The student shall be permitted to migrate only if he/she fulfills the University eligibility criteria for admission to the course applied for migration. R10.3 The migration shall be permitted only up to the fifth semester of the B. Tech program and half the duration of the program in the case of other programs. R10.4 The admission shall be offered on migration basis through lateral transfer of credits. Lateral credit transfer shall be as recommended by the concerned Board of Studies. R10.5 The students shall be allowed to migrate to the University subject to satisfying the rules and regulations of the University as regards to, maximum number of backlogs, grade points, minimum credit requirement for promotion to higher semesters, etc. R10.6 The student shall be offered admission in any of the affiliated colleges/institutions of the University subject to availability of seats. The student shall produce no objection certificate from the concerned college/institute in this regard. R10.7 The students offered admission shall have to take transitory courses/ additional courses of the previous semesters to satisfy the program requirement as recommended by the concerned board of studies. R10.8 The students offered admission shall pay the migration fees and the University fees as prescribed by the University. The application processing fee (University fee) shall be Rs 5000/- (Rupees five thousand only) and the migration fees shall be Rs 20000/- (Rupees twenty thousand only). The migration fee is charged for the meeting expenses of the concerned Board of studies to decide on the student suitability for migration and to recommend the transitory courses/ additional courses to be done by the student to fulfill the academic requirement of the University. The processing fee shall be paid along with the application, and the migration fee shall be paid to the University at the time of offering admission. The fee once paid shall not be refunded under any circumstances. The students in any of the Engineering colleges / institutions, which, before the commencement of KTU Act remained affiliated to Universities except Deemed to be Universities in the State of Kerala, are exempted from paying the processing fee and the migration fee. R10.9 The migrated students shall follow the rules and regulations of the University. R10.10 The students offered admission shall produce a migration certificate from the parent University at the time of admission. R10.11 The student offered admission shall produce a character certificate from the parent institute/University at the time of admission. R10.12 Regulations, Scheme and Syllabus of the respective specialization attested by the Registrar of the parent University or equivalent authority shall be submitted to the University along with the application seeking migration to the University. R10.13 Attested copies of all certificates and mark lists from 10th onwards shall be submitted along with the application for migration (Original certificates and mark lists shall be 14 produced as and when required by the University). R10.14 Assessment of the student suitability for migration in terms of programs, backlogs, grade points, credit requirements, etc shall be done by the concerned Board of Studies. R10.15 Assessment of the transitory courses/ additional courses to be done by the student as per the academic requirement of the University shall be as recommended by the concerned Board of Studies. 11. Minor in Engineering. R11.1 All B. Tech students shall be eligible to register for Minor in Engineering. R11.2 The Minor in Engineering registration shall be along with the registration of the 3rd semester. R11.3 If a student fails in any course of the minor, he/she shall not be eligible to continue the B.Tech Minor. However, the additional credits and grades thus far earned by the student shall be included in the grade card but shall not be considered in calculating the CGPA. R11.4 The student shall earn additional 20 credits to be eligible for the award of B. Tech Degree with Minor. R11.5 Out of the 20 Credits, 12 credits shall be earned by undergoing a minimum of three courses, during the specified period. The total number of contact hours for these three courses shall be 126 Hrs (42Hrs/course). The duration of a course shall be minimum 14 weeks. The remaining 8 credits could be acquired through two MOOCs recommended by the Board of studies and approved by the Academic Council. R11.6 Curriculum and the syllabus of the three courses shall be approved by the Board of studies and the Academic Council. R11.7 The assessment of the courses other than MOOCs and earning of credits shall be as per R6.1 to R6.23. The assessment and certification of the MOOCs shall be as per the prescribed norms of the MOOCs. The candidate shall produce the certification issued by the MOOCs conducting agency in proof of credit attainment. R11.8 Under graduate Degree with minor shall be issued by the University to the students who fulfill all the academic eligibility requirements for the B. Tech program and Minor in Engineering. 12. B. Tech (Honours) R12.1 All B. Tech students are eligible to register B.Tech (Honours). However, their mandatory CGPA at the end of eighth semester shall be 8.5 or higher to be eligible for the award of B. Tech (Honours). R12.2 The B. Tech (Honours) registration shall be along with the registration of the 4th semester. R12.3 If a student fails in any course including the course chosen for B. Tech (Honours), he/she shall not be eligible to continue the B.Tech(Honours). However, the additional credits thus far earned by the student shall be included in the grade card but shall not be considered in calculating the CGPA. R12.4 The student shall earn additional 20 credits to be eligible for the award of B. Tech (Honours) Degree. 15 R12.5 Out of the 20 Credits, 12 credits shall be earned by undergoing minimum three specified B. Tech (Honours) Elective courses of the respective stream. Credits for the B. Tech (Honours) Elective courses are deemed to be earned only on getting at least a grade ‘C’ or better in the composite evaluation. A student shall not be permitted to select the normal elective courses of the respective B. Tech programs for attaining the credit requirements of B. Tech (Honours). The remaining 8 credits could be acquired through two MOOCs of the respective streams recommended by the Board of studies and approved by the Academic Council. R12.6 The assessment and certification of the MOOCs shall be as per the prescribed norms of the MOOCs. The candidate shall produce the certification issued by the MOOCs conducting agency in proof of credit attainment. R12.7 The institutions offering B. Tech Honours programs shall not charge any additional fee from the students. R12.8 B. Tech (Honours) Degree shall be issued by the University to the students who fulfill all the academic eligibility requirements for the B. Tech and B. Tech (Honours) programs. 13. Grace Marks for Sports /Arts Competitions. R13.1 Only bona-fide, regular candidates are eligible for the award of Grace Marks. R13.2 The criterion for the award of Grace Marks is representing the University in officially sponsored national level competitions/championships/ tournaments when called upon to do so. The student shall get official prior permission from the University for representing the University. R13.3 The maximum grace marks that can be awarded to a candidate in a particular semester for all activities put together shall be 5% of the aggregate maximum End Semester Examination marks of all theory courses for which the University conducts End Semester Examinations. R13.4 The maximum grace marks that can be awarded to a student for a theory course in a particular semester for all activities put together shall not exceed 10% of the maximum aggregate marks of End Semester Examination of the course. R13.5 The Grace Marks shall not be awarded to a student for Practical/ Lab/ Viva Voce/ internal assessment/ Seminar etc even though she/he fails for the same. R13.6 Eligible Grace Marks shall be distributed equally on all theory papers/courses of an examination. However, re – distribution of Grace Marks shall be allowed only in the case of those courses of an examination for which the candidate has passed. Re- distribution is possible from passed courses to failed courses only. Re-distribution of Grace Marks is not permissible from failed courses to other courses for a pass. R13.7 The Grace Marks shall be awarded for all theory papers/courses/subjects in a semester. R13.8 Re- distribution shall be done only for enabling a candidate to obtain the minimum marks required for a pass. R13.09 Grace Marks shall not be re – distributed from one semester to another semester. R13.10 If the candidate does not secure the minimum marks required for a pass even after effecting re- distribution, eligible moderation fixed by the respective board if any, shall be awarded to that candidate in addition to the Grace Marks for a pass. R13.11 Eligible Grace Marks shall be awarded for the regular examination of the performing semester only. Grace Marks shall not be awarded for supplementary examinations. 16 R13.12 The performing semester shall be considered from 1st July to 31st December (Odd semester) and 1st January to 30th June (Even Semester). R13.13 Grace Marks shall be awarded on the basis of performance in the respective semester. R13.14 The request for Grace Marks shall be submitted to the Controller of Examinations through the principal along with all relevant documents, within the time limit prescribed by the University. The request for Grace Marks received after the time limit shall not be entertained on any account. R13.15 Only a single highest achievement during the period of a semester shall be considered for awarding the grace marks. 14.Grace Marks for Persons With Disability (PWD) R14.1 A person with disability means a person suffering from not less than 40% of any disability as certified by the District Medical Board. To be eligible for the grace marks, the certificate of disability specifying the percentage of disability shall be produced before the Principal at the time of admission. R14.2 The Grace Marks that can be awarded for PWD candidates shall be 25% of the marks scored by the candidate in each course at the time of finalization of the results. R14.3 Transfer of marks from one paper to another shall not be permitted. Fractions of marks if any, while computing the Grace Marks shall be rounded off to the next higher integer. R14.4 PWD candidates who are eligible for Grace Marks shall be awarded Grace Marks for regular and supplementary chances until they pass the whole examination. R14.5 Grace Marks shall be awarded only for the marks of the End Semester Examinations conducted by the University. R14.6 The request for Grace Marks shall be submitted to the Controller of Examinations through the principal along with all relevant documents, within the time limit prescribed by the University. The request for Grace Marks received after the time limit shall not be entertained on any account. 15. Transitory provision. 15.1 Notwithstanding anything contained in these regulations, the Vice-Chancellor shall, for a period of two years from the date of coming into force of these regulations, has the power to provide by order that these Regulations shall be applied to any B. Tech program with such modifications as may be necessary.
feb1dad7ae28a1ff72e397237a50e9af
{ "intermediate": 0.39992472529411316, "beginner": 0.31012094020843506, "expert": 0.2899543046951294 }
38,860
hello
11b7b0ee94be23de55bcb05793047d18
{ "intermediate": 0.32064199447631836, "beginner": 0.28176039457321167, "expert": 0.39759764075279236 }
38,861
Best industrial mods for Minecraft 1.19.2 ?
57eaaf9350f8c4df516173555bbd6ae7
{ "intermediate": 0.3340262174606323, "beginner": 0.35626572370529175, "expert": 0.30970802903175354 }
38,862
Write Python script to record speech from mic and recognize it to russian text. At beginning pressing enter for start audio capture and second press enter for stop capturing. Avoid errors in your Python script
1e75306b574a00af5be2bcb91c536024
{ "intermediate": 0.29670584201812744, "beginner": 0.14517606794834137, "expert": 0.5581180453300476 }
38,863
Give me example of simple connection of two Python scripts by ip address and port. It support transmit packets of data. Simplify code as possible
30d0db7c859604971f6a5a9da8d88682
{ "intermediate": 0.5202741622924805, "beginner": 0.1859503984451294, "expert": 0.2937754988670349 }
38,864
Give me example of simple connection of two Python scripts by ip address and port. It support transmit packets of data. Simplify code as possible
65793bfc7d97640adcbaa6c45ca02d0e
{ "intermediate": 0.5202741622924805, "beginner": 0.1859503984451294, "expert": 0.2937754988670349 }
38,865
help me solve so it crops the found text so you see the full width of the original picture but the height of the found pattern import cv2 import pytesseract import re # Load image and convert to grayscale image = cv2.imread("vavavav.png") gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) text = pytesseract.image_to_string(image) # Get verbose data including bounding boxes data = pytesseract.image_to_data(gray, output_type=pytesseract.Output.DICT) # Define the pattern to search for pattern = r"Tovchnebaby|Tovchnèbaby|Tovchne\s*baby|Touchmebaby" found = False # Iterate over each text item for i in range(len(data['text'])): print(data) if re.search(pattern, data['text'][i], re.I): x = data["left"][i] y = data["top"][i] w = data["width"][i] h = data["height"][i] # Keep full x-axis length crop = image[y:y+h-20, 0:image.shape[1]] cv2.imshow('crop',crop) input("Press any key to continue...") # Extract number from crop text = pytesseract.image_to_string(crop) print(text) num = re.search(r'\d+', text) if num: print(int(num.group())) else: print("No number found") break if not found: print("No match found for the pattern.")
5a52d4430b82d90b83ed44dfc07f4f97
{ "intermediate": 0.6163522005081177, "beginner": 0.20712262392044067, "expert": 0.17652513086795807 }
38,866
Make me a snake game on python with these features: score, high score, png background, fail and eat sound, background music, difficulty selector at launch, control by arrow keys
29070dee64dbf343fe469101deb290a1
{ "intermediate": 0.4233395457267761, "beginner": 0.22332298755645752, "expert": 0.35333743691444397 }
38,867
hi
79459bad991c0634de8150da7ea409e4
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
38,868
load vgg model .h5
0fb3b7e77eb67a103b61fc617d2eb255
{ "intermediate": 0.2689974904060364, "beginner": 0.26386070251464844, "expert": 0.4671418368816376 }
38,869
j'ai un fichier php : <?php use DB\DataBaseManager; $manager = new DataBaseManager(); $artistDB = $manager->getArtistDB(); $liste_artistes = $artistDB->findAll(); $pageSize = 10; $page = isset($_GET['page']) ? intval($_GET['page']) : 1; $offset = ($page - 1) * $pageSize; $sonDB = $manager->getSonDB(); $liste_sons = $sonDB->findAll($offset, $pageSize); $genreDB = $manager->getGenreDB(); $liste_genres = $genreDB->findAll(); $utilisateurDB = $manager->getUtilisateurDB(); $liste_utilisateurs = $utilisateurDB->findAll(); $playlistDB = $manager->getPlaylistDB(); $liste_playlists = $playlistDB->findAll(); $albumDB = $manager->getAlbumDB(); $liste_albums = $albumDB->findAll(); ?> <aside> <div class="left"> <a href="index.php?action=accueil" class="btn-retour"> <svg width="26" height="16" viewBox="0 0 26 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M8.22816 1.73682L2.00009 7.96489M2.00009 7.96489L8.22816 14.193M2.00009 7.96489H24.4211" stroke="currentColor" stroke-width="2.49123" stroke-linecap="round" stroke-linejoin="round"/> </svg> Retour application </a> <nav> <ul> <li> <a href="" id="goToMenuPrincipal"> <svg width="27" height="17" viewBox="0 0 27 17" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M1.83325 1.2085H25.1666M1.83325 8.50016H25.1666M1.83325 15.7918H25.1666" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> Menu principal </a> </li> <li> <a href="" id="goToArtistes"> <svg width="30" height="23" viewBox="0 0 30 23" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M23.9866 21.7082H26.1667C27.7775 21.7082 29.1809 20.3606 28.6692 18.8332C27.8893 16.5055 25.9706 15.0979 22.5977 14.6103M18.146 9.84388C18.5703 9.97801 19.0564 10.0415 19.6042 10.0415C22.0347 10.0415 23.25 8.7915 23.25 5.6665C23.25 2.5415 22.0347 1.2915 19.6042 1.2915C19.0564 1.2915 18.5703 1.355 18.146 1.48913M10.8542 14.4165C16.6277 14.4165 19.4474 16.1838 20.1527 19.7183C20.3689 20.8015 19.4379 21.7082 18.3333 21.7082H3.375C2.27043 21.7082 1.33943 20.8015 1.5556 19.7183C2.26098 16.1838 5.08064 14.4165 10.8542 14.4165ZM10.8542 10.0415C13.2847 10.0415 14.5 8.7915 14.5 5.6665C14.5 2.5415 13.2847 1.2915 10.8542 1.2915C8.42361 1.2915 7.20833 2.5415 7.20833 5.6665C7.20833 8.7915 8.42361 10.0415 10.8542 10.0415Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> Artistes </a> </li> <li> <a href="" id="goToSons"> <svg width="29" height="29" viewBox="0 0 29 29" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M5.75 14.5C5.75 11.2613 7.50962 8.43351 10.125 6.92059M23.25 14.2123C23.25 17.451 21.4904 20.2788 18.875 21.7917M27.625 14.5C27.625 21.7487 21.7487 27.625 14.5 27.625C7.25126 27.625 1.375 21.7487 1.375 14.5C1.375 7.25126 7.25126 1.375 14.5 1.375C21.7487 1.375 27.625 7.25126 27.625 14.5ZM17.4167 14.5C17.4167 16.1108 16.1108 17.4167 14.5 17.4167C12.8892 17.4167 11.5833 16.1108 11.5833 14.5C11.5833 12.8892 12.8892 11.5833 14.5 11.5833C16.1108 11.5833 17.4167 12.8892 17.4167 14.5Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> Sons </a> </li> <li> <a href="" id="goToGenres"> <svg width="23" height="20" viewBox="0 0 23 20" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M1.29175 7.04183H15.8751M1.29175 1.2085H15.8751M1.29175 12.8752H10.0417M15.8751 12.8752V18.7085L21.7084 15.7918L15.8751 12.8752Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> Genres </a> </li> <li> <a href="" id="goToUtilisateurs"> <svg width="23" height="27" viewBox="0 0 23 27" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M18.2405 24.7722C19.8065 24.7722 21.1404 23.4819 20.7854 21.9567C19.9025 18.1628 16.9499 16.2658 11.1519 16.2658C5.35387 16.2658 2.40129 18.1628 1.51836 21.9567C1.16341 23.4819 2.49732 24.7722 4.06329 24.7722H18.2405Z" stroke="currentColor" stroke-width="2.83544" stroke-linecap="round" stroke-linejoin="round"/> <path fill-rule="evenodd" clip-rule="evenodd" d="M11.1519 12.0127C13.9873 12.0127 15.4051 10.5949 15.4051 7.05063C15.4051 3.50633 13.9873 2.08861 11.1519 2.08861C8.31645 2.08861 6.89873 3.50633 6.89873 7.05063C6.89873 10.5949 8.31645 12.0127 11.1519 12.0127Z" stroke="currentColor" stroke-width="2.83544" stroke-linecap="round" stroke-linejoin="round"/> </svg> Utilisateurs </a> </li> <li> <a href="" id="goToPlaylists"> <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M1 3C1 1.89543 1.89543 1 3 1H4C5.10457 1 6 1.89543 6 3V4C6 5.10457 5.10457 6 4 6H3C1.89543 6 1 5.10457 1 4V3Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> <path d="M10 3C10 1.89543 10.8954 1 12 1H13C14.1046 1 15 1.89543 15 3V4C15 5.10457 14.1046 6 13 6H12C10.8954 6 10 5.10457 10 4V3Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> <path d="M1 12C1 10.8954 1.89543 10 3 10H4C5.10457 10 6 10.8954 6 12V13C6 14.1046 5.10457 15 4 15H3C1.89543 15 1 14.1046 1 13V12Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> <path d="M10 12C10 10.8954 10.8954 10 12 10H13C14.1046 10 15 10.8954 15 12V13C15 14.1046 14.1046 15 13 15H12C10.8954 15 10 14.1046 10 13V12Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> Playlists </a> </li> <li> <a href="" id="goToAlbums"> <svg width="27" height="27" viewBox="0 0 27 27" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M8.8125 21.8333C8.8125 24.1345 7.06361 26 4.90625 26C2.74889 26 1 24.1345 1 21.8333C1 19.5321 2.74889 17.6667 4.90625 17.6667C7.06361 17.6667 8.8125 19.5321 8.8125 21.8333ZM8.8125 21.8333V3.57439C8.8125 3.05949 9.20349 2.62875 9.71598 2.57906L24.9035 1.10633C25.4912 1.04934 26 1.51124 26 2.10166V20.1667M26 20.1667C26 22.4679 24.2511 24.3333 22.0938 24.3333C19.9364 24.3333 18.1875 22.4679 18.1875 20.1667C18.1875 17.8655 19.9364 16 22.0938 16C24.2511 16 26 17.8655 26 20.1667Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> Albums </a> </li> </ul> <div class="active-square" id="activeSquare"></div> </nav> <div class="actions"> <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M10 6V14M14 10H6M10 19C14.9706 19 19 14.9706 19 10C19 5.02944 14.9706 1 10 1C5.02944 1 1 5.02944 1 10C1 14.9706 5.02944 19 10 19Z" stroke="#E2FF08" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> </div> </div> </aside> <div class="right"> <!-- barre de recherche --> <div id="recherche" class="wrapper-recherche"> <div class="text-field"> <img src="/Assets/icons/search.svg" alt="user"/> <input type="text" placeholder="Ma recherche" value=""> </div> </div> <div class="container-tabs"> <main> <section id="pagePrincipale" class="page"> <header> <h2>Menu principal</h2> <svg width="29" height="29" viewBox="0 0 39 39" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M37.6118 9.82166L27.9072 14.9928C32.319 9.33028 28.353 1.28109 19.1767 0V9.98935C15.8932 3.95635 6.60488 3.25634 0.923272 9.82361L10.2961 14.8173C2.99181 14.4254 -2.30948 21.4977 1.01413 29.3226L10.8413 24.0871C6.34922 29.619 9.45097 38.5008 19.1746 39V28.1059C21.8685 34.7941 32.0717 37.0091 37.5188 29.3226L27.2966 23.8766C34.9199 25.066 42.0996 18.019 37.6118 9.82361V9.82166Z" fill="#E2FF08"/> </svg> </header> <div class="menu"> <button class="admin-content"> <svg width="29" height="29" viewBox="0 0 30 23" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M23.9866 21.7082H26.1667C27.7775 21.7082 29.1809 20.3606 28.6692 18.8332C27.8893 16.5055 25.9706 15.0979 22.5977 14.6103M18.146 9.84388C18.5703 9.97801 19.0564 10.0415 19.6042 10.0415C22.0347 10.0415 23.25 8.7915 23.25 5.6665C23.25 2.5415 22.0347 1.2915 19.6042 1.2915C19.0564 1.2915 18.5703 1.355 18.146 1.48913M10.8542 14.4165C16.6277 14.4165 19.4474 16.1838 20.1527 19.7183C20.3689 20.8015 19.4379 21.7082 18.3333 21.7082H3.375C2.27043 21.7082 1.33943 20.8015 1.5556 19.7183C2.26098 16.1838 5.08064 14.4165 10.8542 14.4165ZM10.8542 10.0415C13.2847 10.0415 14.5 8.7915 14.5 5.6665C14.5 2.5415 13.2847 1.2915 10.8542 1.2915C8.42361 1.2915 7.20833 2.5415 7.20833 5.6665C7.20833 8.7915 8.42361 10.0415 10.8542 10.0415Z" stroke="#FEFCE1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> <div class="textes"> <h3>Artistes</h3> <p>Les artistes de l'application</p> </div> </button> <button class="admin-content"> <svg width="29" height="29" viewBox="0 0 29 29" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M5.75 14.5C5.75 11.2613 7.50962 8.43351 10.125 6.92059M23.25 14.2123C23.25 17.451 21.4904 20.2788 18.875 21.7917M27.625 14.5C27.625 21.7487 21.7487 27.625 14.5 27.625C7.25126 27.625 1.375 21.7487 1.375 14.5C1.375 7.25126 7.25126 1.375 14.5 1.375C21.7487 1.375 27.625 7.25126 27.625 14.5ZM17.4167 14.5C17.4167 16.1108 16.1108 17.4167 14.5 17.4167C12.8892 17.4167 11.5833 16.1108 11.5833 14.5C11.5833 12.8892 12.8892 11.5833 14.5 11.5833C16.1108 11.5833 17.4167 12.8892 17.4167 14.5Z" stroke="#FEFCE1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> <div class="textes"> <h3>Sons</h3> <p>Les sons de l'application</p> </div> </butt> <button class="admin-content"> <svg width="29" height="29" viewBox="0 0 23 20" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M1.29175 7.04183H15.8751M1.29175 1.2085H15.8751M1.29175 12.8752H10.0417M15.8751 12.8752V18.7085L21.7084 15.7918L15.8751 12.8752Z" stroke="#FEFCE1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> <div class="textes"> <h3>Genres</h3> <p>Les genres de l'application</p> </div> </button> <button class="admin-content"> <svg width="29" height="29" viewBox="0 0 23 27" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M18.2405 24.7722C19.8065 24.7722 21.1404 23.4819 20.7854 21.9567C19.9025 18.1628 16.9499 16.2658 11.1519 16.2658C5.35387 16.2658 2.40129 18.1628 1.51836 21.9567C1.16341 23.4819 2.49732 24.7722 4.06329 24.7722H18.2405Z" stroke="#FEFCE1" stroke-width="2.83544" stroke-linecap="round" stroke-linejoin="round"/> <path fill-rule="evenodd" clip-rule="evenodd" d="M11.1519 12.0127C13.9873 12.0127 15.4051 10.5949 15.4051 7.05063C15.4051 3.50633 13.9873 2.08861 11.1519 2.08861C8.31645 2.08861 6.89873 3.50633 6.89873 7.05063C6.89873 10.5949 8.31645 12.0127 11.1519 12.0127Z" stroke="#FEFCE1" stroke-width="2.83544" stroke-linecap="round" stroke-linejoin="round"/> </svg> <div class="textes"> <h3>Utilisateurs</h3> <p>Les utilisateurs de l'application</p> </div> </button> <button class="admin-content"> <svg width="29" height="29" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M1 3C1 1.89543 1.89543 1 3 1H4C5.10457 1 6 1.89543 6 3V4C6 5.10457 5.10457 6 4 6H3C1.89543 6 1 5.10457 1 4V3Z" stroke="#FEFCE1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> <path d="M10 3C10 1.89543 10.8954 1 12 1H13C14.1046 1 15 1.89543 15 3V4C15 5.10457 14.1046 6 13 6H12C10.8954 6 10 5.10457 10 4V3Z" stroke="#FEFCE1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> <path d="M1 12C1 10.8954 1.89543 10 3 10H4C5.10457 10 6 10.8954 6 12V13C6 14.1046 5.10457 15 4 15H3C1.89543 15 1 14.1046 1 13V12Z" stroke="#FEFCE1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> <path d="M10 12C10 10.8954 10.8954 10 12 10H13C14.1046 10 15 10.8954 15 12V13C15 14.1046 14.1046 15 13 15H12C10.8954 15 10 14.1046 10 13V12Z" stroke="#FEFCE1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> <div class="textes"> <h3>Playlists</h3> <p>Les playlists de l'application</p> </div> </button> <button class="admin-content"> <svg width="18" height="17" viewBox="0 0 18 17" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M6 13.5C6 14.8807 4.88071 16 3.5 16C2.11929 16 1 14.8807 1 13.5C1 12.1193 2.11929 11 3.5 11C4.88071 11 6 12.1193 6 13.5ZM6 13.5V2.91321C6 2.39601 6.39439 1.96415 6.90946 1.91732L15.9095 1.09914C16.4951 1.0459 17 1.507 17 2.09503V12.5M17 12.5C17 13.8807 15.8807 15 14.5 15C13.1193 15 12 13.8807 12 12.5C12 11.1193 13.1193 10 14.5 10C15.8807 10 17 11.1193 17 12.5Z" stroke="#FEFCE1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> <div class="textes"> <h3>Albums</h3> <p>Les albums de l'application</p> </div> </button> </div> </section> <section id="pageArtistes" class="page"> <header> <h2>Artistes</h2> <svg width="29" height="29" viewBox="0 0 39 39" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M37.6118 9.82166L27.9072 14.9928C32.319 9.33028 28.353 1.28109 19.1767 0V9.98935C15.8932 3.95635 6.60488 3.25634 0.923272 9.82361L10.2961 14.8173C2.99181 14.4254 -2.30948 21.4977 1.01413 29.3226L10.8413 24.0871C6.34922 29.619 9.45097 38.5008 19.1746 39V28.1059C21.8685 34.7941 32.0717 37.0091 37.5188 29.3226L27.2966 23.8766C34.9199 25.066 42.0996 18.019 37.6118 9.82361V9.82166Z" fill="#E2FF08"/> </svg> </header> </section> <section id="pageSons" class="page"> <header> <h2>Sons</h2> <svg width="29" height="29" viewBox="0 0 39 39" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M37.6118 9.82166L27.9072 14.9928C32.319 9.33028 28.353 1.28109 19.1767 0V9.98935C15.8932 3.95635 6.60488 3.25634 0.923272 9.82361L10.2961 14.8173C2.99181 14.4254 -2.30948 21.4977 1.01413 29.3226L10.8413 24.0871C6.34922 29.619 9.45097 38.5008 19.1746 39V28.1059C21.8685 34.7941 32.0717 37.0091 37.5188 29.3226L27.2966 23.8766C34.9199 25.066 42.0996 18.019 37.6118 9.82361V9.82166Z" fill="#E2FF08"/> </svg> </header> </section> <section id="pageGenres" class="page"> <header> <h2>Genres</h2> <svg width="29" height="29" viewBox="0 0 39 39" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M37.6118 9.82166L27.9072 14.9928C32.319 9.33028 28.353 1.28109 19.1767 0V9.98935C15.8932 3.95635 6.60488 3.25634 0.923272 9.82361L10.2961 14.8173C2.99181 14.4254 -2.30948 21.4977 1.01413 29.3226L10.8413 24.0871C6.34922 29.619 9.45097 38.5008 19.1746 39V28.1059C21.8685 34.7941 32.0717 37.0091 37.5188 29.3226L27.2966 23.8766C34.9199 25.066 42.0996 18.019 37.6118 9.82361V9.82166Z" fill="#E2FF08"/> </svg> </header> </section> <section id="pageUtilisateurs" class="page"> <header> <h2>Utilisateurs</h2> <svg width="29" height="29" viewBox="0 0 39 39" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M37.6118 9.82166L27.9072 14.9928C32.319 9.33028 28.353 1.28109 19.1767 0V9.98935C15.8932 3.95635 6.60488 3.25634 0.923272 9.82361L10.2961 14.8173C2.99181 14.4254 -2.30948 21.4977 1.01413 29.3226L10.8413 24.0871C6.34922 29.619 9.45097 38.5008 19.1746 39V28.1059C21.8685 34.7941 32.0717 37.0091 37.5188 29.3226L27.2966 23.8766C34.9199 25.066 42.0996 18.019 37.6118 9.82361V9.82166Z" fill="#E2FF08"/> </svg> </header> </section> <section id="pagePlaylists" class="page"> <header> <h2>Playlists</h2> <svg width="29" height="29" viewBox="0 0 39 39" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M37.6118 9.82166L27.9072 14.9928C32.319 9.33028 28.353 1.28109 19.1767 0V9.98935C15.8932 3.95635 6.60488 3.25634 0.923272 9.82361L10.2961 14.8173C2.99181 14.4254 -2.30948 21.4977 1.01413 29.3226L10.8413 24.0871C6.34922 29.619 9.45097 38.5008 19.1746 39V28.1059C21.8685 34.7941 32.0717 37.0091 37.5188 29.3226L27.2966 23.8766C34.9199 25.066 42.0996 18.019 37.6118 9.82361V9.82166Z" fill="#E2FF08"/> </svg> </header> </section> <section id="pageAlbums" class="page"> <header> <h2>Albums</h2> <svg width="29" height="29" viewBox="0 0 39 39" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M37.6118 9.82166L27.9072 14.9928C32.319 9.33028 28.353 1.28109 19.1767 0V9.98935C15.8932 3.95635 6.60488 3.25634 0.923272 9.82361L10.2961 14.8173C2.99181 14.4254 -2.30948 21.4977 1.01413 29.3226L10.8413 24.0871C6.34922 29.619 9.45097 38.5008 19.1746 39V28.1059C21.8685 34.7941 32.0717 37.0091 37.5188 29.3226L27.2966 23.8766C34.9199 25.066 42.0996 18.019 37.6118 9.82361V9.82166Z" fill="#E2FF08"/> </svg> </header> </section> </main> </div> </div> un fichier css : @font-face { font-family: 'Kicker'; src: url('../fonts/kicker-black/KickerTrial-Black.ttf') format('truetype'); font-weight: 100; font-style: normal; } @font-face { font-family: 'Kicker'; src: url('../fonts/kicker-black/KickerTrial-BlackItalic.ttf') format('truetype'); font-weight: 100; font-style: italic; } @font-face { font-family: 'Kicker'; src: url('../fonts/kicker-bold/KickerTrial-BlackSlanted.ttf') format('truetype'); font-weight: 200; font-style: normal; } @font-face { font-family: 'PP Mori'; src: url('../fonts/pp-mori/PPMori-ExtraLight.otf') format('truetype'); font-weight: 100; font-style: normal; } @font-face { font-family: 'PP Mori'; src: url('../fonts/pp-mori/PPMori-ExtraLightItalic.otf') format('truetype'); font-weight: 100; font-style: italic; } @font-face { font-family: 'PP Mori'; src: url('../fonts/pp-mori/PPMori-Regular.otf') format('truetype'); font-weight: 200; font-style: normal; } @font-face { font-family: 'PP Mori'; src: url('../fonts/pp-mori/PPMori-RegularItalic.otf') format('truetype'); font-weight: 200; font-style: italic; } @font-face { font-family: 'PP Mori'; src: url('../fonts/pp-mori/PPMori-SemiBold.otf') format('truetype'); font-weight: 300; font-style: normal; } @font-face { font-family: 'PP Mori'; src: url('../fonts/pp-mori/PPMori-SemiBoldItalic.otf') format('truetype'); font-weight: 300; font-style: italic; } *{ margin: 0; padding: 0; box-sizing: border-box; } :root { --yellow: #E2FF08; --text-color: #FEFCE1; --text-color-secondary: #7F7E70; --background-color: #000000; --background-secondary: #070808; } body{ background-color: var(--background-color); position: relative; display: flex; justify-content: space-between; font-family: 'PP Mori', sans-serif; min-height: 100vh; max-width: 100vw; overflow:hidden; margin: 0; padding: 0; } nav { position: relative; display: flex; background-color: var(--background-secondary); border-radius: 1rem; padding: 1rem; min-height: 100%; } nav ul { display: flex; flex-direction: column; gap: 0.85rem; height: 100%; list-style: none; position: relative; padding: 0; z-index: 2; } nav ul li { list-style-type: none; width: 100%; } nav .active-square { position: absolute; width: 85%; height: 3.5rem; z-index: 0; background-color: var(--yellow); border-radius: 0.8rem; } nav ul li a { text-decoration: none; color: var(--text-color); gap: 0.7rem; height: 3.5rem; max-height: 3.5rem; display: flex; width: 15.5rem; align-items: center; white-space: nowrap; font-size: 1rem; padding: 1rem; } nav ul li a svg { position: relative; } body .left{ position: relative; width: 15rem; height: 100%; display: flex; gap: 5rem; flex-direction: column; background-color: var(--background-secondary); } body .left img{ align-self: flex-start; } .actions { position: absolute; bottom: 0; right: 0; padding: 1rem; } .actions a { text-decoration: none; font-size: 1rem; margin-left: 1rem; } .btn-retour { cursor: pointer; display: flex; gap:1rem; background-color: var(--background-secondary); border: none; padding: 1.5rem 1rem; border-radius: 1rem; color:var(--yellow); font-family: 'PP Mori'; font-weight: 300; width: 13rem; height: 4.4375rem; font-size: 0.95rem; display: flex; gap: 0.7rem; align-items: center; text-decoration: none; background-color: #0E100F; margin: 1rem 1rem; } .btn-retour a:hover{ filter: brightness(0.8); } .right { position: relative; width: 100%; height: 100%; display: flex; flex-direction: column; } #recherche { background-color: #070808; padding: 1rem 1rem; display: flex; align-items: center; margin-left: 0.7rem; z-index: 2; } .text-field{ width: 100%; display: flex; position: relative; padding: 1.625rem 1.875rem; background-color: #070808; color: var(--text-color-secondary); } .text-field img{ height: 1.5rem; } .text-field input{ position: absolute; top: 0; left: 0; width: 100%; height: 100%; padding-left: 6rem; background-color: transparent; border: none; border-bottom: 1.5px solid var(--text-color-secondary); outline: none; color: var(--text-color-secondary); font-family: 'PP Mori'; font-weight: 300; font-size: 1.25rem; transition: all 0.2s ease-in-out; } .text-field.no-space input{ padding-left: 1rem; } .text-field input:focus{ border-bottom: 1.5px solid var(--yellow); transition: all 0.2s ease-in-out; } h2 { font-family: 'PP Mori', sans-serif; font-size: 3rem; font-weight: 300; color: var(--text-color); margin: 3rem 1rem; } header { display: flex; align-items: center; padding-left: 1.5rem } .menu { margin-top: 1rem; display: grid; grid-template-columns: repeat(3, 1fr); grid-template-rows: repeat(2, 1fr); gap: 1.5rem; } .admin-content { margin-top: 1rem; background-color: #070808; display: flex; align-items: center; justify-content: center; width: 24vw; height: 25vh; margin-left: 2rem; border-radius: 1rem; border: none; cursor: pointer; } .textes { display: flex; flex-direction: column; align-items: flex-start; margin-left: 4.5rem; } .textes h3 { margin-top: 1rem; font-family: "PP Mori"; font-weight: 300; color: #FEFCE1; font-size: 2rem; opacity: 50%; } .textes p { font-family: "PP Mori"; font-size: 0.875rem; color: #FEFCE1; opacity: 30%; margin-top: 0.5rem; } .admin-content svg { width: 5rem; height: 4.5rem; } #pagePrincipale { opacity: 1; display: block; } .page { position: absolute; opacity: 0; padding-right: 2rem; width: 100%; display: flex; gap: 1.15rem; height: 100%; } et un fichier js : const activeSquare = document.querySelector("#activeSquare"); const goToMenuPrincipal = document.querySelector("#goToMenuPrincipal"); const goToArtistes = document.querySelector("#goToArtistes"); const goToSons = document.querySelector("#goToSons"); const goToGenres = document.querySelector("#goToGenres"); const goToUtilisateurs = document.querySelector("#goToUtilisateurs"); const goToPlaylists = document.querySelector("#goToPlaylists"); const goToAlbums = document.querySelector("#goToAlbums"); const sectionMenuPrincipal = document.querySelector("#pagePrincipale"); const sectionMenuArtistes = document.querySelector("#pageArtistes"); const sectionMenuSons = document.querySelector("#pageSons"); const sectionMenuGenres = document.querySelector("#pageGenres"); const sectionMenuUtilisateurs = document.querySelector("#pageUtilisateurs"); const sectionMenuPlaylists = document.querySelector("#pagePlaylists"); const sectionMenuAlbums = document.querySelector("#pageAlbums"); function changeCurrentMenu(e, index) { e?.preventDefault(); function clearActiveSections() { if (sectionMenuPrincipal.classList != null) sectionMenuPrincipal.classList.remove("active-section"); if (sectionMenuArtistes.classList != null) sectionMenuArtistes.classList.remove("active-section"); if (sectionMenuSons.classList != null) sectionMenuSons.classList.remove("active-section"); if (sectionMenuGenres.classList != null) sectionMenuGenres.classList.remove("active-section"); if (sectionMenuUtilisateurs.classList != null) sectionMenuUtilisateurs.classList.remove("active-section"); if (sectionMenuPlaylists.classList != null) sectionMenuPlaylists.classList.remove("active-section"); if (sectionMenuAlbums.classList != null) sectionMenuAlbums.classList.remove("active-section"); } const curSection = document.querySelector(".active-section"); let curIndex = -1; if (e) { const curSectionName = curSection.id.split("page")[1]; curIndex = curSectionName == "Principale" ? 0 : curSectionName == "Artistes" ? 1 : curSectionName == "Sons" ? 2 : curSectionName == "Genres" ? 3 : curSectionName == "Utilisateurs" ? 4 : curSectionName == "Playlists" ? 5 : 6; if (e.target.id.split("goTo")[1] == curSectionName) return; } const menuItemHeight = 3.5; const menuItemMargin = 0.85; const startPosition = 1; const position = startPosition + index * (menuItemHeight + menuItemMargin); gsap.to(activeSquare, { top: `${position}rem`, duration: 0.6, ease: "power4.out" }); const menuItems = [goToMenuPrincipal, goToArtistes, goToSons, goToGenres, goToUtilisateurs, goToPlaylists, goToAlbums]; menuItems.forEach((menuItem, i) => { gsap.to(menuItem, { color: i === index ? "#0E100F" : "#FEFCE1", duration: 0.6, ease: "power4.out" }); }); switch(index) { case 0: gsap.to(goToMenuPrincipal, {color: "#0E100F", duration: 0.6, ease:"power4.out"}); gsap.to(goToArtistes, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToSons, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToGenres, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToUtilisateurs, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToPlaylists, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToAlbums, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.fromTo(sectionMenuPrincipal, {opacity: 0, y: index < curIndex ? "100vw" : "-100vw"}, {opacity: 1, y: 0, duration: 0.6, zIndex: 1, ease:"power4.out"}); gsap.to(curSection, {opacity:0, y: index < curIndex ? "-100vw" : "100vw", duration:0.6, zIndex: -1, ease: "power4.out"}); clearActiveSections(); sectionMenuPrincipal.classList.add("active-section"); break; case 1: gsap.to(goToMenuPrincipal, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToArtistes, {color: "#0E100F", duration: 0.6, ease:"power4.out"}); gsap.to(goToSons, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToGenres, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToUtilisateurs, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToPlaylists, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToAlbums, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.fromTo(sectionMenuArtistes, {opacity: 0, y: index < curIndex ? "100vw" : "-100vw"}, {opacity: 1, y: 0, duration: 0.6, zIndex: 1, ease:"power4.out"}); gsap.to(curSection, {opacity:0, y: index < curIndex ? "-100vw" : "100vw", duration:0.6, zIndex: -1, ease: "power4.out"}); clearActiveSections(); sectionMenuArtistes.classList.add("active-section"); break; case 2: gsap.to(goToMenuPrincipal, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToArtistes, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToSons, {color: "#0E100F", duration: 0.6, ease:"power4.out"}); gsap.to(goToGenres, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToUtilisateurs, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToPlaylists, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToAlbums, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.fromTo(sectionMenuSons, {opacity: 0, y: index < curIndex ? "100vw" : "-100vw"}, {opacity: 1, y: 0, duration: 0.6, zIndex: 1, ease:"power4.out"}); gsap.to(curSection, {opacity:0, y: index < curIndex ? "-100vw" : "100vw", duration:0.6, zIndex: -1, ease: "power4.out"}); clearActiveSections(); sectionMenuSons.classList.add("active-section"); break; case 3: gsap.to(goToMenuPrincipal, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToArtistes, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToSons, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToGenres, {color: "#0E100F", duration: 0.6, ease:"power4.out"}); gsap.to(goToUtilisateurs, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToPlaylists, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToAlbums, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.fromTo(sectionMenuGenres, {opacity: 0, y: index < curIndex ? "100vw" : "-100vw"}, {opacity: 1, y: 0, duration: 0.6, zIndex: 1, ease:"power4.out"}); gsap.to(curSection, {opacity:0, y: index < curIndex ? "-100vw" : "100vw", duration:0.6, zIndex: -1, ease: "power4.out"}); clearActiveSections(); sectionMenuGenres.classList.add("active-section"); break; case 4: gsap.to(goToMenuPrincipal, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToArtistes, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToSons, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToGenres, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToUtilisateurs, {color: "#0E100F", duration: 0.6, ease:"power4.out"}); gsap.to(goToPlaylists, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToAlbums, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.fromTo(sectionMenuUtilisateurs, {opacity: 0, y: index < curIndex ? "100vw" : "-100vw"}, {opacity: 1, y: 0, duration: 0.6, zIndex: 1, ease:"power4.out"}); gsap.to(curSection, {opacity:0, y: index < curIndex ? "-100vw" : "100vw", duration:0.6, zIndex: -1, ease: "power4.out"}); clearActiveSections(); sectionMenuUtilisateurs.classList.add("active-section"); break; case 5: gsap.to(goToMenuPrincipal, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToArtistes, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToSons, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToGenres, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToUtilisateurs, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToPlaylists, {color: "#0E100F", duration: 0.6, ease:"power4.out"}); gsap.to(goToAlbums, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.fromTo(sectionMenuPlaylists, {opacity: 0, y: index < curIndex ? "100vw" : "-100vw"}, {opacity: 1, y: 0, duration: 0.6, zIndex: 1, ease:"power4.out"}); gsap.to(curSection, {opacity:0, y: index < curIndex ? "-100vw" : "100vw", duration:0.6, zIndex: -1, ease: "power4.out"}); clearActiveSections(); sectionMenuPlaylists.classList.add("active-section"); break; case 6: gsap.to(goToMenuPrincipal, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToArtistes, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToSons, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToGenres, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToUtilisateurs, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToPlaylists, {color: "#FEFCE1", duration: 0.6, ease:"power4.out"}); gsap.to(goToAlbums, {color: "#0E100F", duration: 0.6, ease:"power4.out"}); gsap.fromTo(sectionMenuAlbums, {opacity: 0, y: index < curIndex ? "100vw" : "-100vw"}, {opacity: 1, y: 0, duration: 0.6, zIndex: 1, ease:"power4.out"}); gsap.to(curSection, {opacity:0, y: index < curIndex ? "-100vw" : "100vw", duration:0.6, zIndex: -1, ease: "power4.out"}); clearActiveSections(); sectionMenuAlbums.classList.add("active-section"); break; } } changeCurrentMenu(null, 0); goToMenuPrincipal.addEventListener('click', (e) => changeCurrentMenu(e,0)); goToArtistes.addEventListener('click', (e) => changeCurrentMenu(e,1)); goToSons.addEventListener('click', (e) => changeCurrentMenu(e,2)); goToGenres.addEventListener('click', (e) => changeCurrentMenu(e,3)); goToUtilisateurs.addEventListener('click', (e) => changeCurrentMenu(e,4)); goToPlaylists.addEventListener('click', (e) => changeCurrentMenu(e,5)); goToAlbums.addEventListener('click', (e) => changeCurrentMenu(e,6)); je ne sais pas utiliser gsap, mais j'aimerais apprendre à l'utiliser. tu vois j'ai des boutons dans le menu principal de ma page, qui est une page admin d'une application spotify. J'aimerais qu'en cliquant sur un élément, le bouton s'enfonce et ensuite la page s'ouvre en partant du bouton, jusqu'à arriver à la taille initiale, comment faire ?
99ce186065fa3bb51764ca8235412615
{ "intermediate": 0.3738286793231964, "beginner": 0.41830480098724365, "expert": 0.20786650478839874 }
38,870
I am trying to check if my prompt works in achieving a certain output with an LLM consistently. I am giving it input in this format - "Person A": { "address": "2233 South Pard Rd, Chicago, IL, 22002", "name": {"first_name": "Terrance", "middle_name": "Allen", "last_name": "Parker", "suffix": ""}, "ssn": "111-22-3333", "dob": "09/17/1997" }, "Person B": { "address": "2233 South Park Road, Chicago, IL, 22002", "name": {"first_name": "Terrance", "middle_name": "A.", "last_name": "Parker", "suffix": ""}, "ssn": "111-22-3333", "dob": "09/17/1997" } I need your help generating more examples like this. I need you to vary just the ssn and date format in the examples between person a and b.
c29125f0d5974d5c65a532c9dd7101a5
{ "intermediate": 0.4085562229156494, "beginner": 0.236870676279068, "expert": 0.35457316040992737 }
38,871
Hi!
0e77a28448e68fe3e6ccbfa5c47a2f07
{ "intermediate": 0.3230988085269928, "beginner": 0.2665199935436249, "expert": 0.4103812277317047 }
38,872
Hi!
43c44dd7496f45fcf315333c4dc76fd3
{ "intermediate": 0.3230988085269928, "beginner": 0.2665199935436249, "expert": 0.4103812277317047 }
38,873
class Question(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(120)) questionType = db.Column(db.String(120)) questionnaire_id = db.Column(db.Integer, db.ForeignKey('questionnaire.id')) reponse = db.Column(db.String(120)) questionnaire = db.relationship("Questionnaire", backref=db.backref("questions", lazy="dynamic")) __mapper_args__ = { 'polymorphic_identity':'question', 'with_polymorphic':'*', 'polymorphic_on':questionType } def __init__(self, title, questionType, questionnaire_id): self.title = title self.questionType = questionType self.questionnaire_id = questionnaire_id def __repr__(self): return "<Question (%d) %s>" % (self.id, self.title) def get_questions(): return [q.to_json() for q in Question.query.all()] def get_question(question_id): q = Question.query.get(question_id) if q is None: abort(404) return q.to_json() def create_question(json): q = json type_question = json['questionType'] match type_question: case "unique": q = SimpleQuestion(json['title'], json['questionnaire_id'], json['reponse']) case "multiple": q = QuestionMultiple(json['title'], json['questionnaire_id'], json['reponse'], json['prop1'], json['prop2']) db.session.add(q) db.session.commit() return q.to_json() def update_question(question_id, json): q = Question.query.get(question_id) if q is None: abort(404) type = json['questionType'] if type == q.questionType: match type: case "unique": q.reponse = json['reponse'] case "multiple": q.reponse = json['reponse'] q.prop1 = json['prop1'] q.prop2 = json['prop2'] db.session.commit() return q.to_json() def delete_question(question_id): q = Question.query.get(question_id) if q is None: abort(404) db.session.delete(q) db.session.commit() return {"success":True, "message":"supprimé avec succès"} def to_json(self): json = { 'url': url_for('question', question_id=self.id, _external=True), 'id': self.id, 'title': self.title, 'questionType': self.questionType, 'questionnaire_id': self.questionnaire.id, } if isinstance(self, QuestionMultiple): json['reponse'] = int(self.reponse) json['prop1'] = self.prop1 json['prop2'] = self.prop2 else: json['reponse'] = self.reponse return json class QuestionMultiple(Question): id = db.Column(db.Integer, db.ForeignKey('question.id'), primary_key=True) prop1 = db.Column(db.String(120)) prop2 = db.Column(db.String(120)) __mpaer_args__ = { 'polymorphic_identity':'muliplequestion', 'with_polymorphic':'*', 'polymorphic_load':'inline' } def __init__(self, title, questionnaire_id, reponse, prop1, prop2): super().__init__(title, "multiple", questionnaire_id) self.reponse = str(reponse) self.prop1 = prop1 self.prop2 = prop2 def to_json(self): json = super().to_json() return json class SimpleQuestion(Question): id = db.Column(db.Integer, db.ForeignKey('question.id'), primary_key=True) __mapper_args__ = { 'polymorphic_identity':'simplequestion', 'with_polymorphic':'*', 'polymorphic_load':'inline' } def __init__(self, title, questionnaire_id, reponse): super().__init__(title, "unique", questionnaire_id) self.reponse = reponse def to_json(self): json = super().to_json() return json j'ai des problèmes avec le polymorphisme
0d51a68942fce86bb49c3644ef847c6f
{ "intermediate": 0.3319614827632904, "beginner": 0.4930266737937927, "expert": 0.17501188814640045 }
38,874
Could you tell me why I am getting failed to fetch data from soap service? C:\Users\Ninja\Downloads\StepsForSFDLOADER>python test2.py Request: <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <GetConnectRequests xmlns="https://mythologicinteractive.com/Games/SFD/"> <port>52233</port> <serverApplicationInstance>830af0c3-4fa7-4efd-ac27-0a86bc69803f</serverApplicationInstance> </GetConnectRequests> </soap:Body> </soap:Envelope> Response: <?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><GetConnectRequestsResponse xmlns="https://mythologicinteractive.com/Games/SFD/"><GetConnectRequestsResult /></GetConnectRequestsResponse></soap:Body></soap:Envelope> Failed to fetch data from the SOAP service. Heres the code import requests import xml.etree.ElementTree as ET # Define the SOAP request soap_request = """<?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <GetConnectRequests xmlns="https://mythologicinteractive.com/Games/SFD/"> <port>52233</port> <serverApplicationInstance>830af0c3-4fa7-4efd-ac27-0a86bc69803f</serverApplicationInstance> </GetConnectRequests> </soap:Body> </soap:Envelope> """ # Define the SOAP endpoint URL soap_url = "http://mythologicinteractive.com/SFDGameServices.asmx" def fetch_connect_requests(): # Define the headers for the SOAP request headers = { "User-Agent": "Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 4.0.30319.42000)", "Content-Type": "text/xml; charset=utf-8", "SOAPAction": 'https://mythologicinteractive.com/Games/SFD/GetConnectRequests', "Host": "mythologicinteractive.com", "Content-Length": str(len(soap_request)), "Expect": "100-continue", "Connection": "Keep-Alive", } try: # Send the SOAP request response = requests.post(soap_url, data=soap_request, headers=headers) # Print out the request and response for debugging print("Request:") print(response.request.body) print("Response:") print(response.text) # Check if the request was successful (HTTP status code 200) if response.status_code == 200: # Parse the XML response root = ET.fromstring(response.text) # Extract and process the data you need from the XML response connect_requests = root.findall(".//{https://mythologicinteractive.com/Games/SFD/}ConnectRequest") result = [] for connect_request in connect_requests: # Extract information about each connect request and append to the result list request_id = connect_request.find("{https://mythologicinteractive.com/Games/SFD/}RequestId").text # Add more fields if needed... request_info = { "request_id": request_id, # Add more fields if needed... } result.append(request_info) return result else: print(f"Failed to fetch data from the SOAP service. Status Code: {response.status_code}") return None except Exception as e: print(f"An error occurred: {str(e)}") return None # Example usage: connect_requests_data = fetch_connect_requests() if connect_requests_data: for request in connect_requests_data: print(request) else: print("Failed to fetch data from the SOAP service.") Heres the documentation SOAP 1.1 The following is a sample SOAP 1.1 request and response. The placeholders shown need to be replaced with actual values. POST /SFDGameServices.asmx HTTP/1.1 Host: mythologicinteractive.com Content-Type: text/xml; charset=utf-8 Content-Length: length SOAPAction: "https://mythologicinteractive.com/Games/SFD/GetConnectRequests" <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <GetConnectRequests xmlns="https://mythologicinteractive.com/Games/SFD/"> <port>unsignedShort</port> <serverApplicationInstance>guid</serverApplicationInstance> </GetConnectRequests> </soap:Body> </soap:Envelope> HTTP/1.1 200 OK Content-Type: text/xml; charset=utf-8 Content-Length: length <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <GetConnectRequestsResponse xmlns="https://mythologicinteractive.com/Games/SFD/"> <GetConnectRequestsResult> <SFDConnectRequest> <RequestTime>dateTime</RequestTime> <ClientAddressIPv4>string</ClientAddressIPv4> <ClientAddressIPv6>string</ClientAddressIPv6> <ClientLIP>string</ClientLIP> <ClientListeningPort>unsignedShort</ClientListeningPort> <ClientApplicationInstance>guid</ClientApplicationInstance> <ServerAddressIPv4>string</ServerAddressIPv4> <ServerAddressIPv6>string</ServerAddressIPv6> <ServerLIP>string</ServerLIP> <ServerHostPort>unsignedShort</ServerHostPort> <ServerApplicationInstance>guid</ServerApplicationInstance> </SFDConnectRequest> <SFDConnectRequest> <RequestTime>dateTime</RequestTime> <ClientAddressIPv4>string</ClientAddressIPv4> <ClientAddressIPv6>string</ClientAddressIPv6> <ClientLIP>string</ClientLIP> <ClientListeningPort>unsignedShort</ClientListeningPort> <ClientApplicationInstance>guid</ClientApplicationInstance> <ServerAddressIPv4>string</ServerAddressIPv4> <ServerAddressIPv6>string</ServerAddressIPv6> <ServerLIP>string</ServerLIP> <ServerHostPort>unsignedShort</ServerHostPort> <ServerApplicationInstance>guid</ServerApplicationInstance> </SFDConnectRequest> </GetConnectRequestsResult> </GetConnectRequestsResponse> </soap:Body> </soap:Envelope>
8a50bd6293e37ce1263109a8ddad70b4
{ "intermediate": 0.43865764141082764, "beginner": 0.361091673374176, "expert": 0.20025068521499634 }
38,875
I'm looking for automatic image contrast algorithms - not histogram equalization.
9b23abe2c2403dd32117ddf845d21944
{ "intermediate": 0.08808968216180801, "beginner": 0.07413920760154724, "expert": 0.8377711176872253 }
38,876
Please help me find and fix mistake in Python script for speech recognition. Script records only first 10 seconds of mic: import sounddevice as sd from scipy.io.wavfile import write import speech_recognition as sr import os # Function to record audio def record_audio(filename): fs = 44100 # Sample rate print('Recording… Press Enter to stop.') myrecording = sd.rec(int(10 * fs), samplerate=fs, channels=2, dtype='int16') input() # Wait for the user to press Enter to stop recording sd.stop() # Stop the recording write(filename, fs, myrecording) # Save recording to file # Function to recognize speech from an audio file def recognize_speech_from_file(audio_filename, recognizer, language): with sr.AudioFile(audio_filename) as source: audio_data = recognizer.record(source) print('Recognizing speech…') try: # Recognize speech using Google Web Speech API text = recognizer.recognize_google(audio_data, language=language) return text except sr.UnknownValueError: return 'Google Web Speech API could not understand the audio' except sr.RequestError: return 'Could not request results from Google Web Speech API' # Main code def main(): # Check if 'Enter' has been pressed for the first time input('Press Enter to start audio capture…') # Record audio from the microphone audio_filename = 'recording.wav' record_audio(audio_filename) # Check if 'Enter' has been pressed to stop recording input('Recording stopped. Press Enter to start speech recognition…') # Initialize the recognizer recognizer = sr.Recognizer() # Recognize speech recognized_text = recognize_speech_from_file(audio_filename, recognizer, language='ru-RU') # Output the recognized text print('Recognized text:') print(recognized_text) # Delete the temporary audio file os.remove(audio_filename) main()
4542e3acd68cf8270831eb025e35f38c
{ "intermediate": 0.5233471393585205, "beginner": 0.19548159837722778, "expert": 0.2811713218688965 }
38,877
Please help to find and fix mistake in Python code: import sounddevice as sd from scipy.io.wavfile import write import speech_recognition as sr import os import threading # Function to record audio def record_audio(filename): fs = 44100 # Sample rate print('Recording… Press Enter to stop.') # Start recording in a non-blocking way myrecording = sd.rec(samplerate=fs, channels=2, dtype='int16', blocking=False) # A simple function to wait for Enter press def wait_for_enter(): input() sd.stop() # Stop the recording # Start the wait_for_enter function in a separate thread t = threading.Thread(target=wait_for_enter) t.start() t.join() # Wait for the thread to finish, i.e., for Enter to be pressed # Save the recorded data that has been buffered until now write(filename, fs, myrecording) # Function to recognize speech from an audio file def recognize_speech_from_file(audio_filename, recognizer, language): with sr.AudioFile(audio_filename) as source: audio_data = recognizer.record(source) print('Recognizing speech…') try: # Recognize speech using Google Web Speech API text = recognizer.recognize_google(audio_data, language=language) return text except sr.UnknownValueError: return 'Google Web Speech API could not understand the audio' except sr.RequestError: return 'Could not request results from Google Web Speech API' # Main code def main(): # Check if 'Enter' has been pressed for the first time input('Press Enter to start audio capture…') # Record audio from the microphone audio_filename = 'recording.wav' record_audio(audio_filename) # Check if 'Enter' has been pressed to stop recording input('Recording stopped. Press Enter to start speech recognition…') # Initialize the recognizer recognizer = sr.Recognizer() # Recognize speech recognized_text = recognize_speech_from_file(audio_filename, recognizer, language='ru-RU') # Output the recognized text print('Recognized text:') print(recognized_text) # Delete the temporary audio file os.remove(audio_filename) main() Output: Press Enter to start audio capture… Recording… Press Enter to stop. Traceback (most recent call last): File "C:\Users\Zzz\Desktop\record.py", line 67, in <module> main() File "C:\Users\Zzz\Desktop\record.py", line 49, in main record_audio(audio_filename) File "C:\Users\Zzz\Desktop\record.py", line 13, in record_audio myrecording = sd.rec(samplerate=fs, channels=2, dtype='int16', blocking=False) File "C:\Users\Zzz\AppData\Local\Programs\Python\Python310\lib\site-packages\sounddevice.py", line 268, in rec out, ctx.frames = ctx.check_out(out, frames, channels, dtype, mapping) File "C:\Users\Zzz\AppData\Local\Programs\Python\Python310\lib\site-packages\sounddevice.py", line 2509, in check_out raise TypeError('frames must be specified') TypeError: frames must be specified
c9cb4bc46520a47126276529eb75b18d
{ "intermediate": 0.368743896484375, "beginner": 0.39635205268859863, "expert": 0.23490409553050995 }
38,878
Declare a number to infinity in python
8b280aaa9d5b824cd912c763716c16d5
{ "intermediate": 0.3230821490287781, "beginner": 0.33428001403808594, "expert": 0.3426378667354584 }
38,879
How to redirect sound from output device directly to input device microphone in Windows ?
bed630d19799d3ae430106b9445bec2d
{ "intermediate": 0.27542033791542053, "beginner": 0.2118593454360962, "expert": 0.5127202868461609 }
38,880
Write Python script to send ChatGPT request with button in HTML form and print response in real time: URL: https://huggingface.co/spaces/yuntian-deng/ChatGPT4 HTML page source: <!DOCTYPE html> <html class=""> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" /> <meta name="description" content="Discover amazing ML apps made by the community" /> <meta property="fb:app_id" content="1321688464574422" /> <meta name="twitter:card" content="summary_large_image" /> <meta name="twitter:site" content="@huggingface" /> <meta property="og:title" content="Chat-with-GPT4 - a Hugging Face Space by yuntian-deng" /> <meta property="og:type" content="website" /> <meta property="og:url" content="https://huggingface.co/spaces/yuntian-deng/ChatGPT4" /> <meta property="og:image" content="https://cdn-thumbnails.huggingface.co/social-thumbnails/spaces/yuntian-deng/ChatGPT4.png" /> <link rel="stylesheet" href="/front/build/kube-125ae72/style.css" /> <link rel="preconnect" href="https://fonts.gstatic.com" /> <link href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro:ital,wght@0,200;0,300;0,400;0,600;0,700;0,900;1,200;1,300;1,400;1,600;1,700;1,900&display=swap" rel="stylesheet" /> <link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;600;700&display=swap" rel="stylesheet" /> <link rel="preload" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.12.0/katex.min.css" as="style" onload="this.onload=null;this.rel='stylesheet'" /> <noscript> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.12.0/katex.min.css" /> </noscript> <link rel="canonical" href="https://huggingface.co/spaces/yuntian-deng/ChatGPT4"> <title>Chat-with-GPT4 - a Hugging Face Space by yuntian-deng</title> <script defer data-domain="huggingface.co" src="/js/script.js"></script> <script type="text/javascript" src="https://de5282c3ca0c.edge.sdk.awswaf.com/de5282c3ca0c/526cf06acb0d/challenge.js" defer></script> </head> <body class="flex flex-col min-h-screen bg-white dark:bg-gray-950 text-black SpacePage"> <div class="flex min-h-screen flex-col"> <div class="SVELTE_HYDRATER contents" data-props="{&quot;activeTab&quot;:&quot;spaceApp&quot;,&quot;author&quot;:{&quot;avatarUrl&quot;:&quot;https://aeiljuispo.cloudimg.io/v7/https://cdn-uploads.huggingface.co/production/uploads/63081e15a670ed10f9d44229/w1b9uq-9774bMMgJbSPsS.jpeg?w=200&amp;h=200&amp;f=face&quot;,&quot;fullname&quot;:&quot;Yuntian Deng&quot;,&quot;name&quot;:&quot;yuntian-deng&quot;,&quot;type&quot;:&quot;user&quot;,&quot;isPro&quot;:true,&quot;isHf&quot;:false},&quot;canDisable&quot;:false,&quot;discussionsStats&quot;:{&quot;closed&quot;:5,&quot;open&quot;:7,&quot;total&quot;:12},&quot;query&quot;:{},&quot;space&quot;:{&quot;author&quot;:&quot;yuntian-deng&quot;,&quot;colorFrom&quot;:&quot;red&quot;,&quot;colorTo&quot;:&quot;indigo&quot;,&quot;cardData&quot;:{&quot;title&quot;:&quot;Chat-with-GPT4&quot;,&quot;emoji&quot;:&quot;🚀&quot;,&quot;colorFrom&quot;:&quot;red&quot;,&quot;colorTo&quot;:&quot;indigo&quot;,&quot;sdk&quot;:&quot;gradio&quot;,&quot;sdk_version&quot;:&quot;3.21.0&quot;,&quot;app_file&quot;:&quot;app.py&quot;,&quot;pinned&quot;:false,&quot;license&quot;:&quot;mit&quot;,&quot;duplicated_from&quot;:&quot;ysharma/ChatGPT4&quot;,&quot;disable_embedding&quot;:true},&quot;createdAt&quot;:&quot;2023-03-21T03:34:06.000Z&quot;,&quot;emoji&quot;:&quot;🚀&quot;,&quot;discussionsDisabled&quot;:false,&quot;duplicationDisabled&quot;:false,&quot;id&quot;:&quot;yuntian-deng/ChatGPT4&quot;,&quot;isLikedByUser&quot;:false,&quot;isWatchedByUser&quot;:false,&quot;lastModified&quot;:&quot;2023-12-15T04:31:22.000Z&quot;,&quot;likes&quot;:130,&quot;pinned&quot;:false,&quot;private&quot;:false,&quot;gated&quot;:false,&quot;repoType&quot;:&quot;space&quot;,&quot;subdomain&quot;:&quot;yuntian-deng-chatgpt4&quot;,&quot;sdk&quot;:&quot;gradio&quot;,&quot;sdkVersion&quot;:&quot;3.21.0&quot;,&quot;title&quot;:&quot;Chat-with-GPT4&quot;,&quot;originSpace&quot;:{&quot;name&quot;:&quot;ysharma/ChatGPT4&quot;,&quot;author&quot;:{&quot;avatarUrl&quot;:&quot;https://aeiljuispo.cloudimg.io/v7/https://cdn-uploads.huggingface.co/production/uploads/1624431552569-noauth.jpeg?w=200&amp;h=200&amp;f=face&quot;,&quot;fullname&quot;:&quot;yuvraj sharma&quot;,&quot;name&quot;:&quot;ysharma&quot;,&quot;type&quot;:&quot;user&quot;,&quot;isPro&quot;:false,&quot;isHf&quot;:true}},&quot;runtime&quot;:{&quot;stage&quot;:&quot;RUNNING&quot;,&quot;hardware&quot;:{&quot;current&quot;:&quot;cpu-basic&quot;,&quot;requested&quot;:&quot;cpu-basic&quot;},&quot;storage&quot;:null,&quot;gcTimeout&quot;:259200,&quot;replicas&quot;:{&quot;current&quot;:1,&quot;requested&quot;:1}},&quot;iframe&quot;:{&quot;embedSrc&quot;:&quot;https://yuntian-deng-chatgpt4.hf.space&quot;,&quot;src&quot;:&quot;https://yuntian-deng-chatgpt4.hf.space&quot;},&quot;secrets&quot;:[{&quot;key&quot;:&quot;OPENAI_API_KEY&quot;,&quot;updatedAt&quot;:&quot;2023-12-15T04:23:28.410Z&quot;},{&quot;key&quot;:&quot;API_URL&quot;,&quot;updatedAt&quot;:&quot;2023-03-27T06:48:05.734Z&quot;},{&quot;key&quot;:&quot;DISABLED&quot;,&quot;updatedAt&quot;:&quot;2023-03-27T06:48:12.182Z&quot;},{&quot;key&quot;:&quot;NUM_THREADS&quot;,&quot;updatedAt&quot;:&quot;2023-12-15T04:33:55.298Z&quot;}],&quot;variables&quot;:[],&quot;sse&quot;:{&quot;url&quot;:&quot;https://api.hf.space/v1/yuntian-deng/ChatGPT4&quot;,&quot;jwt&quot;:&quot;eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJpYXQiOjE3MDcyNDMwNzcsInN1YiI6Ii9zcGFjZXMveXVudGlhbi1kZW5nL0NoYXRHUFQ0IiwiZXhwIjoxNzA3MzI5NDc3LCJpc3MiOiJodHRwczovL2h1Z2dpbmdmYWNlLmNvIn0.oK3REYgyEL91UCzL-kC87HH9k9rAbuzWfagaB-pAdqOIvmInXLKKnnyAuSbvsa3GQ8UPGeSKgvNIXmLAh-VdDQ&quot;},&quot;dockerJwt&quot;:&quot;eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJpYXQiOjE3MDcyNDMwNzcsInN1YiI6Ii9zcGFjZXMveXVudGlhbi1kZW5nL0NoYXRHUFQ0IiwiZXhwIjoxNzA3MzI5NDc3LCJpc3MiOiJodHRwczovL2h1Z2dpbmdmYWNlLmNvIn0.oK3REYgyEL91UCzL-kC87HH9k9rAbuzWfagaB-pAdqOIvmInXLKKnnyAuSbvsa3GQ8UPGeSKgvNIXmLAh-VdDQ&quot;,&quot;linkedModels&quot;:[],&quot;linkedDatasets&quot;:[],&quot;linkedCollections&quot;:[]}}" data-target="SpaceHeader"> <header class="from-gray-50-to-white relative z-40 border-b border-gray-100 bg-gradient-to-t via-white pt-0.5 dark:via-gray-950"><div class="relative mx-4 mb-2 flex flex-col justify-between max-sm:mt-2 sm:mb-0 xl:flex-row"><div class="flex items-center justify-between xl:min-w-0"><h1 class="my-2 flex w-full min-w-0 flex-wrap items-center gap-y-2 text-lg leading-tight xl:flex-nowrap"><span class="flex flex-shrink-0 flex-nowrap items-center"><a href="/spaces" class="peer order-last font-bold hover:bg-gradient-to-r hover:from-blue-600 hover:via-purple-600 hover:to-pink-600 hover:bg-clip-text hover:text-transparent">Spaces</a> <svg class="hidden peer-hover:block mr-1.5 w-5 animate__animated animate__fadeInUp animate__fast" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M7.80914 18.7462V24.1907H13.2536V18.7462H7.80914Z" fill="#FF3270"></path><path d="M18.7458 18.7462V24.1907H24.1903V18.7462H18.7458Z" fill="#861FFF"></path><path d="M7.80914 7.80982V13.2543H13.2536V7.80982H7.80914Z" fill="#097EFF"></path><path fill-rule="evenodd" clip-rule="evenodd" d="M4 6.41775C4 5.08246 5.08246 4 6.41775 4H14.6457C15.7626 4 16.7026 4.75724 16.9802 5.78629C18.1505 4.67902 19.7302 4 21.4685 4C25.0758 4 28.0003 6.92436 28.0003 10.5317C28.0003 12.27 27.3212 13.8497 26.2139 15.02C27.243 15.2977 28.0003 16.2376 28.0003 17.3545V25.5824C28.0003 26.9177 26.9177 28.0003 25.5824 28.0003H17.0635H14.9367H6.41775C5.08246 28.0003 4 26.9177 4 25.5824V15.1587V14.9367V6.41775ZM7.80952 7.80952V13.254H13.254V7.80952H7.80952ZM7.80952 24.1907V18.7462H13.254V24.1907H7.80952ZM18.7462 24.1907V18.7462H24.1907V24.1907H18.7462ZM18.7462 10.5317C18.7462 9.0283 19.9651 7.80952 21.4685 7.80952C22.9719 7.80952 24.1907 9.0283 24.1907 10.5317C24.1907 12.0352 22.9719 13.254 21.4685 13.254C19.9651 13.254 18.7462 12.0352 18.7462 10.5317Z" fill="black"></path><path d="M21.4681 7.80982C19.9647 7.80982 18.7458 9.02861 18.7458 10.5321C18.7458 12.0355 19.9647 13.2543 21.4681 13.2543C22.9715 13.2543 24.1903 12.0355 24.1903 10.5321C24.1903 9.02861 22.9715 7.80982 21.4681 7.80982Z" fill="#FFD702"></path></svg> <a href="/" class="mr-1.5 w-5 peer-hover:hidden"><img alt="Hugging Face's logo" src="/front/assets/huggingface_logo-noborder.svg" class="w-5"></a></span> <hr class="mx-2 h-2 translate-y-px rounded-sm border-r dark:border-gray-600 xl:mx-2.5"> <div class="group flex flex-none items-center"><div class="relative mr-1.5 flex items-center"><p class="absolute bottom-4 left-0 hidden select-none items-center whitespace-nowrap text-xs text-gray-400 group-hover:flex md:bottom-[-1.1rem] md:pr-4 md:pt-1"><svg class="flex-none mr-1 text-gray-600 dark:text-gray-200" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" viewBox="0 0 32 26" preserveAspectRatio="xMidYMid meet" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M18.5769 0.524814C18.5769 0.234967 18.8126 0 19.1034 0C26.2306 0 32.0001 5.81162 32.0001 12.9704C32.0001 20.1292 26.2306 25.9408 19.1034 25.9408C18.8126 25.9408 18.5769 25.7058 18.5769 25.416C18.5769 25.1261 18.8126 24.8912 19.1034 24.8912C25.64 24.8912 30.9472 19.5586 30.9472 12.9704C30.9472 6.38217 25.64 1.04963 19.1034 1.04963C18.8126 1.04963 18.5769 0.81466 18.5769 0.524814Z" fill="currentcolor"></path><path fill-rule="evenodd" clip-rule="evenodd" d="M13.0034 26C20.1849 26 26.0067 20.1965 26.0067 13.0375C26.0067 5.87847 20.1849 0.0749512 13.0034 0.0749512C5.82181 0.0749512 0 5.87847 0 13.0375C0 20.1965 5.82181 26 13.0034 26ZM13.0656 7.51757C13.6455 7.51757 14.1155 7.98615 14.1155 8.56418V12.0529H17.6152C18.1951 12.0529 18.6651 12.5215 18.6651 13.0995C18.6651 13.6775 18.1951 14.1461 17.6152 14.1461H14.1155V17.6348C14.1155 18.2129 13.6455 18.6815 13.0656 18.6815C12.4857 18.6815 12.0157 18.2129 12.0157 17.6348V14.1461H8.51598C7.93613 14.1461 7.46606 13.6775 7.46606 13.0995C7.46606 12.5215 7.93613 12.0529 8.51598 12.0529H12.0157V8.56418C12.0157 7.98615 12.4857 7.51757 13.0656 7.51757Z" fill="currentcolor" fill-opacity="0.65"></path></svg> Duplicated from <a href="/spaces/ysharma/ChatGPT4" class="font-mono text-[0.65rem] text-gray-500 underline hover:text-gray-600">ysharma/ChatGPT4</a></p> <img alt="" class="w-3.5 h-3.5 rounded-full !w-3 !h-3 flex-none -mr-[0.115rem] group-hover:mr-[0.115rem] transition-all flex-none" src="https://aeiljuispo.cloudimg.io/v7/https://cdn-uploads.huggingface.co/production/uploads/1624431552569-noauth.jpeg?w=200&amp;h=200&amp;f=face" crossorigin="anonymous"> <img alt="" class="w-3.5 h-3.5 rounded-full ring-2 dark:ring-gray-900 ring-white flex-none" src="https://aeiljuispo.cloudimg.io/v7/https://cdn-uploads.huggingface.co/production/uploads/63081e15a670ed10f9d44229/w1b9uq-9774bMMgJbSPsS.jpeg?w=200&amp;h=200&amp;f=face" crossorigin="anonymous"></div> <a href="/yuntian-deng" class="text-gray-400 hover:text-blue-600">yuntian-deng</a> <div class="mx-0.5 text-gray-300">/</div></div> <div class="max-w-full xl:flex xl:min-w-0 xl:flex-nowrap xl:items-center xl:gap-x-1"><a class="break-words font-mono font-semibold hover:text-blue-600 text-[1.07rem] xl:truncate" href="/spaces/yuntian-deng/ChatGPT4">ChatGPT4</a> <button class="relative text-xs mr-3 inline-flex cursor-pointer items-center text-sm focus:outline-none mx-0.5 text-gray-600 " title="Copy space name to clipboard" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> </button></div> <div class="inline-flex items-center overflow-hidden whitespace-nowrap rounded-md border bg-white text-sm leading-none text-gray-500 mr-2 flex-shrink-0"><button class="relative flex items-center overflow-hidden from-red-50 to-transparent dark:from-red-900 px-1.5 py-1 hover:bg-gradient-to-t focus:outline-none" title="Like"><svg class="left-1.5 absolute" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32" fill="currentColor"><path d="M22.45,6a5.47,5.47,0,0,1,3.91,1.64,5.7,5.7,0,0,1,0,8L16,26.13,5.64,15.64a5.7,5.7,0,0,1,0-8,5.48,5.48,0,0,1,7.82,0L16,10.24l2.53-2.58A5.44,5.44,0,0,1,22.45,6m0-2a7.47,7.47,0,0,0-5.34,2.24L16,7.36,14.89,6.24a7.49,7.49,0,0,0-10.68,0,7.72,7.72,0,0,0,0,10.82L16,29,27.79,17.06a7.72,7.72,0,0,0,0-10.82A7.49,7.49,0,0,0,22.45,4Z"></path></svg> <span class="ml-4 pl-0.5 ">like</span></button> <button class="flex items-center border-l px-1.5 py-1 text-gray-400 hover:bg-gray-50 focus:bg-gray-100 focus:outline-none dark:hover:bg-gray-900 dark:focus:bg-gray-800" title="See users who liked this repository">130</button></div> <div class="inline-flex select-none items-center overflow-hidden font-mono text-xs flex-shrink-0 mr-2 rounded-lg border leading-none dark:bg-gray-900 border-green-100 text-green-700 dark:text-green-500"><div class="inline-flex items-center px-2 py-[0.32rem] dark:bg-gray-900 border-green-100 bg-green-50"> <div class="ml-0.5 mr-1.5 inline-block h-1.5 w-1.5 animate-pulse rounded-full bg-green-500"></div> Running </div> </div> <div class="xl:hidden"><div class="relative "> <button class="btn px-1 py-1 text-sm translate-y-0 " type="button"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="p-px" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><circle cx="16" cy="7" r="3" fill="currentColor"></circle><circle cx="16" cy="16" r="3" fill="currentColor"></circle><circle cx="16" cy="25" r="3" fill="currentColor"></circle></svg> </button> </div></div></h1> <div class="flex flex-none items-center justify-center p-0.5 place-self-start p-0 my-2 xl:hidden"><button class="relative z-40 flex h-6 w-8 items-center justify-center" type="button"><svg width="1em" height="1em" viewBox="0 0 10 10" class="text-xl" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" preserveAspectRatio="xMidYMid meet" fill="currentColor"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.65039 2.9999C1.65039 2.8066 1.80709 2.6499 2.00039 2.6499H8.00039C8.19369 2.6499 8.35039 2.8066 8.35039 2.9999C8.35039 3.1932 8.19369 3.3499 8.00039 3.3499H2.00039C1.80709 3.3499 1.65039 3.1932 1.65039 2.9999ZM1.65039 4.9999C1.65039 4.8066 1.80709 4.6499 2.00039 4.6499H8.00039C8.19369 4.6499 8.35039 4.8066 8.35039 4.9999C8.35039 5.1932 8.19369 5.3499 8.00039 5.3499H2.00039C1.80709 5.3499 1.65039 5.1932 1.65039 4.9999ZM2.00039 6.6499C1.80709 6.6499 1.65039 6.8066 1.65039 6.9999C1.65039 7.1932 1.80709 7.3499 2.00039 7.3499H8.00039C8.19369 7.3499 8.35039 7.1932 8.35039 6.9999C8.35039 6.8066 8.19369 6.6499 8.00039 6.6499H2.00039Z"></path></svg> </button> </div></div> <div class="hidden flex-row items-center justify-between gap-x-2 xl:flex xl:flex-none"><div class="-mb-px flex h-12 items-center overflow-x-auto overflow-y-hidden "><a class="tab-alternate active" href="/spaces/yuntian-deng/ChatGPT4"><svg class="mr-1.5 text-gray-400 flex-none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><path class="uim-quaternary" d="M20.23 7.24L12 12L3.77 7.24a1.98 1.98 0 0 1 .7-.71L11 2.76c.62-.35 1.38-.35 2 0l6.53 3.77c.29.173.531.418.7.71z" opacity=".25" fill="currentColor"></path><path class="uim-tertiary" d="M12 12v9.5a2.09 2.09 0 0 1-.91-.21L4.5 17.48a2.003 2.003 0 0 1-1-1.73v-7.5a2.06 2.06 0 0 1 .27-1.01L12 12z" opacity=".5" fill="currentColor"></path><path class="uim-primary" d="M20.5 8.25v7.5a2.003 2.003 0 0 1-1 1.73l-6.62 3.82c-.275.13-.576.198-.88.2V12l8.23-4.76c.175.308.268.656.27 1.01z" fill="currentColor"></path></svg> App </a><a class="tab-alternate " href="/spaces/yuntian-deng/ChatGPT4/tree/main"><svg class="mr-1.5 text-gray-400 flex-none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><path class="uim-tertiary" d="M21 19h-8a1 1 0 0 1 0-2h8a1 1 0 0 1 0 2zm0-4h-8a1 1 0 0 1 0-2h8a1 1 0 0 1 0 2zm0-8h-8a1 1 0 0 1 0-2h8a1 1 0 0 1 0 2zm0 4h-8a1 1 0 0 1 0-2h8a1 1 0 0 1 0 2z" opacity=".5" fill="currentColor"></path><path class="uim-primary" d="M9 19a1 1 0 0 1-1-1V6a1 1 0 0 1 2 0v12a1 1 0 0 1-1 1zm-6-4.333a1 1 0 0 1-.64-1.769L3.438 12l-1.078-.898a1 1 0 0 1 1.28-1.538l2 1.667a1 1 0 0 1 0 1.538l-2 1.667a.999.999 0 0 1-.64.231z" fill="currentColor"></path></svg> <span class="xl:hidden">Files</span> <span class="hidden xl:inline">Files</span> </a><a class="tab-alternate " href="/spaces/yuntian-deng/ChatGPT4/discussions"><svg class="mr-1.5 text-gray-400 flex-none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M20.6081 3C21.7684 3 22.8053 3.49196 23.5284 4.38415C23.9756 4.93678 24.4428 5.82749 24.4808 7.16133C24.9674 7.01707 25.4353 6.93643 25.8725 6.93643C26.9833 6.93643 27.9865 7.37587 28.696 8.17411C29.6075 9.19872 30.0124 10.4579 29.8361 11.7177C29.7523 12.3177 29.5581 12.8555 29.2678 13.3534C29.8798 13.8646 30.3306 14.5763 30.5485 15.4322C30.719 16.1032 30.8939 17.5006 29.9808 18.9403C30.0389 19.0342 30.0934 19.1319 30.1442 19.2318C30.6932 20.3074 30.7283 21.5229 30.2439 22.6548C29.5093 24.3704 27.6841 25.7219 24.1397 27.1727C21.9347 28.0753 19.9174 28.6523 19.8994 28.6575C16.9842 29.4379 14.3477 29.8345 12.0653 29.8345C7.87017 29.8345 4.8668 28.508 3.13831 25.8921C0.356375 21.6797 0.754104 17.8269 4.35369 14.1131C6.34591 12.058 7.67023 9.02782 7.94613 8.36275C8.50224 6.39343 9.97271 4.20438 12.4172 4.20438H12.4179C12.6236 4.20438 12.8314 4.2214 13.0364 4.25468C14.107 4.42854 15.0428 5.06476 15.7115 6.02205C16.4331 5.09583 17.134 4.359 17.7682 3.94323C18.7242 3.31737 19.6794 3 20.6081 3ZM20.6081 5.95917C20.2427 5.95917 19.7963 6.1197 19.3039 6.44225C17.7754 7.44319 14.8258 12.6772 13.7458 14.7131C13.3839 15.3952 12.7655 15.6837 12.2086 15.6837C11.1036 15.6837 10.2408 14.5497 12.1076 13.1085C14.9146 10.9402 13.9299 7.39584 12.5898 7.1776C12.5311 7.16799 12.4731 7.16355 12.4172 7.16355C11.1989 7.16355 10.6615 9.33114 10.6615 9.33114C10.6615 9.33114 9.0863 13.4148 6.38031 16.206C3.67434 18.998 3.5346 21.2388 5.50675 24.2246C6.85185 26.2606 9.42666 26.8753 12.0653 26.8753C14.8021 26.8753 17.6077 26.2139 19.1799 25.793C19.2574 25.7723 28.8193 22.984 27.6081 20.6107C27.4046 20.212 27.0693 20.0522 26.6471 20.0522C24.9416 20.0522 21.8393 22.6726 20.5057 22.6726C20.2076 22.6726 19.9976 22.5416 19.9116 22.222C19.3433 20.1173 28.552 19.2325 27.7758 16.1839C27.639 15.6445 27.2677 15.4256 26.746 15.4263C24.4923 15.4263 19.4358 19.5181 18.3759 19.5181C18.2949 19.5181 18.2368 19.4937 18.2053 19.4419C17.6743 18.557 17.9653 17.9394 21.7082 15.6009C25.4511 13.2617 28.0783 11.8545 26.5841 10.1752C26.4121 9.98141 26.1684 9.8956 25.8725 9.8956C23.6001 9.89634 18.2311 14.9403 18.2311 14.9403C18.2311 14.9403 16.7821 16.496 15.9057 16.496C15.7043 16.496 15.533 16.4139 15.4169 16.2112C14.7956 15.1296 21.1879 10.1286 21.5484 8.06535C21.7928 6.66715 21.3771 5.95917 20.6081 5.95917Z" fill="#FF9D00"></path><path d="M5.50686 24.2246C3.53472 21.2387 3.67446 18.9979 6.38043 16.206C9.08641 13.4147 10.6615 9.33111 10.6615 9.33111C10.6615 9.33111 11.2499 6.95933 12.59 7.17757C13.93 7.39581 14.9139 10.9401 12.1069 13.1084C9.29997 15.276 12.6659 16.7489 13.7459 14.713C14.8258 12.6772 17.7747 7.44316 19.304 6.44221C20.8326 5.44128 21.9089 6.00204 21.5484 8.06532C21.188 10.1286 14.795 15.1295 15.4171 16.2118C16.0391 17.2934 18.2312 14.9402 18.2312 14.9402C18.2312 14.9402 25.0907 8.49588 26.5842 10.1752C28.0776 11.8545 25.4512 13.2616 21.7082 15.6008C17.9646 17.9393 17.6744 18.557 18.2054 19.4418C18.7372 20.3266 26.9998 13.1351 27.7759 16.1838C28.5513 19.2324 19.3434 20.1173 19.9117 22.2219C20.48 24.3274 26.3979 18.2382 27.6082 20.6107C28.8193 22.9839 19.2574 25.7722 19.18 25.7929C16.0914 26.62 8.24723 28.3726 5.50686 24.2246Z" fill="#FFD21E"></path></svg> Community <div class="ml-1.5 flex h-4 min-w-[1rem] items-center justify-center rounded px-1 text-xs leading-none shadow-sm bg-black text-white dark:bg-gray-800 dark:text-gray-200">12 </div> </a> </div> <div class="mt-0"><div class="relative "> <button class="btn px-1 py-1 text-base translate-y-px " type="button"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="p-0.5" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><circle cx="16" cy="7" r="3" fill="currentColor"></circle><circle cx="16" cy="16" r="3" fill="currentColor"></circle><circle cx="16" cy="25" r="3" fill="currentColor"></circle></svg> </button> </div></div> </div></div> </header> </div> <div class="SVELTE_HYDRATER contents" data-props="{}" data-target="GoogleAnalyticsTracker"></div> <div class="SVELTE_HYDRATER contents" data-props="{}" data-target="SSOBanner"></div> <main class="flex flex-1 flex-col"><div class="SVELTE_HYDRATER contents" data-props="{&quot;iframeSrc&quot;:&quot;https://yuntian-deng-chatgpt4.hf.space/?__theme=light&quot;,&quot;runningSdk&quot;:&quot;gradio&quot;,&quot;containerClass&quot;:&quot;container&quot;,&quot;privateSpace&quot;:false}" data-target="SpaceIframe"> <iframe src="https://yuntian-deng-chatgpt4.hf.space/?__theme=light" aria-label="Space app" class="container space-iframe flex-grow overflow-hidden bg-white p-0 outline-none dark:bg-white" allow="accelerometer; ambient-light-sensor; autoplay; battery; camera; clipboard-read; clipboard-write; display-capture; document-domain; encrypted-media; fullscreen; geolocation; gyroscope; layout-animations; legacy-image-formats; magnetometer; microphone; midi; oversized-images; payment; picture-in-picture; publickey-credentials-get; sync-xhr; usb; vr ; wake-lock; xr-spatial-tracking" sandbox="allow-downloads allow-forms allow-modals allow-pointer-lock allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts allow-storage-access-by-user-activation" scrolling="no"></iframe></div></main> </div> <script> import("/front/build/kube-125ae72/index.js"); window.moonSha = "kube-125ae72/"; window.hubConfig = JSON.parse(`{"features":{"signupDisabled":false},"sshGitUrl":"git@hf.co","moonHttpUrl":"https://huggingface.co","captchaApiKey":"bd5f2066-93dc-4bdd-a64b-a24646ca3859","captchaDisabledOnSignup":true,"datasetsServerPublicUrl":"https://datasets-server.huggingface.co","stripePublicKey":"pk_live_x2tdjFXBCvXo2FFmMybezpeM00J6gPCAAc","environment":"production","userAgent":"HuggingFace (production)"}`); </script> <!-- Stripe --> <script> if (["hf.co", "huggingface.co"].includes(window.location.hostname)) { const script = document.createElement("script"); script.src = "https://js.stripe.com/v3/"; script.async = true; document.head.appendChild(script); } </script> <!-- Google analytics v4 --> <script> if (["hf.co", "huggingface.co"].includes(window.location.hostname)) { const script = document.createElement("script"); script.src = "https://www.googletagmanager.com/gtag/js?id=G-8Q63TH4CSL"; script.async = true; document.head.appendChild(script); window.dataLayer = window.dataLayer || []; function gtag() { if (window.dataLayer !== undefined) { window.dataLayer.push(arguments); } } gtag("js", new Date()); gtag("config", "G-8Q63TH4CSL", { page_path: "/spaces/yuntian-deng/ChatGPT4" }); /// ^ See https://developers.google.com/analytics/devguides/collection/gtagjs/pages gtag("consent", "default", { ad_storage: "denied", analytics_storage: "denied" }); /// ^ See https://developers.google.com/tag-platform/gtagjs/reference#consent /// TODO: ask the user for their consent and update this with gtag('consent', 'update') } </script> </body> </html>
35e771af32c98e9a619eb82019854ad4
{ "intermediate": 0.3118627667427063, "beginner": 0.40449976921081543, "expert": 0.28363746404647827 }
38,881
this is in a worker.js file let wasmbuffers; let wasmmodule = () => { const Module = { repeater: 0 }; Module.decodeBlendInternal = blended => { const startTime = performance.now(); const extra = new Uint8Array(blended); Module.asm.j(24, 132); const pos = Module.asm.j(228, 132); // The original version copied starting from the second byte of ‘extra’, // since it used ‘extra[i + 1]’. Adjusting the set operation accordingly. Module.HEAPU8.set(extra.subarray(1, 133), pos); Module.asm.j(172, 36); const index = Module.asm.j(4, 152); // Create a new ArrayBuffer to hold the 64-byte result. const arraybuffer = new ArrayBuffer(64); const list = new Uint8Array(arraybuffer); // Use ‘set’ method to copy 64 bytes from ‘index’ directly into ‘list’. // Now, since ‘list’ is created based on a new ArrayBuffer, ‘set’ operates like a memcpy. list.set(Module.HEAPU8.subarray(index, index + 64)); // Peformance Benchmark const endTime = performance.now(); const executionTime = endTime - startTime; console.log(`decodeBlendInternal execution time: ${executionTime} milliseconds`); return arraybuffer; }; Module.onDecodeOpcode5 = (blended, hostname, callback) => { console.log(JSON.stringify(Array.from(new Uint8Array(blended)))); console.log(hostname); Module.blended = blended; Module.hostname = hostname; // Decode the blended data const decoded = Module.decodeBlendInternal(blended); const mcs = Module.asm.j(187, 22); // Create opcode6Data as a Uint8Array instead of pushing into a regular array const opcode6Data = new Uint8Array(17); opcode6Data[0] = 6; opcode6Data.set(Module.HEAPU8.subarray(mcs, mcs + 16), 1); callback({ 5: new Uint8Array(decoded), 6: opcode6Data }); console.log({ 5: new Uint8Array(decoded), 6: opcode6Data }); }; Module.finalizeOpcode10 = blended => { const decoded = Module.decodeBlendInternal(blended); const list = new Uint8Array(decoded); return Uint8Array.of(10, ...list); }; function instantiate(wasmbuffers) { WebAssembly.instantiate(wasmbuffers, { "a": { 'd': () => { }, 'f': () => { }, 'c': () => { }, 'e': () => { }, 'b': () => [0, 0, 1, 0, 24][(Module.repeater %= 5, Module.repeater++)], 'a': () => (Module.HEAPU8.set(new Uint8Array([...new TextEncoder().encode(Module.hostname)]), 200), 200) } }).then(asm => { Module.asm = asm.instance.exports; Module.HEAPU8 = new Uint8Array(Module.asm.g.buffer) Module.asm.h(); Module.asm.i(0, 0); Module.ready = true; if (Module.opcode5Callback) Module.onDecodeOpcode5(Module.blended, Module.hostname, Module.opcode5Callback); }); } wasmbuffers ? instantiate(wasmbuffers) : fetch("https://cdn.glitch.global/ac6cfcd4-73cc-46ca-87ec-b913932b390f/zombs_wasm%20(4).wasm?v=1705666953205").then(e => e.arrayBuffer().then(r => { wasmbuffers = new Uint8Array(r); instantiate(wasmbuffers); })); return Module; }; const Module = wasmmodule(); onmessage = async function (event) { const { action, data, hostname } = event.data; if (action === 'test') console.log(Module); if (action === 'finalizeOpcode10') { const result = Module.finalizeOpcode10(new Uint8Array(data)); postMessage({ status: 'finalized', result: result }); } else if (action === 'onDecodeOpcode5') { const result = onDecodeOpcode5(new Uint8Array(data), hostname); postMessage({ status: 'decoded', result: result }); } } requesting finalizeOpcode10 causes the wasm to eventually overflow, why/
ee7954c8087a63643992ff156c0c3959
{ "intermediate": 0.36863669753074646, "beginner": 0.35550209879875183, "expert": 0.2758611738681793 }
38,882
Write Python script to load webpage like in browser and parse some data after full loaded page
e084889cedd2c7fe6f27a7394fb6c4ea
{ "intermediate": 0.5785071849822998, "beginner": 0.14480404555797577, "expert": 0.2766887843608856 }
38,883
Can I define model temperature in a prompt>?
c4b705bd24fb7c5e2e73d102e14ac0cd
{ "intermediate": 0.4170985817909241, "beginner": 0.2603445053100586, "expert": 0.3225569427013397 }
38,884
If i want to learn anything or any subject how i can use chatgpt for it?
f302e4edffaeb930e5d463f13db9b7a3
{ "intermediate": 0.4108477532863617, "beginner": 0.15855200588703156, "expert": 0.43060028553009033 }
38,885
Give me some logo names I can use in quasar / vue that looks like subsites or subsiting or routing. Like icon="" values that represent subsiting
89a794dbf50d0a13fd5b32123a56fd12
{ "intermediate": 0.544285237789154, "beginner": 0.07889578491449356, "expert": 0.3768189251422882 }
38,886
Write processing code that detects the series of 4 numbers in this array. int [] row = {5, 5, 5, 1, 1, 1, 1};
ea776f2b8401538cfb50a601aded84d9
{ "intermediate": 0.49816879630088806, "beginner": 0.1284961700439453, "expert": 0.37333497405052185 }
38,887
can we design date based self destruction macro in excel file to delete macro?
d6573d6ffdc87c33b5d8e658fde57a55
{ "intermediate": 0.3237954378128052, "beginner": 0.14145031571388245, "expert": 0.5347542762756348 }
38,888
i have this script '@app.post('/process_image', response_class=HTMLResponse, status_code=200) async def process_image(request: Request, file: UploadFile = File(...)): try: image_contents = await file.read() image = Image.open(io.BytesIO(image_contents)) image_array = np.array(image) visualised_origine, instances = run_prediction('model_final_lines', image_array) results = [] for i, instance_idx in tqdm(enumerate(range(len(instances))), desc="Processing Instances"): if instances.pred_classes[instance_idx] != 0: continue polygon = instances.pred_masks[instance_idx].cpu().numpy().astype(np.uint8) contours, _ = cv2.findContours(polygon, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) if not contours: continue for contour_idx, contour in enumerate(tqdm(contours, desc=f"Processing Contours for Instance {i}")): x, y, w, h = cv2.boundingRect(contour) area = w * h # Add a condition based on width and height if w < 1500 and h < 80: continue mask = np.zeros_like(image_array, dtype=np.uint8) cv2.drawContours(mask, [contour], contourIdx=-1, color=(255,) * mask.shape[2], thickness=cv2.FILLED) masked_image = cv2.bitwise_and(image_array, mask) cropped_image = masked_image[y:y + h, x:x + w] # Run prediction for the letter letter_prediction, _ = run_prediction('model_letter', cropped_image) # Encode the letter prediction prediction_letters = encode_image_to_base64(letter_prediction) # Encode the cropped image encoded_image_64 = encode_image_to_base64(cropped_image) # add the test character : test = classify_character(cropped_image, model5) # add loop to crop the character results.append({'original': encoded_image_64, 'letter_prediction': prediction_letters, 'contour_idx': contour_idx, 'instance_idx': i, 'area': area, 'test': test}) return templates.TemplateResponse( "result_template.html", { "request": request, "code": 200, "encoded_image": encode_image_to_base64(image_array), "encoded_predicted": encode_image_to_base64(visualised_origine), "message": "Success", "results": results } ) except Exception as e: logging.error(f"Error processing image: {e}") return templates.TemplateResponse( "result_template.html", { "request": request, "code": 500, "message": f"Error: {e}", } ) # a more meaningful response can be used ' that take image and crop the image in the each crop take the character loop i didnt add the loop now but this it will take time i need a way to do 5 image crope them at the same time
5c4a095c94f73f2c069ffd07b184f2a6
{ "intermediate": 0.3082422614097595, "beginner": 0.41825830936431885, "expert": 0.27349939942359924 }
38,889
optimise tis "# FastAPI endpoint for processing images @app.post('/process_image', response_class=HTMLResponse, status_code=200) async def process_image(request: Request, file: UploadFile = File(...)): try: image_contents = await file.read() image = Image.open(io.BytesIO(image_contents)) image_array = np.array(image) visualised_origine, instances = await run_prediction('model_final_lines', image_array) results = [] async def process_contour(contour_idx, contour, i): x, y, w, h = cv2.boundingRect(contour) area = w * h # Add a condition based on width and height if w < 1500 and h < 80: return mask = np.zeros_like(image_array, dtype=np.uint8) cv2.drawContours(mask, [contour], contourIdx=-1, color=(255,) * mask.shape[2], thickness=cv2.FILLED) masked_image = cv2.bitwise_and(image_array, mask) cropped_image = masked_image[y:y + h, x:x + w] # Run prediction for the letter asynchronously letter_prediction, _ = await run_prediction('model_letter', cropped_image) # Encode the letter prediction prediction_letters = encode_image_to_base64(letter_prediction) # Encode the cropped image encoded_image_64 = encode_image_to_base64(cropped_image) # add the test character : test = classify_character(cropped_image, model5) # add loop to crop the character results.append({'original': encoded_image_64, 'letter_prediction': prediction_letters, 'contour_idx': contour_idx, 'instance_idx': i, 'area': area, 'test': test}) for i, instance_idx in enumerate(range(len(instances))): if instances.pred_classes[instance_idx] != 0: continue polygon = instances.pred_masks[instance_idx].cpu().numpy().astype(np.uint8) contours, _ = cv2.findContours(polygon, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) if not contours: continue print(f"Processing Contours for Instance {i}") await asyncio.gather(*[process_contour(contour_idx, contour, i) for contour_idx, contour in enumerate(contours)]) print("Image Processing Completed") return templates.TemplateResponse( "result_template.html", { "request": request, "code": 200, "encoded_image": encode_image_to_base64(image_array), "encoded_predicted": encode_image_to_base64(visualised_origine), "message": "Success", "results": results } ) except Exception as e: logging.error(f"Error processing image: {e}") return templates.TemplateResponse( "result_template.html", { "request": request, "code": 500, "message": f"Error: {e}", } ) # a more meaningful response can be used
ded21fc765e24c0562688ea5bb2f75f5
{ "intermediate": 0.2997872829437256, "beginner": 0.5223743319511414, "expert": 0.17783838510513306 }
38,890
Are you able to analyze a database?
d89383ba802b6c3b2ec8d857d6a701db
{ "intermediate": 0.2982984185218811, "beginner": 0.3545020818710327, "expert": 0.3471994996070862 }
38,891
I need your help to generate more examples like this - “Person A”: { “address”: “1456 East 52nd Street, New York, NY, 10022”, “name”: {“first_name”: “Maria”, “middle_name”: “Elizabeth”, “last_name”: “Fernandez”, “suffix”: “”}, “ssn”: “234-56-7890”, “dob”: “1985-07-23” }, “Person B”: { “address”: “1456 East 52nd Street, New York, NY, 10022”, “name”: {“first_name”: “Maria”, “middle_name”: “E.”, “last_name”: “Fernandez”, “suffix”: “”}, “ssn”: “234567890”, “dob”: “July 23, 1985” } Vary the formatting on ssn and dob between person A and person B, so I can test the full functionality of the prompt I have created
94385c31d4995f17dd8d576cb33dc36c
{ "intermediate": 0.3166290521621704, "beginner": 0.3702267110347748, "expert": 0.3131442666053772 }
38,892
Can you explain what the shufps x86 instruction does and how to call it?
2e8ef40c2f46c9b0e510dc29601e1678
{ "intermediate": 0.34344738721847534, "beginner": 0.13876987993717194, "expert": 0.5177826881408691 }
38,893
Flip System.out.printf("%d\t%d\t%s\t%s\t\t%d\t\t%s\t\t%d\t\t%s\n", and System.out.println("X\tCount\tEm Prob\tP(X)\t\tCount(500)\tEm Prob(500)\tCount(10000)\tEm Prob(10000)"); import java.text.DecimalFormat; import java.util.Random; public class MyProgram { public static void main(String[] args) { int [] rollCounts = simulateDiceRolls(36); int [] rollCounts500 = simulateDiceRolls(500); int [] rollCounts10000 = simulateDiceRolls(10000); System.out.println("X\tCount\tEm Prob\tP(X)\t\tCount(500)\tEm Prob(500)\tCount(10000)\tEm Prob(10000)"); DecimalFormat df = new DecimalFormat("#.####"); for(int i = 2; i <=12; i++){ double theoreticalProbability = getTheoreticalProbability(i); System.out.printf("%d\t%d\t%s\t%s\t\t%d\t\t%s\t\t%d\t\t%s\n", i, rollCounts[i-2], df.format(rollCounts[i-2]/36.0), df.format(theoreticalProbability), rollCounts500[i-2], df.format(rollCounts500[i-2]/500.0), rollCounts10000[i-2], df.format(rollCounts10000[i-2]/10000.0)); } } public static int[] simulateDiceRolls(int numberOfRolls) { Random random = new Random(); int[] counts = new int[11]; for (int i = 0; i < numberOfRolls; i++) { int die1 = random.nextInt(6) + 1; int die2 = random.nextInt(6) + 1; int sum = die1 + die2; counts[sum - 2]++; } return counts; } public static double getTheoreticalProbability(int sum) { int[] occurrences = {1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1}; return occurrences[sum - 2] / 36.0; } }
181f57077952d8e0d5ee2358a4900c72
{ "intermediate": 0.231955423951149, "beginner": 0.5082074403762817, "expert": 0.25983718037605286 }
38,894
Flip System.out.printf("%d\t%d\t%s\t%s\t\t%d\t\t%s\t\t%d\t\t%s\n", and System.out.println("X\tCount\tEm Prob\tP(X)\t\tCount(500)\tEm Prob(500)\tCount(10000)\tEm Prob(10000)") so the output looks like X 2 3 4 5 6 7 8 9 10 11 12 Count EmProb P(X) Count(500) EmProb(500) Count(10000) EmProb(10000) import java.text.DecimalFormat; import java.util.Random; public class MyProgram { public static void main(String[] args) { int [] rollCounts = simulateDiceRolls(36); int [] rollCounts500 = simulateDiceRolls(500); int [] rollCounts10000 = simulateDiceRolls(10000); System.out.println("X\tCount\tEm Prob\tP(X)\t\tCount(500)\tEm Prob(500)\tCount(10000)\tEm Prob(10000)"); DecimalFormat df = new DecimalFormat("#.####"); for(int i = 2; i <=12; i++){ double theoreticalProbability = getTheoreticalProbability(i); System.out.printf("%d\t%d\t%s\t%s\t\t%d\t\t%s\t\t%d\t\t%s\n", i, rollCounts[i-2], df.format(rollCounts[i-2]/36.0), df.format(theoreticalProbability), rollCounts500[i-2], df.format(rollCounts500[i-2]/500.0), rollCounts10000[i-2], df.format(rollCounts10000[i-2]/10000.0)); } } public static int[] simulateDiceRolls(int numberOfRolls) { Random random = new Random(); int[] counts = new int[11]; for (int i = 0; i < numberOfRolls; i++) { int die1 = random.nextInt(6) + 1; int die2 = random.nextInt(6) + 1; int sum = die1 + die2; counts[sum - 2]++; } return counts; } public static double getTheoreticalProbability(int sum) { int[] occurrences = {1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1}; return occurrences[sum - 2] / 36.0; } }
ee22d3b49369fa74d407f2ec381426d4
{ "intermediate": 0.21299861371517181, "beginner": 0.5604082345962524, "expert": 0.22659312188625336 }
38,895
np.where
c239cfe831a3a17c6e02918ea2b521d1
{ "intermediate": 0.24464359879493713, "beginner": 0.3696359694004059, "expert": 0.385720431804657 }
38,896
Fix my code to output like this.  Count is how many rolls resulted in a sum of the X amount  Em Prob is the empirical probability from that simulation (count / numberRolled)  P(X) is the theoretical probability: 2 Die Simulator Theoretial Probability of rolling two die: X 2 3 4 5 6 7 8 9 10 11 12 P(X) 0.0278 0.0556 0.0833 0.1111 0.1389 0.1667 0.1389 0.1111 0.0833 0.0556 0.0278 Results Rolling 36 die: X 2 3 4 5 6 7 8 9 10 11 12 Count 1 2 3 7 2 7 7 3 3 1 0 Em Prob 0.0278 0.0556 0.0833 0.1944 0.0556 0.1944 0.1944 0.0833 0.0833 .0278 0 import java.text.DecimalFormat; import java.util.Random; public class MyProgram { public static void main(String[] args) { int [] rollCounts = simulateDiceRolls(36); int [] rollCounts500 = simulateDiceRolls(500); int [] rollCounts10000 = simulateDiceRolls(10000); System.out.println("X\tCount\tEm Prob\tP(X)\t\tCount(500)\tEm Prob(500)\tCount(10000)\tEm Prob(10000)"); DecimalFormat df = new DecimalFormat("#.####"); for(int i = 2; i <=12; i++){ double theoreticalProbability = getTheoreticalProbability(i); System.out.printf("%d\t%d\t%s\t%s\t\t%d\t\t%s\t\t%d\t\t%s\n", i, rollCounts[i-2], df.format(rollCounts[i-2]/36.0), df.format(theoreticalProbability), rollCounts500[i-2], df.format(rollCounts500[i-2]/500.0), rollCounts10000[i-2], df.format(rollCounts10000[i-2]/10000.0)); } } public static int[] simulateDiceRolls(int numberOfRolls) { Random random = new Random(); int[] counts = new int[11]; for (int i = 0; i < numberOfRolls; i++) { int die1 = random.nextInt(6) + 1; int die2 = random.nextInt(6) + 1; int sum = die1 + die2; counts[sum - 2]++; } return counts; } public static double getTheoreticalProbability(int sum) { int[] occurrences = {1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1}; return occurrences[sum - 2] / 36.0; } }
8d639b715e27d2493874bf83ba364717
{ "intermediate": 0.25586432218551636, "beginner": 0.5288344621658325, "expert": 0.2153012901544571 }
38,897
Fix my code to output like this.  Count is how many rolls resulted in a sum of the X amount  Em Prob is the empirical probability from that simulation (count / numberRolled)  P(X) is the theoretical probability: 2 Die Simulator Theoretial Probability of rolling two die: X 2 3 4 5 6 7 8 9 10 11 12 P(X) 0.0278 0.0556 0.0833 0.1111 0.1389 0.1667 0.1389 0.1111 0.0833 0.0556 0.0278 Results Rolling 36 die: X 2 3 4 5 6 7 8 9 10 11 12 Count 1 2 3 7 2 7 7 3 3 1 0 Em Prob 0.0278 0.0556 0.0833 0.1944 0.0556 0.1944 0.1944 0.0833 0.0833 .0278 0 ... countinue for 500 die and 10,000 die import java.text.DecimalFormat; import java.util.Random; public class MyProgram { public static void main(String[] args) { int [] rollCounts = simulateDiceRolls(36); int [] rollCounts500 = simulateDiceRolls(500); int [] rollCounts10000 = simulateDiceRolls(10000); System.out.println("X\tCount\tEm Prob\tP(X)\t\tCount(500)\tEm Prob(500)\tCount(10000)\tEm Prob(10000)"); DecimalFormat df = new DecimalFormat("#.####"); for(int i = 2; i <=12; i++){ double theoreticalProbability = getTheoreticalProbability(i); System.out.printf("%d\t%d\t%s\t%s\t\t%d\t\t%s\t\t%d\t\t%s\n", i, rollCounts[i-2], df.format(rollCounts[i-2]/36.0), df.format(theoreticalProbability), rollCounts500[i-2], df.format(rollCounts500[i-2]/500.0), rollCounts10000[i-2], df.format(rollCounts10000[i-2]/10000.0)); } } public static int[] simulateDiceRolls(int numberOfRolls) { Random random = new Random(); int[] counts = new int[11]; for (int i = 0; i < numberOfRolls; i++) { int die1 = random.nextInt(6) + 1; int die2 = random.nextInt(6) + 1; int sum = die1 + die2; counts[sum - 2]++; } return counts; } public static double getTheoreticalProbability(int sum) { int[] occurrences = {1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1}; return occurrences[sum - 2] / 36.0; } }
05dd705220df8ff7de2585f931194229
{ "intermediate": 0.23819315433502197, "beginner": 0.5552411079406738, "expert": 0.2065657377243042 }
38,898
Please explain in easy terms why this code doesnt work: #include <stdio.h> void swap(int a, int b); int main(void) { int x = 1; int y = 2; printf("x is %i, y is %i\n", x, y); swap(x, y); printf("x is %i, y is %i\n", x, y); } void swap(int a, int b) { int tmp = a; a = b; b = tmp; }
9a4b3d38ab25efe3340841b2a8e4724f
{ "intermediate": 0.30696552991867065, "beginner": 0.5897842645645142, "expert": 0.10325020551681519 }
38,899
Fix my code to not use: %-10d, %-10.4f or printf import java.text.DecimalFormat; import java.util.Random; public class MyProgram { public static void main(String[] args) { int[] rollCounts36 = simulateDiceRolls(36); int[] rollCounts500 = simulateDiceRolls(500); int[] rollCounts10000 = simulateDiceRolls(10000); System.out.println("2 Die Simulator\n"); System.out.println("Theoretical Probability of rolling two die:"); System.out.print("X "); for (int i = 2; i <= 12; i++) { System.out.printf("%-10d", i); } System.out.print("\nP(X) "); for (int i = 2; i <= 12; i++) { System.out.printf("%-10.4f", getTheoreticalProbability(i)); } System.out.println("\n"); displayResults("Results Rolling 36 die:", rollCounts36, 36); displayResults("\nResults Rolling 500 die:", rollCounts500, 500); displayResults("\nResults Rolling 10000 die:", rollCounts10000, 10000); } public static int[] simulateDiceRolls(int numberOfRolls) { Random random = new Random(); int[] counts = new int[11]; for (int i = 0; i < numberOfRolls; i++) { int die1 = random.nextInt(6) + 1; int die2 = random.nextInt(6) + 1; int sum = die1 + die2; counts[sum - 2]++; } return counts; } public static double getTheoreticalProbability(int sum) { int[] occurrences = {1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1}; return occurrences[sum - 2] / 36.0; } public static void displayResults(String title, int[] rollCounts, int numberOfRolls) { DecimalFormat df = new DecimalFormat("#.####"); System.out.println(title); System.out.print("X "); for (int i = 2; i <= 12; i++) { System.out.printf("%-10d", i); } System.out.print("\nCount "); for (int count : rollCounts) { System.out.printf("%-10d", count); } System.out.print("\nEm Prob"); for (int count : rollCounts) { System.out.printf("%-10s", df.format(count / (double) numberOfRolls)); } System.out.println("\n"); } }
f28fa24ad809faa8575320a13079bd51
{ "intermediate": 0.3629794418811798, "beginner": 0.42204782366752625, "expert": 0.21497276425361633 }
38,900
Fix my code to not use: %-10d, %-10.4f , printf , %-10s, or String format import java.text.DecimalFormat; import java.util.Random; public class MyProgram { public static void main(String[] args) { int[] rollCounts36 = simulateDiceRolls(36); int[] rollCounts500 = simulateDiceRolls(500); int[] rollCounts10000 = simulateDiceRolls(10000); System.out.println("2 Die Simulator\n"); System.out.println("Theoretical Probability of rolling two die:"); System.out.print("X "); for (int i = 2; i <= 12; i++) { System.out.printf("%-10d", i); } System.out.print("\nP(X) "); for (int i = 2; i <= 12; i++) { System.out.printf("%-10.4f", getTheoreticalProbability(i)); } System.out.println("\n"); displayResults("Results Rolling 36 die:", rollCounts36, 36); displayResults("\nResults Rolling 500 die:", rollCounts500, 500); displayResults("\nResults Rolling 10000 die:", rollCounts10000, 10000); } public static int[] simulateDiceRolls(int numberOfRolls) { Random random = new Random(); int[] counts = new int[11]; for (int i = 0; i < numberOfRolls; i++) { int die1 = random.nextInt(6) + 1; int die2 = random.nextInt(6) + 1; int sum = die1 + die2; counts[sum - 2]++; } return counts; } public static double getTheoreticalProbability(int sum) { int[] occurrences = {1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1}; return occurrences[sum - 2] / 36.0; } public static void displayResults(String title, int[] rollCounts, int numberOfRolls) { DecimalFormat df = new DecimalFormat("#.####"); System.out.println(title); System.out.print("X "); for (int i = 2; i <= 12; i++) { System.out.printf("%-10d", i); } System.out.print("\nCount "); for (int count : rollCounts) { System.out.printf("%-10d", count); } System.out.print("\nEm Prob"); for (int count : rollCounts) { System.out.printf("%-10s", df.format(count / (double) numberOfRolls)); } System.out.println("\n"); } }
10aaefd781ccd64d8479ecb5d73b01e9
{ "intermediate": 0.3492066562175751, "beginner": 0.46447333693504333, "expert": 0.1863199770450592 }
38,901
Fix my code to not use: %-10d, %-10.4f , printf , %-10s, or String format or “%-” or “s” or s or StringBuilder import java.text.DecimalFormat; import java.util.Random; public class MyProgram { public static void main(String[] args) { int[] rollCounts36 = simulateDiceRolls(36); int[] rollCounts500 = simulateDiceRolls(500); int[] rollCounts10000 = simulateDiceRolls(10000); System.out.println("2 Die Simulator\n"); System.out.println("Theoretical Probability of rolling two die:"); System.out.print("X "); for (int i = 2; i <= 12; i++) { System.out.printf("%-10d", i); } System.out.print("\nP(X) "); for (int i = 2; i <= 12; i++) { System.out.printf("%-10.4f", getTheoreticalProbability(i)); } System.out.println("\n"); displayResults("Results Rolling 36 die:", rollCounts36, 36); displayResults("\nResults Rolling 500 die:", rollCounts500, 500); displayResults("\nResults Rolling 10000 die:", rollCounts10000, 10000); } public static int[] simulateDiceRolls(int numberOfRolls) { Random random = new Random(); int[] counts = new int[11]; for (int i = 0; i < numberOfRolls; i++) { int die1 = random.nextInt(6) + 1; int die2 = random.nextInt(6) + 1; int sum = die1 + die2; counts[sum - 2]++; } return counts; } public static double getTheoreticalProbability(int sum) { int[] occurrences = {1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1}; return occurrences[sum - 2] / 36.0; } public static void displayResults(String title, int[] rollCounts, int numberOfRolls) { DecimalFormat df = new DecimalFormat("#.####"); System.out.println(title); System.out.print("X "); for (int i = 2; i <= 12; i++) { System.out.printf("%-10d", i); } System.out.print("\nCount "); for (int count : rollCounts) { System.out.printf("%-10d", count); } System.out.print("\nEm Prob"); for (int count : rollCounts) { System.out.printf("%-10s", df.format(count / (double) numberOfRolls)); } System.out.println("\n"); } }
3c9d2295f8e94de5ebfdbe21aeb1175d
{ "intermediate": 0.3483589291572571, "beginner": 0.44126996397972107, "expert": 0.21037106215953827 }
38,902
pub fn read_bed(file: &PathBuf) -> Result<(), Error> { let mut f = File::open(file)?; let mut contents = String::new(); f.read_to_string(&mut contents)?; let mut mapper: HashMap<String, String> = HashMap::new(); contents.par_lines().filter_map(|line| { let l = line; let tokens = l.split('\t'); let mut tokens = tokens.skip(3); let tx_id = tokens.next()?; let mut tokens = tokens.skip(1); let strand = tokens.next()?; mapper.insert(tx_id.to_string(), strand.to_string()) }); Ok(()) } error[E0596]: cannot borrow `mapper` as mutable, as it is a captured variable in a `Fn` closure --> src/utils.rs:179:9 | 179 | mapper.insert(tx_id.to_string(), strand.to_string()) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot borrow as mutable
104b92c5a9237885de351bb9b28145ea
{ "intermediate": 0.49717265367507935, "beginner": 0.41258376836776733, "expert": 0.09024356305599213 }
38,903
how to move element using revit api using flask app
827f87db84ac676ad7e91d0ea359693d
{ "intermediate": 0.8200573325157166, "beginner": 0.08258520811796188, "expert": 0.09735749661922455 }
38,904
message.alientvault.com
2df92e2463a8dd67f5aa14a6c78a05da
{ "intermediate": 0.31660765409469604, "beginner": 0.30255118012428284, "expert": 0.3808411657810211 }
38,905
// main.js import { generate_password } from './static/wasm.js'; const websiteInput = document.getElementById('website'); const emailInput = document.getElementById('email'); const keyInput = document.getElementById('key'); const copyButton = document.getElementById('copy-password'); // Updated ID // Function to get the current tab's URL async function getCurrentTabUrl() { console.log('getCurrentTabUrl() called'); const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); return tab.url; } // Function to save the email to local storage async function saveEmail(email) { console.log('saveEmail() called'); await chrome.storage.local.set({ 'email': email }); } // Function to retrieve the email from local storage and autofill async function autofillEmail() { console.log('autofillEmail() called'); const data = await chrome.storage.local.get('email'); const savedEmail = data.email || ''; emailInput.value = savedEmail; } // Autofill the current website getCurrentTabUrl().then(url => { websiteInput.value = url; console.log('getCurrentTabUrl() returned', url); }); // Autofill the email if it's saved in local storage autofillEmail(); copyButton.addEventListener('click', async () => { await init(); const website = websiteInput.value.trim(); const email = emailInput.value.trim(); const key = keyInput.value.trim(); if (website === '' || email === '' || key === '') { alert('Please fill all fields'); return; } const password = generate_password(email, website, key); saveEmail(email); navigator.clipboard.writeText(password); alert('Password copied to clipboard!'); console.log('Password copied to clipboard'); }); I want the browser extension to check the website and input it every time the popup is opened. It should also save the email and populate it when opened
ed5ce3eff98720adb3976918aa696130
{ "intermediate": 0.5010361671447754, "beginner": 0.253833144903183, "expert": 0.24513065814971924 }
38,906
// lib.rs // Compile with "wasm-pack build --target web --out-name wasm --out-dir ./static" use sha2::{Digest, Sha256}; use wasm_bindgen::prelude::*; // GENERATE_PASSWORD FUNCTION: TAKES EMAIL, WEBSITE, AND KEY AS INPUT AND RETURNS A PASSWORD #[wasm_bindgen] pub fn generate_password(email: &str, website: &str, key: &str) -> String { let input = format!("{}{}{}", email, website, key); let mut hasher = Sha256::new(); hasher.update(input); let result = hasher.finalize(); let password = format!("{:x}", result); println!("printing from lib.rs, password: {}", password); password } // Cleans urls: eg. https://github.com/GageHoweTamu/PWGen -> github.com #[wasm_bindgen] pub fn clean_url(url: &str) -> String { match url.find("://") { Some(i) => { let start = i + 3; match url[start..].find("/") { Some(j) => url[start..start + j].to_string(), None => url[start..].to_string(), } } None => url.to_string(), } } // main.js import { generate_password, clean_url } from './static/wasm.js'; const websiteInput = document.getElementById('website'); const emailInput = document.getElementById('email'); const keyInput = document.getElementById('key'); const copyButton = document.getElementById('copy-password'); // Updated ID // Function to get the current tab's URL async function getCurrentTabUrl() { console.log('getCurrentTabUrl() called'); const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); console.log('getCurrentTabUrl() returned ', tab.url); // return clean_url(tab.url); // why does this not work? Error: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '__wbindgen_add_to_stack_pointer') return tab.url; } // Function to save the email to local storage async function saveEmail(email) { console.log('saveEmail() called'); await chrome.storage.local.set({ 'email': email }); } // Function to retrieve the email from local storage and autofill async function autofillEmail() { console.log('autofillEmail() called'); const data = await chrome.storage.local.get('email'); const savedEmail = data.email || ''; emailInput.value = savedEmail; } // Autofill the current website getCurrentTabUrl().then(url => { websiteInput.value = url; console.log('getCurrentTabUrl() returned', url); }); // Autofill the email if it's saved in local storage autofillEmail(); window.addEventListener('load', async () => { websiteInput.value = await getCurrentTabUrl(); await autofillEmail(); }); copyButton.addEventListener('click', async () => { // generate and copy password const website = websiteInput.value.trim(); const email = emailInput.value.trim(); const key = keyInput.value.trim(); if (!website || !email || !key) { alert('Please fill all fields'); return; } const password = generate_password(email, website, key); saveEmail(email); navigator.clipboard.writeText(password); alert('Password copied to clipboard!'); console.log('Password copied to clipboard'); }); let wasm; let WASM_VECTOR_LEN = 0; let cachedUint8Memory0 = null; function getUint8Memory0() { if (cachedUint8Memory0 === null || cachedUint8Memory0.byteLength === 0) { cachedUint8Memory0 = new Uint8Array(wasm.memory.buffer); } return cachedUint8Memory0; } const cachedTextEncoder = (typeof TextEncoder !== 'undefined' ? new TextEncoder('utf-8') : { encode: () => { throw Error('TextEncoder not available') } } ); const encodeString = (typeof cachedTextEncoder.encodeInto === 'function' ? function (arg, view) { return cachedTextEncoder.encodeInto(arg, view); } : function (arg, view) { const buf = cachedTextEncoder.encode(arg); view.set(buf); return { read: arg.length, written: buf.length }; }); function passStringToWasm0(arg, malloc, realloc) { if (realloc === undefined) { const buf = cachedTextEncoder.encode(arg); const ptr = malloc(buf.length, 1) >>> 0; getUint8Memory0().subarray(ptr, ptr + buf.length).set(buf); WASM_VECTOR_LEN = buf.length; return ptr; } let len = arg.length; let ptr = malloc(len, 1) >>> 0; const mem = getUint8Memory0(); let offset = 0; for (; offset < len; offset++) { const code = arg.charCodeAt(offset); if (code > 0x7F) break; mem[ptr + offset] = code; } if (offset !== len) { if (offset !== 0) { arg = arg.slice(offset); } ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0; const view = getUint8Memory0().subarray(ptr + offset, ptr + len); const ret = encodeString(arg, view); offset += ret.written; } WASM_VECTOR_LEN = offset; return ptr; } let cachedInt32Memory0 = null; function getInt32Memory0() { if (cachedInt32Memory0 === null || cachedInt32Memory0.byteLength === 0) { cachedInt32Memory0 = new Int32Array(wasm.memory.buffer); } return cachedInt32Memory0; } const cachedTextDecoder = (typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }) : { decode: () => { throw Error('TextDecoder not available') } } ); if (typeof TextDecoder !== 'undefined') { cachedTextDecoder.decode(); }; function getStringFromWasm0(ptr, len) { ptr = ptr >>> 0; return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len)); } /** * @param {string} email * @param {string} website * @param {string} key * @returns {string} */ export function generate_password(email, website, key) { let deferred4_0; let deferred4_1; try { const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); const ptr0 = passStringToWasm0(email, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); const len0 = WASM_VECTOR_LEN; const ptr1 = passStringToWasm0(website, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); const len1 = WASM_VECTOR_LEN; const ptr2 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); const len2 = WASM_VECTOR_LEN; wasm.generate_password(retptr, ptr0, len0, ptr1, len1, ptr2, len2); var r0 = getInt32Memory0()[retptr / 4 + 0]; var r1 = getInt32Memory0()[retptr / 4 + 1]; deferred4_0 = r0; deferred4_1 = r1; return getStringFromWasm0(r0, r1); } finally { wasm.__wbindgen_add_to_stack_pointer(16); wasm.__wbindgen_free(deferred4_0, deferred4_1, 1); } } /** * @param {string} url * @returns {string} */ export function clean_url(url) { let deferred2_0; let deferred2_1; try { const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); const ptr0 = passStringToWasm0(url, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); const len0 = WASM_VECTOR_LEN; wasm.clean_url(retptr, ptr0, len0); var r0 = getInt32Memory0()[retptr / 4 + 0]; var r1 = getInt32Memory0()[retptr / 4 + 1]; deferred2_0 = r0; deferred2_1 = r1; return getStringFromWasm0(r0, r1); } finally { wasm.__wbindgen_add_to_stack_pointer(16); wasm.__wbindgen_free(deferred2_0, deferred2_1, 1); } } async function __wbg_load(module, imports) { if (typeof Response === 'function' && module instanceof Response) { if (typeof WebAssembly.instantiateStreaming === 'function') { try { return await WebAssembly.instantiateStreaming(module, imports); } catch (e) { if (module.headers.get('Content-Type') != 'application/wasm') { console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e); } else { throw e; } } } const bytes = await module.arrayBuffer(); return await WebAssembly.instantiate(bytes, imports); } else { const instance = await WebAssembly.instantiate(module, imports); if (instance instanceof WebAssembly.Instance) { return { instance, module }; } else { return instance; } } } function __wbg_get_imports() { const imports = {}; imports.wbg = {}; return imports; } function __wbg_init_memory(imports, maybe_memory) { } function __wbg_finalize_init(instance, module) { wasm = instance.exports; __wbg_init.__wbindgen_wasm_module = module; cachedInt32Memory0 = null; cachedUint8Memory0 = null; return wasm; } function initSync(module) { if (wasm !== undefined) return wasm; const imports = __wbg_get_imports(); __wbg_init_memory(imports); if (!(module instanceof WebAssembly.Module)) { module = new WebAssembly.Module(module); } const instance = new WebAssembly.Instance(module, imports); return __wbg_finalize_init(instance, module); } async function __wbg_init(input) { if (wasm !== undefined) return wasm; if (typeof input === 'undefined') { input = new URL('wasm_bg.wasm', import.meta.url); } const imports = __wbg_get_imports(); if (typeof input === 'string' || (typeof Request === 'function' && input instanceof Request) || (typeof URL === 'function' && input instanceof URL)) { input = fetch(input); } __wbg_init_memory(imports); const { instance, module } = await __wbg_load(await input, imports); return __wbg_finalize_init(instance, module); } export { initSync } export default __wbg_init; Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '__wbindgen_add_to_stack_pointer') Why the error? How can i fix it
ff93189928b7440d56604157373bc150
{ "intermediate": 0.2985728085041046, "beginner": 0.5694890022277832, "expert": 0.13193809986114502 }
38,907
Please help me to restore wireless internet connection in Linux Debian. It broken after update. I know it is some problem with linux-headers. I don't know what network manager in use. I always used networking service to restart connection
c1a4009c168dfd91d9c2cc24f55cc148
{ "intermediate": 0.44612249732017517, "beginner": 0.29000839591026306, "expert": 0.26386910676956177 }
38,908
// main.js import { generate_password } from './static/wasm.js'; const websiteInput = document.getElementById('website'); const emailInput = document.getElementById('email'); const keyInput = document.getElementById('key'); const copyButton = document.getElementById('copy-password'); // Updated ID // Function to get the current tab's URL async function getCurrentTabUrl() { console.log('getCurrentTabUrl() called'); const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); console.log('getCurrentTabUrl() returned ', tab.url); return clean_url(tab.url); // why does this not work? Error: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '__wbindgen_add_to_stack_pointer') // return tab.url; } async function saveEmail(email) { console.log('saveEmail() called'); await chrome.storage.local.set({ 'email': email }); } async function autofillEmail() { console.log('autofillEmail() called'); const data = await chrome.storage.local.get('email'); const savedEmail = data.email || ''; emailInput.value = savedEmail; } getCurrentTabUrl().then(url => { websiteInput.value = url; console.log('getCurrentTabUrl() returned', url); }); window.addEventListener('load', async () => { websiteInput.value = await getCurrentTabUrl(); await autofillEmail(); }); emailInput.addEventListener('input', async () => { await saveEmail(emailInput.value); }); function clean_url(url) { // Cleans urls: eg. https://github.com/GageHoweTamu/PWGen -> github.com const start = url.indexOf("://") >= 0 ? url.indexOf("://") + 3 : 0; const end = url.slice(start).indexOf('/') >= 0 ? url.slice(start).indexOf('/') : url.length - start; return url.slice(start, start + end); } copyButton.addEventListener('click', async () => { // generate and copy password const website = websiteInput.value.trim(); const email = emailInput.value.trim(); const key = keyInput.value.trim(); if (!website || !email || !key) { alert('Please fill all fields'); return; } const password = generate_password(email, website, key); saveEmail(email); navigator.clipboard.writeText(password); alert('Password copied to clipboard!'); console.log('Password copied to clipboard'); }); // lib.rs // Compile with "wasm-pack build --target web --out-name wasm --out-dir ./static" use sha2::{Digest, Sha256}; use wasm_bindgen::prelude::*; // GENERATE_PASSWORD FUNCTION: TAKES EMAIL, WEBSITE, AND KEY AS INPUT AND RETURNS A PASSWORD #[wasm_bindgen] pub fn generate_password(email: &str, website: &str, key: &str) -> String { let input = format!("{}{}{}", email, website, key); let mut hasher = Sha256::new(); hasher.update(input); let result = hasher.finalize(); let password = format!("{:x}", result); println!("printing from lib.rs, password: {}", password); password } <!-- File: index.html --> <!-- web dev is cool--> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Password Generator Extension</title> <link rel="stylesheet" type="text/css" href="styles.css"> </head> <body> <h1>PWGen</h1> <p>Fill in the following details:</p> <form> <label for="website">Website:</label><br> <input type="text" id="website" name="website"><br> <label for="email">Email:</label><br> <input type="text" id="email" name="email"><br> <label for="key">Key (Password):</label><br> <input type="password" id="key" name="key"><br><br> <button type="button" id="copy-password">Copy Password</button> </form> <script type="module" src="./main.js"></script> </body> </html> I get this error when clicking the copy button: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '__wbindgen_add_to_stack_pointer') Context index.html Stack Trace static/wasm.js:108 (anonymous function) let wasm; let WASM_VECTOR_LEN = 0; let cachedUint8Memory0 = null; function getUint8Memory0() { if (cachedUint8Memory0 === null || cachedUint8Memory0.byteLength === 0) { cachedUint8Memory0 = new Uint8Array(wasm.memory.buffer); } return cachedUint8Memory0; } const cachedTextEncoder = (typeof TextEncoder !== 'undefined' ? new TextEncoder('utf-8') : { encode: () => { throw Error('TextEncoder not available') } } ); const encodeString = (typeof cachedTextEncoder.encodeInto === 'function' ? function (arg, view) { return cachedTextEncoder.encodeInto(arg, view); } : function (arg, view) { const buf = cachedTextEncoder.encode(arg); view.set(buf); return { read: arg.length, written: buf.length }; }); function passStringToWasm0(arg, malloc, realloc) { if (realloc === undefined) { const buf = cachedTextEncoder.encode(arg); const ptr = malloc(buf.length, 1) >>> 0; getUint8Memory0().subarray(ptr, ptr + buf.length).set(buf); WASM_VECTOR_LEN = buf.length; return ptr; } let len = arg.length; let ptr = malloc(len, 1) >>> 0; const mem = getUint8Memory0(); let offset = 0; for (; offset < len; offset++) { const code = arg.charCodeAt(offset); if (code > 0x7F) break; mem[ptr + offset] = code; } if (offset !== len) { if (offset !== 0) { arg = arg.slice(offset); } ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0; const view = getUint8Memory0().subarray(ptr + offset, ptr + len); const ret = encodeString(arg, view); offset += ret.written; } WASM_VECTOR_LEN = offset; return ptr; } let cachedInt32Memory0 = null; function getInt32Memory0() { if (cachedInt32Memory0 === null || cachedInt32Memory0.byteLength === 0) { cachedInt32Memory0 = new Int32Array(wasm.memory.buffer); } return cachedInt32Memory0; } const cachedTextDecoder = (typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }) : { decode: () => { throw Error('TextDecoder not available') } } ); if (typeof TextDecoder !== 'undefined') { cachedTextDecoder.decode(); }; function getStringFromWasm0(ptr, len) { ptr = ptr >>> 0; return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len)); } /** * @param {string} email * @param {string} website * @param {string} key * @returns {string} */ export function generate_password(email, website, key) { let deferred4_0; let deferred4_1; try { const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); const ptr0 = passStringToWasm0(email, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); const len0 = WASM_VECTOR_LEN; const ptr1 = passStringToWasm0(website, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); const len1 = WASM_VECTOR_LEN; const ptr2 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); const len2 = WASM_VECTOR_LEN; wasm.generate_password(retptr, ptr0, len0, ptr1, len1, ptr2, len2); var r0 = getInt32Memory0()[retptr / 4 + 0]; var r1 = getInt32Memory0()[retptr / 4 + 1]; deferred4_0 = r0; deferred4_1 = r1; return getStringFromWasm0(r0, r1); } finally { wasm.__wbindgen_add_to_stack_pointer(16); wasm.__wbindgen_free(deferred4_0, deferred4_1, 1); } } Why is the error occurring? It only happens when I call a wasm function
b06104b31888f0f786ed348223d18958
{ "intermediate": 0.4400184154510498, "beginner": 0.36735624074935913, "expert": 0.19262532889842987 }
38,909
You are an accessibility expert. Here is the accessibility bug we found: Screen reader announce the same name as "sjekk din pris" under two different sections. Suggest an issue category for same.
6f4348895663368a5a3118db16ea0f73
{ "intermediate": 0.18985526263713837, "beginner": 0.4557926654815674, "expert": 0.35435205698013306 }
38,910
// main.js import { generate_password } from './static/wasm.js'; const websiteInput = document.getElementById('website'); const emailInput = document.getElementById('email'); const keyInput = document.getElementById('key'); const copyButton = document.getElementById('copy-password'); // Updated ID // Function to get the current tab's URL async function getCurrentTabUrl() { console.log('getCurrentTabUrl() called'); const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); console.log('getCurrentTabUrl() returned ', tab.url); return clean_url(tab.url); // why does this not work? Error: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '__wbindgen_add_to_stack_pointer') // return tab.url; } async function saveEmail(email) { console.log('saveEmail() called'); await chrome.storage.local.set({ 'email': email }); } async function autofillEmail() { console.log('autofillEmail() called'); const data = await chrome.storage.local.get('email'); const savedEmail = data.email || ''; emailInput.value = savedEmail; } getCurrentTabUrl().then(url => { websiteInput.value = url; console.log('getCurrentTabUrl() returned', url); }); window.addEventListener('load', async () => { websiteInput.value = await getCurrentTabUrl(); await autofillEmail(); }); emailInput.addEventListener('input', async () => { await saveEmail(emailInput.value); }); function clean_url(url) { // Cleans urls: eg. https://github.com/GageHoweTamu/PWGen -> github.com const start = url.indexOf("://") >= 0 ? url.indexOf("://") + 3 : 0; const end = url.slice(start).indexOf('/') >= 0 ? url.slice(start).indexOf('/') : url.length - start; return url.slice(start, start + end); } copyButton.addEventListener('click', async () => { // generate and copy password const website = websiteInput.value.trim(); const email = emailInput.value.trim(); const key = keyInput.value.trim(); if (!website || !email || !key) { alert('Please fill all fields'); return; } const password = generate_password(email, website, key); saveEmail(email); navigator.clipboard.writeText(password); alert('Password copied to clipboard!'); console.log('Password copied to clipboard'); }); // lib.rs // Compile with "wasm-pack build --target web --out-name wasm --out-dir ./static" use sha2::{Digest, Sha256}; use wasm_bindgen::prelude::*; // GENERATE_PASSWORD FUNCTION: TAKES EMAIL, WEBSITE, AND KEY AS INPUT AND RETURNS A PASSWORD #[wasm_bindgen] pub fn generate_password(email: &str, website: &str, key: &str) -> String { let input = format!("{}{}{}", email, website, key); let mut hasher = Sha256::new(); hasher.update(input); let result = hasher.finalize(); let password = format!("{:x}", result); println!("printing from lib.rs, password: {}", password); password } <!-- File: index.html --> <!-- web dev is cool--> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Password Generator Extension</title> <link rel="stylesheet" type="text/css" href="styles.css"> </head> <body> <h1>PWGen</h1> <p>Fill in the following details:</p> <form> <label for="website">Website:</label><br> <input type="text" id="website" name="website"><br> <label for="email">Email:</label><br> <input type="text" id="email" name="email"><br> <label for="key">Key (Password):</label><br> <input type="password" id="key" name="key"><br><br> <button type="button" id="copy-password">Copy Password</button> </form> <script type="module" src="./main.js"></script> </body> </html> { "manifest_version": 3, "name": "PWGen", "version": "1.0", "description": "A browser extension for generating passwords using Rust and SHA-256 hashing.", "action": { "default_popup": "index.html", "default_icon": { "16": "icon.png", "48": "icon.png", "128": "icon.png" } }, "permissions": ["clipboardWrite", "storage", "activeTab"], "icons": { "16": "icon.png", "48": "icon.png", "128": "icon.png" } } Why are there be errors when generate_password is called?
a8d7be4f7aad18a4cc403fe61d72399e
{ "intermediate": 0.4381813704967499, "beginner": 0.3695926070213318, "expert": 0.1922260820865631 }
38,911
What's EINVAL error for recv function?
560b50a343b1e21194b94e2620f10a02
{ "intermediate": 0.38185203075408936, "beginner": 0.28371429443359375, "expert": 0.3344336748123169 }
38,912
make so if it detects any like pris or ---- then skip it: while ((match = regex.exec(parsedText)) !== null) { parsedText = parsedText.replace(match[0], ''); newparsedText = parsedText.slice(0, match.index); if (match[1] !== " Pris " && match[1] !== " --- ") { new_products.push({ pris: match[1], källa: match[2] }); } for example this time it made it look like: <span class="highlight" style="color: var(--secondary-color); font-weight: 600;">Pris</span> <span class="highlight" style="color: var(--secondary-color); font-weight: 600;">Källa</span>
d5ffe05055c9d737f2f9b2a15b59ad3d
{ "intermediate": 0.40324121713638306, "beginner": 0.23916515707969666, "expert": 0.3575936555862427 }
38,913
make so it wont render the last data: while ((match = regex.exec(parsedText)) !== null) { parsedText = parsedText.replace(match[0], ''); newparsedText = parsedText.slice(0, match.index); const prisText = match[1].replace(/<[^>]*>?/gm, '').trim(); //find snippets in a string like eBay","snippets":["Philips HTS7140 Heimkinosysteme for sale online const snippets = match[1].match(/snippets\s*:\s*\[(.*?)\]/); const dashRegex = /^-+$/; // Check if prisText is neither “Pris” nor “—” if (prisText !== "Pris" && !dashRegex.test(prisText)) { new_products.push({ pris: match[1], källa: match[2] }); } } example text: eBay","snippets":["Philips HTS7140 Heimkinosysteme for sale online if it has the snippet in it then skip it
e22767ded61b7ed70cac932fd22994b6
{ "intermediate": 0.43751922249794006, "beginner": 0.3240355849266052, "expert": 0.2384452074766159 }
38,914
if an audio is on a=440 and the whole thing is C. if i slow it down with percentages, how much do i for every semitones in percent until -100%
dc2485eabe8abbb71d8c9992c84811de
{ "intermediate": 0.24055489897727966, "beginner": 0.4898971617221832, "expert": 0.2695479393005371 }
38,915
Is this code correct num = int(input()) sum = 0 for i in range(num, 11): if num % 2 == 0: sum += num if sum % 2 == 0: print("YES") else: print("NO")
7cd3152af31c94c030ee10389bdbb583
{ "intermediate": 0.1588667780160904, "beginner": 0.7274436354637146, "expert": 0.1136896014213562 }
38,916
quilt_loader: Quilt Loader 0.20.0-beta.4 quilt_networking: Quilt Networking 1.1.0-beta.26+1.18.2 quilt_recipe: Quilt Recipe API 1.1.0-beta.26+1.18.2 quilt_registry: Quilt Registry API 1.1.0-beta.26+1.18.2 quilt_registry_entry_attachments: Quilt Registry Entry Attachments 1.1.0-beta.26+1.18.2 quilt_resource_loader: Quilt Resource Loader 1.1.0-beta.26+1.18.2 quilt_screen: Quilt Screen API 1.1.0-beta.26+1.18.2 quilt_tags: Quilt Tags API 1.1.0-beta.26+1.18.2 quilt_tooltip: Quilt Tooltip API 1.1.0-beta.26+1.18.2 quilted_fabric_api: Quilted Fabric API 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_api_base: Quilted Fabric API Base 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_api_lookup_api_v1: Quilted Fabric API Lookup API (v1) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_biome_api_v1: Quilted Fabric Biome API (v1) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_blockrenderlayer_v1: Quilted Fabric BlockRenderLayer Registration (v1) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_command_api_v1: Quilted Fabric Command API (v1) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_commands_v0: Quilted Fabric Commands (v0) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_containers_v0: Quilted Fabric Containers (v0) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_content_registries_v0: Quilted Fabric Content Registries (v0) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_convention_tags_api_v1: Quilted Fabric Convention Tags API (v1) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_crash_report_info_v1: Quilted Fabric Crash Report Info (v1) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_dimensions_v1: Quilted Fabric Dimensions API (v1) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_entity_events_v1: Quilted Fabric Entity Events (v1) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_events_interaction_v0: Quilted Fabric Events Interaction (v0) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_events_lifecycle_v0: Quilted Fabric Events Lifecycle (v0) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_game_rule_api_v1: Quilted Fabric Game Rule API (v1) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_item_api_v1: Quilted Fabric Item API (v1) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_item_groups_v0: Quilted Fabric Item Groups (v0) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_key_binding_api_v1: Quilted Fabric Key Binding API (v1) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_keybindings_v0: Quilted Fabric Key Bindings (v0) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_lifecycle_events_v1: Quilted Fabric Lifecycle Events (v1) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_loot_api_v2: Quilted Fabric Loot API (v2) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_loot_tables_v1: Quilted Fabric Loot Tables (v1) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_mining_level_api_v1: Quilted Fabric Mining Level API (v1) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_models_v0: Quilted Fabric Models (v0) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_networking_api_v1: Quilted Fabric Networking API (v1) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_networking_v0: Quilted Fabric Networking (v0) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_object_builder_api_v1: Quilted Fabric Object Builder API (v1) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_particles_v1: Quilted Fabric Particles (v1) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_registry_sync_v0: Quilted Fabric Registry Sync (v0) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_renderer_api_v1: Quilted Fabric Renderer API (v1) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_renderer_indigo: Quilted Fabric Renderer - Indigo 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_renderer_registries_v1: Quilted Fabric Renderer Registries (v1) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_rendering_data_attachment_v1: Quilted Fabric Rendering Data Attachment (v1) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_rendering_fluids_v1: Quilted Fabric Rendering Fluids (v1) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_rendering_v0: Quilted Fabric Rendering (v0) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_rendering_v1: Quilted Fabric Rendering (v1) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_resource_conditions_api_v1: Quilted Fabric Resource Conditions API (v1) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_resource_loader_v0: Quilted Fabric Resource Loader (v0) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_screen_api_v1: Quilted Fabric Screen API (v1) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_screen_handler_api_v1: Quilted Fabric Screen Handler API (v1) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_textures_v0: Quilted Fabric Textures (v0) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_transfer_api_v1: Quilted Fabric Transfer API (v1) 1.0.0-beta.28+0.67.0-1.18.2 quilted_fabric_transitive_access_wideners_v1: Quilted Fabric Transitive Access Wideners (v1) 1.0.0-beta.28+0.67.0-1.18.2 reach-entity-attributes: Reach Entity Attributes 2.2.0 reeses-sodium-options: Reese's Sodium Options 1.6.3+mc1.18.2-build.88 registrate-fabric: Registrate for Fabric MC1.18.2-1.1.11 roughlyenoughitems: Roughly Enough Items 8.3.642 roughlyenoughresources: Roughly Enough Resources 2.5.0 satin: Satin 1.7.2 serialization_hooks: Serialization Hooks 0.3.23 sodium: Sodium 0.4.1+build.15 sodium-extra: Sodium Extra 0.4.18+mc1.18.2-build.98 splasher: Splasher 4.0.5 spruceui: SpruceUI 3.3.3+1.18 stacc: Stacc 1.2.3 star: Star 1.3+1.18.2 starlight: Starlight 1.0.2+fabric.89b8d9f stenographer: Stenographer 1.0.1-patch2 step-height-entity-attribute: Step Height Entity Attribute 1.0.0 structures_compass: Structures Compass 1.18.2-1.4.2 tags_binder: Tags Binder 0.1.2 tconstruct: Hephaestus 1.18.2-3.5.2.155 team_reborn_energy: Energy 2.2.0 terrablender: TerraBlender 1.1.0.102 terraform-biome-remapper-api-v1: Terraform Biome Remapper API (v1) 3.1.0 terraform-config-api-v1: Terraform Config API (v1) 3.1.0 terraform-dirt-api-v1: Terraform Dirt API (v1) 3.1.0 terraform-shapes-api-v1: Terraform Shapes API (v1) 3.1.0 terraform-surfaces-api-v1: Terraform Surfaces API (v1) 3.1.0 terraform-tree-api-v1: Terraform Tree API (v1) 3.1.0 terraform-wood-api-v1: Terraform Wood API (v1) 3.1.0 terrestria: Terrestria 4.0.6 terrestria-client: Terrestria: Client 4.0.6 terrestria-common: Terrestria: Common 4.0.6 terrestria-worldgen: Terrestria: World Generation 4.0.6 trinkets: Trinkets 3.3.1 verticality: Verticality 1.4.1 xaerominimap: Xaero's Minimap 23.9.7 xaeroworldmap: Xaero's World Map 1.37.7 xlpackets: XLPackets 3.1-1.18.2 Quilted Fabric API: !! WARNING !! This instance is using Fabric API modules re-implemented by QSL. If the issue comes from Quilted Fabric API, DO NOT report to Fabric; report them to Quilt instead! Flywheel Backend: GL33 Instanced Arrays Server Running: true Player Count: 1 / 8; [class_3222['TonyH'/1044, l='ServerLevel[FJ的niubility世界]', x=1999.65, y=73.00, z=61.87]] Data Packs: vanilla, cabricality/data_overrides World Generation: Stable Type: Integrated Server (map_client.txt) Is Modded: Definitely; Client brand changed to 'quilt'; Server brand changed to 'quilt' #@!@# Game crashed! Crash report saved to: #@!@# D:\Minecraft\.minecraft\versions\Cabricality\crash-reports\crash-2024-02-07_16.03.41-server.txt AL lib: (EE) alc_cleanup: 1 device not closed 这是Minecraft崩溃日志,帮我分析一下是什么原因
5fb5657e06c14849fe6c631ea7a00b89
{ "intermediate": 0.34297698736190796, "beginner": 0.4261091649532318, "expert": 0.230913907289505 }
38,917
hi
8acb614a77db1729b2c227494eb85ff8
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
38,918
File "C:\Users\AME\AppData\Local\Programs\Python\Python311\Lib\site-packages\bs4\__init__.py", line 328, in __init__ for (self.markup, self.original_encoding, self.declared_html_encoding, File "C:\Users\AME\AppData\Local\Programs\Python\Python311\Lib\site-packages\bs4\builder\_htmlparser.py", line 361, in prepare_markup dammit = UnicodeDammit( ^^^^^^^^^^^^^^ File "C:\Users\AME\AppData\Local\Programs\Python\Python311\Lib\site-packages\bs4\dammit.py", line 584, in __init__ self.detector = EncodingDetector( ^^^^^^^^^^^^^^^^^ File "C:\Users\AME\AppData\Local\Programs\Python\Python311\Lib\site-packages\bs4\dammit.py", line 389, in __init__ self.markup, self.sniffed_encoding = self.strip_byte_order_mark(markup) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\AME\AppData\Local\Programs\Python\Python311\Lib\site-packages\bs4\dammit.py", line 470, in strip_byte_order_mark elif data[:3] == b'\xef\xbb\xbf': ~~~~^^^^ TypeError: unhashable type: 'slice'
29c113f65d0b36c3ed0d38e93e5027de
{ "intermediate": 0.463906466960907, "beginner": 0.2771773934364319, "expert": 0.25891610980033875 }
38,919
File "c:\Users\AME\Documents\PriceChecker-master\discogs-master\dist\vinyl-price-suggester-main\VinylPrices\tuner\Jobb_server_server\Cleanup\get_pictures.py", line 128, in get_images url = soup.a["href"] ~~~~~~^^^^^^^^ TypeError: 'NoneType' object is not subscriptable ['https://www.ebay.com/p/96897245', 'https://productz.com/en/philips-hts7140/p/5glVg', 'https://www.ebay.com/p/146420549'] c:\Users\AME\Documents\PriceChecker-master\discogs-master\dist\vinyl-price-suggester-main\VinylPrices\tuner\Jobb_server_server\Cleanup\get_pictures.py:127: MarkupResemblesLocatorWarning: The input looks more like a URL than markup. You may want to use an HTTP client like requests to get the document behind the URL, and feed that document to Beautiful Soup. def get_images(links, destination_dir): print(links) with requests.Session() as session: session.headers.update( { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" } ) with ThreadPoolExecutor(max_workers=15) as executor: for link in links: if link: soup = BeautifulSoup(link, "html.parser") url = soup.a["href"] executor.submit(download_images, url, destination_dir, session)
fc6306bd3e77018dc9669b305b5cd806
{ "intermediate": 0.5151883959770203, "beginner": 0.28012362122535706, "expert": 0.20468798279762268 }
38,920
Привет! Я хочу добавить в свой бот некоторые функции. Первая - количество использований "Замены фона" в личном кабинете пользователя. При этом должно быть 2 разных строки: "Количество замен с общими фонами" и "Количество замен с личными фонами" Вот код моего бота: import asyncio from io import BytesIO from PIL import Image, ImageFilter import aiohttp import time from aiogram import Bot, Dispatcher, types, executor from aiogram.contrib.fsm_storage.memory import MemoryStorage from aiogram.dispatcher import FSMContext from aiogram.dispatcher.filters.state import State, StatesGroup from aiosqlite import connect import logging from aiogram.utils.exceptions import MessageNotModified from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton, ParseMode from aiogram import types from aiogram.dispatcher.middlewares import BaseMiddleware from aiogram.dispatcher.handler import CancelHandler from aiogram.dispatcher.middlewares import LifetimeControllerMiddleware from collections import defaultdict import ssl logging.basicConfig(level=logging.INFO) ADMINS=[989037374,6663889022] TOKEN = "6937803168:AAE-eV82HlqV3M0w7a8U89aJBpkGfywCz7A" bot = Bot(token=TOKEN) storage = MemoryStorage() dp = Dispatcher(bot, storage=storage) # Создание таблиц если они не существуют async def init_db(): logging.info("инициализация БД") async with connect('bot.db') as db: await db.execute(""" CREATE TABLE IF NOT EXISTS backgrounds ( id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, photo_id TEXT NOT NULL ) """) await db.execute(""" CREATE TABLE IF NOT EXISTS userphotos ( id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, photo_id TEXT NOT NULL ) """) await db.execute(""" CREATE TABLE IF NOT EXISTS users ( user_id INTEGER PRIMARY KEY, is_banned INTEGER DEFAULT 0, first_name TEXT, username TEXT ) """) await db.execute(""" CREATE TABLE IF NOT EXISTS common_backgrounds ( id INTEGER PRIMARY KEY, photo_id TEXT NOT NULL ) """) await db.commit() from aiogram.utils.markdown import escape_md class MailingState(StatesGroup): waiting_for_message = State() waiting_for_buttons = State() # Обработчик команды /post, передаем состояние ожидания сообщения для рассылки @dp.message_handler(commands=['post'], user_id=ADMINS, state='*') async def cmd_post(message: types.Message): await MailingState.waiting_for_message.set() await message.reply("Отправьте текст рассылки") # Обработчик текста рассылки, переводим в состояние ожидания кнопок @dp.message_handler(state=MailingState.waiting_for_message, content_types=types.ContentTypes.TEXT) async def post_message(message: types.Message, state: FSMContext): await MailingState.waiting_for_buttons.set() await state.update_data(mailing_text=message.text) await message.reply( "Теперь отправьте данные для inline-кнопок в формате: Текст кнопки;URL на каждую кнопку или /skip, если кнопки не нужны.") # Обработчик кнопок для рассылки или пропуска их добавления @dp.message_handler(state=MailingState.waiting_for_buttons) async def post_buttons(message: types.Message, state: FSMContext): if message.text != "/skip": # Разбиваем сообщение по строкам и создаем кнопки lines = message.text.split("\n") buttons = [InlineKeyboardButton(text=line.split(';')[0], url=line.split(';')[1]) for line in lines if len(line.split(';')) == 2] markup = InlineKeyboardMarkup() markup.add(*buttons) else: markup = None # Получаем данные из состояния и текст рассылки data = await state.get_data() text = data.get('mailing_text') mode = data.get('mailing_mode') # Запускаем рассылку success_count, failure_count = await send_mailing(text, mode, markup) await state.finish() # Сброс состояния после рассылки await message.answer(f"Рассылка выполнена. Успешно: {success_count}. Неудачно: {failure_count}.") async def send_mailing(text, parse_mode, keyboard=None): async with connect('bot.db') as db: cursor = await db.execute("SELECT user_id FROM users") user_ids = [row[0] for row in await cursor.fetchall()] success_count = 0 failure_count = 0 for user_id in user_ids: try: await bot.send_message( chat_id=user_id, text=text, reply_markup=keyboard, parse_mode=types.ParseMode.HTML ) success_count += 1 except Exception as e: # Обрабатываем возможные исключения, например, если пользователь заблокировал бота logging.error(f"Failed to send message to {user_id}: {e}") failure_count += 1 return success_count, failure_count # Обработчик команды /skip для пропуска добавления кнопок @dp.message_handler(state=MailingState.waiting_for_buttons, commands=['skip']) async def post_skip(message: types.Message, state: FSMContext): await post_buttons(message, state) # Хэндлер команды /sql для выполнения произвольных SQL-запросов (ТОЛЬКО для администраторов) @dp.message_handler(commands=['sql'], user_id=ADMINS) async def execute_sql_command(message: types.Message): # Получаем аргументы команды (SQL-запрос) sql_query = message.get_args() # Проверяем, что запрос не пустой if not sql_query: await message.reply("Введите SQL-запрос.") return # Подключаемся к базе данных и выполняем запрос async with connect('bot.db') as db: try: await db.execute(sql_query) await db.commit() await message.reply("SQL-запрос успешно выполнен.") except Exception as e: await message.reply(f"Ошибка при выполнении SQL-запроса: {e}") class UploadBackgroundState(StatesGroup): waiting_for_backgrounds = State() class UploadUserPhotoState(StatesGroup): waiting_for_user_photo = State() # Админ-команда для очистки таблицы с общими фонами @dp.message_handler(commands=['clear_common'], user_id=ADMINS) async def clear_common_backgrounds(message: types.Message): async with connect('bot.db') as db: await db.execute("DELETE FROM common_backgrounds") await db.commit() await message.reply("Все общие фоны были успешно удалены из базы данных.") # Админ-команда для просмотра количества общих фонов @dp.message_handler(commands=['count_common'], user_id=ADMINS) async def count_common_backgrounds(message: types.Message): async with connect('bot.db') as db: cursor = await db.execute("SELECT COUNT(*) FROM common_backgrounds") count = await cursor.fetchone() await message.reply(f"Количество общих фонов в базе данных: {count[0]}") async def generate_invite_link(chat_id): try: chat_invite_link = await bot.create_chat_invite_link(chat_id, expire_date=int(time.time()) + 900) # на 15 минут return chat_invite_link.invite_link except Exception as e: logging.error(e) return None async def is_user_subscribed(chat_id, user_id): try: member = await bot.get_chat_member(chat_id, user_id) return member.status not in ["left", "kicked"] except Exception as e: logging.error(e) return False # По умолчанию считаем, что пользователь не подписан, если возникла ошибка CHANNEL_ID = "-1002046113496" # ID вашего канала class SubscriptionCheckMiddleware(BaseMiddleware): def __init__(self, channel_id): super().__init__() self.channel_id = channel_id async def on_process_message(self, message: types.Message, data: dict): member = await bot.get_chat_member(self.channel_id, message.from_user.id) if member.status not in ["member", "administrator", "creator"]: invite_link = await generate_invite_link(self.channel_id) if invite_link: keyboard = InlineKeyboardMarkup().add( InlineKeyboardButton("🔗 Подписаться на канал", url=invite_link) ) await message.answer( f"🔒 Для продолжения работы с ботом *необходимо подписаться на наш новостной канал\.*\n\n👌 Если вы уже подписались на канал, нажмите /start",parse_mode="MarkdownV2", reply_markup=keyboard ) # прерываем обработку следующих хэндлеров raise CancelHandler() async def post_process(self, obj, data, *args): pass dp.middleware.setup(SubscriptionCheckMiddleware(CHANNEL_ID)) @dp.message_handler(commands=['count']) async def count_backgrounds(message: types.Message): user_id = message.from_user.id async with connect('bot.db') as db: cursor = await db.execute("SELECT COUNT(*) FROM backgrounds WHERE user_id = ?", (user_id,)) count = await cursor.fetchone() await message.answer(f"У вас в базе данных *{count[0]}* фоновых изображений\.",parse_mode="MarkdownV2") @dp.message_handler(commands=['ex']) async def export_backgrounds(message: types.Message): user_id = message.from_user.id try: # Получаем количество изображений для выгрузки из команды command_args = message.get_args().split() # если ничего не введено, выгрузить все num_images = int(command_args[0]) if command_args else -1 except (IndexError, ValueError): await message.answer("Укажите количество фонов для выгрузки. Например: /ex 10") return async with connect('bot.db') as db: # Если num_images равен -1, значит выгрузить все изображения query = "SELECT id, photo_id FROM backgrounds LIMIT ?" cursor = await db.execute(query, (10 if num_images == -1 else num_images,)) backgrounds_chunk = await cursor.fetchall() while backgrounds_chunk: media_group = [types.InputMediaPhoto(photo[1]) for photo in backgrounds_chunk] await bot.send_media_group(message.chat.id, media_group) # Удаляем отправленные фоны из БД await db.executemany("DELETE FROM backgrounds WHERE id = ?", [(photo[0],) for photo in backgrounds_chunk]) await db.commit() if num_images != -1: num_images -= len(backgrounds_chunk) if num_images <= 0: break # Получаем следующую пачку изображений cursor = await db.execute(query, (10 if num_images == -1 else min(num_images, 10),)) backgrounds_chunk = await cursor.fetchall() await message.answer("*Все запрошенные фоновые изображения были выгружены и удалены из базы данных\.*",parse_mode="MarkdownV2") LOG_CHANNEL_ID = "@smenalogs" async def log_to_channel(user: types.User, action: str): message_to_send = f"Пользователь @{user.username} ({user.id}) выполнил действие: {action}" await bot.send_message(LOG_CHANNEL_ID, message_to_send) stop_keyboard = ReplyKeyboardMarkup(resize_keyboard=True).add(KeyboardButton("Стоп")) async def start_keyboard(): # Создаем начальную клавиатуру с кнопками "Замена фона" и "Личный кабинет" return ReplyKeyboardMarkup(resize_keyboard=True).add( KeyboardButton("🖼 Замена фона") ).add( KeyboardButton("📊 Личный кабинет") ) @dp.message_handler(commands=['stop'], state='*') async def stop_processing(message: types.Message, state: FSMContext): # … await message.reply("Обработка фотографий прекращена.", reply_markup=await start_keyboard()) await state.finish() @dp.message_handler(commands=['start', 'help']) async def send_welcome(message: types.Message): user_id = message.from_user.id first_name = message.from_user.first_name username = message.from_user.username # Подключаемся к БД и проверяем, существует ли пользователь async with connect('bot.db') as db: cursor = await db.execute("SELECT user_id FROM users WHERE user_id = ?", (user_id,)) user_exists = await cursor.fetchone() # Если пользователя нет в БД, сохраняем его if not user_exists: await db.execute("INSERT INTO users (user_id, first_name, username) VALUES (?, ?, ?)", (user_id, first_name, username)) await db.commit() # Создаем кнопки button_photos = KeyboardButton("🖼 Замена фона") button_cabinet = KeyboardButton("📊 Личный кабинет") # Отправляем сообщение вместе с клавиатурой await message.answer( "Привет! Пользуйся кнопками", reply_markup=await start_keyboard() ) await log_to_channel(message.from_user, "прописал /start") @dp.callback_query_handler( lambda c: c.data == 'toggle_common_backgrounds_on' or c.data == 'toggle_common_backgrounds_off') async def toggle_common_backgrounds(callback_query: types.CallbackQuery): user_id = callback_query.from_user.id # Переключаем состояние использования общих фонов new_setting = not (callback_query.data == 'toggle_common_backgrounds_on') # Сохраняем новое состояние в базу данных async with connect('bot.db') as db: await db.execute("UPDATE users SET use_common_backgrounds = ? WHERE user_id = ?", (int(new_setting), user_id)) await db.commit() # Ответное сообщение пользователю reply_text = "Общие фоны включены." if new_setting else "Общие фоны выключены." await bot.answer_callback_query(callback_query.id, reply_text) # Обновить сообщение в "личном кабинете", чтобы отразить изменения с "включено/выключено" await personal_cabinet(callback_query) @dp.callback_query_handler(lambda c: c.data == 'support') async def support_callback(callback_query: types.CallbackQuery): support_text = ( "❓ Если у вас есть вопросы, предложения, проблемы \- обращайтесь к администратору бота\.\n\n" "*Нажмите на кнопку ниже, чтобы связаться\.*" ) admin_button = InlineKeyboardMarkup().add( InlineKeyboardButton("👨‍💻 Администратор бота", url="t.me/ih82seeucry") ) await bot.edit_message_text( chat_id=callback_query.message.chat.id, message_id=callback_query.message.message_id, text=support_text, parse_mode="MarkdownV2", reply_markup=admin_button ) @dp.message_handler(lambda message: message.text == "📊 Личный кабинет") async def personal_cabinet(message_or_query): # Определяем, является ли объект сообщением или коллбэк-запросом if isinstance(message_or_query, types.Message): user_id = message_or_query.from_user.id message = message_or_query elif isinstance(message_or_query, types.CallbackQuery): user_id = message_or_query.from_user.id message = message_or_query.message else: return # Если полученный объект не поддерживается, не предпринимать никаких действий async with connect('bot.db') as db: cursor = await db.execute("SELECT COUNT(*) FROM backgrounds WHERE user_id = ?", (user_id,)) count = (await cursor.fetchone())[0] cursor = await db.execute("SELECT use_common_backgrounds FROM users WHERE user_id = ?", (user_id,)) use_common_backgrounds = (await cursor.fetchone())[0] common_bg_status = "включено" if use_common_backgrounds else "выключено" toggle_text = "Общие фоны: вкл" if use_common_backgrounds else "Общие фоны: выкл" callback_data = 'toggle_common_backgrounds_on' if use_common_backgrounds else 'toggle_common_backgrounds_off' keyboard = InlineKeyboardMarkup(row_width=1).add( InlineKeyboardButton("Загрузить фоны", callback_data='upload_backgrounds'), InlineKeyboardButton("Загрузить креатив", callback_data='upload_user_photos'), InlineKeyboardButton("Очистить фоны", callback_data='clear_backgrounds'), InlineKeyboardButton(toggle_text, callback_data=callback_data), InlineKeyboardButton("Поддержка", callback_data='support') ) text_message = f"*📊 Личный кабинет*\n\nКоличество фонов: {count}\nИспользование общих фонов *{common_bg_status}*" if isinstance(message_or_query, types.CallbackQuery): try: # Метод для изменения текста сообщения и клавиатуры await bot.edit_message_text(text=text_message, chat_id=message.chat.id, message_id=message.message_id, parse_mode="MarkdownV2", reply_markup=keyboard) except MessageNotModified: # Ничего не делаем, если содержимое сообщения не изменилось pass else: await message.answer(text_message, parse_mode="MarkdownV2", reply_markup=keyboard) @dp.callback_query_handler(lambda c: c.data == 'upload_backgrounds') async def upload_backgrounds(callback_query: types.CallbackQuery): await upload_background_start(callback_query.message) await bot.send_message(callback_query.from_user.id, "Отправьте фоны для загрузки или нажмите Стоп, чтобы завершить.", reply_markup=stop_keyboard) @dp.callback_query_handler(lambda c: c.data == 'upload_user_photos') async def upload_user_photos(callback_query: types.CallbackQuery): await clear_user_photos_action(callback_query.from_user.id) await upload_user_photo_start(callback_query.message) await bot.send_message(callback_query.from_user.id, "Отправьте креатив для загрузки или нажмите Стоп, чтобы завершить.", reply_markup=stop_keyboard) @dp.callback_query_handler(lambda c: c.data == 'clear_backgrounds') async def clear_backgrounds(callback_query: types.CallbackQuery): confirmation_keyboard = InlineKeyboardMarkup().add( InlineKeyboardButton("Да", callback_data='confirm_clear_backgrounds'), InlineKeyboardButton("Нет", callback_data='cancel_clear_backgrounds') ) await callback_query.message.edit_text( "Вы уверены, что хотите удалить все свои фоны из базы? Это действие необратимо.", reply_markup=confirmation_keyboard ) @dp.callback_query_handler(lambda c: c.data == 'confirm_clear_backgrounds') async def confirm_clear_backgrounds(callback_query: types.CallbackQuery): user_id = callback_query.from_user.id async with connect('bot.db') as db: await db.execute("DELETE FROM backgrounds WHERE user_id = ?", (user_id,)) await db.commit() await bot.answer_callback_query(callback_query.id, "Ваши фоновые изображения были удалены из базы данных.") await callback_query.message.delete() await log_to_channel(callback_query.from_user, "очистил свои фоновые изображения") await send_welcome(callback_query.message) @dp.callback_query_handler(lambda c: c.data == 'cancel_clear_backgrounds') async def cancel_clear_backgrounds(callback_query: types.CallbackQuery): await callback_query.message.delete() await send_welcome(callback_query.message) # общие фоны class UploadCommonBackgroundState(StatesGroup): waiting_for_common_backgrounds = State() @dp.message_handler(commands=['common'], user_id=ADMINS, state='*') async def upload_common_background_start(message: types.Message): await UploadCommonBackgroundState.waiting_for_common_backgrounds.set() await message.reply("Отправьте общие фоны для загрузки или нажмите Стоп, чтобы сохранить их в базу данных.", reply_markup=stop_keyboard) @dp.message_handler(content_types=['photo'], state=UploadCommonBackgroundState.waiting_for_common_backgrounds) async def upload_common_background(message: types.Message, state: FSMContext): photo_id = message.photo[-1].file_id state_data = await state.get_data() buffer = state_data.get('buffer', []) buffer.append(photo_id) await state.update_data(buffer=buffer) await message.reply( "Фон добавлен в очередь. Продолжайте добавлять фоны или нажмите Стоп, чтобы сохранить их в базу данных.") @dp.message_handler(lambda message: message.text.lower() == "стоп", state=UploadCommonBackgroundState.waiting_for_common_backgrounds) async def stop_uploading_common_backgrounds(message: types.Message, state: FSMContext): state_data = await state.get_data() buffer = state_data.get('buffer', []) if buffer: async with connect('bot.db') as db: await db.executemany("INSERT INTO common_backgrounds (photo_id) VALUES (?)", [(photo_id,) for photo_id in buffer]) await db.commit() await state.finish() await message.reply("Все общие фоны сохранены в базу данных.", reply_markup=await start_keyboard()) @dp.callback_query_handler(lambda c: c.data == 'back_to_start') async def back_to_start(callback_query: types.CallbackQuery): await send_welcome(callback_query.message) @dp.message_handler(commands=['clear_upload']) async def clear_backgrounds(message: types.Message): user_id = message.from_user.id # Получаем ID пользователя async with connect('bot.db') as db: # Удаляем только фоны конкретного пользователя await db.execute("DELETE FROM backgrounds WHERE user_id = ?", (user_id,)) await db.commit() await message.answer("Ваши фоновые изображения были удалены из базы данных.") await log_to_channel(message.from_user, "очистил свои фоновые изображения") async def clear_user_photos_action(user_id: int): async with connect('bot.db') as db: await db.execute("DELETE FROM userphotos WHERE user_id = ?", (user_id,)) await db.commit() @dp.message_handler(commands=['clear_user']) async def clear_user_photos(message: types.Message): user_id = message.from_user.id await clear_user_photos_action(user_id) await message.answer("Ваш креатив был удален из базы данных.") await log_to_channel(message.from_user, "очистил userphoto") # Инициируем FSM для загрузки фонов @dp.message_handler(commands=['upload'], state='*') async def upload_background_start(message: types.Message): logging.info("прием аплоад") await UploadBackgroundState.waiting_for_backgrounds.set() await log_to_channel(message.from_user, "прописал /upload") # Инициируем FSM для загрузки пользовательского фото @dp.message_handler(commands=['user'], state='*') async def upload_user_photo_start(message: types.Message): logging.info("прием юзер фото") await UploadUserPhotoState.waiting_for_user_photo.set() await log_to_channel(message.from_user, "загружает userphoto") # Обработка загрузки фоновых фотографий @dp.message_handler(content_types=['photo'], state=UploadBackgroundState.waiting_for_backgrounds) async def upload_background(message: types.Message, state: FSMContext): user_id = message.from_user.id photo_id = message.photo[-1].file_id state_data = await state.get_data() buffer = state_data.get("buffer", []) buffer.append((user_id, photo_id)) await state.update_data(buffer=buffer) await message.answer("*Фон добавлен\.* Не забудьте нажать Стоп, чтобы сохранить все ваши фото в базу",parse_mode="MarkdownV2") # Обработка загрузки пользовательских фотографий @dp.message_handler(content_types=['photo'], state=UploadUserPhotoState.waiting_for_user_photo) async def upload_user_photo(message: types.Message, state: FSMContext): user_id = message.from_user.id photo_id = message.photo[-1].file_id state_data = await state.get_data() buffer = state_data.get("buffer", []) buffer.append((user_id, photo_id)) await state.update_data(buffer=buffer) await message.answer("*Фото креатива добавлено в очередь\.* Не забудьте нажать Стоп, чтобы сохранить все ваши фото в базу",parse_mode="MarkdownV2") # Переход обратно в обычное состояние после команды /stop @dp.message_handler(commands=['stop'], state='*') async def stop_processing(message: types.Message, state: FSMContext): logging.info("Процесс остановлен пользователем") await state.finish() await message.reply("Обработка фотографий прекращена.", reply_markup=await start_keyboard()) @dp.message_handler(lambda message: message.text.lower() == "стоп", state=UploadBackgroundState.waiting_for_backgrounds) async def stop_processing_background(message: types.Message, state: FSMContext): state_data = await state.get_data() buffer = state_data.get("buffer", []) if buffer: async with connect('bot.db') as db: await db.executemany("INSERT INTO backgrounds (user_id, photo_id) VALUES (?, ?)", buffer) await db.commit() await state.update_data(buffer=[]) # Очистка буфера после сохранения await state.finish() await message.answer("*Все фоны сохранены в базу данных\.*",parse_mode="MarkdownV2", reply_markup=await start_keyboard()) # Обработка команды "Стоп" для загрузки фотографий пользователя @dp.message_handler(lambda message: message.text.lower() == "стоп", state=UploadUserPhotoState.waiting_for_user_photo) async def stop_processing_user_photo(message: types.Message, state: FSMContext): state_data = await state.get_data() buffer = state_data.get("buffer", []) if buffer: async with connect('bot.db') as db: await db.executemany("INSERT INTO userphotos (user_id, photo_id) VALUES (?, ?)", buffer) await db.commit() await state.update_data(buffer=[]) # Очистка буфера после сохранения await state.finish() await message.answer("*Все ваши фотографии сохранены в базу данных\.*",parse_mode="MarkdownV2", reply_markup=await start_keyboard()) async def fetch_photo(file_url): async with aiohttp.ClientSession() as session: async with session.get(file_url, ssl=False) as resp: return await resp.read() async def create_banned_users_table(): async with connect('bot.db') as db: await db.execute(""" CREATE TABLE IF NOT EXISTS banned_users ( user_id INTEGER PRIMARY KEY ) """) await db.commit() class BanUserState(StatesGroup): waiting_for_user_id = State() # Добавьте обработку команды /ban только для администраторов @dp.message_handler(commands=['ban'], user_id=ADMINS) # Замените ADMINS на список ID администраторов async def ban_user_command(message: types.Message): args = message.get_args().split() if not args or not args[0].isdigit(): await message.reply("Необходимо указать ID пользователя для блокировки: /ban 123456789") return user_id_to_ban = int(args[0]) async with connect('bot.db') as db: await db.execute("INSERT OR IGNORE INTO banned_users (user_id) VALUES (?)", (user_id_to_ban,)) await db.commit() await message.reply(f"Пользователь {user_id_to_ban} заблокирован.") # Добавьте проверку на наличие пользователя в списке заблокированных перед любым действием с ботом class CheckBanMiddleware(BaseMiddleware): async def on_process_message(self, message: types.Message, data: dict): user_id = message.from_user.id async with connect('bot.db') as db: cursor = await db.execute("SELECT user_id FROM banned_users WHERE user_id = ?", (user_id,)) is_banned = await cursor.fetchone() is not None if is_banned: admin_button = InlineKeyboardMarkup().add( InlineKeyboardButton("👨‍💻 Администратор бота", url="t.me/ih82seeucry") ) await message.answer( "*Вы заблокированы администратором бота\.* Если у вас есть вопросы \- обратитесь к администратору по кнопке ниже\.", parse_mode="MarkdownV2", reply_markup=admin_button) raise CancelHandler() # Регистрируйте middleware dp.middleware.setup(CheckBanMiddleware()) @dp.message_handler(commands=['unban'], user_id=ADMINS) # Замените ADMINS на список ID администраторов async def unban_user_command(message: types.Message): args = message.get_args().split() if not args or not args[0].isdigit(): await message.reply("Необходимо указать ID пользователя для разблокировки: /unban 123456789") return user_id_to_unban = int(args[0]) async with connect('bot.db') as db: await db.execute("DELETE FROM banned_users WHERE user_id = ?", (user_id_to_unban,)) await db.commit() await message.reply(f"Пользователь {user_id_to_unban} разблокирован.") # Use this handler to get photos from the database, apply changes, and send to the user @dp.message_handler(commands=['photos']) async def send_processed_photos(message: types.Message): user_id = message.from_user.id async with connect('bot.db') as db: cursor = await db.execute("SELECT COUNT(*) FROM userphotos WHERE user_id = ?", (user_id,)) user_photo_count = (await cursor.fetchone())[0] cursor = await db.execute("SELECT id, photo_id FROM backgrounds WHERE user_id = ?", (user_id,)) backgrounds = await cursor.fetchall() cursor = await db.execute("SELECT id, photo_id FROM userphotos WHERE user_id = ?", (user_id,)) user_photos = await cursor.fetchall() if not backgrounds or not user_photos: await message.reply("Необходимо загрузить фоновые изображения и/или креатив.") return used_background_ids = [] # Сюда будут собираться ID использованных фонов для последующего удаления media_groups = [] # Здесь будут храниться пачки изображений для отправки for user_photo in user_photos: if not backgrounds: await message.reply("Количество фонов меньше количества фотографий в креативе.") break # Если фоновых изображений недостаточно, прекращаем обработку background = backgrounds.pop(0) # Получаем первый фон из списка used_background_ids.append(background[0]) # Добавляем ID фона в список использованных processed_image_io = await apply_background(user_photo[1], background[1], padding_horizontal=100, padding_vertical=70) media_groups.append(types.InputMediaPhoto(processed_image_io)) # Если в текущей пачке 4 изображения или это последняя итерация, отправляем пачку if len(media_groups) == user_photo_count or not backgrounds: await bot.send_media_group(message.chat.id, media=media_groups) media_groups = [] # Очищаем текущую пачку для следующей # Удаляем использованные фоны из базы данных if used_background_ids: await db.executemany("DELETE FROM backgrounds WHERE id = ?", [(id,) for id in used_background_ids]) await db.commit() # Function to apply background to user photo async def apply_background(user_photo_id, background_photo_id, padding_horizontal=100, padding_vertical=70, blur_radius=5): logging.info("обработка фото") user_photo_file = await bot.get_file(user_photo_id) background_photo_file = await bot.get_file(background_photo_id) user_photo_url = bot.get_file_url(user_photo_file.file_path) background_photo_url = bot.get_file_url(background_photo_file.file_path) user_photo_data = await fetch_photo(user_photo_url) background_photo_data = await fetch_photo(background_photo_url) with Image.open(BytesIO(user_photo_data)) as user_image, Image.open(BytesIO(background_photo_data)) as background_image: user_image = user_image.convert('RGBA') background_image = background_image.convert('RGBA') background_image = background_image.filter(ImageFilter.GaussianBlur(blur_radius)) # Задаем размер фона, увеличенный на указанные отступы new_background_width = user_image.width + padding_horizontal * 2 # Слева и справа new_background_height = user_image.height + padding_vertical * 2 # Сверху и снизу background_image = background_image.resize((new_background_width, new_background_height), Image.Resampling.LANCZOS) # Готовим позицию для наложения фото пользователя на фон user_image_position = (padding_horizontal, padding_vertical) # Отступы слева и сверху # Накладываем пользовательское изображение на фон background_image.paste(user_image, user_image_position, user_image.split()[3]) # Используем альфа-канал для маски # Сохраняем во временный файл result_image_io = BytesIO() background_image.save(result_image_io, format='PNG') result_image_io.seek(0) return result_image_io @dp.message_handler(lambda message: message.text == "🖼 Замена фона") async def on_change_background_button(message: types.Message): process_message = await message.answer("*Фото обрабатываются, подождите\.\.\.*",parse_mode="MarkdownV2") user_id = message.from_user.id async with connect('bot.db') as db: # Убедитесь, что используете контекстный менеджер # Определяем, должны ли использоваться общие фоны cursor = await db.execute("SELECT use_common_backgrounds FROM users WHERE user_id = ?", (user_id,)) use_common_backgrounds = (await cursor.fetchone())[0] # В зависимости от настроек выбираем фоны if use_common_backgrounds: cursor = await db.execute("SELECT photo_id FROM common_backgrounds ORDER BY RANDOM()") else: cursor = await db.execute("SELECT photo_id FROM backgrounds WHERE user_id = ?", (user_id,)) backgrounds = await cursor.fetchall() # Получаем фотографии пользователя cursor = await db.execute("SELECT photo_id FROM userphotos WHERE user_id = ?", (user_id,)) user_photos = await cursor.fetchall() if not backgrounds or not user_photos: await message.answer("Необходимо загрузить фоновые изображения и/или креатив.") return used_background_ids = [] # Список использованных личных фонов для удаления media_groups = [] background_index = 0 for user_photo in user_photos: # Начинаем по новой сначала списка, если фонов меньше чем фото if background_index >= len(backgrounds): background_index = 0 background = backgrounds[background_index] background_index += 1 if not use_common_backgrounds: used_background_ids.append(background[0]) # Добавляем ID фона в список использованных личных фонов # Применяем фон к фотографии пользователя processed_image_io = await apply_background(user_photo[0], background[0]) media_groups.append(types.InputMediaPhoto(processed_image_io)) # Отправляем обработанные фото пользователю await bot.delete_message(chat_id=process_message.chat.id, message_id=process_message.message_id) if media_groups: await bot.send_media_group(message.chat.id, media=media_groups) # Удаляем использованные личные фоны из базы данных if used_background_ids and not use_common_backgrounds: async with connect('bot.db') as db: await db.executemany("DELETE FROM backgrounds WHERE id = ?", [(id,) for id in used_background_ids]) await db.commit() # Init DB on startup async def on_startup(_): print("Starting bot…") await init_db() await create_banned_users_table() # Starting the bot if __name__ == '__main__': executor.start_polling(dp, skip_updates=True, on_startup=on_startup)
e99a03f532a018c90795a220c8a76f34
{ "intermediate": 0.3354271948337555, "beginner": 0.5972244739532471, "expert": 0.06734836101531982 }
38,921
Hi, currently this script performs OCR based on the image_paths which is great , the file location of all has C:\Users\ADAM7\Desktop\Projects_demo\03_ocr\output\1_output which only works for 1_output. I want it to cater to all other folders in the location C:\Users\ADAM7\Desktop\Projects_demo\03_ocr\output such as 2_output, 3_output , etc. The format of folder name is fixed is like 1_output, 2_output and so on. The file paths are fixed , the only thing i want changed is the 1_output to have all folders in that path C:\Users\ADAM7\Desktop\Projects_demo\03_ocr\output. After running the first one, an excel should be generated as expected. Next, the 2_output folder results and entries should add to the same excel and so on. My code now: import os import azure.ai.vision as sdk import openpyxl from openpyxl.styles import Font, PatternFill from openpyxl.utils import get_column_letter import os # Exported to environment variable, safer and more secure for sensitive information like APIs VISION_ENDPOINT = os.environ.get("VISION_ENDPOINT") VISION_KEY = os.environ.get("VISION_KEY") #to set: setx VISION_KEY if VISION_ENDPOINT is None or VISION_KEY is None: raise ValueError("VISION_ENDPOINT and VISION_KEY must be set in the environment") service_options = sdk.VisionServiceOptions(VISION_ENDPOINT, VISION_KEY) # Specify the paths to your local image files image_paths = [ r'C:\Users\ADAM7\Desktop\Projects_demo\03_ocr\output\1_output\01_lead_number.jpg', r'C:\Users\ADAM7\Desktop\Projects_demo\03_ocr\output\1_output\02_company.jpg', r'C:\Users\ADAM7\Desktop\Projects_demo\03_ocr\output\1_output\03_name.jpg', r'C:\Users\ADAM7\Desktop\Projects_demo\03_ocr\output\1_output\07_industry.jpg', r'C:\Users\ADAM7\Desktop\Projects_demo\03_ocr\output\1_output\08_interest.jpg', r'C:\Users\ADAM7\Desktop\Projects_demo\03_ocr\output\1_output\11_preparedBy.jpg', r'C:\Users\ADAM7\Desktop\Projects_demo\03_ocr\output\1_output\06_category_resized.jpg\06_category_resized.jpg', r'C:\Users\ADAM7\Desktop\Projects_demo\03_ocr\output\1_output\09_product_resized.jpg\09_product_resized.jpg', r'C:\Users\ADAM7\Desktop\Projects_demo\03_ocr\output\1_output\05_nameCards.jpg' ] # Specify corresponding headers headers = ["Lead Number", "Company", "Name", "Industry", "Interest", "Prepared by","Category","Product", "Etc"] # Initialize the Excel workbook and sheet excel_file_path = r'C:\Users\ADAM7\Desktop\Projects_demo\03_ocr\test.xlsx' wb = openpyxl.Workbook() sheet = wb.active # Write headers to the Excel sheet and apply formatting sheet.append(headers) # Header formatting for cell in sheet[1]: cell.font = Font(bold=True) cell.fill = PatternFill(start_color="DDDDDD", end_color="DDDDDD", fill_type="solid") # Initialize a list to store the extracted information extracted_info_list = [] # Iterate through each image path and extract information using OCR for image_path, header in zip(image_paths, headers): with open(image_path, 'rb') as image_file: image_buffer = image_file.read() image_source_buffer = sdk.ImageSourceBuffer() image_source_buffer.image_writer.write(image_buffer) vision_source = sdk.VisionSource(image_source_buffer=image_source_buffer) analysis_options = sdk.ImageAnalysisOptions() analysis_options.features = ( sdk.ImageAnalysisFeature.TEXT ) analysis_options.language = "en" analysis_options.gender_neutral_caption = False image_analyzer = sdk.ImageAnalyzer(service_options, vision_source, analysis_options) result = image_analyzer.analyze() # Extract relevant information from OCR result extracted_info = "" if result.reason == sdk.ImageAnalysisResultReason.ANALYZED and result.text is not None: for line in result.text.lines: extracted_info += line.content + " " # Append the extracted information to the list extracted_info_list.append(extracted_info) # Append the list to the Excel sheet as a single row sheet.append(extracted_info_list) # Auto-adjust column width for column in sheet.columns: max_length = 0 column = [cell for cell in column] for cell in column: try: if len(str(cell.value)) > max_length: max_length = len(cell.value) except: pass adjusted_width = (max_length + 2) sheet.column_dimensions[get_column_letter(column[0].column)].width = adjusted_width # Save the Excel file wb.save(excel_file_path) print(f"Completed. Check '{excel_file_path}' for the results.")
52b4a91cce2b5778d35472863841a9a9
{ "intermediate": 0.43323948979377747, "beginner": 0.3372000455856323, "expert": 0.2295604646205902 }
38,922
как работает этот кусок кода public static void CallExternalProcess(string processPath, string arguments) { Process myProcess = new Process(); myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; myProcess.StartInfo.CreateNoWindow = true; myProcess.StartInfo.UseShellExecute = false; myProcess.StartInfo.FileName = processPath; myProcess.StartInfo.Arguments = arguments; myProcess.EnableRaisingEvents = true; myProcess.Start(); myProcess.WaitForExit(); int ExitCode = myProcess.ExitCode; }
1633b519054c163b60e211b5c1707742
{ "intermediate": 0.40021708607673645, "beginner": 0.341139018535614, "expert": 0.25864389538764954 }
38,923
write adaptive header with logo img and 3 links menu, when screen is smaller than 550px make only logo and hamburger icon, with menu when icon clicked. use only html and css
a97fa2bc479721f6d6ea935be798125f
{ "intermediate": 0.3871655762195587, "beginner": 0.287141889333725, "expert": 0.3256925046443939 }
38,924
Помоги решить ошибку в коде: ERROR:asyncio:Task exception was never retrieved future: <Task finished name='Task-69' coro=<Dispatcher._process_polling_updates() done, defined at C:\Users\Аскар\PycharmProjects\smena tt\.venv\Lib\site-packages\aiogram\dispatcher\dispatcher.py:407> exception=TypeError('tuple indices must be integers or slices, not str')> Traceback (most recent call last): File "C:\Users\Аскар\PycharmProjects\smena tt\.venv\Lib\site-packages\aiogram\dispatcher\dispatcher.py", line 415, in _process_polling_updates for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Аскар\PycharmProjects\smena tt\.venv\Lib\site-packages\aiogram\dispatcher\dispatcher.py", line 235, in process_updates return await asyncio.gather(*tasks) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Аскар\PycharmProjects\smena tt\.venv\Lib\site-packages\aiogram\dispatcher\handler.py", line 117, in notify response = await handler_obj.handler(*args, **partial_data) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Аскар\PycharmProjects\smena tt\.venv\Lib\site-packages\aiogram\dispatcher\dispatcher.py", line 256, in process_update return await self.message_handlers.notify(update.message) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Аскар\PycharmProjects\smena tt\.venv\Lib\site-packages\aiogram\dispatcher\handler.py", line 117, in notify response = await handler_obj.handler(*args, **partial_data) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Аскар\PycharmProjects\smena tt\main.py", line 853, in on_change_background_button used_background_ids.append(background['id']) ~~~~~~~~~~^^^^^^ TypeError: tuple indices must be integers or slices, not str Вот весь код: import asyncio from io import BytesIO from PIL import Image, ImageFilter import aiohttp import time import random from aiogram import Bot, Dispatcher, types, executor from aiogram.contrib.fsm_storage.memory import MemoryStorage from aiogram.dispatcher import FSMContext from aiogram.dispatcher.filters.state import State, StatesGroup from aiosqlite import connect import logging from aiogram.utils.exceptions import MessageNotModified from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton, ParseMode from aiogram import types from aiogram.dispatcher.middlewares import BaseMiddleware from aiogram.dispatcher.handler import CancelHandler from aiogram.dispatcher.middlewares import LifetimeControllerMiddleware from collections import defaultdict import ssl logging.basicConfig(level=logging.INFO) ADMINS=[989037374,6663889022] TOKEN = "6937803168:AAE-eV82HlqV3M0w7a8U89aJBpkGfywCz7A" bot = Bot(token=TOKEN) storage = MemoryStorage() dp = Dispatcher(bot, storage=storage) # Создание таблиц если они не существуют async def init_db(): logging.info("инициализация БД") async with connect('bot.db') as db: await db.execute(""" CREATE TABLE IF NOT EXISTS backgrounds ( id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, photo_id TEXT NOT NULL ) """) await db.execute(""" CREATE TABLE IF NOT EXISTS userphotos ( id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, photo_id TEXT NOT NULL ) """) await db.execute(""" CREATE TABLE IF NOT EXISTS users ( user_id INTEGER PRIMARY KEY, is_banned INTEGER DEFAULT 0, first_name TEXT, username TEXT ) """) await db.execute(""" CREATE TABLE IF NOT EXISTS common_backgrounds ( id INTEGER PRIMARY KEY, photo_id TEXT NOT NULL ) """) await db.commit() from aiogram.utils.markdown import escape_md class MailingState(StatesGroup): waiting_for_message = State() waiting_for_buttons = State() from aiogram.utils.markdown import quote_html @dp.message_handler(commands=['profile'], user_id=ADMINS, state='*') async def cmd_profile(message: types.Message): # Разбор аргумента команды arg = message.get_args() # Проверка, является ли аргумент числом (user_id) или строкой (username) user_id = None username = None if arg.isdigit(): user_id = int(arg) elif arg.startswith('@'): username = arg[1:] # Удаляем @ в начале # Если аргумент отсутствует if not user_id and not username: await message.reply("Необходимо указать user_id или username пользователя.") return # Поиск пользователя async with connect('bot.db') as db: if user_id: cursor = await db.execute(""" SELECT user_id, username, use_common_backgrounds, common_backgrounds_count, personal_backgrounds_count, is_banned FROM users WHERE user_id = ?""", (user_id,)) else: cursor = await db.execute(""" SELECT user_id, username, use_common_backgrounds, common_backgrounds_count, personal_backgrounds_count, is_banned FROM users WHERE username = ?""", (username,)) user_data = await cursor.fetchone() # Если пользователь не найден if not user_data: await message.reply("Пользователь не найден.") return # Формирование сообщения для отправки администратору profile_text = ( f"👨 *Профиль пользователя*\n\n" f"User ID: {user_data[0]}\n" f"Username: @{quote_html(user_data[1])}\n\n" f"Использование общих фонов: *{'вкл' if user_data[2] else 'выкл'}*\n" f"Количество использований общих фонов: {user_data[3]}\n" f"Количество использований личных фонов: {user_data[4]}\n" f"Статус: *{'забанен' if user_data[5] else 'активен'}*" ) # Создание инлайн-кнопок buttons = [ InlineKeyboardButton("Забанить", callback_data=f'ban_{user_data[0]}'), InlineKeyboardButton("Разбанить", callback_data=f'unban_{user_data[0]}') ] keyboard = InlineKeyboardMarkup().add(*buttons) # Отправка сообщения await message.reply(profile_text, parse_mode="MarkdownV2", reply_markup = keyboard) @dp.callback_query_handler(lambda c: c.data.startswith('ban_')) async def process_ban_button(callback_query: types.CallbackQuery): admin_id = callback_query.from_user.id if admin_id not in ADMINS: # Проверяем, что вызывающий команду является администратором await callback_query.answer("Вы не являетесь администратором.") return user_id_to_ban = int(callback_query.data.split('_')[1]) async with connect('bot.db') as db: await db.execute("INSERT OR IGNORE INTO banned_users (user_id) VALUES (?)", (user_id_to_ban,)) await db.commit() await callback_query.answer(f"Пользователь {user_id_to_ban} заблокирован.") @dp.callback_query_handler(lambda c: c.data.startswith('unban_')) async def process_unban_button(callback_query: types.CallbackQuery): admin_id = callback_query.from_user.id if admin_id not in ADMINS: await callback_query.answer("Вы не являетесь администратором.") return user_id_to_unban = int(callback_query.data.split('_')[1]) async with connect('bot.db') as db: await db.execute("DELETE FROM banned_users WHERE user_id = ?", (user_id_to_unban,)) await db.commit() await callback_query.answer(f"Пользователь {user_id_to_unban} разблокирован.") # Обработчик команды /post, передаем состояние ожидания сообщения для рассылки @dp.message_handler(commands=['post'], user_id=ADMINS, state='*') async def cmd_post(message: types.Message): await MailingState.waiting_for_message.set() await message.reply("Отправьте текст рассылки") # Обработчик текста рассылки, переводим в состояние ожидания кнопок @dp.message_handler(state=MailingState.waiting_for_message, content_types=types.ContentTypes.TEXT) async def post_message(message: types.Message, state: FSMContext): await MailingState.waiting_for_buttons.set() await state.update_data(mailing_text=message.text) await message.reply( "Теперь отправьте данные для inline-кнопок в формате: Текст кнопки;URL на каждую кнопку или /skip, если кнопки не нужны.") # Обработчик кнопок для рассылки или пропуска их добавления @dp.message_handler(state=MailingState.waiting_for_buttons) async def post_buttons(message: types.Message, state: FSMContext): if message.text != "/skip": # Разбиваем сообщение по строкам и создаем кнопки lines = message.text.split("\n") buttons = [InlineKeyboardButton(text=line.split(';')[0], url=line.split(';')[1]) for line in lines if len(line.split(';')) == 2] markup = InlineKeyboardMarkup() markup.add(*buttons) else: markup = None # Получаем данные из состояния и текст рассылки data = await state.get_data() text = data.get('mailing_text') mode = data.get('mailing_mode') # Запускаем рассылку success_count, failure_count = await send_mailing(text, mode, markup) await state.finish() # Сброс состояния после рассылки await message.answer(f"Рассылка выполнена. Успешно: {success_count}. Неудачно: {failure_count}.") async def send_mailing(text, parse_mode, keyboard=None): async with connect('bot.db') as db: cursor = await db.execute("SELECT user_id FROM users") user_ids = [row[0] for row in await cursor.fetchall()] success_count = 0 failure_count = 0 for user_id in user_ids: try: await bot.send_message( chat_id=user_id, text=text, reply_markup=keyboard, parse_mode=types.ParseMode.HTML ) success_count += 1 except Exception as e: # Обрабатываем возможные исключения, например, если пользователь заблокировал бота logging.error(f"Failed to send message to {user_id}: {e}") failure_count += 1 return success_count, failure_count # Обработчик команды /skip для пропуска добавления кнопок @dp.message_handler(state=MailingState.waiting_for_buttons, commands=['skip']) async def post_skip(message: types.Message, state: FSMContext): await post_buttons(message, state) # Хэндлер команды /sql для выполнения произвольных SQL-запросов (ТОЛЬКО для администраторов) @dp.message_handler(commands=['sql'], user_id=ADMINS) async def execute_sql_command(message: types.Message): # Получаем аргументы команды (SQL-запрос) sql_query = message.get_args() # Проверяем, что запрос не пустой if not sql_query: await message.reply("Введите SQL-запрос.") return # Подключаемся к базе данных и выполняем запрос async with connect('bot.db') as db: try: await db.execute(sql_query) await db.commit() await message.reply("SQL-запрос успешно выполнен.") except Exception as e: await message.reply(f"Ошибка при выполнении SQL-запроса: {e}") class UploadBackgroundState(StatesGroup): waiting_for_backgrounds = State() class UploadUserPhotoState(StatesGroup): waiting_for_user_photo = State() # Админ-команда для очистки таблицы с общими фонами @dp.message_handler(commands=['clear_common'], user_id=ADMINS) async def clear_common_backgrounds(message: types.Message): async with connect('bot.db') as db: await db.execute("DELETE FROM common_backgrounds") await db.commit() await message.reply("Все общие фоны были успешно удалены из базы данных.") # Админ-команда для просмотра количества общих фонов @dp.message_handler(commands=['count_common'], user_id=ADMINS) async def count_common_backgrounds(message: types.Message): async with connect('bot.db') as db: cursor = await db.execute("SELECT COUNT(*) FROM common_backgrounds") count = await cursor.fetchone() await message.reply(f"Количество общих фонов в базе данных: {count[0]}") async def generate_invite_link(chat_id): try: chat_invite_link = await bot.create_chat_invite_link(chat_id, expire_date=int(time.time()) + 900) # на 15 минут return chat_invite_link.invite_link except Exception as e: logging.error(e) return None async def is_user_subscribed(chat_id, user_id): try: member = await bot.get_chat_member(chat_id, user_id) return member.status not in ["left", "kicked"] except Exception as e: logging.error(e) return False # По умолчанию считаем, что пользователь не подписан, если возникла ошибка CHANNEL_ID = "-1002046113496" # ID вашего канала class SubscriptionCheckMiddleware(BaseMiddleware): def __init__(self, channel_id): super().__init__() self.channel_id = channel_id async def on_process_message(self, message: types.Message, data: dict): member = await bot.get_chat_member(self.channel_id, message.from_user.id) if member.status not in ["member", "administrator", "creator"]: invite_link = await generate_invite_link(self.channel_id) if invite_link: keyboard = InlineKeyboardMarkup().add( InlineKeyboardButton("🔗 Подписаться на канал", url=invite_link) ) await message.answer( f"🔒 Для продолжения работы с ботом *необходимо подписаться на наш новостной канал\.*\n\n👌 Если вы уже подписались на канал, нажмите /start",parse_mode="MarkdownV2", reply_markup=keyboard ) # прерываем обработку следующих хэндлеров raise CancelHandler() async def post_process(self, obj, data, *args): pass dp.middleware.setup(SubscriptionCheckMiddleware(CHANNEL_ID)) @dp.message_handler(commands=['count']) async def count_backgrounds(message: types.Message): user_id = message.from_user.id async with connect('bot.db') as db: cursor = await db.execute("SELECT COUNT(*) FROM backgrounds WHERE user_id = ?", (user_id,)) count = await cursor.fetchone() await message.answer(f"У вас в базе данных *{count[0]}* фоновых изображений\.",parse_mode="MarkdownV2") @dp.message_handler(commands=['ex']) async def export_backgrounds(message: types.Message): user_id = message.from_user.id try: # Получаем количество изображений для выгрузки из команды command_args = message.get_args().split() # если ничего не введено, выгрузить все num_images = int(command_args[0]) if command_args else -1 except (IndexError, ValueError): await message.answer("Укажите количество фонов для выгрузки. Например: /ex 10") return async with connect('bot.db') as db: # Если num_images равен -1, значит выгрузить все изображения query = "SELECT id, photo_id FROM backgrounds LIMIT ?" cursor = await db.execute(query, (10 if num_images == -1 else num_images,)) backgrounds_chunk = await cursor.fetchall() while backgrounds_chunk: media_group = [types.InputMediaPhoto(photo[1]) for photo in backgrounds_chunk] await bot.send_media_group(message.chat.id, media_group) # Удаляем отправленные фоны из БД await db.executemany("DELETE FROM backgrounds WHERE id = ?", [(photo[0],) for photo in backgrounds_chunk]) await db.commit() if num_images != -1: num_images -= len(backgrounds_chunk) if num_images <= 0: break # Получаем следующую пачку изображений cursor = await db.execute(query, (10 if num_images == -1 else min(num_images, 10),)) backgrounds_chunk = await cursor.fetchall() await message.answer("*Все запрошенные фоновые изображения были выгружены и удалены из базы данных\.*",parse_mode="MarkdownV2") LOG_CHANNEL_ID = "@smenalogs" async def log_to_channel(user: types.User, action: str): message_to_send = f"Пользователь @{user.username} ({user.id}) выполнил действие: {action}" await bot.send_message(LOG_CHANNEL_ID, message_to_send) stop_keyboard = ReplyKeyboardMarkup(resize_keyboard=True).add(KeyboardButton("Стоп")) async def start_keyboard(): # Создаем начальную клавиатуру с кнопками "Замена фона" и "Личный кабинет" return ReplyKeyboardMarkup(resize_keyboard=True).add( KeyboardButton("🖼 Замена фона") ).add( KeyboardButton("📊 Личный кабинет") ) @dp.message_handler(commands=['stop'], state='*') async def stop_processing(message: types.Message, state: FSMContext): # … await message.reply("Обработка фотографий прекращена.", reply_markup=await start_keyboard()) await state.finish() @dp.message_handler(commands=['start', 'help']) async def send_welcome(message: types.Message): user_id = message.from_user.id first_name = message.from_user.first_name username = message.from_user.username # Подключаемся к БД и проверяем, существует ли пользователь async with connect('bot.db') as db: cursor = await db.execute("SELECT user_id FROM users WHERE user_id = ?", (user_id,)) user_exists = await cursor.fetchone() # Если пользователя нет в БД, сохраняем его if not user_exists: await db.execute("INSERT INTO users (user_id, first_name, username) VALUES (?, ?, ?)", (user_id, first_name, username)) await db.commit() # Создаем кнопки button_photos = KeyboardButton("🖼 Замена фона") button_cabinet = KeyboardButton("📊 Личный кабинет") # Отправляем сообщение вместе с клавиатурой await message.answer( "Привет! Пользуйся кнопками", reply_markup=await start_keyboard() ) await log_to_channel(message.from_user, "прописал /start") @dp.callback_query_handler( lambda c: c.data == 'toggle_common_backgrounds_on' or c.data == 'toggle_common_backgrounds_off') async def toggle_common_backgrounds(callback_query: types.CallbackQuery): user_id = callback_query.from_user.id # Переключаем состояние использования общих фонов new_setting = not (callback_query.data == 'toggle_common_backgrounds_on') # Сохраняем новое состояние в базу данных async with connect('bot.db') as db: await db.execute("UPDATE users SET use_common_backgrounds = ? WHERE user_id = ?", (int(new_setting), user_id)) await db.commit() # Ответное сообщение пользователю reply_text = "Общие фоны включены." if new_setting else "Общие фоны выключены." await bot.answer_callback_query(callback_query.id, reply_text) # Обновить сообщение в "личном кабинете", чтобы отразить изменения с "включено/выключено" await personal_cabinet(callback_query) @dp.callback_query_handler(lambda c: c.data == 'support') async def support_callback(callback_query: types.CallbackQuery): support_text = ( "❓ Если у вас есть вопросы, предложения, проблемы \- обращайтесь к администратору бота\.\n\n" "*Нажмите на кнопку ниже, чтобы связаться\.*" ) admin_button = InlineKeyboardMarkup().add( InlineKeyboardButton("👨‍💻 Администратор бота", url="t.me/ih82seeucry") ) await bot.edit_message_text( chat_id=callback_query.message.chat.id, message_id=callback_query.message.message_id, text=support_text, parse_mode="MarkdownV2", reply_markup=admin_button ) @dp.message_handler(lambda message: message.text == "📊 Личный кабинет") async def personal_cabinet(message_or_query): # Определяем, является ли объект сообщением или коллбэк-запросом if isinstance(message_or_query, types.Message): user_id = message_or_query.from_user.id message = message_or_query elif isinstance(message_or_query, types.CallbackQuery): user_id = message_or_query.from_user.id message = message_or_query.message else: return # Если полученный объект не поддерживается, не предпринимать никаких действий async with connect('bot.db') as db: cursor = await db.execute("SELECT COUNT(*) FROM backgrounds WHERE user_id = ?", (user_id,)) count = (await cursor.fetchone())[0] cursor = await db.execute("SELECT use_common_backgrounds FROM users WHERE user_id = ?", (user_id,)) use_common_backgrounds = (await cursor.fetchone())[0] common_bg_status = "включено" if use_common_backgrounds else "выключено" cursor = await db.execute( "SELECT common_backgrounds_count, personal_backgrounds_count FROM users WHERE user_id = ?", (user_id,)) counts = await cursor.fetchone() common_bg_count = counts[0] personal_bg_count = counts[1] toggle_text = "Общие фоны: вкл" if use_common_backgrounds else "Общие фоны: выкл" callback_data = 'toggle_common_backgrounds_on' if use_common_backgrounds else 'toggle_common_backgrounds_off' keyboard = InlineKeyboardMarkup(row_width=1).add( InlineKeyboardButton("Загрузить фоны", callback_data='upload_backgrounds'), InlineKeyboardButton("Загрузить креатив", callback_data='upload_user_photos'), InlineKeyboardButton("Очистить фоны", callback_data='clear_backgrounds'), InlineKeyboardButton(toggle_text, callback_data=callback_data), InlineKeyboardButton("Поддержка", callback_data='support') ) text_message = f"*📊 Личный кабинет*\n\nКоличество фонов: {count}\nИспользование общих фонов *{common_bg_status}*\n\nКоличество использований общих фонов: {common_bg_count}\nКоличество использований личных фонов: {personal_bg_count}" if isinstance(message_or_query, types.CallbackQuery): try: # Метод для изменения текста сообщения и клавиатуры await bot.edit_message_text(text=text_message, chat_id=message.chat.id, message_id=message.message_id, parse_mode="MarkdownV2", reply_markup=keyboard) except MessageNotModified: # Ничего не делаем, если содержимое сообщения не изменилось pass else: await message.answer(text_message, parse_mode="MarkdownV2", reply_markup=keyboard) @dp.callback_query_handler(lambda c: c.data == 'upload_backgrounds') async def upload_backgrounds(callback_query: types.CallbackQuery): await upload_background_start(callback_query.message) await bot.send_message(callback_query.from_user.id, "Отправьте фоны для загрузки или нажмите Стоп, чтобы завершить.", reply_markup=stop_keyboard) @dp.callback_query_handler(lambda c: c.data == 'upload_user_photos') async def upload_user_photos(callback_query: types.CallbackQuery): await clear_user_photos_action(callback_query.from_user.id) await upload_user_photo_start(callback_query.message) await bot.send_message(callback_query.from_user.id, "Отправьте креатив для загрузки или нажмите Стоп, чтобы завершить.", reply_markup=stop_keyboard) @dp.callback_query_handler(lambda c: c.data == 'clear_backgrounds') async def clear_backgrounds(callback_query: types.CallbackQuery): confirmation_keyboard = InlineKeyboardMarkup().add( InlineKeyboardButton("Да", callback_data='confirm_clear_backgrounds'), InlineKeyboardButton("Нет", callback_data='cancel_clear_backgrounds') ) await callback_query.message.edit_text( "Вы уверены, что хотите удалить все свои фоны из базы? Это действие необратимо.", reply_markup=confirmation_keyboard ) @dp.callback_query_handler(lambda c: c.data == 'confirm_clear_backgrounds') async def confirm_clear_backgrounds(callback_query: types.CallbackQuery): user_id = callback_query.from_user.id async with connect('bot.db') as db: await db.execute("DELETE FROM backgrounds WHERE user_id = ?", (user_id,)) await db.commit() await bot.answer_callback_query(callback_query.id, "Ваши фоновые изображения были удалены из базы данных.") await callback_query.message.delete() await log_to_channel(callback_query.from_user, "очистил свои фоновые изображения") await send_welcome(callback_query.message) @dp.callback_query_handler(lambda c: c.data == 'cancel_clear_backgrounds') async def cancel_clear_backgrounds(callback_query: types.CallbackQuery): await callback_query.message.delete() await send_welcome(callback_query.message) # общие фоны class UploadCommonBackgroundState(StatesGroup): waiting_for_common_backgrounds = State() @dp.message_handler(commands=['common'], user_id=ADMINS, state='*') async def upload_common_background_start(message: types.Message): await UploadCommonBackgroundState.waiting_for_common_backgrounds.set() await message.reply("Отправьте общие фоны для загрузки или нажмите Стоп, чтобы сохранить их в базу данных.", reply_markup=stop_keyboard) @dp.message_handler(content_types=['photo'], state=UploadCommonBackgroundState.waiting_for_common_backgrounds) async def upload_common_background(message: types.Message, state: FSMContext): photo_id = message.photo[-1].file_id state_data = await state.get_data() buffer = state_data.get('buffer', []) buffer.append(photo_id) await state.update_data(buffer=buffer) await message.reply( "Фон добавлен в очередь. Продолжайте добавлять фоны или нажмите Стоп, чтобы сохранить их в базу данных.") @dp.message_handler(lambda message: message.text.lower() == "стоп", state=UploadCommonBackgroundState.waiting_for_common_backgrounds) async def stop_uploading_common_backgrounds(message: types.Message, state: FSMContext): state_data = await state.get_data() buffer = state_data.get('buffer', []) if buffer: async with connect('bot.db') as db: await db.executemany("INSERT INTO common_backgrounds (photo_id) VALUES (?)", [(photo_id,) for photo_id in buffer]) await db.commit() await state.finish() await message.reply("Все общие фоны сохранены в базу данных.", reply_markup=await start_keyboard()) @dp.callback_query_handler(lambda c: c.data == 'back_to_start') async def back_to_start(callback_query: types.CallbackQuery): await send_welcome(callback_query.message) @dp.message_handler(commands=['clear_upload']) async def clear_backgrounds(message: types.Message): user_id = message.from_user.id # Получаем ID пользователя async with connect('bot.db') as db: # Удаляем только фоны конкретного пользователя await db.execute("DELETE FROM backgrounds WHERE user_id = ?", (user_id,)) await db.commit() await message.answer("Ваши фоновые изображения были удалены из базы данных.") await log_to_channel(message.from_user, "очистил свои фоновые изображения") async def clear_user_photos_action(user_id: int): async with connect('bot.db') as db: await db.execute("DELETE FROM userphotos WHERE user_id = ?", (user_id,)) await db.commit() @dp.message_handler(commands=['clear_user']) async def clear_user_photos(message: types.Message): user_id = message.from_user.id await clear_user_photos_action(user_id) await message.answer("Ваш креатив был удален из базы данных.") await log_to_channel(message.from_user, "очистил userphoto") # Инициируем FSM для загрузки фонов @dp.message_handler(commands=['upload'], state='*') async def upload_background_start(message: types.Message): logging.info("прием аплоад") await UploadBackgroundState.waiting_for_backgrounds.set() await log_to_channel(message.from_user, "прописал /upload") # Инициируем FSM для загрузки пользовательского фото @dp.message_handler(commands=['user'], state='*') async def upload_user_photo_start(message: types.Message): logging.info("прием юзер фото") await UploadUserPhotoState.waiting_for_user_photo.set() await log_to_channel(message.from_user, "загружает userphoto") # Обработка загрузки фоновых фотографий @dp.message_handler(content_types=['photo'], state=UploadBackgroundState.waiting_for_backgrounds) async def upload_background(message: types.Message, state: FSMContext): user_id = message.from_user.id photo_id = message.photo[-1].file_id state_data = await state.get_data() buffer = state_data.get("buffer", []) buffer.append((user_id, photo_id)) await state.update_data(buffer=buffer) await message.answer("*Фон добавлен\.* Не забудьте нажать Стоп, чтобы сохранить все ваши фото в базу",parse_mode="MarkdownV2") # Обработка загрузки пользовательских фотографий @dp.message_handler(content_types=['photo'], state=UploadUserPhotoState.waiting_for_user_photo) async def upload_user_photo(message: types.Message, state: FSMContext): user_id = message.from_user.id photo_id = message.photo[-1].file_id state_data = await state.get_data() buffer = state_data.get("buffer", []) buffer.append((user_id, photo_id)) await state.update_data(buffer=buffer) await message.answer("*Фото креатива добавлено в очередь\.* Не забудьте нажать Стоп, чтобы сохранить все ваши фото в базу",parse_mode="MarkdownV2") # Переход обратно в обычное состояние после команды /stop @dp.message_handler(commands=['stop'], state='*') async def stop_processing(message: types.Message, state: FSMContext): logging.info("Процесс остановлен пользователем") await state.finish() await message.reply("Обработка фотографий прекращена.", reply_markup=await start_keyboard()) @dp.message_handler(lambda message: message.text.lower() == "стоп", state=UploadBackgroundState.waiting_for_backgrounds) async def stop_processing_background(message: types.Message, state: FSMContext): state_data = await state.get_data() buffer = state_data.get("buffer", []) if buffer: async with connect('bot.db') as db: await db.executemany("INSERT INTO backgrounds (user_id, photo_id) VALUES (?, ?)", buffer) await db.commit() await state.update_data(buffer=[]) # Очистка буфера после сохранения await state.finish() await message.answer("*Все фоны сохранены в базу данных\.*",parse_mode="MarkdownV2", reply_markup=await start_keyboard()) # Обработка команды "Стоп" для загрузки фотографий пользователя @dp.message_handler(lambda message: message.text.lower() == "стоп", state=UploadUserPhotoState.waiting_for_user_photo) async def stop_processing_user_photo(message: types.Message, state: FSMContext): state_data = await state.get_data() buffer = state_data.get("buffer", []) if buffer: async with connect('bot.db') as db: await db.executemany("INSERT INTO userphotos (user_id, photo_id) VALUES (?, ?)", buffer) await db.commit() await state.update_data(buffer=[]) # Очистка буфера после сохранения await state.finish() await message.answer("*Все ваши фотографии сохранены в базу данных\.*",parse_mode="MarkdownV2", reply_markup=await start_keyboard()) async def fetch_photo(file_url): async with aiohttp.ClientSession() as session: async with session.get(file_url, ssl=False) as resp: return await resp.read() async def create_banned_users_table(): async with connect('bot.db') as db: await db.execute(""" CREATE TABLE IF NOT EXISTS banned_users ( user_id INTEGER PRIMARY KEY ) """) await db.commit() class BanUserState(StatesGroup): waiting_for_user_id = State() # Добавьте обработку команды /ban только для администраторов @dp.message_handler(commands=['ban'], user_id=ADMINS) # Замените ADMINS на список ID администраторов async def ban_user_command(message: types.Message): args = message.get_args().split() if not args or not args[0].isdigit(): await message.reply("Необходимо указать ID пользователя для блокировки: /ban 123456789") return user_id_to_ban = int(args[0]) async with connect('bot.db') as db: await db.execute("INSERT OR IGNORE INTO banned_users (user_id) VALUES (?)", (user_id_to_ban,)) await db.commit() await message.reply(f"Пользователь {user_id_to_ban} заблокирован.") # Добавьте проверку на наличие пользователя в списке заблокированных перед любым действием с ботом class CheckBanMiddleware(BaseMiddleware): async def on_process_message(self, message: types.Message, data: dict): user_id = message.from_user.id async with connect('bot.db') as db: cursor = await db.execute("SELECT user_id FROM banned_users WHERE user_id = ?", (user_id,)) is_banned = await cursor.fetchone() is not None if is_banned: admin_button = InlineKeyboardMarkup().add( InlineKeyboardButton("👨‍💻 Администратор бота", url="t.me/ih82seeucry") ) await message.answer( "*Вы заблокированы администратором бота\.* Если у вас есть вопросы \- обратитесь к администратору по кнопке ниже\.", parse_mode="MarkdownV2", reply_markup=admin_button) raise CancelHandler() # Регистрируйте middleware dp.middleware.setup(CheckBanMiddleware()) @dp.message_handler(commands=['unban'], user_id=ADMINS) # Замените ADMINS на список ID администраторов async def unban_user_command(message: types.Message): args = message.get_args().split() if not args or not args[0].isdigit(): await message.reply("Необходимо указать ID пользователя для разблокировки: /unban 123456789") return user_id_to_unban = int(args[0]) async with connect('bot.db') as db: await db.execute("DELETE FROM banned_users WHERE user_id = ?", (user_id_to_unban,)) await db.commit() await message.reply(f"Пользователь {user_id_to_unban} разблокирован.") # Use this handler to get photos from the database, apply changes, and send to the user @dp.message_handler(commands=['photos']) async def send_processed_photos(message: types.Message): user_id = message.from_user.id async with connect('bot.db') as db: cursor = await db.execute("SELECT COUNT(*) FROM userphotos WHERE user_id = ?", (user_id,)) user_photo_count = (await cursor.fetchone())[0] cursor = await db.execute("SELECT id, photo_id FROM backgrounds WHERE user_id = ?", (user_id,)) backgrounds = await cursor.fetchall() cursor = await db.execute("SELECT id, photo_id FROM userphotos WHERE user_id = ?", (user_id,)) user_photos = await cursor.fetchall() if not backgrounds or not user_photos: await message.reply("Необходимо загрузить фоновые изображения и/или креатив.") return used_background_ids = [] # Сюда будут собираться ID использованных фонов для последующего удаления media_groups = [] # Здесь будут храниться пачки изображений для отправки for user_photo in user_photos: if not backgrounds: await message.reply("Количество фонов меньше количества фотографий в креативе.") break # Если фоновых изображений недостаточно, прекращаем обработку background = backgrounds.pop(0) # Получаем первый фон из списка used_background_ids.append(background[0]) # Добавляем ID фона в список использованных processed_image_io = await apply_background(user_photo[1], background[1], padding_horizontal=100, padding_vertical=70) media_groups.append(types.InputMediaPhoto(processed_image_io)) # Если в текущей пачке 4 изображения или это последняя итерация, отправляем пачку if len(media_groups) == user_photo_count or not backgrounds: await bot.send_media_group(message.chat.id, media=media_groups) media_groups = [] # Очищаем текущую пачку для следующей # Удаляем использованные фоны из базы данных if used_background_ids: await db.executemany("DELETE FROM backgrounds WHERE id = ?", [(id,) for id in used_background_ids]) await db.commit() # Function to apply background to user photo async def apply_background(user_photo_id, background_photo_id, padding_horizontal=100, padding_vertical=70, blur_radius=5): logging.info("обработка фото") user_photo_file = await bot.get_file(user_photo_id) background_photo_file = await bot.get_file(background_photo_id) user_photo_url = bot.get_file_url(user_photo_file.file_path) background_photo_url = bot.get_file_url(background_photo_file.file_path) user_photo_data = await fetch_photo(user_photo_url) background_photo_data = await fetch_photo(background_photo_url) with Image.open(BytesIO(user_photo_data)) as user_image, Image.open(BytesIO(background_photo_data)) as background_image: user_image = user_image.convert('RGBA') background_image = background_image.convert('RGBA') background_image = background_image.filter(ImageFilter.GaussianBlur(blur_radius)) # Задаем размер фона, увеличенный на указанные отступы new_background_width = user_image.width + padding_horizontal * 2 # Слева и справа new_background_height = user_image.height + padding_vertical * 2 # Сверху и снизу background_image = background_image.resize((new_background_width, new_background_height), Image.Resampling.LANCZOS) # Готовим позицию для наложения фото пользователя на фон user_image_position = (padding_horizontal, padding_vertical) # Отступы слева и сверху # Накладываем пользовательское изображение на фон background_image.paste(user_image, user_image_position, user_image.split()[3]) # Используем альфа-канал для маски # Сохраняем во временный файл result_image_io = BytesIO() background_image.save(result_image_io, format='PNG') result_image_io.seek(0) return result_image_io async def delete_used_backgrounds(used_background_ids): if used_background_ids: async with connect('bot.db') as db: await db.executemany("DELETE FROM backgrounds WHERE id = ?", [(bg_id,) for bg_id in used_background_ids]) await db.commit() async def get_use_common_backgrounds(db, user_id): cursor = await db.execute("SELECT use_common_backgrounds FROM users WHERE user_id = ?", (user_id,)) result = await cursor.fetchone() return result[0] if result else False async def get_backgrounds(db, user_id, use_common_backgrounds): if use_common_backgrounds: cursor = await db.execute("SELECT id, photo_id FROM common_backgrounds") else: cursor = await db.execute("SELECT id, photo_id FROM backgrounds WHERE user_id = ?", (user_id,)) return await cursor.fetchall() async def get_user_photos(db, user_id): cursor = await db.execute("SELECT photo_id FROM userphotos WHERE user_id = ?", (user_id,)) return await cursor.fetchall() @dp.message_handler(lambda message: message.text == "🖼 Замена фона") async def on_change_background_button(message: types.Message): user_id = message.from_user.id used_background_ids = [] async with connect('bot.db') as db: use_common_backgrounds = await get_use_common_backgrounds(db, user_id) backgrounds = await get_backgrounds(db, user_id, use_common_backgrounds) user_photos = await get_user_photos(db, user_id) if not backgrounds or not user_photos: await message.answer("Необходимо загрузить фоновые изображения и/или креатив.") return media_groups = [] background_index = 0 for user_photo in user_photos: if not use_common_backgrounds: background = backgrounds[background_index] used_background_ids.append(background['id']) background_index += 1 if background_index >= len(backgrounds): background_index = 0 else: background = random.choice(backgrounds) # случайный фон для общего использования processed_image_io = await apply_background(user_photo['photo_id'], background['photo_id']) media_groups.append(types.InputMediaPhoto(processed_image_io)) if media_groups: await bot.send_media_group(message.chat.id, media=media_groups) await delete_used_backgrounds(used_background_ids) # Init DB on startup async def on_startup(_): print("Starting bot…") await init_db() await create_banned_users_table() # Starting the bot if __name__ == '__main__': executor.start_polling(dp, skip_updates=True, on_startup=on_startup)
8694597e1e15bd360db47b0974b5df5b
{ "intermediate": 0.39033517241477966, "beginner": 0.4141954481601715, "expert": 0.1954694390296936 }
38,925
Помоги решить ошибку: ERROR:asyncio:Task exception was never retrieved future: <Task finished name='Task-99' coro=<Dispatcher._process_polling_updates() done, defined at C:\Users\Аскар\PycharmProjects\smena tt\.venv\Lib\site-packages\aiogram\dispatcher\dispatcher.py:407> exception=BadRequest('Invalid file_id')> Traceback (most recent call last): File "C:\Users\Аскар\PycharmProjects\smena tt\.venv\Lib\site-packages\aiogram\dispatcher\dispatcher.py", line 415, in _process_polling_updates for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Аскар\PycharmProjects\smena tt\.venv\Lib\site-packages\aiogram\dispatcher\dispatcher.py", line 235, in process_updates return await asyncio.gather(*tasks) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Аскар\PycharmProjects\smena tt\.venv\Lib\site-packages\aiogram\dispatcher\handler.py", line 117, in notify response = await handler_obj.handler(*args, **partial_data) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Аскар\PycharmProjects\smena tt\.venv\Lib\site-packages\aiogram\dispatcher\dispatcher.py", line 256, in process_update return await self.message_handlers.notify(update.message) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Аскар\PycharmProjects\smena tt\.venv\Lib\site-packages\aiogram\dispatcher\handler.py", line 117, in notify response = await handler_obj.handler(*args, **partial_data) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Аскар\PycharmProjects\smena tt\main.py", line 860, in on_change_background_button processed_image_io = await apply_background(user_photo[0], background[0]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Аскар\PycharmProjects\smena tt\main.py", line 782, in apply_background background_photo_file = await bot.get_file(background_photo_id) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Аскар\PycharmProjects\smena tt\.venv\Lib\site-packages\aiogram\bot\bot.py", line 1791, in get_file result = await self.request(api.Methods.GET_FILE, payload) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Аскар\PycharmProjects\smena tt\.venv\Lib\site-packages\aiogram\bot\base.py", line 236, in request return await api.make_request(await self.get_session(), self.server, self.__token, method, data, files, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Аскар\PycharmProjects\smena tt\.venv\Lib\site-packages\aiogram\bot\api.py", line 140, in make_request return check_result(method, response.content_type, response.status, await response.text()) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Аскар\PycharmProjects\smena tt\.venv\Lib\site-packages\aiogram\bot\api.py", line 115, in check_result exceptions.BadRequest.detect(description) File "C:\Users\Аскар\PycharmProjects\smena tt\.venv\Lib\site-packages\aiogram\utils\exceptions.py", line 141, in detect raise cls(description) aiogram.utils.exceptions.BadRequest: Invalid file_id Вот код моего бота: import asyncio from io import BytesIO from PIL import Image, ImageFilter import aiohttp import time import random from aiogram import Bot, Dispatcher, types, executor from aiogram.contrib.fsm_storage.memory import MemoryStorage from aiogram.dispatcher import FSMContext from aiogram.dispatcher.filters.state import State, StatesGroup from aiosqlite import connect import logging from aiogram.utils.exceptions import MessageNotModified from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton, ParseMode from aiogram import types from aiogram.dispatcher.middlewares import BaseMiddleware from aiogram.dispatcher.handler import CancelHandler from aiogram.dispatcher.middlewares import LifetimeControllerMiddleware from collections import defaultdict import ssl logging.basicConfig(level=logging.INFO) ADMINS=[989037374,6663889022] TOKEN = "6937803168:AAE-eV82HlqV3M0w7a8U89aJBpkGfywCz7A" bot = Bot(token=TOKEN) storage = MemoryStorage() dp = Dispatcher(bot, storage=storage) # Создание таблиц если они не существуют async def init_db(): logging.info("инициализация БД") async with connect('bot.db') as db: await db.execute(""" CREATE TABLE IF NOT EXISTS backgrounds ( id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, photo_id TEXT NOT NULL ) """) await db.execute(""" CREATE TABLE IF NOT EXISTS userphotos ( id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, photo_id TEXT NOT NULL ) """) await db.execute(""" CREATE TABLE IF NOT EXISTS users ( user_id INTEGER PRIMARY KEY, is_banned INTEGER DEFAULT 0, first_name TEXT, username TEXT ) """) await db.execute(""" CREATE TABLE IF NOT EXISTS common_backgrounds ( id INTEGER PRIMARY KEY, photo_id TEXT NOT NULL ) """) await db.commit() from aiogram.utils.markdown import escape_md class MailingState(StatesGroup): waiting_for_message = State() waiting_for_buttons = State() from aiogram.utils.markdown import quote_html @dp.message_handler(commands=['profile'], user_id=ADMINS, state='*') async def cmd_profile(message: types.Message): # Разбор аргумента команды arg = message.get_args() # Проверка, является ли аргумент числом (user_id) или строкой (username) user_id = None username = None if arg.isdigit(): user_id = int(arg) elif arg.startswith('@'): username = arg[1:] # Удаляем @ в начале # Если аргумент отсутствует if not user_id and not username: await message.reply("Необходимо указать user_id или username пользователя.") return # Поиск пользователя async with connect('bot.db') as db: if user_id: cursor = await db.execute(""" SELECT user_id, username, use_common_backgrounds, common_backgrounds_count, personal_backgrounds_count, is_banned FROM users WHERE user_id = ?""", (user_id,)) else: cursor = await db.execute(""" SELECT user_id, username, use_common_backgrounds, common_backgrounds_count, personal_backgrounds_count, is_banned FROM users WHERE username = ?""", (username,)) user_data = await cursor.fetchone() # Если пользователь не найден if not user_data: await message.reply("Пользователь не найден.") return # Формирование сообщения для отправки администратору profile_text = ( f"👨 *Профиль пользователя*\n\n" f"User ID: {user_data[0]}\n" f"Username: @{quote_html(user_data[1])}\n\n" f"Использование общих фонов: *{'вкл' if user_data[2] else 'выкл'}*\n" f"Количество использований общих фонов: {user_data[3]}\n" f"Количество использований личных фонов: {user_data[4]}\n" f"Статус: *{'забанен' if user_data[5] else 'активен'}*" ) # Создание инлайн-кнопок buttons = [ InlineKeyboardButton("Забанить", callback_data=f'ban_{user_data[0]}'), InlineKeyboardButton("Разбанить", callback_data=f'unban_{user_data[0]}') ] keyboard = InlineKeyboardMarkup().add(*buttons) # Отправка сообщения await message.reply(profile_text, parse_mode="MarkdownV2", reply_markup = keyboard) @dp.callback_query_handler(lambda c: c.data.startswith('ban_')) async def process_ban_button(callback_query: types.CallbackQuery): admin_id = callback_query.from_user.id if admin_id not in ADMINS: # Проверяем, что вызывающий команду является администратором await callback_query.answer("Вы не являетесь администратором.") return user_id_to_ban = int(callback_query.data.split('_')[1]) async with connect('bot.db') as db: await db.execute("INSERT OR IGNORE INTO banned_users (user_id) VALUES (?)", (user_id_to_ban,)) await db.commit() await callback_query.answer(f"Пользователь {user_id_to_ban} заблокирован.") @dp.callback_query_handler(lambda c: c.data.startswith('unban_')) async def process_unban_button(callback_query: types.CallbackQuery): admin_id = callback_query.from_user.id if admin_id not in ADMINS: await callback_query.answer("Вы не являетесь администратором.") return user_id_to_unban = int(callback_query.data.split('_')[1]) async with connect('bot.db') as db: await db.execute("DELETE FROM banned_users WHERE user_id = ?", (user_id_to_unban,)) await db.commit() await callback_query.answer(f"Пользователь {user_id_to_unban} разблокирован.") # Обработчик команды /post, передаем состояние ожидания сообщения для рассылки @dp.message_handler(commands=['post'], user_id=ADMINS, state='*') async def cmd_post(message: types.Message): await MailingState.waiting_for_message.set() await message.reply("Отправьте текст рассылки") # Обработчик текста рассылки, переводим в состояние ожидания кнопок @dp.message_handler(state=MailingState.waiting_for_message, content_types=types.ContentTypes.TEXT) async def post_message(message: types.Message, state: FSMContext): await MailingState.waiting_for_buttons.set() await state.update_data(mailing_text=message.text) await message.reply( "Теперь отправьте данные для inline-кнопок в формате: Текст кнопки;URL на каждую кнопку или /skip, если кнопки не нужны.") # Обработчик кнопок для рассылки или пропуска их добавления @dp.message_handler(state=MailingState.waiting_for_buttons) async def post_buttons(message: types.Message, state: FSMContext): if message.text != "/skip": # Разбиваем сообщение по строкам и создаем кнопки lines = message.text.split("\n") buttons = [InlineKeyboardButton(text=line.split(';')[0], url=line.split(';')[1]) for line in lines if len(line.split(';')) == 2] markup = InlineKeyboardMarkup() markup.add(*buttons) else: markup = None # Получаем данные из состояния и текст рассылки data = await state.get_data() text = data.get('mailing_text') mode = data.get('mailing_mode') # Запускаем рассылку success_count, failure_count = await send_mailing(text, mode, markup) await state.finish() # Сброс состояния после рассылки await message.answer(f"Рассылка выполнена. Успешно: {success_count}. Неудачно: {failure_count}.") async def send_mailing(text, parse_mode, keyboard=None): async with connect('bot.db') as db: cursor = await db.execute("SELECT user_id FROM users") user_ids = [row[0] for row in await cursor.fetchall()] success_count = 0 failure_count = 0 for user_id in user_ids: try: await bot.send_message( chat_id=user_id, text=text, reply_markup=keyboard, parse_mode=types.ParseMode.HTML ) success_count += 1 except Exception as e: # Обрабатываем возможные исключения, например, если пользователь заблокировал бота logging.error(f"Failed to send message to {user_id}: {e}") failure_count += 1 return success_count, failure_count # Обработчик команды /skip для пропуска добавления кнопок @dp.message_handler(state=MailingState.waiting_for_buttons, commands=['skip']) async def post_skip(message: types.Message, state: FSMContext): await post_buttons(message, state) # Хэндлер команды /sql для выполнения произвольных SQL-запросов (ТОЛЬКО для администраторов) @dp.message_handler(commands=['sql'], user_id=ADMINS) async def execute_sql_command(message: types.Message): # Получаем аргументы команды (SQL-запрос) sql_query = message.get_args() # Проверяем, что запрос не пустой if not sql_query: await message.reply("Введите SQL-запрос.") return # Подключаемся к базе данных и выполняем запрос async with connect('bot.db') as db: try: await db.execute(sql_query) await db.commit() await message.reply("SQL-запрос успешно выполнен.") except Exception as e: await message.reply(f"Ошибка при выполнении SQL-запроса: {e}") class UploadBackgroundState(StatesGroup): waiting_for_backgrounds = State() class UploadUserPhotoState(StatesGroup): waiting_for_user_photo = State() # Админ-команда для очистки таблицы с общими фонами @dp.message_handler(commands=['clear_common'], user_id=ADMINS) async def clear_common_backgrounds(message: types.Message): async with connect('bot.db') as db: await db.execute("DELETE FROM common_backgrounds") await db.commit() await message.reply("Все общие фоны были успешно удалены из базы данных.") # Админ-команда для просмотра количества общих фонов @dp.message_handler(commands=['count_common'], user_id=ADMINS) async def count_common_backgrounds(message: types.Message): async with connect('bot.db') as db: cursor = await db.execute("SELECT COUNT(*) FROM common_backgrounds") count = await cursor.fetchone() await message.reply(f"Количество общих фонов в базе данных: {count[0]}") async def generate_invite_link(chat_id): try: chat_invite_link = await bot.create_chat_invite_link(chat_id, expire_date=int(time.time()) + 900) # на 15 минут return chat_invite_link.invite_link except Exception as e: logging.error(e) return None async def is_user_subscribed(chat_id, user_id): try: member = await bot.get_chat_member(chat_id, user_id) return member.status not in ["left", "kicked"] except Exception as e: logging.error(e) return False # По умолчанию считаем, что пользователь не подписан, если возникла ошибка CHANNEL_ID = "-1002046113496" # ID вашего канала class SubscriptionCheckMiddleware(BaseMiddleware): def __init__(self, channel_id): super().__init__() self.channel_id = channel_id async def on_process_message(self, message: types.Message, data: dict): member = await bot.get_chat_member(self.channel_id, message.from_user.id) if member.status not in ["member", "administrator", "creator"]: invite_link = await generate_invite_link(self.channel_id) if invite_link: keyboard = InlineKeyboardMarkup().add( InlineKeyboardButton("🔗 Подписаться на канал", url=invite_link) ) await message.answer( f"🔒 Для продолжения работы с ботом *необходимо подписаться на наш новостной канал\.*\n\n👌 Если вы уже подписались на канал, нажмите /start",parse_mode="MarkdownV2", reply_markup=keyboard ) # прерываем обработку следующих хэндлеров raise CancelHandler() async def post_process(self, obj, data, *args): pass dp.middleware.setup(SubscriptionCheckMiddleware(CHANNEL_ID)) @dp.message_handler(commands=['count']) async def count_backgrounds(message: types.Message): user_id = message.from_user.id async with connect('bot.db') as db: cursor = await db.execute("SELECT COUNT(*) FROM backgrounds WHERE user_id = ?", (user_id,)) count = await cursor.fetchone() await message.answer(f"У вас в базе данных *{count[0]}* фоновых изображений\.",parse_mode="MarkdownV2") @dp.message_handler(commands=['ex']) async def export_backgrounds(message: types.Message): user_id = message.from_user.id try: # Получаем количество изображений для выгрузки из команды command_args = message.get_args().split() # если ничего не введено, выгрузить все num_images = int(command_args[0]) if command_args else -1 except (IndexError, ValueError): await message.answer("Укажите количество фонов для выгрузки. Например: /ex 10") return async with connect('bot.db') as db: # Если num_images равен -1, значит выгрузить все изображения query = "SELECT id, photo_id FROM backgrounds LIMIT ?" cursor = await db.execute(query, (10 if num_images == -1 else num_images,)) backgrounds_chunk = await cursor.fetchall() while backgrounds_chunk: media_group = [types.InputMediaPhoto(photo[1]) for photo in backgrounds_chunk] await bot.send_media_group(message.chat.id, media_group) # Удаляем отправленные фоны из БД await db.executemany("DELETE FROM backgrounds WHERE id = ?", [(photo[0],) for photo in backgrounds_chunk]) await db.commit() if num_images != -1: num_images -= len(backgrounds_chunk) if num_images <= 0: break # Получаем следующую пачку изображений cursor = await db.execute(query, (10 if num_images == -1 else min(num_images, 10),)) backgrounds_chunk = await cursor.fetchall() await message.answer("*Все запрошенные фоновые изображения были выгружены и удалены из базы данных\.*",parse_mode="MarkdownV2") LOG_CHANNEL_ID = "@smenalogs" async def log_to_channel(user: types.User, action: str): message_to_send = f"Пользователь @{user.username} ({user.id}) выполнил действие: {action}" await bot.send_message(LOG_CHANNEL_ID, message_to_send) stop_keyboard = ReplyKeyboardMarkup(resize_keyboard=True).add(KeyboardButton("Стоп")) async def start_keyboard(): # Создаем начальную клавиатуру с кнопками "Замена фона" и "Личный кабинет" return ReplyKeyboardMarkup(resize_keyboard=True).add( KeyboardButton("🖼 Замена фона") ).add( KeyboardButton("📊 Личный кабинет") ) @dp.message_handler(commands=['stop'], state='*') async def stop_processing(message: types.Message, state: FSMContext): # … await message.reply("Обработка фотографий прекращена.", reply_markup=await start_keyboard()) await state.finish() @dp.message_handler(commands=['start', 'help']) async def send_welcome(message: types.Message): user_id = message.from_user.id first_name = message.from_user.first_name username = message.from_user.username # Подключаемся к БД и проверяем, существует ли пользователь async with connect('bot.db') as db: cursor = await db.execute("SELECT user_id FROM users WHERE user_id = ?", (user_id,)) user_exists = await cursor.fetchone() # Если пользователя нет в БД, сохраняем его if not user_exists: await db.execute("INSERT INTO users (user_id, first_name, username) VALUES (?, ?, ?)", (user_id, first_name, username)) await db.commit() # Создаем кнопки button_photos = KeyboardButton("🖼 Замена фона") button_cabinet = KeyboardButton("📊 Личный кабинет") # Отправляем сообщение вместе с клавиатурой await message.answer( "Привет! Пользуйся кнопками", reply_markup=await start_keyboard() ) await log_to_channel(message.from_user, "прописал /start") @dp.callback_query_handler( lambda c: c.data == 'toggle_common_backgrounds_on' or c.data == 'toggle_common_backgrounds_off') async def toggle_common_backgrounds(callback_query: types.CallbackQuery): user_id = callback_query.from_user.id # Переключаем состояние использования общих фонов new_setting = not (callback_query.data == 'toggle_common_backgrounds_on') # Сохраняем новое состояние в базу данных async with connect('bot.db') as db: await db.execute("UPDATE users SET use_common_backgrounds = ? WHERE user_id = ?", (int(new_setting), user_id)) await db.commit() # Ответное сообщение пользователю reply_text = "Общие фоны включены." if new_setting else "Общие фоны выключены." await bot.answer_callback_query(callback_query.id, reply_text) # Обновить сообщение в "личном кабинете", чтобы отразить изменения с "включено/выключено" await personal_cabinet(callback_query) @dp.callback_query_handler(lambda c: c.data == 'support') async def support_callback(callback_query: types.CallbackQuery): support_text = ( "❓ Если у вас есть вопросы, предложения, проблемы \- обращайтесь к администратору бота\.\n\n" "*Нажмите на кнопку ниже, чтобы связаться\.*" ) admin_button = InlineKeyboardMarkup().add( InlineKeyboardButton("👨‍💻 Администратор бота", url="t.me/ih82seeucry") ) await bot.edit_message_text( chat_id=callback_query.message.chat.id, message_id=callback_query.message.message_id, text=support_text, parse_mode="MarkdownV2", reply_markup=admin_button ) @dp.message_handler(lambda message: message.text == "📊 Личный кабинет") async def personal_cabinet(message_or_query): # Определяем, является ли объект сообщением или коллбэк-запросом if isinstance(message_or_query, types.Message): user_id = message_or_query.from_user.id message = message_or_query elif isinstance(message_or_query, types.CallbackQuery): user_id = message_or_query.from_user.id message = message_or_query.message else: return # Если полученный объект не поддерживается, не предпринимать никаких действий async with connect('bot.db') as db: cursor = await db.execute("SELECT COUNT(*) FROM backgrounds WHERE user_id = ?", (user_id,)) count = (await cursor.fetchone())[0] cursor = await db.execute("SELECT use_common_backgrounds FROM users WHERE user_id = ?", (user_id,)) use_common_backgrounds = (await cursor.fetchone())[0] common_bg_status = "включено" if use_common_backgrounds else "выключено" cursor = await db.execute( "SELECT common_backgrounds_count, personal_backgrounds_count FROM users WHERE user_id = ?", (user_id,)) counts = await cursor.fetchone() common_bg_count = counts[0] personal_bg_count = counts[1] toggle_text = "Общие фоны: вкл" if use_common_backgrounds else "Общие фоны: выкл" callback_data = 'toggle_common_backgrounds_on' if use_common_backgrounds else 'toggle_common_backgrounds_off' keyboard = InlineKeyboardMarkup(row_width=1).add( InlineKeyboardButton("Загрузить фоны", callback_data='upload_backgrounds'), InlineKeyboardButton("Загрузить креатив", callback_data='upload_user_photos'), InlineKeyboardButton("Очистить фоны", callback_data='clear_backgrounds'), InlineKeyboardButton(toggle_text, callback_data=callback_data), InlineKeyboardButton("Поддержка", callback_data='support') ) text_message = f"*📊 Личный кабинет*\n\nКоличество фонов: {count}\nИспользование общих фонов *{common_bg_status}*\n\nКоличество использований общих фонов: {common_bg_count}\nКоличество использований личных фонов: {personal_bg_count}" if isinstance(message_or_query, types.CallbackQuery): try: # Метод для изменения текста сообщения и клавиатуры await bot.edit_message_text(text=text_message, chat_id=message.chat.id, message_id=message.message_id, parse_mode="MarkdownV2", reply_markup=keyboard) except MessageNotModified: # Ничего не делаем, если содержимое сообщения не изменилось pass else: await message.answer(text_message, parse_mode="MarkdownV2", reply_markup=keyboard) @dp.callback_query_handler(lambda c: c.data == 'upload_backgrounds') async def upload_backgrounds(callback_query: types.CallbackQuery): await upload_background_start(callback_query.message) await bot.send_message(callback_query.from_user.id, "Отправьте фоны для загрузки или нажмите Стоп, чтобы завершить.", reply_markup=stop_keyboard) @dp.callback_query_handler(lambda c: c.data == 'upload_user_photos') async def upload_user_photos(callback_query: types.CallbackQuery): await clear_user_photos_action(callback_query.from_user.id) await upload_user_photo_start(callback_query.message) await bot.send_message(callback_query.from_user.id, "Отправьте креатив для загрузки или нажмите Стоп, чтобы завершить.", reply_markup=stop_keyboard) @dp.callback_query_handler(lambda c: c.data == 'clear_backgrounds') async def clear_backgrounds(callback_query: types.CallbackQuery): confirmation_keyboard = InlineKeyboardMarkup().add( InlineKeyboardButton("Да", callback_data='confirm_clear_backgrounds'), InlineKeyboardButton("Нет", callback_data='cancel_clear_backgrounds') ) await callback_query.message.edit_text( "Вы уверены, что хотите удалить все свои фоны из базы? Это действие необратимо.", reply_markup=confirmation_keyboard ) @dp.callback_query_handler(lambda c: c.data == 'confirm_clear_backgrounds') async def confirm_clear_backgrounds(callback_query: types.CallbackQuery): user_id = callback_query.from_user.id async with connect('bot.db') as db: await db.execute("DELETE FROM backgrounds WHERE user_id = ?", (user_id,)) await db.commit() await bot.answer_callback_query(callback_query.id, "Ваши фоновые изображения были удалены из базы данных.") await callback_query.message.delete() await log_to_channel(callback_query.from_user, "очистил свои фоновые изображения") await send_welcome(callback_query.message) @dp.callback_query_handler(lambda c: c.data == 'cancel_clear_backgrounds') async def cancel_clear_backgrounds(callback_query: types.CallbackQuery): await callback_query.message.delete() await send_welcome(callback_query.message) # общие фоны class UploadCommonBackgroundState(StatesGroup): waiting_for_common_backgrounds = State() @dp.message_handler(commands=['common'], user_id=ADMINS, state='*') async def upload_common_background_start(message: types.Message): await UploadCommonBackgroundState.waiting_for_common_backgrounds.set() await message.reply("Отправьте общие фоны для загрузки или нажмите Стоп, чтобы сохранить их в базу данных.", reply_markup=stop_keyboard) @dp.message_handler(content_types=['photo'], state=UploadCommonBackgroundState.waiting_for_common_backgrounds) async def upload_common_background(message: types.Message, state: FSMContext): photo_id = message.photo[-1].file_id state_data = await state.get_data() buffer = state_data.get('buffer', []) buffer.append(photo_id) await state.update_data(buffer=buffer) await message.reply( "Фон добавлен в очередь. Продолжайте добавлять фоны или нажмите Стоп, чтобы сохранить их в базу данных.") @dp.message_handler(lambda message: message.text.lower() == "стоп", state=UploadCommonBackgroundState.waiting_for_common_backgrounds) async def stop_uploading_common_backgrounds(message: types.Message, state: FSMContext): state_data = await state.get_data() buffer = state_data.get('buffer', []) if buffer: async with connect('bot.db') as db: await db.executemany("INSERT INTO common_backgrounds (photo_id) VALUES (?)", [(photo_id,) for photo_id in buffer]) await db.commit() await state.finish() await message.reply("Все общие фоны сохранены в базу данных.", reply_markup=await start_keyboard()) @dp.callback_query_handler(lambda c: c.data == 'back_to_start') async def back_to_start(callback_query: types.CallbackQuery): await send_welcome(callback_query.message) @dp.message_handler(commands=['clear_upload']) async def clear_backgrounds(message: types.Message): user_id = message.from_user.id # Получаем ID пользователя async with connect('bot.db') as db: # Удаляем только фоны конкретного пользователя await db.execute("DELETE FROM backgrounds WHERE user_id = ?", (user_id,)) await db.commit() await message.answer("Ваши фоновые изображения были удалены из базы данных.") await log_to_channel(message.from_user, "очистил свои фоновые изображения") async def clear_user_photos_action(user_id: int): async with connect('bot.db') as db: await db.execute("DELETE FROM userphotos WHERE user_id = ?", (user_id,)) await db.commit() @dp.message_handler(commands=['clear_user']) async def clear_user_photos(message: types.Message): user_id = message.from_user.id await clear_user_photos_action(user_id) await message.answer("Ваш креатив был удален из базы данных.") await log_to_channel(message.from_user, "очистил userphoto") # Инициируем FSM для загрузки фонов @dp.message_handler(commands=['upload'], state='*') async def upload_background_start(message: types.Message): logging.info("прием аплоад") await UploadBackgroundState.waiting_for_backgrounds.set() await log_to_channel(message.from_user, "прописал /upload") # Инициируем FSM для загрузки пользовательского фото @dp.message_handler(commands=['user'], state='*') async def upload_user_photo_start(message: types.Message): logging.info("прием юзер фото") await UploadUserPhotoState.waiting_for_user_photo.set() await log_to_channel(message.from_user, "загружает userphoto") # Обработка загрузки фоновых фотографий @dp.message_handler(content_types=['photo'], state=UploadBackgroundState.waiting_for_backgrounds) async def upload_background(message: types.Message, state: FSMContext): user_id = message.from_user.id photo_id = message.photo[-1].file_id state_data = await state.get_data() buffer = state_data.get("buffer", []) buffer.append((user_id, photo_id)) await state.update_data(buffer=buffer) await message.answer("*Фон добавлен\.* Не забудьте нажать Стоп, чтобы сохранить все ваши фото в базу",parse_mode="MarkdownV2") # Обработка загрузки пользовательских фотографий @dp.message_handler(content_types=['photo'], state=UploadUserPhotoState.waiting_for_user_photo) async def upload_user_photo(message: types.Message, state: FSMContext): user_id = message.from_user.id photo_id = message.photo[-1].file_id state_data = await state.get_data() buffer = state_data.get("buffer", []) buffer.append((user_id, photo_id)) await state.update_data(buffer=buffer) await message.answer("*Фото креатива добавлено в очередь\.* Не забудьте нажать Стоп, чтобы сохранить все ваши фото в базу",parse_mode="MarkdownV2") # Переход обратно в обычное состояние после команды /stop @dp.message_handler(commands=['stop'], state='*') async def stop_processing(message: types.Message, state: FSMContext): logging.info("Процесс остановлен пользователем") await state.finish() await message.reply("Обработка фотографий прекращена.", reply_markup=await start_keyboard()) @dp.message_handler(lambda message: message.text.lower() == "стоп", state=UploadBackgroundState.waiting_for_backgrounds) async def stop_processing_background(message: types.Message, state: FSMContext): state_data = await state.get_data() buffer = state_data.get("buffer", []) if buffer: async with connect('bot.db') as db: await db.executemany("INSERT INTO backgrounds (user_id, photo_id) VALUES (?, ?)", buffer) await db.commit() await state.update_data(buffer=[]) # Очистка буфера после сохранения await state.finish() await message.answer("*Все фоны сохранены в базу данных\.*",parse_mode="MarkdownV2", reply_markup=await start_keyboard()) # Обработка команды "Стоп" для загрузки фотографий пользователя @dp.message_handler(lambda message: message.text.lower() == "стоп", state=UploadUserPhotoState.waiting_for_user_photo) async def stop_processing_user_photo(message: types.Message, state: FSMContext): state_data = await state.get_data() buffer = state_data.get("buffer", []) if buffer: async with connect('bot.db') as db: await db.executemany("INSERT INTO userphotos (user_id, photo_id) VALUES (?, ?)", buffer) await db.commit() await state.update_data(buffer=[]) # Очистка буфера после сохранения await state.finish() await message.answer("*Все ваши фотографии сохранены в базу данных\.*",parse_mode="MarkdownV2", reply_markup=await start_keyboard()) async def fetch_photo(file_url): async with aiohttp.ClientSession() as session: async with session.get(file_url, ssl=False) as resp: return await resp.read() async def create_banned_users_table(): async with connect('bot.db') as db: await db.execute(""" CREATE TABLE IF NOT EXISTS banned_users ( user_id INTEGER PRIMARY KEY ) """) await db.commit() class BanUserState(StatesGroup): waiting_for_user_id = State() # Добавьте обработку команды /ban только для администраторов @dp.message_handler(commands=['ban'], user_id=ADMINS) # Замените ADMINS на список ID администраторов async def ban_user_command(message: types.Message): args = message.get_args().split() if not args or not args[0].isdigit(): await message.reply("Необходимо указать ID пользователя для блокировки: /ban 123456789") return user_id_to_ban = int(args[0]) async with connect('bot.db') as db: await db.execute("INSERT OR IGNORE INTO banned_users (user_id) VALUES (?)", (user_id_to_ban,)) await db.commit() await message.reply(f"Пользователь {user_id_to_ban} заблокирован.") # Добавьте проверку на наличие пользователя в списке заблокированных перед любым действием с ботом class CheckBanMiddleware(BaseMiddleware): async def on_process_message(self, message: types.Message, data: dict): user_id = message.from_user.id async with connect('bot.db') as db: cursor = await db.execute("SELECT user_id FROM banned_users WHERE user_id = ?", (user_id,)) is_banned = await cursor.fetchone() is not None if is_banned: admin_button = InlineKeyboardMarkup().add( InlineKeyboardButton("👨‍💻 Администратор бота", url="t.me/ih82seeucry") ) await message.answer( "*Вы заблокированы администратором бота\.* Если у вас есть вопросы \- обратитесь к администратору по кнопке ниже\.", parse_mode="MarkdownV2", reply_markup=admin_button) raise CancelHandler() # Регистрируйте middleware dp.middleware.setup(CheckBanMiddleware()) @dp.message_handler(commands=['unban'], user_id=ADMINS) # Замените ADMINS на список ID администраторов async def unban_user_command(message: types.Message): args = message.get_args().split() if not args or not args[0].isdigit(): await message.reply("Необходимо указать ID пользователя для разблокировки: /unban 123456789") return user_id_to_unban = int(args[0]) async with connect('bot.db') as db: await db.execute("DELETE FROM banned_users WHERE user_id = ?", (user_id_to_unban,)) await db.commit() await message.reply(f"Пользователь {user_id_to_unban} разблокирован.") # Use this handler to get photos from the database, apply changes, and send to the user @dp.message_handler(commands=['photos']) async def send_processed_photos(message: types.Message): user_id = message.from_user.id async with connect('bot.db') as db: cursor = await db.execute("SELECT COUNT(*) FROM userphotos WHERE user_id = ?", (user_id,)) user_photo_count = (await cursor.fetchone())[0] cursor = await db.execute("SELECT id, photo_id FROM backgrounds WHERE user_id = ?", (user_id,)) backgrounds = await cursor.fetchall() cursor = await db.execute("SELECT id, photo_id FROM userphotos WHERE user_id = ?", (user_id,)) user_photos = await cursor.fetchall() if not backgrounds or not user_photos: await message.reply("Необходимо загрузить фоновые изображения и/или креатив.") return used_background_ids = [] # Сюда будут собираться ID использованных фонов для последующего удаления media_groups = [] # Здесь будут храниться пачки изображений для отправки for user_photo in user_photos: if not backgrounds: await message.reply("Количество фонов меньше количества фотографий в креативе.") break # Если фоновых изображений недостаточно, прекращаем обработку background = backgrounds.pop(0) # Получаем первый фон из списка used_background_ids.append(background[0]) # Добавляем ID фона в список использованных processed_image_io = await apply_background(user_photo[1], background[1], padding_horizontal=100, padding_vertical=70) media_groups.append(types.InputMediaPhoto(processed_image_io)) # Если в текущей пачке 4 изображения или это последняя итерация, отправляем пачку if len(media_groups) == user_photo_count or not backgrounds: await bot.send_media_group(message.chat.id, media=media_groups) media_groups = [] # Очищаем текущую пачку для следующей # Удаляем использованные фоны из базы данных if used_background_ids: await db.executemany("DELETE FROM backgrounds WHERE id = ?", [(id,) for id in used_background_ids]) await db.commit() # Function to apply background to user photo async def apply_background(user_photo_id, background_photo_id, padding_horizontal=100, padding_vertical=70, blur_radius=5): logging.info("обработка фото") user_photo_file = await bot.get_file(user_photo_id) background_photo_file = await bot.get_file(background_photo_id) user_photo_url = bot.get_file_url(user_photo_file.file_path) background_photo_url = bot.get_file_url(background_photo_file.file_path) user_photo_data = await fetch_photo(user_photo_url) background_photo_data = await fetch_photo(background_photo_url) with Image.open(BytesIO(user_photo_data)) as user_image, Image.open(BytesIO(background_photo_data)) as background_image: user_image = user_image.convert('RGBA') background_image = background_image.convert('RGBA') background_image = background_image.filter(ImageFilter.GaussianBlur(blur_radius)) # Задаем размер фона, увеличенный на указанные отступы new_background_width = user_image.width + padding_horizontal * 2 # Слева и справа new_background_height = user_image.height + padding_vertical * 2 # Сверху и снизу background_image = background_image.resize((new_background_width, new_background_height), Image.Resampling.LANCZOS) # Готовим позицию для наложения фото пользователя на фон user_image_position = (padding_horizontal, padding_vertical) # Отступы слева и сверху # Накладываем пользовательское изображение на фон background_image.paste(user_image, user_image_position, user_image.split()[3]) # Используем альфа-канал для маски # Сохраняем во временный файл result_image_io = BytesIO() background_image.save(result_image_io, format='PNG') result_image_io.seek(0) return result_image_io async def delete_used_backgrounds(used_background_ids): if used_background_ids: async with connect('bot.db') as db: await db.executemany("DELETE FROM backgrounds WHERE id = ?", [(bg_id,) for bg_id in used_background_ids]) await db.commit() async def get_use_common_backgrounds(db, user_id): cursor = await db.execute("SELECT use_common_backgrounds FROM users WHERE user_id = ?", (user_id,)) result = await cursor.fetchone() return result[0] if result else False async def get_backgrounds(db, user_id, use_common_backgrounds): if use_common_backgrounds: cursor = await db.execute("SELECT id, photo_id FROM common_backgrounds") else: cursor = await db.execute("SELECT id, photo_id FROM backgrounds WHERE user_id = ?", (user_id,)) return await cursor.fetchall() async def get_user_photos(db, user_id): cursor = await db.execute("SELECT photo_id FROM userphotos WHERE user_id = ?", (user_id,)) return await cursor.fetchall() @dp.message_handler(lambda message: message.text == "🖼 Замена фона") async def on_change_background_button(message: types.Message): user_id = message.from_user.id used_background_ids = [] async with connect('bot.db') as db: use_common_backgrounds = await get_use_common_backgrounds(db, user_id) backgrounds = await get_backgrounds(db, user_id, use_common_backgrounds) user_photos = await get_user_photos(db, user_id) if not backgrounds or not user_photos: await message.answer("Необходимо загрузить фоновые изображения и/или креатив.") return media_groups = [] background_index = 0 for user_photo in user_photos: if not use_common_backgrounds: background = backgrounds[background_index] used_background_ids.append(background[0]) background_index += 1 if background_index >= len(backgrounds): background_index = 0 else: background = random.choice(backgrounds) # случайный фон для общего использования processed_image_io = await apply_background(user_photo[0], background[0]) media_groups.append(types.InputMediaPhoto(processed_image_io)) if media_groups: await bot.send_media_group(message.chat.id, media=media_groups) await delete_used_backgrounds(used_background_ids) # Init DB on startup async def on_startup(_): print("Starting bot…") await init_db() await create_banned_users_table() # Starting the bot if __name__ == '__main__': executor.start_polling(dp, skip_updates=True, on_startup=on_startup)
568ee3e9718a7294e4cbff0babc599a0
{ "intermediate": 0.3549785912036896, "beginner": 0.4219400882720947, "expert": 0.2230813205242157 }
38,926
Помоги решить проблему с тем, что личные фоны не удаляются из БД после использования. При этом они удаляются при использовании команд /ex и /clear. Вот код бота: import asyncio from io import BytesIO from PIL import Image, ImageFilter import aiohttp import time from aiogram import Bot, Dispatcher, types, executor from aiogram.contrib.fsm_storage.memory import MemoryStorage from aiogram.dispatcher import FSMContext from aiogram.dispatcher.filters.state import State, StatesGroup from aiosqlite import connect import logging from aiogram.utils.exceptions import MessageNotModified from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton, ParseMode from aiogram import types from aiogram.dispatcher.middlewares import BaseMiddleware from aiogram.dispatcher.handler import CancelHandler from aiogram.dispatcher.middlewares import LifetimeControllerMiddleware from collections import defaultdict import ssl logging.basicConfig(level=logging.INFO) ADMINS=[989037374,6663889022] TOKEN = "6937803168:AAE-eV82HlqV3M0w7a8U89aJBpkGfywCz7A" bot = Bot(token=TOKEN) storage = MemoryStorage() dp = Dispatcher(bot, storage=storage) # Создание таблиц если они не существуют async def init_db(): logging.info("инициализация БД") async with connect('bot.db') as db: await db.execute(""" CREATE TABLE IF NOT EXISTS backgrounds ( id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, photo_id TEXT NOT NULL ) """) await db.execute(""" CREATE TABLE IF NOT EXISTS userphotos ( id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, photo_id TEXT NOT NULL ) """) await db.execute(""" CREATE TABLE IF NOT EXISTS users ( user_id INTEGER PRIMARY KEY, is_banned INTEGER DEFAULT 0, first_name TEXT, username TEXT ) """) await db.execute(""" CREATE TABLE IF NOT EXISTS common_backgrounds ( id INTEGER PRIMARY KEY, photo_id TEXT NOT NULL ) """) await db.commit() from aiogram.utils.markdown import escape_md class MailingState(StatesGroup): waiting_for_message = State() waiting_for_buttons = State() from aiogram.utils.markdown import quote_html @dp.message_handler(commands=['profile'], user_id=ADMINS, state='*') async def cmd_profile(message: types.Message): # Разбор аргумента команды arg = message.get_args() # Проверка, является ли аргумент числом (user_id) или строкой (username) user_id = None username = None if arg.isdigit(): user_id = int(arg) elif arg.startswith('@'): username = arg[1:] # Удаляем @ в начале # Если аргумент отсутствует if not user_id and not username: await message.reply("Необходимо указать user_id или username пользователя.") return # Поиск пользователя async with connect('bot.db') as db: if user_id: cursor = await db.execute(""" SELECT user_id, username, use_common_backgrounds, common_backgrounds_count, personal_backgrounds_count, is_banned FROM users WHERE user_id = ?""", (user_id,)) else: cursor = await db.execute(""" SELECT user_id, username, use_common_backgrounds, common_backgrounds_count, personal_backgrounds_count, is_banned FROM users WHERE username = ?""", (username,)) user_data = await cursor.fetchone() # Если пользователь не найден if not user_data: await message.reply("Пользователь не найден.") return # Формирование сообщения для отправки администратору profile_text = ( f"👨 *Профиль пользователя*\n\n" f"User ID: {user_data[0]}\n" f"Username: @{quote_html(user_data[1])}\n\n" f"Использование общих фонов: *{'вкл' if user_data[2] else 'выкл'}*\n" f"Количество использований общих фонов: {user_data[3]}\n" f"Количество использований личных фонов: {user_data[4]}\n" f"Статус: *{'забанен' if user_data[5] else 'активен'}*" ) # Создание инлайн-кнопок buttons = [ InlineKeyboardButton("Забанить", callback_data=f'ban_{user_data[0]}'), InlineKeyboardButton("Разбанить", callback_data=f'unban_{user_data[0]}') ] keyboard = InlineKeyboardMarkup().add(*buttons) # Отправка сообщения await message.reply(profile_text, parse_mode="MarkdownV2", reply_markup = keyboard) @dp.callback_query_handler(lambda c: c.data.startswith('ban_')) async def process_ban_button(callback_query: types.CallbackQuery): admin_id = callback_query.from_user.id if admin_id not in ADMINS: # Проверяем, что вызывающий команду является администратором await callback_query.answer("Вы не являетесь администратором.") return user_id_to_ban = int(callback_query.data.split('_')[1]) async with connect('bot.db') as db: await db.execute("INSERT OR IGNORE INTO banned_users (user_id) VALUES (?)", (user_id_to_ban,)) await db.commit() await callback_query.answer(f"Пользователь {user_id_to_ban} заблокирован.") @dp.callback_query_handler(lambda c: c.data.startswith('unban_')) async def process_unban_button(callback_query: types.CallbackQuery): admin_id = callback_query.from_user.id if admin_id not in ADMINS: await callback_query.answer("Вы не являетесь администратором.") return user_id_to_unban = int(callback_query.data.split('_')[1]) async with connect('bot.db') as db: await db.execute("DELETE FROM banned_users WHERE user_id = ?", (user_id_to_unban,)) await db.commit() await callback_query.answer(f"Пользователь {user_id_to_unban} разблокирован.") # Обработчик команды /post, передаем состояние ожидания сообщения для рассылки @dp.message_handler(commands=['post'], user_id=ADMINS, state='*') async def cmd_post(message: types.Message): await MailingState.waiting_for_message.set() await message.reply("Отправьте текст рассылки") # Обработчик текста рассылки, переводим в состояние ожидания кнопок @dp.message_handler(state=MailingState.waiting_for_message, content_types=types.ContentTypes.TEXT) async def post_message(message: types.Message, state: FSMContext): await MailingState.waiting_for_buttons.set() await state.update_data(mailing_text=message.text) await message.reply( "Теперь отправьте данные для inline-кнопок в формате: Текст кнопки;URL на каждую кнопку или /skip, если кнопки не нужны.") # Обработчик кнопок для рассылки или пропуска их добавления @dp.message_handler(state=MailingState.waiting_for_buttons) async def post_buttons(message: types.Message, state: FSMContext): if message.text != "/skip": # Разбиваем сообщение по строкам и создаем кнопки lines = message.text.split("\n") buttons = [InlineKeyboardButton(text=line.split(';')[0], url=line.split(';')[1]) for line in lines if len(line.split(';')) == 2] markup = InlineKeyboardMarkup() markup.add(*buttons) else: markup = None # Получаем данные из состояния и текст рассылки data = await state.get_data() text = data.get('mailing_text') mode = data.get('mailing_mode') # Запускаем рассылку success_count, failure_count = await send_mailing(text, mode, markup) await state.finish() # Сброс состояния после рассылки await message.answer(f"Рассылка выполнена. Успешно: {success_count}. Неудачно: {failure_count}.") async def send_mailing(text, parse_mode, keyboard=None): async with connect('bot.db') as db: cursor = await db.execute("SELECT user_id FROM users") user_ids = [row[0] for row in await cursor.fetchall()] success_count = 0 failure_count = 0 for user_id in user_ids: try: await bot.send_message( chat_id=user_id, text=text, reply_markup=keyboard, parse_mode=types.ParseMode.HTML ) success_count += 1 except Exception as e: # Обрабатываем возможные исключения, например, если пользователь заблокировал бота logging.error(f"Failed to send message to {user_id}: {e}") failure_count += 1 return success_count, failure_count # Обработчик команды /skip для пропуска добавления кнопок @dp.message_handler(state=MailingState.waiting_for_buttons, commands=['skip']) async def post_skip(message: types.Message, state: FSMContext): await post_buttons(message, state) # Хэндлер команды /sql для выполнения произвольных SQL-запросов (ТОЛЬКО для администраторов) @dp.message_handler(commands=['sql'], user_id=ADMINS) async def execute_sql_command(message: types.Message): # Получаем аргументы команды (SQL-запрос) sql_query = message.get_args() # Проверяем, что запрос не пустой if not sql_query: await message.reply("Введите SQL-запрос.") return # Подключаемся к базе данных и выполняем запрос async with connect('bot.db') as db: try: await db.execute(sql_query) await db.commit() await message.reply("SQL-запрос успешно выполнен.") except Exception as e: await message.reply(f"Ошибка при выполнении SQL-запроса: {e}") class UploadBackgroundState(StatesGroup): waiting_for_backgrounds = State() class UploadUserPhotoState(StatesGroup): waiting_for_user_photo = State() # Админ-команда для очистки таблицы с общими фонами @dp.message_handler(commands=['clear_common'], user_id=ADMINS) async def clear_common_backgrounds(message: types.Message): async with connect('bot.db') as db: await db.execute("DELETE FROM common_backgrounds") await db.commit() await message.reply("Все общие фоны были успешно удалены из базы данных.") # Админ-команда для просмотра количества общих фонов @dp.message_handler(commands=['count_common'], user_id=ADMINS) async def count_common_backgrounds(message: types.Message): async with connect('bot.db') as db: cursor = await db.execute("SELECT COUNT(*) FROM common_backgrounds") count = await cursor.fetchone() await message.reply(f"Количество общих фонов в базе данных: {count[0]}") async def generate_invite_link(chat_id): try: chat_invite_link = await bot.create_chat_invite_link(chat_id, expire_date=int(time.time()) + 900) # на 15 минут return chat_invite_link.invite_link except Exception as e: logging.error(e) return None async def is_user_subscribed(chat_id, user_id): try: member = await bot.get_chat_member(chat_id, user_id) return member.status not in ["left", "kicked"] except Exception as e: logging.error(e) return False # По умолчанию считаем, что пользователь не подписан, если возникла ошибка CHANNEL_ID = "-1002046113496" # ID вашего канала class SubscriptionCheckMiddleware(BaseMiddleware): def __init__(self, channel_id): super().__init__() self.channel_id = channel_id async def on_process_message(self, message: types.Message, data: dict): member = await bot.get_chat_member(self.channel_id, message.from_user.id) if member.status not in ["member", "administrator", "creator"]: invite_link = await generate_invite_link(self.channel_id) if invite_link: keyboard = InlineKeyboardMarkup().add( InlineKeyboardButton("🔗 Подписаться на канал", url=invite_link) ) await message.answer( f"🔒 Для продолжения работы с ботом *необходимо подписаться на наш новостной канал\.*\n\n👌 Если вы уже подписались на канал, нажмите /start",parse_mode="MarkdownV2", reply_markup=keyboard ) # прерываем обработку следующих хэндлеров raise CancelHandler() async def post_process(self, obj, data, *args): pass dp.middleware.setup(SubscriptionCheckMiddleware(CHANNEL_ID)) @dp.message_handler(commands=['count']) async def count_backgrounds(message: types.Message): user_id = message.from_user.id async with connect('bot.db') as db: cursor = await db.execute("SELECT COUNT(*) FROM backgrounds WHERE user_id = ?", (user_id,)) count = await cursor.fetchone() await message.answer(f"У вас в базе данных *{count[0]}* фоновых изображений\.",parse_mode="MarkdownV2") @dp.message_handler(commands=['ex']) async def export_backgrounds(message: types.Message): user_id = message.from_user.id try: # Получаем количество изображений для выгрузки из команды command_args = message.get_args().split() # если ничего не введено, выгрузить все num_images = int(command_args[0]) if command_args else -1 except (IndexError, ValueError): await message.answer("Укажите количество фонов для выгрузки. Например: /ex 10") return async with connect('bot.db') as db: # Если num_images равен -1, значит выгрузить все изображения query = "SELECT id, photo_id FROM backgrounds LIMIT ?" cursor = await db.execute(query, (10 if num_images == -1 else num_images,)) backgrounds_chunk = await cursor.fetchall() while backgrounds_chunk: media_group = [types.InputMediaPhoto(photo[1]) for photo in backgrounds_chunk] await bot.send_media_group(message.chat.id, media_group) # Удаляем отправленные фоны из БД await db.executemany("DELETE FROM backgrounds WHERE id = ?", [(photo[0],) for photo in backgrounds_chunk]) await db.commit() if num_images != -1: num_images -= len(backgrounds_chunk) if num_images <= 0: break # Получаем следующую пачку изображений cursor = await db.execute(query, (10 if num_images == -1 else min(num_images, 10),)) backgrounds_chunk = await cursor.fetchall() await message.answer("*Все запрошенные фоновые изображения были выгружены и удалены из базы данных\.*",parse_mode="MarkdownV2") LOG_CHANNEL_ID = "@smenalogs" async def log_to_channel(user: types.User, action: str): message_to_send = f"Пользователь @{user.username} ({user.id}) выполнил действие: {action}" await bot.send_message(LOG_CHANNEL_ID, message_to_send) stop_keyboard = ReplyKeyboardMarkup(resize_keyboard=True).add(KeyboardButton("Стоп")) async def start_keyboard(): # Создаем начальную клавиатуру с кнопками "Замена фона" и "Личный кабинет" return ReplyKeyboardMarkup(resize_keyboard=True).add( KeyboardButton("🖼 Замена фона") ).add( KeyboardButton("📊 Личный кабинет") ) @dp.message_handler(commands=['stop'], state='*') async def stop_processing(message: types.Message, state: FSMContext): # … await message.reply("Обработка фотографий прекращена.", reply_markup=await start_keyboard()) await state.finish() @dp.message_handler(commands=['start', 'help']) async def send_welcome(message: types.Message): user_id = message.from_user.id first_name = message.from_user.first_name username = message.from_user.username # Подключаемся к БД и проверяем, существует ли пользователь async with connect('bot.db') as db: cursor = await db.execute("SELECT user_id FROM users WHERE user_id = ?", (user_id,)) user_exists = await cursor.fetchone() # Если пользователя нет в БД, сохраняем его if not user_exists: await db.execute("INSERT INTO users (user_id, first_name, username) VALUES (?, ?, ?)", (user_id, first_name, username)) await db.commit() # Создаем кнопки button_photos = KeyboardButton("🖼 Замена фона") button_cabinet = KeyboardButton("📊 Личный кабинет") # Отправляем сообщение вместе с клавиатурой await message.answer( "Привет! Пользуйся кнопками", reply_markup=await start_keyboard() ) await log_to_channel(message.from_user, "прописал /start") @dp.callback_query_handler( lambda c: c.data == 'toggle_common_backgrounds_on' or c.data == 'toggle_common_backgrounds_off') async def toggle_common_backgrounds(callback_query: types.CallbackQuery): user_id = callback_query.from_user.id # Переключаем состояние использования общих фонов new_setting = not (callback_query.data == 'toggle_common_backgrounds_on') # Сохраняем новое состояние в базу данных async with connect('bot.db') as db: await db.execute("UPDATE users SET use_common_backgrounds = ? WHERE user_id = ?", (int(new_setting), user_id)) await db.commit() # Ответное сообщение пользователю reply_text = "Общие фоны включены." if new_setting else "Общие фоны выключены." await bot.answer_callback_query(callback_query.id, reply_text) # Обновить сообщение в "личном кабинете", чтобы отразить изменения с "включено/выключено" await personal_cabinet(callback_query) @dp.callback_query_handler(lambda c: c.data == 'support') async def support_callback(callback_query: types.CallbackQuery): support_text = ( "❓ Если у вас есть вопросы, предложения, проблемы \- обращайтесь к администратору бота\.\n\n" "*Нажмите на кнопку ниже, чтобы связаться\.*" ) admin_button = InlineKeyboardMarkup().add( InlineKeyboardButton("👨‍💻 Администратор бота", url="t.me/ih82seeucry") ) await bot.edit_message_text( chat_id=callback_query.message.chat.id, message_id=callback_query.message.message_id, text=support_text, parse_mode="MarkdownV2", reply_markup=admin_button ) @dp.message_handler(lambda message: message.text == "📊 Личный кабинет") async def personal_cabinet(message_or_query): # Определяем, является ли объект сообщением или коллбэк-запросом if isinstance(message_or_query, types.Message): user_id = message_or_query.from_user.id message = message_or_query elif isinstance(message_or_query, types.CallbackQuery): user_id = message_or_query.from_user.id message = message_or_query.message else: return # Если полученный объект не поддерживается, не предпринимать никаких действий async with connect('bot.db') as db: cursor = await db.execute("SELECT COUNT(*) FROM backgrounds WHERE user_id = ?", (user_id,)) count = (await cursor.fetchone())[0] cursor = await db.execute("SELECT use_common_backgrounds FROM users WHERE user_id = ?", (user_id,)) use_common_backgrounds = (await cursor.fetchone())[0] common_bg_status = "включено" if use_common_backgrounds else "выключено" cursor = await db.execute( "SELECT common_backgrounds_count, personal_backgrounds_count FROM users WHERE user_id = ?", (user_id,)) counts = await cursor.fetchone() common_bg_count = counts[0] personal_bg_count = counts[1] toggle_text = "Общие фоны: вкл" if use_common_backgrounds else "Общие фоны: выкл" callback_data = 'toggle_common_backgrounds_on' if use_common_backgrounds else 'toggle_common_backgrounds_off' keyboard = InlineKeyboardMarkup(row_width=1).add( InlineKeyboardButton("Загрузить фоны", callback_data='upload_backgrounds'), InlineKeyboardButton("Загрузить креатив", callback_data='upload_user_photos'), InlineKeyboardButton("Очистить фоны", callback_data='clear_backgrounds'), InlineKeyboardButton(toggle_text, callback_data=callback_data), InlineKeyboardButton("Поддержка", callback_data='support') ) text_message = f"*📊 Личный кабинет*\n\nКоличество фонов: {count}\nИспользование общих фонов *{common_bg_status}*\n\nКоличество использований общих фонов: {common_bg_count}\nКоличество использований личных фонов: {personal_bg_count}" if isinstance(message_or_query, types.CallbackQuery): try: # Метод для изменения текста сообщения и клавиатуры await bot.edit_message_text(text=text_message, chat_id=message.chat.id, message_id=message.message_id, parse_mode="MarkdownV2", reply_markup=keyboard) except MessageNotModified: # Ничего не делаем, если содержимое сообщения не изменилось pass else: await message.answer(text_message, parse_mode="MarkdownV2", reply_markup=keyboard) @dp.callback_query_handler(lambda c: c.data == 'upload_backgrounds') async def upload_backgrounds(callback_query: types.CallbackQuery): await upload_background_start(callback_query.message) await bot.send_message(callback_query.from_user.id, "Отправьте фоны для загрузки или нажмите Стоп, чтобы завершить.", reply_markup=stop_keyboard) @dp.callback_query_handler(lambda c: c.data == 'upload_user_photos') async def upload_user_photos(callback_query: types.CallbackQuery): await clear_user_photos_action(callback_query.from_user.id) await upload_user_photo_start(callback_query.message) await bot.send_message(callback_query.from_user.id, "Отправьте креатив для загрузки или нажмите Стоп, чтобы завершить.", reply_markup=stop_keyboard) @dp.callback_query_handler(lambda c: c.data == 'clear_backgrounds') async def clear_backgrounds(callback_query: types.CallbackQuery): confirmation_keyboard = InlineKeyboardMarkup().add( InlineKeyboardButton("Да", callback_data='confirm_clear_backgrounds'), InlineKeyboardButton("Нет", callback_data='cancel_clear_backgrounds') ) await callback_query.message.edit_text( "Вы уверены, что хотите удалить все свои фоны из базы? Это действие необратимо.", reply_markup=confirmation_keyboard ) @dp.callback_query_handler(lambda c: c.data == 'confirm_clear_backgrounds') async def confirm_clear_backgrounds(callback_query: types.CallbackQuery): user_id = callback_query.from_user.id async with connect('bot.db') as db: await db.execute("DELETE FROM backgrounds WHERE user_id = ?", (user_id,)) await db.commit() await bot.answer_callback_query(callback_query.id, "Ваши фоновые изображения были удалены из базы данных.") await callback_query.message.delete() await log_to_channel(callback_query.from_user, "очистил свои фоновые изображения") await send_welcome(callback_query.message) @dp.callback_query_handler(lambda c: c.data == 'cancel_clear_backgrounds') async def cancel_clear_backgrounds(callback_query: types.CallbackQuery): await callback_query.message.delete() await send_welcome(callback_query.message) # общие фоны class UploadCommonBackgroundState(StatesGroup): waiting_for_common_backgrounds = State() @dp.message_handler(commands=['common'], user_id=ADMINS, state='*') async def upload_common_background_start(message: types.Message): await UploadCommonBackgroundState.waiting_for_common_backgrounds.set() await message.reply("Отправьте общие фоны для загрузки или нажмите Стоп, чтобы сохранить их в базу данных.", reply_markup=stop_keyboard) @dp.message_handler(content_types=['photo'], state=UploadCommonBackgroundState.waiting_for_common_backgrounds) async def upload_common_background(message: types.Message, state: FSMContext): photo_id = message.photo[-1].file_id state_data = await state.get_data() buffer = state_data.get('buffer', []) buffer.append(photo_id) await state.update_data(buffer=buffer) await message.reply( "Фон добавлен в очередь. Продолжайте добавлять фоны или нажмите Стоп, чтобы сохранить их в базу данных.") @dp.message_handler(lambda message: message.text.lower() == "стоп", state=UploadCommonBackgroundState.waiting_for_common_backgrounds) async def stop_uploading_common_backgrounds(message: types.Message, state: FSMContext): state_data = await state.get_data() buffer = state_data.get('buffer', []) if buffer: async with connect('bot.db') as db: await db.executemany("INSERT INTO common_backgrounds (photo_id) VALUES (?)", [(photo_id,) for photo_id in buffer]) await db.commit() await state.finish() await message.reply("Все общие фоны сохранены в базу данных.", reply_markup=await start_keyboard()) @dp.callback_query_handler(lambda c: c.data == 'back_to_start') async def back_to_start(callback_query: types.CallbackQuery): await send_welcome(callback_query.message) @dp.message_handler(commands=['clear_upload']) async def clear_backgrounds(message: types.Message): user_id = message.from_user.id # Получаем ID пользователя async with connect('bot.db') as db: # Удаляем только фоны конкретного пользователя await db.execute("DELETE FROM backgrounds WHERE user_id = ?", (user_id,)) await db.commit() await message.answer("Ваши фоновые изображения были удалены из базы данных.") await log_to_channel(message.from_user, "очистил свои фоновые изображения") async def clear_user_photos_action(user_id: int): async with connect('bot.db') as db: await db.execute("DELETE FROM userphotos WHERE user_id = ?", (user_id,)) await db.commit() @dp.message_handler(commands=['clear_user']) async def clear_user_photos(message: types.Message): user_id = message.from_user.id await clear_user_photos_action(user_id) await message.answer("Ваш креатив был удален из базы данных.") await log_to_channel(message.from_user, "очистил userphoto") # Инициируем FSM для загрузки фонов @dp.message_handler(commands=['upload'], state='*') async def upload_background_start(message: types.Message): logging.info("прием аплоад") await UploadBackgroundState.waiting_for_backgrounds.set() await log_to_channel(message.from_user, "прописал /upload") # Инициируем FSM для загрузки пользовательского фото @dp.message_handler(commands=['user'], state='*') async def upload_user_photo_start(message: types.Message): logging.info("прием юзер фото") await UploadUserPhotoState.waiting_for_user_photo.set() await log_to_channel(message.from_user, "загружает userphoto") # Обработка загрузки фоновых фотографий @dp.message_handler(content_types=['photo'], state=UploadBackgroundState.waiting_for_backgrounds) async def upload_background(message: types.Message, state: FSMContext): user_id = message.from_user.id photo_id = message.photo[-1].file_id state_data = await state.get_data() buffer = state_data.get("buffer", []) buffer.append((user_id, photo_id)) await state.update_data(buffer=buffer) await message.answer("*Фон добавлен\.* Не забудьте нажать Стоп, чтобы сохранить все ваши фото в базу",parse_mode="MarkdownV2") # Обработка загрузки пользовательских фотографий @dp.message_handler(content_types=['photo'], state=UploadUserPhotoState.waiting_for_user_photo) async def upload_user_photo(message: types.Message, state: FSMContext): user_id = message.from_user.id photo_id = message.photo[-1].file_id state_data = await state.get_data() buffer = state_data.get("buffer", []) buffer.append((user_id, photo_id)) await state.update_data(buffer=buffer) await message.answer("*Фото креатива добавлено в очередь\.* Не забудьте нажать Стоп, чтобы сохранить все ваши фото в базу",parse_mode="MarkdownV2") # Переход обратно в обычное состояние после команды /stop @dp.message_handler(commands=['stop'], state='*') async def stop_processing(message: types.Message, state: FSMContext): logging.info("Процесс остановлен пользователем") await state.finish() await message.reply("Обработка фотографий прекращена.", reply_markup=await start_keyboard()) @dp.message_handler(lambda message: message.text.lower() == "стоп", state=UploadBackgroundState.waiting_for_backgrounds) async def stop_processing_background(message: types.Message, state: FSMContext): state_data = await state.get_data() buffer = state_data.get("buffer", []) if buffer: async with connect('bot.db') as db: await db.executemany("INSERT INTO backgrounds (user_id, photo_id) VALUES (?, ?)", buffer) await db.commit() await state.update_data(buffer=[]) # Очистка буфера после сохранения await state.finish() await message.answer("*Все фоны сохранены в базу данных\.*",parse_mode="MarkdownV2", reply_markup=await start_keyboard()) # Обработка команды "Стоп" для загрузки фотографий пользователя @dp.message_handler(lambda message: message.text.lower() == "стоп", state=UploadUserPhotoState.waiting_for_user_photo) async def stop_processing_user_photo(message: types.Message, state: FSMContext): state_data = await state.get_data() buffer = state_data.get("buffer", []) if buffer: async with connect('bot.db') as db: await db.executemany("INSERT INTO userphotos (user_id, photo_id) VALUES (?, ?)", buffer) await db.commit() await state.update_data(buffer=[]) # Очистка буфера после сохранения await state.finish() await message.answer("*Все ваши фотографии сохранены в базу данных\.*",parse_mode="MarkdownV2", reply_markup=await start_keyboard()) async def fetch_photo(file_url): async with aiohttp.ClientSession() as session: async with session.get(file_url, ssl=False) as resp: return await resp.read() async def create_banned_users_table(): async with connect('bot.db') as db: await db.execute(""" CREATE TABLE IF NOT EXISTS banned_users ( user_id INTEGER PRIMARY KEY ) """) await db.commit() class BanUserState(StatesGroup): waiting_for_user_id = State() # Добавьте обработку команды /ban только для администраторов @dp.message_handler(commands=['ban'], user_id=ADMINS) # Замените ADMINS на список ID администраторов async def ban_user_command(message: types.Message): args = message.get_args().split() if not args or not args[0].isdigit(): await message.reply("Необходимо указать ID пользователя для блокировки: /ban 123456789") return user_id_to_ban = int(args[0]) async with connect('bot.db') as db: await db.execute("INSERT OR IGNORE INTO banned_users (user_id) VALUES (?)", (user_id_to_ban,)) await db.commit() await message.reply(f"Пользователь {user_id_to_ban} заблокирован.") # Добавьте проверку на наличие пользователя в списке заблокированных перед любым действием с ботом class CheckBanMiddleware(BaseMiddleware): async def on_process_message(self, message: types.Message, data: dict): user_id = message.from_user.id async with connect('bot.db') as db: cursor = await db.execute("SELECT user_id FROM banned_users WHERE user_id = ?", (user_id,)) is_banned = await cursor.fetchone() is not None if is_banned: admin_button = InlineKeyboardMarkup().add( InlineKeyboardButton("👨‍💻 Администратор бота", url="t.me/ih82seeucry") ) await message.answer( "*Вы заблокированы администратором бота\.* Если у вас есть вопросы \- обратитесь к администратору по кнопке ниже\.", parse_mode="MarkdownV2", reply_markup=admin_button) raise CancelHandler() # Регистрируйте middleware dp.middleware.setup(CheckBanMiddleware()) @dp.message_handler(commands=['unban'], user_id=ADMINS) # Замените ADMINS на список ID администраторов async def unban_user_command(message: types.Message): args = message.get_args().split() if not args or not args[0].isdigit(): await message.reply("Необходимо указать ID пользователя для разблокировки: /unban 123456789") return user_id_to_unban = int(args[0]) async with connect('bot.db') as db: await db.execute("DELETE FROM banned_users WHERE user_id = ?", (user_id_to_unban,)) await db.commit() await message.reply(f"Пользователь {user_id_to_unban} разблокирован.") # Use this handler to get photos from the database, apply changes, and send to the user @dp.message_handler(commands=['photos']) async def send_processed_photos(message: types.Message): user_id = message.from_user.id async with connect('bot.db') as db: cursor = await db.execute("SELECT COUNT(*) FROM userphotos WHERE user_id = ?", (user_id,)) user_photo_count = (await cursor.fetchone())[0] cursor = await db.execute("SELECT id, photo_id FROM backgrounds WHERE user_id = ?", (user_id,)) backgrounds = await cursor.fetchall() cursor = await db.execute("SELECT id, photo_id FROM userphotos WHERE user_id = ?", (user_id,)) user_photos = await cursor.fetchall() if not backgrounds or not user_photos: await message.reply("Необходимо загрузить фоновые изображения и/или креатив.") return used_background_ids = [] # Сюда будут собираться ID использованных фонов для последующего удаления media_groups = [] # Здесь будут храниться пачки изображений для отправки for user_photo in user_photos: if not backgrounds: await message.reply("Количество фонов меньше количества фотографий в креативе.") break # Если фоновых изображений недостаточно, прекращаем обработку background = backgrounds.pop(0) # Получаем первый фон из списка used_background_ids.append(background[0]) # Добавляем ID фона в список использованных processed_image_io = await apply_background(user_photo[1], background[1], padding_horizontal=100, padding_vertical=70) media_groups.append(types.InputMediaPhoto(processed_image_io)) # Если в текущей пачке 4 изображения или это последняя итерация, отправляем пачку if len(media_groups) == user_photo_count or not backgrounds: await bot.send_media_group(message.chat.id, media=media_groups) media_groups = [] # Очищаем текущую пачку для следующей # Удаляем использованные фоны из базы данных if used_background_ids: await db.executemany("DELETE FROM backgrounds WHERE id = ?", [(id,) for id in used_background_ids]) await db.commit() # Function to apply background to user photo async def apply_background(user_photo_id, background_photo_id, padding_horizontal=100, padding_vertical=70, blur_radius=5): logging.info("обработка фото") user_photo_file = await bot.get_file(user_photo_id) background_photo_file = await bot.get_file(background_photo_id) user_photo_url = bot.get_file_url(user_photo_file.file_path) background_photo_url = bot.get_file_url(background_photo_file.file_path) user_photo_data = await fetch_photo(user_photo_url) background_photo_data = await fetch_photo(background_photo_url) with Image.open(BytesIO(user_photo_data)) as user_image, Image.open(BytesIO(background_photo_data)) as background_image: user_image = user_image.convert('RGBA') background_image = background_image.convert('RGBA') background_image = background_image.filter(ImageFilter.GaussianBlur(blur_radius)) # Задаем размер фона, увеличенный на указанные отступы new_background_width = user_image.width + padding_horizontal * 2 # Слева и справа new_background_height = user_image.height + padding_vertical * 2 # Сверху и снизу background_image = background_image.resize((new_background_width, new_background_height), Image.Resampling.LANCZOS) # Готовим позицию для наложения фото пользователя на фон user_image_position = (padding_horizontal, padding_vertical) # Отступы слева и сверху # Накладываем пользовательское изображение на фон background_image.paste(user_image, user_image_position, user_image.split()[3]) # Используем альфа-канал для маски # Сохраняем во временный файл result_image_io = BytesIO() background_image.save(result_image_io, format='PNG') result_image_io.seek(0) return result_image_io @dp.message_handler(lambda message: message.text == "🖼 Замена фона") async def on_change_background_button(message: types.Message): process_message = await message.answer("*Фото обрабатываются, подождите\.\.\.*",parse_mode="MarkdownV2") user_id = message.from_user.id async with connect('bot.db') as db: # Убедитесь, что используете контекстный менеджер # Определяем, должны ли использоваться общие фоны cursor = await db.execute("SELECT use_common_backgrounds FROM users WHERE user_id = ?", (user_id,)) use_common_backgrounds = (await cursor.fetchone())[0] # В зависимости от настроек выбираем фоны if use_common_backgrounds: cursor = await db.execute("SELECT photo_id FROM common_backgrounds ORDER BY RANDOM()") else: cursor = await db.execute("SELECT photo_id FROM backgrounds WHERE user_id = ?", (user_id,)) backgrounds = await cursor.fetchall() # Получаем фотографии пользователя cursor = await db.execute("SELECT photo_id FROM userphotos WHERE user_id = ?", (user_id,)) user_photos = await cursor.fetchall() if not backgrounds or not user_photos: await message.answer("Необходимо загрузить фоновые изображения и/или креатив.") return used_background_ids = [] # Список использованных личных фонов для удаления media_groups = [] background_index = 0 for user_photo in user_photos: # Начинаем по новой сначала списка, если фонов меньше чем фото if background_index >= len(backgrounds): background_index = 0 background = backgrounds[background_index] background_index += 1 if not use_common_backgrounds: used_background_ids.append(background[0]) # Добавляем ID фона в список использованных личных фонов # Применяем фон к фотографии пользователя processed_image_io = await apply_background(user_photo[0], background[0]) media_groups.append(types.InputMediaPhoto(processed_image_io)) # Отправляем обработанные фото пользователю await bot.delete_message(chat_id=process_message.chat.id, message_id=process_message.message_id) if media_groups: await bot.send_media_group(message.chat.id, media=media_groups) async with connect('bot.db') as db: # Обновление счетчика замен фона if use_common_backgrounds: await db.execute( "UPDATE users SET common_backgrounds_count = common_backgrounds_count + 1 WHERE user_id = ?", (user_id,)) else: await db.execute( "UPDATE users SET personal_backgrounds_count = personal_backgrounds_count + 1 WHERE user_id = ?", (user_id,)) # Удаление использованных фонов if used_background_ids and not use_common_backgrounds: await db.executemany("DELETE FROM backgrounds WHERE id = ?", [(id,) for id in used_background_ids]) await db.commit() # Commit транзакции только один раз, после всех изменений await db.commit() # Init DB on startup async def on_startup(_): print("Starting bot…") await init_db() await create_banned_users_table() # Starting the bot if __name__ == '__main__': executor.start_polling(dp, skip_updates=True, on_startup=on_startup)
09a2aaa9ac7ab23336f5cf44e758eb05
{ "intermediate": 0.47120505571365356, "beginner": 0.3199944794178009, "expert": 0.20880047976970673 }
38,927
Помоги решить проблему. Личные фоны не удаляются из базы после использования, а идут по кругу. Вот код: @dp.message_handler(lambda message: message.text == "🖼 Замена фона") async def on_change_background_button(message: types.Message): process_message = await message.answer("*Фото обрабатываются, подождите\.\.\.*",parse_mode="MarkdownV2") user_id = message.from_user.id async with connect('bot.db') as db: # Убедитесь, что используете контекстный менеджер # Определяем, должны ли использоваться общие фоны cursor = await db.execute("SELECT use_common_backgrounds FROM users WHERE user_id = ?", (user_id,)) use_common_backgrounds = (await cursor.fetchone())[0] # В зависимости от настроек выбираем фоны if use_common_backgrounds: cursor = await db.execute("SELECT photo_id FROM common_backgrounds ORDER BY RANDOM()") else: cursor = await db.execute("SELECT photo_id FROM backgrounds WHERE user_id = ?", (user_id,)) backgrounds = await cursor.fetchall() # Получаем фотографии пользователя cursor = await db.execute("SELECT photo_id FROM userphotos WHERE user_id = ?", (user_id,)) user_photos = await cursor.fetchall() if not backgrounds or not user_photos: await message.answer("Необходимо загрузить фоновые изображения и/или креатив.") return used_background_ids = [] # Список использованных личных фонов для удаления media_groups = [] background_index = 0 for user_photo in user_photos: # Начинаем по новой сначала списка, если фонов меньше чем фото if background_index >= len(backgrounds): background_index = 0 background = backgrounds[background_index] background_index += 1 if not use_common_backgrounds: used_background_ids.append(background[0]) # Добавляем ID фона в список использованных личных фонов # Применяем фон к фотографии пользователя processed_image_io = await apply_background(user_photo[0], background[0]) media_groups.append(types.InputMediaPhoto(processed_image_io)) # Отправляем обработанные фото пользователю await bot.delete_message(chat_id=process_message.chat.id, message_id=process_message.message_id) if media_groups: await bot.send_media_group(message.chat.id, media=media_groups) async with connect('bot.db') as db: # Обновление счетчика замен фона if use_common_backgrounds: await db.execute( "UPDATE users SET common_backgrounds_count = common_backgrounds_count + 1 WHERE user_id = ?", (user_id,)) else: await db.execute( "UPDATE users SET personal_backgrounds_count = personal_backgrounds_count + 1 WHERE user_id = ?", (user_id,)) # Удаление использованных фонов if used_background_ids and not use_common_backgrounds: await db.executemany("DELETE FROM backgrounds WHERE id = ?", [(id,) for id in used_background_ids]) await db.commit() # Commit транзакции только один раз, после всех изменений await db.commit()
3805f461ce248fdae18615498d9a3c64
{ "intermediate": 0.3076316714286804, "beginner": 0.5657566785812378, "expert": 0.12661170959472656 }
38,928
<?php use DB\DataBaseManager; $manager = new DataBaseManager(); $artistDB = $manager->getArtistDB(); $liste_artistes = $artistDB->findAll(); $pageSize = 10; $page = isset($_GET['page']) ? intval($_GET['page']) : 1; $offset = ($page - 1) * $pageSize; $sonDB = $manager->getSonDB(); $liste_sons = $sonDB->findAll($offset, $pageSize); $genreDB = $manager->getGenreDB(); $liste_genres = $genreDB->findAll(); $utilisateurDB = $manager->getUtilisateurDB(); $liste_utilisateurs = $utilisateurDB->findAll(); $playlistDB = $manager->getPlaylistDB(); $liste_playlists = $playlistDB->findAll(); $albumDB = $manager->getAlbumDB(); $liste_albums = $albumDB->findAll(); ?> <aside> <div class="left"> <a href="index.php?action=accueil" class="btn-retour"> <svg width="26" height="16" viewBox="0 0 26 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M8.22816 1.73682L2.00009 7.96489M2.00009 7.96489L8.22816 14.193M2.00009 7.96489H24.4211" stroke="currentColor" stroke-width="2.49123" stroke-linecap="round" stroke-linejoin="round"/> </svg> Retour application </a> <nav> <ul> <li> <a href="" id="goToMenuPrincipal"> <svg width="27" height="17" viewBox="0 0 27 17" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M1.83325 1.2085H25.1666M1.83325 8.50016H25.1666M1.83325 15.7918H25.1666" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> Menu principal </a> </li> <li> <a href="" id="goToArtistes"> <svg width="30" height="23" viewBox="0 0 30 23" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M23.9866 21.7082H26.1667C27.7775 21.7082 29.1809 20.3606 28.6692 18.8332C27.8893 16.5055 25.9706 15.0979 22.5977 14.6103M18.146 9.84388C18.5703 9.97801 19.0564 10.0415 19.6042 10.0415C22.0347 10.0415 23.25 8.7915 23.25 5.6665C23.25 2.5415 22.0347 1.2915 19.6042 1.2915C19.0564 1.2915 18.5703 1.355 18.146 1.48913M10.8542 14.4165C16.6277 14.4165 19.4474 16.1838 20.1527 19.7183C20.3689 20.8015 19.4379 21.7082 18.3333 21.7082H3.375C2.27043 21.7082 1.33943 20.8015 1.5556 19.7183C2.26098 16.1838 5.08064 14.4165 10.8542 14.4165ZM10.8542 10.0415C13.2847 10.0415 14.5 8.7915 14.5 5.6665C14.5 2.5415 13.2847 1.2915 10.8542 1.2915C8.42361 1.2915 7.20833 2.5415 7.20833 5.6665C7.20833 8.7915 8.42361 10.0415 10.8542 10.0415Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> Artistes </a> </li> <li> <a href="" id="goToSons"> <svg width="29" height="29" viewBox="0 0 29 29" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M5.75 14.5C5.75 11.2613 7.50962 8.43351 10.125 6.92059M23.25 14.2123C23.25 17.451 21.4904 20.2788 18.875 21.7917M27.625 14.5C27.625 21.7487 21.7487 27.625 14.5 27.625C7.25126 27.625 1.375 21.7487 1.375 14.5C1.375 7.25126 7.25126 1.375 14.5 1.375C21.7487 1.375 27.625 7.25126 27.625 14.5ZM17.4167 14.5C17.4167 16.1108 16.1108 17.4167 14.5 17.4167C12.8892 17.4167 11.5833 16.1108 11.5833 14.5C11.5833 12.8892 12.8892 11.5833 14.5 11.5833C16.1108 11.5833 17.4167 12.8892 17.4167 14.5Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> Sons </a> </li> <li> <a href="" id="goToGenres"> <svg width="23" height="20" viewBox="0 0 23 20" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M1.29175 7.04183H15.8751M1.29175 1.2085H15.8751M1.29175 12.8752H10.0417M15.8751 12.8752V18.7085L21.7084 15.7918L15.8751 12.8752Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> Genres </a> </li> <li> <a href="" id="goToUtilisateurs"> <svg width="23" height="27" viewBox="0 0 23 27" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M18.2405 24.7722C19.8065 24.7722 21.1404 23.4819 20.7854 21.9567C19.9025 18.1628 16.9499 16.2658 11.1519 16.2658C5.35387 16.2658 2.40129 18.1628 1.51836 21.9567C1.16341 23.4819 2.49732 24.7722 4.06329 24.7722H18.2405Z" stroke="currentColor" stroke-width="2.83544" stroke-linecap="round" stroke-linejoin="round"/> <path fill-rule="evenodd" clip-rule="evenodd" d="M11.1519 12.0127C13.9873 12.0127 15.4051 10.5949 15.4051 7.05063C15.4051 3.50633 13.9873 2.08861 11.1519 2.08861C8.31645 2.08861 6.89873 3.50633 6.89873 7.05063C6.89873 10.5949 8.31645 12.0127 11.1519 12.0127Z" stroke="currentColor" stroke-width="2.83544" stroke-linecap="round" stroke-linejoin="round"/> </svg> Utilisateurs </a> </li> <li> <a href="" id="goToPlaylists"> <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M1 3C1 1.89543 1.89543 1 3 1H4C5.10457 1 6 1.89543 6 3V4C6 5.10457 5.10457 6 4 6H3C1.89543 6 1 5.10457 1 4V3Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> <path d="M10 3C10 1.89543 10.8954 1 12 1H13C14.1046 1 15 1.89543 15 3V4C15 5.10457 14.1046 6 13 6H12C10.8954 6 10 5.10457 10 4V3Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> <path d="M1 12C1 10.8954 1.89543 10 3 10H4C5.10457 10 6 10.8954 6 12V13C6 14.1046 5.10457 15 4 15H3C1.89543 15 1 14.1046 1 13V12Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> <path d="M10 12C10 10.8954 10.8954 10 12 10H13C14.1046 10 15 10.8954 15 12V13C15 14.1046 14.1046 15 13 15H12C10.8954 15 10 14.1046 10 13V12Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> Playlists </a> </li> <li> <a href="" id="goToAlbums"> <svg width="27" height="27" viewBox="0 0 27 27" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M8.8125 21.8333C8.8125 24.1345 7.06361 26 4.90625 26C2.74889 26 1 24.1345 1 21.8333C1 19.5321 2.74889 17.6667 4.90625 17.6667C7.06361 17.6667 8.8125 19.5321 8.8125 21.8333ZM8.8125 21.8333V3.57439C8.8125 3.05949 9.20349 2.62875 9.71598 2.57906L24.9035 1.10633C25.4912 1.04934 26 1.51124 26 2.10166V20.1667M26 20.1667C26 22.4679 24.2511 24.3333 22.0938 24.3333C19.9364 24.3333 18.1875 22.4679 18.1875 20.1667C18.1875 17.8655 19.9364 16 22.0938 16C24.2511 16 26 17.8655 26 20.1667Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> Albums </a> </li> </ul> <div class="active-square" id="activeSquare"></div> </nav> <div class="actions"> <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M10 6V14M14 10H6M10 19C14.9706 19 19 14.9706 19 10C19 5.02944 14.9706 1 10 1C5.02944 1 1 5.02944 1 10C1 14.9706 5.02944 19 10 19Z" stroke="#E2FF08" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> </div> </div> </aside> <div class="right"> <!-- barre de recherche --> <div id="recherche" class="wrapper-recherche"> <div class="text-field"> <img src="/Assets/icons/search.svg" alt="user"/> <input type="text" placeholder="Ma recherche" value=""> </div> </div> <div class="container-tabs"> <main> <section id="pagePrincipale" class="page"> <header> <h2>Menu principal</h2> <svg width="29" height="29" viewBox="0 0 39 39" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M37.6118 9.82166L27.9072 14.9928C32.319 9.33028 28.353 1.28109 19.1767 0V9.98935C15.8932 3.95635 6.60488 3.25634 0.923272 9.82361L10.2961 14.8173C2.99181 14.4254 -2.30948 21.4977 1.01413 29.3226L10.8413 24.0871C6.34922 29.619 9.45097 38.5008 19.1746 39V28.1059C21.8685 34.7941 32.0717 37.0091 37.5188 29.3226L27.2966 23.8766C34.9199 25.066 42.0996 18.019 37.6118 9.82361V9.82166Z" fill="#E2FF08"/> </svg> </header> <div class="menu"> <button class="admin-content"> <svg width="29" height="29" viewBox="0 0 30 23" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M23.9866 21.7082H26.1667C27.7775 21.7082 29.1809 20.3606 28.6692 18.8332C27.8893 16.5055 25.9706 15.0979 22.5977 14.6103M18.146 9.84388C18.5703 9.97801 19.0564 10.0415 19.6042 10.0415C22.0347 10.0415 23.25 8.7915 23.25 5.6665C23.25 2.5415 22.0347 1.2915 19.6042 1.2915C19.0564 1.2915 18.5703 1.355 18.146 1.48913M10.8542 14.4165C16.6277 14.4165 19.4474 16.1838 20.1527 19.7183C20.3689 20.8015 19.4379 21.7082 18.3333 21.7082H3.375C2.27043 21.7082 1.33943 20.8015 1.5556 19.7183C2.26098 16.1838 5.08064 14.4165 10.8542 14.4165ZM10.8542 10.0415C13.2847 10.0415 14.5 8.7915 14.5 5.6665C14.5 2.5415 13.2847 1.2915 10.8542 1.2915C8.42361 1.2915 7.20833 2.5415 7.20833 5.6665C7.20833 8.7915 8.42361 10.0415 10.8542 10.0415Z" stroke="#FEFCE1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> <div class="textes"> <h3>Artistes</h3> <p>Les artistes de l'application</p> </div> </button> <button class="admin-content"> <svg width="29" height="29" viewBox="0 0 29 29" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M5.75 14.5C5.75 11.2613 7.50962 8.43351 10.125 6.92059M23.25 14.2123C23.25 17.451 21.4904 20.2788 18.875 21.7917M27.625 14.5C27.625 21.7487 21.7487 27.625 14.5 27.625C7.25126 27.625 1.375 21.7487 1.375 14.5C1.375 7.25126 7.25126 1.375 14.5 1.375C21.7487 1.375 27.625 7.25126 27.625 14.5ZM17.4167 14.5C17.4167 16.1108 16.1108 17.4167 14.5 17.4167C12.8892 17.4167 11.5833 16.1108 11.5833 14.5C11.5833 12.8892 12.8892 11.5833 14.5 11.5833C16.1108 11.5833 17.4167 12.8892 17.4167 14.5Z" stroke="#FEFCE1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> <div class="textes"> <h3>Sons</h3> <p>Les sons de l'application</p> </div> </button> <button class="admin-content"> <svg width="29" height="29" viewBox="0 0 23 20" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M1.29175 7.04183H15.8751M1.29175 1.2085H15.8751M1.29175 12.8752H10.0417M15.8751 12.8752V18.7085L21.7084 15.7918L15.8751 12.8752Z" stroke="#FEFCE1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> <div class="textes"> <h3>Genres</h3> <p>Les genres de l'application</p> </div> </button> <button class="admin-content"> <svg width="29" height="29" viewBox="0 0 23 27" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M18.2405 24.7722C19.8065 24.7722 21.1404 23.4819 20.7854 21.9567C19.9025 18.1628 16.9499 16.2658 11.1519 16.2658C5.35387 16.2658 2.40129 18.1628 1.51836 21.9567C1.16341 23.4819 2.49732 24.7722 4.06329 24.7722H18.2405Z" stroke="#FEFCE1" stroke-width="2.83544" stroke-linecap="round" stroke-linejoin="round"/> <path fill-rule="evenodd" clip-rule="evenodd" d="M11.1519 12.0127C13.9873 12.0127 15.4051 10.5949 15.4051 7.05063C15.4051 3.50633 13.9873 2.08861 11.1519 2.08861C8.31645 2.08861 6.89873 3.50633 6.89873 7.05063C6.89873 10.5949 8.31645 12.0127 11.1519 12.0127Z" stroke="#FEFCE1" stroke-width="2.83544" stroke-linecap="round" stroke-linejoin="round"/> </svg> <div class="textes"> <h3>Utilisateurs</h3> <p>Les utilisateurs de l'application</p> </div> </button> <button class="admin-content"> <svg width="29" height="29" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M1 3C1 1.89543 1.89543 1 3 1H4C5.10457 1 6 1.89543 6 3V4C6 5.10457 5.10457 6 4 6H3C1.89543 6 1 5.10457 1 4V3Z" stroke="#FEFCE1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> <path d="M10 3C10 1.89543 10.8954 1 12 1H13C14.1046 1 15 1.89543 15 3V4C15 5.10457 14.1046 6 13 6H12C10.8954 6 10 5.10457 10 4V3Z" stroke="#FEFCE1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> <path d="M1 12C1 10.8954 1.89543 10 3 10H4C5.10457 10 6 10.8954 6 12V13C6 14.1046 5.10457 15 4 15H3C1.89543 15 1 14.1046 1 13V12Z" stroke="#FEFCE1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> <path d="M10 12C10 10.8954 10.8954 10 12 10H13C14.1046 10 15 10.8954 15 12V13C15 14.1046 14.1046 15 13 15H12C10.8954 15 10 14.1046 10 13V12Z" stroke="#FEFCE1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> <div class="textes"> <h3>Playlists</h3> <p>Les playlists de l'application</p> </div> </button> <button class="admin-content"> <svg width="18" height="17" viewBox="0 0 18 17" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M6 13.5C6 14.8807 4.88071 16 3.5 16C2.11929 16 1 14.8807 1 13.5C1 12.1193 2.11929 11 3.5 11C4.88071 11 6 12.1193 6 13.5ZM6 13.5V2.91321C6 2.39601 6.39439 1.96415 6.90946 1.91732L15.9095 1.09914C16.4951 1.0459 17 1.507 17 2.09503V12.5M17 12.5C17 13.8807 15.8807 15 14.5 15C13.1193 15 12 13.8807 12 12.5C12 11.1193 13.1193 10 14.5 10C15.8807 10 17 11.1193 17 12.5Z" stroke="#FEFCE1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> <div class="textes"> <h3>Albums</h3> <p>Les albums de l'application</p> </div> </button> </div> </section> <section id="pageArtistes" class="page"> <header> <h2>Artistes</h2> <svg width="29" height="29" viewBox="0 0 39 39" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M37.6118 9.82166L27.9072 14.9928C32.319 9.33028 28.353 1.28109 19.1767 0V9.98935C15.8932 3.95635 6.60488 3.25634 0.923272 9.82361L10.2961 14.8173C2.99181 14.4254 -2.30948 21.4977 1.01413 29.3226L10.8413 24.0871C6.34922 29.619 9.45097 38.5008 19.1746 39V28.1059C21.8685 34.7941 32.0717 37.0091 37.5188 29.3226L27.2966 23.8766C34.9199 25.066 42.0996 18.019 37.6118 9.82361V9.82166Z" fill="#E2FF08"/> </svg> </header> <table id="tableArtistes"> <thead> <tr> <td>ID</td> <td>Nom</td> <td>Image</td> <td>Actions</td> </tr> </thead> <tbody> <?php foreach ($liste_artistes as $artiste) : ?> <tr> <td><?= $artiste->getId() ?></td> <td><?= $artiste->getName() ?></td> <td><?= "" ?></td> <td> <button class="btn-modifier">Modifier</button> <button class="btn-supprimer">Supprimer</button> </td> </tr> <?php endforeach; ?> </tbody> </table> </section> <section id="pageSons" class="page"> <header> <h2>Sons</h2> <svg width="29" height="29" viewBox="0 0 39 39" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M37.6118 9.82166L27.9072 14.9928C32.319 9.33028 28.353 1.28109 19.1767 0V9.98935C15.8932 3.95635 6.60488 3.25634 0.923272 9.82361L10.2961 14.8173C2.99181 14.4254 -2.30948 21.4977 1.01413 29.3226L10.8413 24.0871C6.34922 29.619 9.45097 38.5008 19.1746 39V28.1059C21.8685 34.7941 32.0717 37.0091 37.5188 29.3226L27.2966 23.8766C34.9199 25.066 42.0996 18.019 37.6118 9.82361V9.82166Z" fill="#E2FF08"/> </svg> </header> <table id="tableSons"> <thead> <tr> <td>ID</td> <td>Titre</td> <td>Duree</td> <td>MP3</td> <td>Album</td> <td>NbStream</td> <td>Actions</td> </tr> </thead> <tbody> </tbody> </table> </section> <section id="pageGenres" class="page"> <header> <h2>Genres</h2> <svg width="29" height="29" viewBox="0 0 39 39" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M37.6118 9.82166L27.9072 14.9928C32.319 9.33028 28.353 1.28109 19.1767 0V9.98935C15.8932 3.95635 6.60488 3.25634 0.923272 9.82361L10.2961 14.8173C2.99181 14.4254 -2.30948 21.4977 1.01413 29.3226L10.8413 24.0871C6.34922 29.619 9.45097 38.5008 19.1746 39V28.1059C21.8685 34.7941 32.0717 37.0091 37.5188 29.3226L27.2966 23.8766C34.9199 25.066 42.0996 18.019 37.6118 9.82361V9.82166Z" fill="#E2FF08"/> </svg> </header> </section> <section id="pageUtilisateurs" class="page"> <header> <h2>Utilisateurs</h2> <svg width="29" height="29" viewBox="0 0 39 39" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M37.6118 9.82166L27.9072 14.9928C32.319 9.33028 28.353 1.28109 19.1767 0V9.98935C15.8932 3.95635 6.60488 3.25634 0.923272 9.82361L10.2961 14.8173C2.99181 14.4254 -2.30948 21.4977 1.01413 29.3226L10.8413 24.0871C6.34922 29.619 9.45097 38.5008 19.1746 39V28.1059C21.8685 34.7941 32.0717 37.0091 37.5188 29.3226L27.2966 23.8766C34.9199 25.066 42.0996 18.019 37.6118 9.82361V9.82166Z" fill="#E2FF08"/> </svg> </header> </section> <section id="pagePlaylists" class="page"> <header> <h2>Playlists</h2> <svg width="29" height="29" viewBox="0 0 39 39" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M37.6118 9.82166L27.9072 14.9928C32.319 9.33028 28.353 1.28109 19.1767 0V9.98935C15.8932 3.95635 6.60488 3.25634 0.923272 9.82361L10.2961 14.8173C2.99181 14.4254 -2.30948 21.4977 1.01413 29.3226L10.8413 24.0871C6.34922 29.619 9.45097 38.5008 19.1746 39V28.1059C21.8685 34.7941 32.0717 37.0091 37.5188 29.3226L27.2966 23.8766C34.9199 25.066 42.0996 18.019 37.6118 9.82361V9.82166Z" fill="#E2FF08"/> </svg> </header> </section> <section id="pageAlbums" class="page"> <header> <h2>Albums</h2> <svg width="29" height="29" viewBox="0 0 39 39" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M37.6118 9.82166L27.9072 14.9928C32.319 9.33028 28.353 1.28109 19.1767 0V9.98935C15.8932 3.95635 6.60488 3.25634 0.923272 9.82361L10.2961 14.8173C2.99181 14.4254 -2.30948 21.4977 1.01413 29.3226L10.8413 24.0871C6.34922 29.619 9.45097 38.5008 19.1746 39V28.1059C21.8685 34.7941 32.0717 37.0091 37.5188 29.3226L27.2966 23.8766C34.9199 25.066 42.0996 18.019 37.6118 9.82361V9.82166Z" fill="#E2FF08"/> </svg> </header> </section> </main> </div> </div> j'ai voulu lister les sons dans un tableau mais comme un son contient des fichiers mp3 ça a fait bugger la page. comment régler ce problème ?
9c3aa148987ee3ad78111b335ed0614e
{ "intermediate": 0.49464163184165955, "beginner": 0.343176007270813, "expert": 0.1621823012828827 }
38,929
hi
a0f569557313092546269576c01ad574
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
38,930
Properties Graph Production Technology
0f790674b753d25636f283460245eaeb
{ "intermediate": 0.31058403849601746, "beginner": 0.30781155824661255, "expert": 0.3816043734550476 }
38,931
I want to create auto resizing box according to text using After Effects Expressions, Text has Animator effects and I added margin option as well but now with the following scripts I have an issue of anchor point does not follow the overall size with the margin. I want the anchor point to be locked on the bottom left corner of the box. Position script: var textLayer = thisComp.layer("text"); var textRect = textLayer.sourceRectAtTime(time, false); var textLayerAnchor = textLayer.transform.anchorPoint.value; var textLayerPosition = textLayer.transform.position.value; var marginSlider = thisLayer.effect("Margin")("Slider").value; var manualDescentAdjustment = 5; // Value in pixels to manually adjust for font descent // The visual margin to add around the text var marginX = -marginSlider / 2; // Half margin for left offset var marginY = marginSlider / 2 + manualDescentAdjustment; // Half margin plus descent adjustment for bottom offset var xPos = textLayerPosition[0] + textRect.left - textLayerAnchor[0] + marginX; var yPos = textLayerPosition[1] - textLayerAnchor[1] + textRect.top + textRect.height + marginY; [xPos, yPos] Scale Script: var textLayer = thisComp.layer("text"); var textRect = textLayer.sourceRectAtTime(time, false); var rangeSelectorStart = textLayer.text.animator("Animator 1").selector("Range Selector 1").start / 100; var visibleTextWidth = textRect.width * rangeSelectorStart; var margin = thisLayer.effect("Margin")("Slider").value; var fullWidth = textRect.width + margin; var originalScale = thisLayer.transform.scale.value; var scaleX = (visibleTextWidth / fullWidth) * originalScale[0]; [scaleX, originalScale[1]] Size Script: var textLayer = thisComp.layer("text"); var textRect = textLayer.sourceRectAtTime(time, false); var marginSlider = thisLayer.effect("Margin")("Slider"); // Add the margin to the rectangle size if not using the Offset Path for the margin var widthWithMargin = textRect.width + marginSlider.value; var heightWithMargin = textRect.height + marginSlider.value; [widthWithMargin, heightWithMargin]
c74c050fb17d363f66ebef8086e48320
{ "intermediate": 0.4344214200973511, "beginner": 0.3495723009109497, "expert": 0.21600627899169922 }
38,932
Hi GPT! Are you capable to answer a batch of questions?
f891df675018f07e36086e3e0c985910
{ "intermediate": 0.37251996994018555, "beginner": 0.20722907781600952, "expert": 0.42025095224380493 }
38,933
how to make changes to game.progect file depending on the target platform for the bundle build (Defold engine)
5ff10bf083760ef4ae52f315d462326d
{ "intermediate": 0.29404211044311523, "beginner": 0.4028419852256775, "expert": 0.30311593413352966 }
38,934
which titan did captain levi defeat in AoT
1c8569901bb245fdb9576ee6c18625a3
{ "intermediate": 0.3682348132133484, "beginner": 0.2776166796684265, "expert": 0.3541485667228699 }
38,935
I want to create auto resizing box according to text using After Effects Expressions, Text has an Animator effect and I want rectangle shape box to follow it with keyframes, size and position values. In addition there is a margin option for box. The name of text layer is "text".
8ecb5e0b706c7dc85c25ab060050a8bc
{ "intermediate": 0.43605706095695496, "beginner": 0.2627842128276825, "expert": 0.30115869641304016 }
38,936
stage.set_background("winter") toby = codesters.Sprite("penguin", -200, -150) green_present = codesters.Sprite("present7", -50, -200) purple_present = codesters.Sprite("present6", 200, -150) stage.wait(1) toby.glide_to(-50, -200) def collision(sprite, hit_sprite): image = hit_sprite.get_image_name() if image == "present7": hit_sprite.say("Hooray!") stage.wait(1) stage.remove_sprite(hit_sprite) sprite.glide_to(200, -150) if image == "present6": stage.remove_sprite(sprite) toby.event_collision(collision) Collision events take two parameters, sprite and hit_sprite. The sprite refers to the sprite connected to the event handler. The hit_sprite becomes whatever the main sprite hits. Click Run and watch the stage to see what's wrong. Oops! The present should disappear, not the penguin! Fix the code so purple_present disappears by using .remove_sprite() to remove hit_sprite.
c4a06be3b47417109cc499fd1739d691
{ "intermediate": 0.4825142025947571, "beginner": 0.27544599771499634, "expert": 0.24203981459140778 }
38,937
write a script for adaptive AI on unity. Use Navicat Mesh Agent but don't use ML-Agents.
2c6a52f0882677bf7713604c85191ce4
{ "intermediate": 0.2909155488014221, "beginner": 0.10963635891675949, "expert": 0.5994481444358826 }
38,938
i need you to update my code, for the below requirement: In this graph, edges between transistor 'device nodes' and 'net nodes' may have more than one edges. in such cases their may be a overlap of two edges is occured, to avoid the the overlapping, we need to adjust edge positions if multiple edges exist between the same two nodes. edges must not be overlap, when it is connected between same 'device nodes' and 'net nodes'. Code: # Create an empty graph G = nx.MultiGraph() # Parse the netlist components = Phrase_Netlist_withincode.parse_netlist(netlist_content) # Call the function to add vertex features add_vertex_components_features(G, components) add_vertex_nets_features(G, components) # Draw the multigraph with Ve(Components) on the below and Vn(nets) on the top device_nodes = [node for node, data in G.nodes(data=True) if 'device_type' in data and data['device_type'] in ['transistor', 'passive', 'current_source', 'voltage_source']] net_nodes = [node for node, data in G.nodes(data=True) if 'device_type' in data and data['device_type'] == 'net'] # Get the positions for the bipartite layout if device_nodes and net_nodes: pos = nx.bipartite_layout(G, device_nodes, align='horizontal') else: pos = nx.spring_layout(G) # Fallback layout if no device or net nodes found # Draw nodes with labels nx.draw_networkx_nodes(G, pos, nodelist=device_nodes, node_size=1000, node_color='lightgrey') nx.draw_networkx_nodes(G, pos, nodelist=net_nodes, node_shape='s', node_size=1000, node_color='lightgrey') # Draw edges with labels for u, v, data in G.edges(data=True): edge_color = data['color'] edge_label = data['label'] nx.draw_networkx_edges(G, pos, edgelist=[(u, v)], edge_color=edge_color, width=2) nx.draw_networkx_edge_labels(G, pos, edge_labels={(u, v): edge_label}, font_color=edge_color) # Draw labels nx.draw_networkx_labels(G, pos) # Show the plot plt.axis('off') plt.show()
7edc59e466b427287f3f2631d7bc49d8
{ "intermediate": 0.3460829555988312, "beginner": 0.21535378694534302, "expert": 0.4385632872581482 }
38,940
defold engine pixel perfect android render tips
de13c458e86116787ba5d1f9c953448d
{ "intermediate": 0.29362890124320984, "beginner": 0.2520730197429657, "expert": 0.45429810881614685 }
38,941
This javascript function is giving an error - function handleBetClick() { // Deduct 5 from the purse variable purse -= 5; // Assuming you have a reference to the parent div element and the labels/buttons you want to remove var parentDiv = document.getElementById('results'); // Get reference to the parent div // Get references to both labels and radio buttons var redLabel = document.querySelector('label[for="red"]'); // Get reference to the red label var blueLabel = document.querySelector('label[for="blue"]'); // Get reference to the blue label var redRadio = document.getElementById('red'); // Get reference to the red radio button var blueRadio = document.getElementById('blue'); // Get reference to the blue radio button // Check which radio button is checked var chosenColor = ""; if (redRadio.checked) { chosenColor = "red"; } else if (blueRadio.checked) { chosenColor = "blue"; } // Write the chosen color to the results element if (chosenColor) { parentDiv.innerHTML = "You bet on " + chosenColor + " $" + purse;; } else { parentDiv.innerHTML = "Please choose a color to bet on."; } // Add the Start Race button var startRaceButton = document.createElement('button'); startRaceButton.textContent = "Start Race"; startRaceButton.setAttribute('onclick', 'handleButtonClick()'); // Set onclick event handler parentDiv.appendChild(startRaceButton); } - I think I might need to use event delegation on a parent element to handle radio button clicks
04a79e97af826c0624bafeb853d4c9ac
{ "intermediate": 0.43000900745391846, "beginner": 0.40455755591392517, "expert": 0.16543348133563995 }
38,942
In this javascript I want to add 10 to the variable purse if chosenColor = markerName at the end of the animation - var map = L.map("map").setView( [51.30972224688452, -0.2523653990087098], 16 ); L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", { attribution: "© OpenStreetMap contributors", }).addTo(map); var coordinates = [ [51.308825549058525, -0.25823790701605276], [51.30839408180202, -0.2566395279193898], [51.307656036301125, -0.25480502463921084], [51.306917978929505, -0.2529705213580371], [51.3064864937372, -0.25129948866700147], [51.306179909687216, -0.24964159973208666], [51.3062253296757, -0.24715321409433955], [51.30670223684001, -0.24606341016544775], [51.307667390936444, -0.24471931865267038], [51.30821241016443, -0.24457401146190705], [51.30964305483954, -0.24436031366209932], [51.31014263453639, -0.24454194764962267], [51.310926055380605, -0.24546828099036588], [51.311743523740404, -0.25008178428984706], [51.31306400013452, -0.2569787258762801], ]; var horsetwo = [ [51.30924537110482, -0.2583229938208831], [51.30856411139439, -0.25581644478381804], [51.307814714031, -0.25439969967663956], [51.30733781842764, -0.2530556081638622], [51.30688362753119, -0.2516388630557742], [51.306565691229196, -0.2500041571624365], [51.306474851881035, -0.24855108525656533], [51.3065202715776, -0.24738862773227766], [51.30736052785454, -0.24575392183893996], [51.307746586391005, -0.24531800026662154], [51.30860952902316, -0.2450637126837023], [51.309608705481565, -0.24477309830214722], [51.31019911770832, -0.24520901987355614], [51.31069869135118, -0.24597188262413283], [51.31278775856248, -0.25716053629662383], ]; var polyline = L.polyline(coordinates, { color: "red" }).addTo(map); var polyline2 = L.polyline(horsetwo, { color: "blue" }).addTo(map); var red = L.marker(coordinates[0]).addTo(map); red._icon.classList.add("huechange"); var marker2 = L.marker(horsetwo[0]).addTo(map); var currentIndex = 0; // Keep track of the current index var currentIndex2 = 0; // Keep track of the current index for 'horsetwo' var winnerDeclared = false; // Flag to track if winner is declared function animateMarker() { animate(red, coordinates, currentIndex, "red"); } function animateMarkerTwo() { animate(marker2, horsetwo, currentIndex2, "blue"); } function animate(red, coords, index, markerName) { var distance = red.getLatLng().distanceTo(coords[index + 1]); var minSpeed = 160; var minDuration = (distance / minSpeed) * 1000; var maxDuration = 2000; var duration = Math.random() * (maxDuration - minDuration) + minDuration; var startTime = Date.now(); function easeInOut(t) { return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t; } function animateStep() { var elapsed = Date.now() - startTime; var progress = elapsed / duration; var easedProgress = easeInOut(progress); if (progress < 1) { var currentCoord = coords[index]; var nextCoord = coords[index + 1]; var lat = currentCoord[0] + (nextCoord[0] - currentCoord[0]) * easedProgress; var lng = currentCoord[1] + (nextCoord[1] - currentCoord[1]) * easedProgress; var interpolatedLatLng = L.latLng(lat, lng); red.setLatLng(interpolatedLatLng); requestAnimationFrame(animateStep); } else { index++; if (index < coords.length - 1) { setTimeout(function () { animate(red, coords, index, markerName); }, 500); } else { if (!winnerDeclared) { winnerDeclared = true; document.getElementById("results").innerHTML = "The winner is " + markerName; } } } } animateStep(); } function handleButtonClick() { animateMarker(); animateMarkerTwo(); } var purse = 200; document.getElementById("betting").innerHTML = "$" + purse; // Function to handle radio button click event function handleRadioButtonClick() { // Check which radio button is selected var color = document.querySelector('input[name="color"]:checked').value; // Create the button element var button = document.createElement("button"); button.setAttribute("id", "bet"); button.setAttribute("onclick", "handleBetClick()"); button.textContent = "Place Bet"; // Get the 'betting' element var bettingElement = document.getElementById("betting"); // Append the button to the 'betting' element bettingElement.innerHTML = ""; // Clear previous content bettingElement.appendChild(button); // Add event listener to the newly created button button.addEventListener("click", handleBetClick); } // Add event listeners to radio buttons document.getElementById("red").addEventListener("click", handleRadioButtonClick); document.getElementById("blue").addEventListener("click", handleRadioButtonClick); document.getElementById('red').onclick = handleBetClick.bind(this); document.getElementById('blue').onclick = handleBetClick.bind(this); function handleBetClick() { // Deduct 5 from the purse variable purse -= 5; // Assuming you have a reference to the parent div element and the labels/buttons you want to remove var parentDiv = document.getElementById('results'); // Get reference to the parent div // Get references to both labels and radio buttons var redLabel = document.querySelector('label[for="red"]'); // Get reference to the red label var blueLabel = document.querySelector('label[for="blue"]'); // Get reference to the blue label var redRadio = document.getElementById('red'); // Get reference to the red radio button var blueRadio = document.getElementById('blue'); // Get reference to the blue radio button // Check which radio button is checked var chosenColor = ""; if (redRadio.checked) { chosenColor = "red"; } else if (blueRadio.checked) { chosenColor = "blue"; } // Write the chosen color to the results element if (chosenColor) { parentDiv.innerHTML = "You bet on " + chosenColor + " $" + purse; } else { parentDiv.innerHTML = "Please choose a color to bet on."; } // Add the Start Race button var startRaceButton = document.createElement('button'); startRaceButton.textContent = "Start Race"; startRaceButton.setAttribute('onclick', 'handleButtonClick()'); // Set onclick event handler parentDiv.appendChild(startRaceButton); }
29dfac2f03cc03b0035d9dd9b784a7d1
{ "intermediate": 0.31802743673324585, "beginner": 0.48432350158691406, "expert": 0.19764912128448486 }
38,943
Make an function in processing that'll detect if there is a series of 4 numbers in a row basically a connect 4 win checker. use this array. int [] r = {5, 5, 5, 1, 1, 1, 1};
189ce961461a6c7aafc0a39a536cac88
{ "intermediate": 0.355570912361145, "beginner": 0.1882389932870865, "expert": 0.4561900496482849 }
38,944
why does this javascript give the error that chosenColor is not defined - var map = L.map("map").setView( [51.30972224688452, -0.2523653990087098], 16 ); L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", { attribution: "© OpenStreetMap contributors", }).addTo(map); var coordinates = [ [51.308825549058525, -0.25823790701605276], [51.30839408180202, -0.2566395279193898], [51.307656036301125, -0.25480502463921084], [51.306917978929505, -0.2529705213580371], [51.3064864937372, -0.25129948866700147], [51.306179909687216, -0.24964159973208666], [51.3062253296757, -0.24715321409433955], [51.30670223684001, -0.24606341016544775], [51.307667390936444, -0.24471931865267038], [51.30821241016443, -0.24457401146190705], [51.30964305483954, -0.24436031366209932], [51.31014263453639, -0.24454194764962267], [51.310926055380605, -0.24546828099036588], [51.311743523740404, -0.25008178428984706], [51.31306400013452, -0.2569787258762801], ]; var horsetwo = [ [51.30924537110482, -0.2583229938208831], [51.30856411139439, -0.25581644478381804], [51.307814714031, -0.25439969967663956], [51.30733781842764, -0.2530556081638622], [51.30688362753119, -0.2516388630557742], [51.306565691229196, -0.2500041571624365], [51.306474851881035, -0.24855108525656533], [51.3065202715776, -0.24738862773227766], [51.30736052785454, -0.24575392183893996], [51.307746586391005, -0.24531800026662154], [51.30860952902316, -0.2450637126837023], [51.309608705481565, -0.24477309830214722], [51.31019911770832, -0.24520901987355614], [51.31069869135118, -0.24597188262413283], [51.31278775856248, -0.25716053629662383], ]; var polyline = L.polyline(coordinates, { color: "red" }).addTo(map); var polyline2 = L.polyline(horsetwo, { color: "blue" }).addTo(map); var red = L.marker(coordinates[0]).addTo(map); red._icon.classList.add("huechange"); var marker2 = L.marker(horsetwo[0]).addTo(map); var currentIndex = 0; // Keep track of the current index var currentIndex2 = 0; // Keep track of the current index for 'horsetwo' var winnerDeclared = false; // Flag to track if winner is declared function animateMarker() { animate(red, coordinates, currentIndex, "red"); } function animateMarkerTwo() { animate(marker2, horsetwo, currentIndex2, "blue"); } function handleButtonClick() { animateMarker(); animateMarkerTwo(); } var purse = 200; document.getElementById("betting").innerHTML = "$" + purse; // Function to handle radio button click event function handleRadioButtonClick() { // Check which radio button is selected var color = document.querySelector('input[name="color"]:checked').value; // Create the button element var button = document.createElement("button"); button.setAttribute("id", "bet"); button.setAttribute("onclick", "handleBetClick()"); button.textContent = "Place Bet"; // Get the 'betting' element var bettingElement = document.getElementById("betting"); // Append the button to the 'betting' element bettingElement.innerHTML = ""; // Clear previous content bettingElement.appendChild(button); // Add event listener to the newly created button button.addEventListener("click", handleBetClick); } // Add event listeners to radio buttons document.getElementById("red").addEventListener("click", handleRadioButtonClick); document.getElementById("blue").addEventListener("click", handleRadioButtonClick); document.getElementById('red').onclick = handleBetClick.bind(this); document.getElementById('blue').onclick = handleBetClick.bind(this); function handleBetClick() { // Deduct 5 from the purse variable purse -= 5; // Assuming you have a reference to the parent div element and the labels/buttons you want to remove var parentDiv = document.getElementById('results'); // Get reference to the parent div // Get references to both labels and radio buttons var redLabel = document.querySelector('label[for="red"]'); // Get reference to the red label var blueLabel = document.querySelector('label[for="blue"]'); // Get reference to the blue label var redRadio = document.getElementById('red'); // Get reference to the red radio button var blueRadio = document.getElementById('blue'); // Get reference to the blue radio button // Check which radio button is checked var chosenColor = ""; if (redRadio.checked) { chosenColor = "red"; } else if (blueRadio.checked) { chosenColor = "blue"; } // Write the chosen color to the results element if (chosenColor) { parentDiv.innerHTML = "You bet on " + chosenColor + " $" + purse; } else { parentDiv.innerHTML = "Please choose a color to bet on."; } // Add the Start Race button var startRaceButton = document.createElement('button'); startRaceButton.textContent = "Start Race"; startRaceButton.setAttribute('onclick', 'handleButtonClick()'); // Set onclick event handler parentDiv.appendChild(startRaceButton); } function animate(red, coords, index, markerName) { var distance = red.getLatLng().distanceTo(coords[index + 1]); var minSpeed = 160; var minDuration = (distance / minSpeed) * 1000; var maxDuration = 2000; var duration = Math.random() * (maxDuration - minDuration) + minDuration; var startTime = Date.now(); function easeInOut(t) { return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t; } function animateStep() { var elapsed = Date.now() - startTime; var progress = elapsed / duration; var easedProgress = easeInOut(progress); if (progress < 1) { var currentCoord = coords[index]; var nextCoord = coords[index + 1]; var lat = currentCoord[0] + (nextCoord[0] - currentCoord[0]) * easedProgress; var lng = currentCoord[1] + (nextCoord[1] - currentCoord[1]) * easedProgress; var interpolatedLatLng = L.latLng(lat, lng); red.setLatLng(interpolatedLatLng); requestAnimationFrame(animateStep); } else { index++; if (index < coords.length - 1) { setTimeout(function () { animate(red, coords, index, markerName); }, 500); } else { if (!winnerDeclared) { winnerDeclared = true; document.getElementById("results").innerHTML = "The winner is " + markerName; if (chosenColor === markerName) { purse += 10; document.getElementById("betting").innerHTML = "$" + purse; } } } } } animateStep(); }
0fa3a3b1a90a58ccfb20531616785081
{ "intermediate": 0.306641548871994, "beginner": 0.4022301435470581, "expert": 0.2911282777786255 }
38,945
get screen size Defold engine android build
9916195cbe3939fd02462d78eaf59450
{ "intermediate": 0.3853502869606018, "beginner": 0.2127329260110855, "expert": 0.4019167721271515 }
38,946
I am trying out a few examples to see how my model performs. I need your help to generate more examples like this. The examples must be pairs of people and you can make slight variations to the formatting of ssn and dob Person 1: { "address": "1701 Enterprise Rd, Starfleet, CA, 94101", "name": {"first_name": "William", "middle_name": "Titan", "last_name": "Riker"}, "ssn": "456-78-9012", "dob": "11/12/2335" } Person 2: { "address": "1701 Enterprise Road, Starfleet, CA, 94101", "name": {"first_name": "Will", "middle_name": "T.", "last_name": "Riker"}, "ssn": "456789012", "dob": "11/12/2335" }
1b12036ece79f9897e2dcd72d7561466
{ "intermediate": 0.34754276275634766, "beginner": 0.33940815925598145, "expert": 0.3130490779876709 }
38,947
get screen size in pixels on android platform Defold engine
4ed268cbcd7481016b5e233dadb99091
{ "intermediate": 0.38436463475227356, "beginner": 0.20589454472064972, "expert": 0.4097408354282379 }
38,948
I am trying to prompt an llm model. In doing so, I want the model to compare two people whose information would be provided in this format - Person 1: { “address”: “42 Galactic Hwy, Vogon, GD, 00101”, “name”: {“first_name”: “Arthur”, “middle_name”: “Philip”, “last_name”: “Dent”}, “ssn”: “987-65-4320”, “dob”: “03/15/2108” } Person 2: { “address”: “42 Galactic Highway, Vogon, GD, 00101”, “name”: {“first_name”: “Arthur”, “middle_name”: “P.”, “last_name”: “Dent”}, “ssn”: “987654320”, “dob”: “15/03/2108” } Here, when comparing the middle names of the two people, I want the model to assign a score of 1 if the first person's middle name is written in full while the second one's middle name field only has an initial, and they match. If the initials do not match, give it a 0
323f455db7dbf66ef3fd297ca97ba0f2
{ "intermediate": 0.2933148443698883, "beginner": 0.2192983627319336, "expert": 0.4873868525028229 }
38,949
Can you help me improve this such that the model does not output any false positives or false negatives - Middle Name: Score 1 for matching initials. Else assign a score of 0.
7998bf48737202dd180c7be79884c087
{ "intermediate": 0.18802359700202942, "beginner": 0.14422543346881866, "expert": 0.6677509546279907 }