row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
47,390
Could not locate function 'mse'. Make sure custom classes are decorated with `@keras.saving.register_keras_serializable()`. Full object config: {'module': 'keras.metrics', 'class_name': 'function', 'config': 'mse', 'registered_name': 'mse'}
5bc14aa246da2d20c6592cf1d7771d9e
{ "intermediate": 0.3062802851200104, "beginner": 0.5054958462715149, "expert": 0.18822385370731354 }
47,391
from tensorflow.keras.models import load_model # Load the pre-trained model model_y1 = load_model('snn_1142_hlp5_5m_relu_trainloss05_mae12_valloss12_mae14.h5') Could not locate function 'mse'. Make sure custom classes are decorated with `@keras.saving.register_keras_serializable()`. Full object config: {'module': 'keras.metrics', 'class_name': 'function', 'config': 'mse', 'registered_name': 'mse'}
ae4c44193dbe68502504650c8f320099
{ "intermediate": 0.3540143370628357, "beginner": 0.4212368428707123, "expert": 0.22474884986877441 }
47,392
how to train text-bison model on gcp
2123e02d28b81fe445538ba5bba22d2f
{ "intermediate": 0.08587486296892166, "beginner": 0.0880136713385582, "expert": 0.8261114954948425 }
47,393
from tensorflow.keras.models import load_model # Load the pre-trained model model_y5 = load_model('snn_1142_hlp5_5m_relu_trainloss05_mae12_valloss12_mae14.h5') error: { "name": "AttributeError", "message": "partially initialized module 'charset_normalizer' has no attribute 'md__mypyc' (most likely due to a circular import)", "stack": "--------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) File c:\\Users\\arisa\\.conda\\envs\\tf\\lib\\site-packages\\requests\\compat.py:11 10 try: ---> 11 import chardet 12 except ImportError: ModuleNotFoundError: No module named 'chardet' During handling of the above exception, another exception occurred: AttributeError Traceback (most recent call last) Cell In[9], line 1 ----> 1 from tensorflow.keras.models import load_model 3 # Load the pre-trained model 4 model_y5 = load_model('snn_1142_hlp5_5m_relu_trainloss05_mae12_valloss12_mae14.h5') File c:\\Users\\arisa\\.conda\\envs\\tf\\lib\\site-packages\\tensorflow\\__init__.py:51 49 from ._api.v2 import autograph 50 from ._api.v2 import bitwise ---> 51 from ._api.v2 import compat 52 from ._api.v2 import config 53 from ._api.v2 import data File c:\\Users\\arisa\\.conda\\envs\\tf\\lib\\site-packages\\tensorflow\\_api\\v2\\compat\\__init__.py:37 3 \"\"\"Compatibility functions. 4 5 The `tf.compat` module contains two sets of compatibility functions. (...) 32 33 \"\"\" 35 import sys as _sys ---> 37 from . import v1 38 from . import v2 39 from tensorflow.python.compat.compat import forward_compatibility_horizon File c:\\Users\\arisa\\.conda\\envs\\tf\\lib\\site-packages\\tensorflow\\_api\\v2\\compat\\v1\\__init__.py:30 28 from . import autograph 29 from . import bitwise ---> 30 from . import compat 31 from . import config 32 from . import data File c:\\Users\\arisa\\.conda\\envs\\tf\\lib\\site-packages\\tensorflow\\_api\\v2\\compat\\v1\\compat\\__init__.py:38 35 import sys as _sys 37 from . import v1 ---> 38 from . import v2 39 from tensorflow.python.compat.compat import forward_compatibility_horizon 40 from tensorflow.python.compat.compat import forward_compatible File c:\\Users\\arisa\\.conda\\envs\\tf\\lib\\site-packages\\tensorflow\\_api\\v2\\compat\\v1\\compat\\v2\\__init__.py:28 25 # pylint: disable=g-bad-import-order 27 from . import compat ---> 28 from tensorflow._api.v2.compat.v2 import __internal__ 29 from tensorflow._api.v2.compat.v2 import __operators__ 30 from tensorflow._api.v2.compat.v2 import audio File c:\\Users\\arisa\\.conda\\envs\\tf\\lib\\site-packages\\tensorflow\\_api\\v2\\compat\\v2\\__init__.py:33 31 from . import autograph 32 from . import bitwise ---> 33 from . import compat 34 from . import config 35 from . import data File c:\\Users\\arisa\\.conda\\envs\\tf\\lib\\site-packages\\tensorflow\\_api\\v2\\compat\\v2\\compat\\__init__.py:38 35 import sys as _sys 37 from . import v1 ---> 38 from . import v2 39 from tensorflow.python.compat.compat import forward_compatibility_horizon 40 from tensorflow.python.compat.compat import forward_compatible File c:\\Users\\arisa\\.conda\\envs\\tf\\lib\\site-packages\\tensorflow\\_api\\v2\\compat\\v2\\compat\\v2\\__init__.py:37 35 from tensorflow._api.v2.compat.v2 import data 36 from tensorflow._api.v2.compat.v2 import debugging ---> 37 from tensorflow._api.v2.compat.v2 import distribute 38 from tensorflow._api.v2.compat.v2 import dtypes 39 from tensorflow._api.v2.compat.v2 import errors File c:\\Users\\arisa\\.conda\\envs\\tf\\lib\\site-packages\\tensorflow\\_api\\v2\\compat\\v2\\distribute\\__init__.py:182 180 from . import cluster_resolver 181 from . import coordinator --> 182 from . import experimental 183 from tensorflow.python.distribute.collective_all_reduce_strategy import CollectiveAllReduceStrategy as MultiWorkerMirroredStrategy 184 from tensorflow.python.distribute.cross_device_ops import CrossDeviceOps File c:\\Users\\arisa\\.conda\\envs\\tf\\lib\\site-packages\\tensorflow\\_api\\v2\\compat\\v2\\distribute\\experimental\\__init__.py:10 8 from . import coordinator 9 from . import partitioners ---> 10 from . import rpc 11 from tensorflow.python.distribute.central_storage_strategy import CentralStorageStrategy 12 from tensorflow.python.distribute.collective_all_reduce_strategy import _CollectiveAllReduceStrategyExperimental as MultiWorkerMirroredStrategy File c:\\Users\\arisa\\.conda\\envs\\tf\\lib\\site-packages\\tensorflow\\_api\\v2\\compat\\v2\\distribute\\experimental\\rpc\\__init__.py:8 3 \"\"\"Public API for tf.distribute.experimental.rpc namespace. 4 \"\"\" 6 import sys as _sys ----> 8 from tensorflow.python.distribute.experimental.rpc.rpc_ops import Client 9 from tensorflow.python.distribute.experimental.rpc.rpc_ops import Server File c:\\Users\\arisa\\.conda\\envs\\tf\\lib\\site-packages\\tensorflow\\python\\distribute\\experimental\\__init__.py:22 20 from tensorflow.python.distribute import parameter_server_strategy 21 from tensorflow.python.distribute import tpu_strategy ---> 22 from tensorflow.python.distribute.failure_handling import failure_handling 23 # pylint: enable=unused-import File c:\\Users\\arisa\\.conda\\envs\\tf\\lib\\site-packages\\tensorflow\\python\\distribute\\failure_handling\\failure_handling.py:33 31 from tensorflow.python.checkpoint import checkpoint_management 32 from tensorflow.python.distribute import multi_worker_util ---> 33 from tensorflow.python.distribute.failure_handling import gce_util 34 from tensorflow.python.eager import context 35 from tensorflow.python.framework import constant_op File c:\\Users\\arisa\\.conda\\envs\\tf\\lib\\site-packages\\tensorflow\\python\\distribute\\failure_handling\\gce_util.py:20 17 import os 18 import sys ---> 20 import requests 22 from six.moves.urllib import request 23 from tensorflow.python.eager import context File c:\\Users\\arisa\\.conda\\envs\\tf\\lib\\site-packages\\requests\\__init__.py:45 41 import warnings 43 import urllib3 ---> 45 from .exceptions import RequestsDependencyWarning 47 try: 48 from charset_normalizer import __version__ as charset_normalizer_version File c:\\Users\\arisa\\.conda\\envs\\tf\\lib\\site-packages\\requests\\exceptions.py:9 1 \"\"\" 2 requests.exceptions 3 ~~~~~~~~~~~~~~~~~~~ 4 5 This module contains the set of Requests' exceptions. 6 \"\"\" 7 from urllib3.exceptions import HTTPError as BaseHTTPError ----> 9 from .compat import JSONDecodeError as CompatJSONDecodeError 12 class RequestException(IOError): 13 \"\"\"There was an ambiguous exception that occurred while handling your 14 request. 15 \"\"\" File c:\\Users\\arisa\\.conda\\envs\\tf\\lib\\site-packages\\requests\\compat.py:13 11 import chardet 12 except ImportError: ---> 13 import charset_normalizer as chardet 15 import sys 17 # ------- 18 # Pythons 19 # ------- 20 21 # Syntax sugar. File c:\\Users\\arisa\\.conda\\envs\\tf\\lib\\site-packages\\charset_normalizer\\__init__.py:23 1 \"\"\" 2 Charset-Normalizer 3 ~~~~~~~~~~~~~~ (...) 21 :license: MIT, see LICENSE for more details. 22 \"\"\" ---> 23 from charset_normalizer.api import from_fp, from_path, from_bytes, normalize 24 from charset_normalizer.legacy import detect 25 from charset_normalizer.version import __version__, VERSION File c:\\Users\\arisa\\.conda\\envs\\tf\\lib\\site-packages\\charset_normalizer\\api.py:10 7 PathLike = Union[str, 'os.PathLike[str]'] # type: ignore 9 from charset_normalizer.constant import TOO_SMALL_SEQUENCE, TOO_BIG_SEQUENCE, IANA_SUPPORTED ---> 10 from charset_normalizer.md import mess_ratio 11 from charset_normalizer.models import CharsetMatches, CharsetMatch 12 from warnings import warn AttributeError: partially initialized module 'charset_normalizer' has no attribute 'md__mypyc' (most likely due to a circular import)" }
cb6e294d59f68831eb7118edc84d0db8
{ "intermediate": 0.33923372626304626, "beginner": 0.530543327331543, "expert": 0.13022297620773315 }
47,394
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order. Example 1: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. Example 2: Input: nums = [3,2,4], target = 6 Output: [1,2] Example 3: Input: nums = [3,3], target = 6 Output: [0,1] Constraints: 2 <= nums.length <= 104 -109 <= nums[i] <= 109 -109 <= target <= 109 Only one valid answer exists. Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?
0219f519b750dd050d9bf85c82e7da8c
{ "intermediate": 0.22256533801555634, "beginner": 0.12728416919708252, "expert": 0.6501505374908447 }
47,395
hi
bd6d8ce87b54a3badcb0fe1b0fc45647
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
47,396
Привет! Response от API приведен ниже. Мне нужно написать такую программу на python, которая будет определять текущее время по UTC+05:00, день недели (week_day=1 в ответе API означает понедельник) и текущую неделю (при условии, что первый день первой недели - 28 августа 2023). После этого код должен находить в ответе текущую неделю и близжайшее занятие (по времени, т.е. если сегодня 7 утра первого дня 29 недели, то близжайшее занятие - Экология и устойчивое развитие (Green Class) в 08:00-09:20 в аудитории 9-205). Вот ответ API: [ { "index": 0, "schedule_id": 59551, "schedule_weeks": [ "", "29", "30", "32", "" ], "schedule_subject_title": "Экология и устойчивое развитие (Green Class)", "schedule_weekday_id": 1, "schedule_time_title": "08:00-09:20", "building_title": "Корпус 9", "room_title": "9-205", "comment": "", "type": "Практика (семинар)", "teacher": "Ганиева Е. С. ", "teacher_fullname": "Ганиева Екатерина Сергеевна", "teacher_id": 1460214 }, { "index": 15, "schedule_id": 73386, "schedule_weeks": [ "", "38", "39", "" ], "schedule_subject_title": "Основы компьютерного инжиниринга", "schedule_weekday_id": 2, "schedule_time_title": "08:00-09:20", "building_title": "Корпус 6", "room_title": "6-303а", "comment": "", "type": "Лабораторная работа", "teacher": "Трубин В. Д. ", "teacher_fullname": "Трубин Владислав Дмитриевич", "teacher_id": 1431312 }, { "index": 16, "schedule_id": 57914, "schedule_weeks": [ "", "21", "22", "23", "24", "25", "26", "27", "28", "29", "32", "33", "34", "35", "36", "37", "" ], "schedule_subject_title": "Техническая и вычислительная физика", "schedule_weekday_id": 2, "schedule_time_title": "08:00-09:20", "building_title": "Корпус 2", "room_title": "2-212", "comment": "", "type": "Лекция", "teacher": "Басырова Е. Р. ", "teacher_fullname": "Басырова Елена Рафаиловна", "teacher_id": 1391408 }, { "index": 29, "schedule_id": 59250, "schedule_weeks": [ "", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "34", "35", "" ], "schedule_subject_title": "Высшая математика", "schedule_weekday_id": 3, "schedule_time_title": "08:00-09:20", "building_title": "Корпус 3", "room_title": "3-202", "comment": "", "type": "Практика (семинар)", "teacher": "Нусратуллина Л. Р. ", "teacher_fullname": "Нусратуллина Лилия Ринатовна", "teacher_id": 1448012 }, { "index": 38, "schedule_id": 73322, "schedule_weeks": [ "", "35", "36", "" ], "schedule_subject_title": "Карьера: проектирование и управление", "schedule_weekday_id": 4, "schedule_time_title": "08:00-09:20", "building_title": "Корпус 5", "room_title": "5-(403+405)", "comment": "", "type": "Практика (семинар)", "teacher": "Арсланов А. Ф. ", "teacher_fullname": "Арсланов Альберт Фанзильевич", "teacher_id": 1596084 }, { "index": 49, "schedule_id": 75284, "schedule_weeks": [ "", "36", "37", "38", "39", "" ], "schedule_subject_title": "Основы компьютерного инжиниринга", "schedule_weekday_id": 6, "schedule_time_title": "08:00-09:20", "building_title": "Корпус 6", "room_title": "6-301", "comment": "", "type": "Лабораторная работа", "teacher": "Трубин В. Д. ", "teacher_fullname": "Трубин Владислав Дмитриевич", "teacher_id": 1431312 }, { "index": 54, "schedule_id": 60401, "schedule_weeks": [ "", "24", "25", "" ], "schedule_subject_title": "Человек и общество", "schedule_weekday_id": 4, "schedule_time_title": "08:00-09:20", "building_title": "Корпус 9", "room_title": "9-605", "comment": "Правоведение", "type": "Лекция", "teacher": "Иксанов Р. А. ", "teacher_id": 1448402 }, { "index": 56, "schedule_id": 66659, "schedule_weeks": [ "", "40", "" ], "schedule_subject_title": "Авиация будущего", "schedule_weekday_id": 6, "schedule_time_title": "08:00-09:20", "building_title": "Испытательный блок кафедры АД", "room_title": "2", "comment": "ЛИК", "type": "Практика (семинар)", "teacher": "Преподаватель не определён", "teacher_id": 0 }, { "index": 57, "schedule_id": 73082, "schedule_weeks": [ "", "31", "" ], "schedule_subject_title": "Основы саморазвития", "schedule_weekday_id": 6, "schedule_time_title": "08:00-09:20", "building_title": "Корпус 3", "room_title": "3-401", "comment": "", "type": "Лекция", "teacher": "Арсланов А. Ф. ", "teacher_id": 1596084 }, { "index": 58, "schedule_id": 69544, "schedule_weeks": [ "", "27", "29", "32", "33", "" ], "schedule_subject_title": "Основы саморазвития", "schedule_weekday_id": 6, "schedule_time_title": "08:00-09:20", "building_title": "Корпус 3", "room_title": "3-402", "comment": "", "type": "Лекция", "teacher": "Арсланов А. Ф. ", "teacher_id": 1596084 }, { "index": 59, "schedule_id": 73079, "schedule_weeks": [ "", "30", "" ], "schedule_subject_title": "Основы саморазвития", "schedule_weekday_id": 6, "schedule_time_title": "08:00-09:20", "building_title": "Корпус 3", "room_title": "3-415", "comment": "", "type": "Лекция", "teacher": "Арсланов А. Ф. ", "teacher_id": 1596084 }, { "index": 1, "schedule_id": 69299, "schedule_weeks": [ "", "27", "" ], "schedule_subject_title": "Человек и общество", "schedule_weekday_id": 1, "schedule_time_title": "09:35-10:55", "building_title": "Корпус 9", "room_title": "9-504", "comment": "социология", "type": "Практика (семинар)", "teacher": "Тулебаева А. А. ", "teacher_fullname": "Тулебаева Альфия Ахатовна", "teacher_id": 1391666 }, { "index": 2, "schedule_id": 68478, "schedule_weeks": [ "", "26", "" ], "schedule_subject_title": "Человек и общество", "schedule_weekday_id": 1, "schedule_time_title": "09:35-10:55", "building_title": "Корпус 9", "room_title": "9-104", "comment": "", "type": "Практика (семинар)", "teacher": "Тулебаева А. А. ", "teacher_fullname": "Тулебаева Альфия Ахатовна", "teacher_id": 1391666 }, { "index": 3, "schedule_id": 59552, "schedule_weeks": [ "", "29", "30", "32", "" ], "schedule_subject_title": "Экология и устойчивое развитие (Green Class)", "schedule_weekday_id": 1, "schedule_time_title": "09:35-10:55", "building_title": "Корпус 9", "room_title": "9-205", "comment": "", "type": "Практика (семинар)", "teacher": "Ганиева Е. С. ", "teacher_fullname": "Ганиева Екатерина Сергеевна", "teacher_id": 1460214 }, { "index": 4, "schedule_id": 72918, "schedule_weeks": [ "", "33", "" ], "schedule_subject_title": "Авиация будущего", "schedule_weekday_id": 1, "schedule_time_title": "09:35-10:55", "building_title": "Корпус 2", "room_title": "2-504", "comment": "", "type": "Практика (семинар)", "teacher": "Сахабутдинов Р. М. ", "teacher_fullname": "Сахабутдинов Ринат Масхарович", "teacher_id": 1446520 }, { "index": 17, "schedule_id": 73235, "schedule_weeks": [ "", "34", "35", "36", "37", "" ], "schedule_subject_title": "Основы проектной деятельности", "schedule_weekday_id": 2, "schedule_time_title": "09:35-10:55", "building_title": "Корпус 3", "room_title": "3-202", "comment": "", "type": "Практика (семинар)", "teacher": "Арсланов А. Ф. ", "teacher_fullname": "Арсланов Альберт Фанзильевич", "teacher_id": 1596084 }, { "index": 18, "schedule_id": 73387, "schedule_weeks": [ "", "38", "39", "" ], "schedule_subject_title": "Основы компьютерного инжиниринга", "schedule_weekday_id": 2, "schedule_time_title": "09:35-10:55", "building_title": "Корпус 6", "room_title": "6-303а", "comment": "", "type": "Лабораторная работа", "teacher": "Трубин В. Д. ", "teacher_fullname": "Трубин Владислав Дмитриевич", "teacher_id": 1431312 }, { "index": 19, "schedule_id": 71803, "schedule_weeks": [ "", "33", "" ], "schedule_subject_title": "Авиация будущего", "schedule_weekday_id": 2, "schedule_time_title": "09:35-10:55", "building_title": "Корпус 2", "room_title": "2-120", "comment": "", "type": "Практика (семинар)", "teacher": "Каменев С. И. ", "teacher_fullname": "Каменев Сергей Иванович", "teacher_id": 1393088 }, { "index": 20, "schedule_id": 57912, "schedule_weeks": [ "", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "" ], "schedule_subject_title": "Высшая математика", "schedule_weekday_id": 2, "schedule_time_title": "09:35-10:55", "building_title": "Корпус 7", "room_title": "7-401", "comment": "", "type": "Лекция", "teacher": "Нусратуллина Л. Р. ", "teacher_fullname": "Нусратуллина Лилия Ринатовна", "teacher_id": 1448012 }, { "index": 30, "schedule_id": 59255, "schedule_weeks": [ "", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "34", "35", "" ], "schedule_subject_title": "Высшая математика", "schedule_weekday_id": 3, "schedule_time_title": "09:35-10:55", "building_title": "Корпус 3", "room_title": "3-202", "comment": "", "type": "Практика (семинар)", "teacher": "Нусратуллина Л. Р. ", "teacher_fullname": "Нусратуллина Лилия Ринатовна", "teacher_id": 1448012 }, { "index": 46, "schedule_id": 57923, "schedule_weeks": [ "", "21", "24", "25", "27", "29", "30", "31", "32", "33", "34", "35", "" ], "schedule_subject_title": "Основы проектной деятельности", "schedule_weekday_id": 5, "schedule_time_title": "09:35-10:55", "building_title": "Корпус 7", "room_title": "7-406", "comment": "", "type": "Лекция", "teacher": "Матягина Т. В. ", "teacher_fullname": "Матягина Татьяна Владимировна", "teacher_id": 1392900 }, { "index": 50, "schedule_id": 75285, "schedule_weeks": [ "", "36", "37", "38", "39", "" ], "schedule_subject_title": "Основы компьютерного инжиниринга", "schedule_weekday_id": 6, "schedule_time_title": "09:35-10:55", "building_title": "Корпус 6", "room_title": "6-301", "comment": "", "type": "Лабораторная работа", "teacher": "Трубин В. Д. ", "teacher_fullname": "Трубин Владислав Дмитриевич", "teacher_id": 1431312 }, { "index": 51, "schedule_id": 57931, "schedule_weeks": [ "", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "" ], "schedule_subject_title": "История России", "schedule_weekday_id": 6, "schedule_time_title": "09:35-10:55", "building_title": "Корпус 9", "room_title": "9-501", "comment": "25,26,27 недели в ауд. 7-201", "type": "Лекция", "teacher": "Зарипов А. Я. ", "teacher_fullname": "Зарипов Айрат Янсурович", "teacher_id": 1393146 }, { "index": 55, "schedule_id": 58347, "schedule_weeks": [ "", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "38", "" ], "schedule_subject_title": "Физическая культура и спорт", "schedule_weekday_id": 4, "schedule_time_title": "09:35-10:55", "building_title": "Корпус 3 (Спортзал нижний)", "room_title": "Спортивный зал", "comment": "", "type": "Физвоспитание", "teacher": "Преподаватель не определён", "teacher_id": 0 }, { "index": 5, "schedule_id": 57904, "schedule_weeks": [ "", "22", "" ], "schedule_subject_title": "Авиация будущего", "schedule_weekday_id": 1, "schedule_time_title": "11:35-12:55", "building_title": "Корпус 7", "room_title": "7-204", "comment": "", "type": "Лекция", "teacher": "Каменев С. И. ", "teacher_fullname": "Каменев Сергей Иванович", "teacher_id": 1393088 }, { "index": 6, "schedule_id": 59553, "schedule_weeks": [ "", "33", "34", "35", "" ], "schedule_subject_title": "Экология и устойчивое развитие (Green Class)", "schedule_weekday_id": 1, "schedule_time_title": "11:35-12:55", "building_title": "Корпус 9", "room_title": "9-301", "comment": "", "type": "Практика (семинар)", "teacher": "Ганиева Е. С. ", "teacher_fullname": "Ганиева Екатерина Сергеевна", "teacher_id": 1460214 }, { "index": 7, "schedule_id": 69302, "schedule_weeks": [ "", "27", "" ], "schedule_subject_title": "Человек и общество", "schedule_weekday_id": 1, "schedule_time_title": "11:35-12:55", "building_title": "Корпус 9", "room_title": "9-504", "comment": "социология", "type": "Практика (семинар)", "teacher": "Тулебаева А. А. ", "teacher_fullname": "Тулебаева Альфия Ахатовна", "teacher_id": 1391666 }, { "index": 21, "schedule_id": 73242, "schedule_weeks": [ "", "35", "36", "37", "" ], "schedule_subject_title": "Основы проектной деятельности", "schedule_weekday_id": 2, "schedule_time_title": "11:35-12:55", "building_title": "Корпус 3", "room_title": "3-202", "comment": "", "type": "Практика (семинар)", "teacher": "Арсланов А. Ф. ", "teacher_fullname": "Арсланов Альберт Фанзильевич", "teacher_id": 1596084 }, { "index": 22, "schedule_id": 73265, "schedule_weeks": [ "", "38", "39", "" ], "schedule_subject_title": "Основы саморазвития", "schedule_weekday_id": 2, "schedule_time_title": "11:35-12:55", "building_title": "Корпус 5", "room_title": "5-404", "comment": "", "type": "Практика (семинар)", "teacher": "Арсланов А. Ф. ", "teacher_fullname": "Арсланов Альберт Фанзильевич", "teacher_id": 1596084 }, { "index": 23, "schedule_id": 65259, "schedule_weeks": [ "", "28", "29", "30", "31", "32", "33", "34", "" ], "schedule_subject_title": "Экономическая и финансовая грамотность", "schedule_weekday_id": 2, "schedule_time_title": "11:35-12:55", "building_title": "Корпус 9", "room_title": "9-507", "comment": "", "type": "Практика (семинар)", "teacher": "Ханова О. Ю. ", "teacher_fullname": "Ханова Оксана Юрьевна", "teacher_id": 1392468 }, { "index": 31, "schedule_id": 59468, "schedule_weeks": [ "", "22", "23", "25", "26", "27", "28", "29", "31", "32", "34", "35", "37", "38", "" ], "schedule_subject_title": "Техническая и вычислительная физика", "schedule_weekday_id": 3, "schedule_time_title": "11:35-12:55", "building_title": "Корпус 7", "room_title": "7-305", "comment": "", "type": "Практика (семинар)", "teacher": "Басырова Е. Р. ", "teacher_fullname": "Басырова Елена Рафаиловна", "teacher_id": 1391408 }, { "index": 39, "schedule_id": 73377, "schedule_weeks": [ "", "31", "33", "35", "39", "40", "41", "" ], "schedule_subject_title": "Основы компьютерного инжиниринга", "schedule_weekday_id": 4, "schedule_time_title": "11:35-12:55", "building_title": "Корпус 6", "room_title": "6-309", "comment": "", "type": "Лабораторная работа", "teacher": "Трубин В. Д. ", "teacher_fullname": "Трубин Владислав Дмитриевич", "teacher_id": 1431312 }, { "index": 40, "schedule_id": 57910, "schedule_weeks": [ "", "21", "23", "24", "25", "26", "27", "28", "29", "" ], "schedule_subject_title": "Экономическая и финансовая грамотность", "schedule_weekday_id": 4, "schedule_time_title": "11:35-12:55", "building_title": "Корпус 9", "room_title": "9-501", "comment": "23 неделя ауд. 7-201, 29 нед. ауд. 7-201", "type": "Лекция", "teacher": "Ханова О. Ю. ", "teacher_fullname": "Ханова Оксана Юрьевна", "teacher_id": 1392468 }, { "index": 47, "schedule_id": 57928, "schedule_weeks": [ "", "21", "22", "23", "24", "25", "27", "29", "30", "31", "32", "" ], "schedule_subject_title": "Карьера: проектирование и управление", "schedule_weekday_id": 5, "schedule_time_title": "11:35-12:55", "building_title": "Корпус 3", "room_title": "3-401", "comment": "", "type": "Лекция", "teacher": "Арсланов А. Ф. ", "teacher_fullname": "Арсланов Альберт Фанзильевич", "teacher_id": 1596084 }, { "index": 48, "schedule_id": 74540, "schedule_weeks": [ "", "36", "37", "" ], "schedule_subject_title": "История России", "schedule_weekday_id": 5, "schedule_time_title": "11:35-12:55", "building_title": "Корпус 9", "room_title": "9-103", "comment": "", "type": "Практика (семинар)", "teacher": "Зарипов А. Я. ", "teacher_fullname": "Зарипов Айрат Янсурович", "teacher_id": 1393146 }, { "index": 52, "schedule_id": 74544, "schedule_weeks": [ "", "32", "33", "34", "35", "" ], "schedule_subject_title": "Человек и общество", "schedule_weekday_id": 6, "schedule_time_title": "11:35-12:55", "building_title": "Корпус 9", "room_title": "9-407", "comment": "Правоведение", "type": "Практика (семинар)", "teacher": "Иксанов Р. А. ", "teacher_fullname": "Иксанов Радмир Аузагиевич", "teacher_id": 1448402 }, { "index": 53, "schedule_id": 60390, "schedule_weeks": [ "", "23", "24", "25", "26", "" ], "schedule_subject_title": "Человек и общество", "schedule_weekday_id": 1, "schedule_time_title": "11:35-12:55", "building_title": "Корпус 9", "room_title": "9-605", "comment": "Социология", "type": "Лекция", "teacher": "Тулебаева А. А. ", "teacher_id": 1391666 }, { "index": 8, "schedule_id": 60845, "schedule_weeks": [ "", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "" ], "schedule_subject_title": "Иностранный язык", "schedule_weekday_id": 1, "schedule_time_title": "13:10-14:30", "building_title": "Корпус 1", "room_title": "1-303", "comment": "", "type": "Практика (семинар)", "teacher": "Преподаватель не определён", "teacher_fullname": "Преподаватель не определён", "teacher_id": 0 }, { "index": 24, "schedule_id": 73267, "schedule_weeks": [ "", "38", "39", "" ], "schedule_subject_title": "Основы саморазвития", "schedule_weekday_id": 2, "schedule_time_title": "13:10-14:30", "building_title": "Корпус 5", "room_title": "5-404", "comment": "", "type": "Практика (семинар)", "teacher": "Арсланов А. Ф. ", "teacher_fullname": "Арсланов Альберт Фанзильевич", "teacher_id": 1596084 }, { "index": 25, "schedule_id": 73239, "schedule_weeks": [ "", "31", "32", "33", "34", "" ], "schedule_subject_title": "Основы проектной деятельности", "schedule_weekday_id": 2, "schedule_time_title": "13:10-14:30", "building_title": "Корпус 3", "room_title": "3-202", "comment": "", "type": "Практика (семинар)", "teacher": "Арсланов А. Ф. ", "teacher_fullname": "Арсланов Альберт Фанзильевич", "teacher_id": 1596084 }, { "index": 26, "schedule_id": 73263, "schedule_weeks": [ "", "35", "36", "37", "" ], "schedule_subject_title": "Основы саморазвития", "schedule_weekday_id": 2, "schedule_time_title": "13:10-14:30", "building_title": "Корпус 3", "room_title": "3-202", "comment": "", "type": "Практика (семинар)", "teacher": "Арсланов А. Ф. ", "teacher_fullname": "Арсланов Альберт Фанзильевич", "teacher_id": 1596084 }, { "index": 32, "schedule_id": 58161, "schedule_weeks": [ "", "23", "24", "25", "" ], "schedule_subject_title": "История России", "schedule_weekday_id": 3, "schedule_time_title": "13:10-14:30", "building_title": "Корпус 9", "room_title": "9-501", "comment": "23 нед. ауд. 7-406", "type": "Лекция", "teacher": "Зарипов А. Я. ", "teacher_fullname": "Зарипов Айрат Янсурович", "teacher_id": 1393146 }, { "index": 33, "schedule_id": 57993, "schedule_weeks": [ "", "22", "" ], "schedule_subject_title": "Экология и устойчивое развитие (Green Class)", "schedule_weekday_id": 3, "schedule_time_title": "13:10-14:30", "building_title": "Корпус 2", "room_title": "2-218", "comment": "", "type": "Лекция", "teacher": "Ганиева Е. С. ", "teacher_fullname": "Ганиева Екатерина Сергеевна", "teacher_id": 1460214 }, { "index": 34, "schedule_id": 73328, "schedule_weeks": [ "", "35", "37", "" ], "schedule_subject_title": "Карьера: проектирование и управление", "schedule_weekday_id": 3, "schedule_time_title": "13:10-14:30", "building_title": "Корпус 5", "room_title": "5-404", "comment": "", "type": "Практика (семинар)", "teacher": "Арсланов А. Ф. ", "teacher_fullname": "Арсланов Альберт Фанзильевич", "teacher_id": 1596084 }, { "index": 35, "schedule_id": 67596, "schedule_weeks": [ "", "26", "27", "" ], "schedule_subject_title": "Человек и общество", "schedule_weekday_id": 3, "schedule_time_title": "13:10-14:30", "building_title": "Корпус 7", "room_title": "7-406", "comment": "", "type": "Лекция", "teacher": "Иксанов Р. А. ", "teacher_fullname": "Иксанов Радмир Аузагиевич", "teacher_id": 1448402 }, { "index": 41, "schedule_id": 64536, "schedule_weeks": [ "", "28", "30", "32", "34", "36", "38", "" ], "schedule_subject_title": "История России", "schedule_weekday_id": 4, "schedule_time_title": "13:10-14:30", "building_title": "Корпус 7", "room_title": "7-407", "comment": "", "type": "Практика (семинар)", "teacher": "Зарипов А. Я. ", "teacher_fullname": "Зарипов Айрат Янсурович", "teacher_id": 1393146 }, { "index": 42, "schedule_id": 73383, "schedule_weeks": [ "", "31", "33", "35", "39", "40", "41", "" ], "schedule_subject_title": "Основы компьютерного инжиниринга", "schedule_weekday_id": 4, "schedule_time_title": "13:10-14:30", "building_title": "Корпус 6", "room_title": "6-309", "comment": "", "type": "Лабораторная работа", "teacher": "Трубин В. Д. ", "teacher_fullname": "Трубин Владислав Дмитриевич", "teacher_id": 1431312 }, { "index": 43, "schedule_id": 58388, "schedule_weeks": [ "", "21", "22", "23", "" ], "schedule_subject_title": "Основы компьютерного инжиниринга", "schedule_weekday_id": 4, "schedule_time_title": "13:10-14:30", "building_title": "Корпус 9", "room_title": "9-202", "comment": "", "type": "Лекция", "teacher": "Соколова А. В. ", "teacher_fullname": "Соколова Анна Васильевна", "teacher_id": 1392622 }, { "index": 44, "schedule_id": 58389, "schedule_weeks": [ "", "24", "25", "26", "" ], "schedule_subject_title": "Основы компьютерного инжиниринга", "schedule_weekday_id": 4, "schedule_time_title": "13:10-14:30", "building_title": "Корпус 9", "room_title": "9-202", "comment": "", "type": "Лекция", "teacher": "Филосова Е. И. ", "teacher_fullname": "Филосова Елена Ивановна", "teacher_id": 1392490 }, { "index": 9, "schedule_id": 60843, "schedule_weeks": [ "", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "" ], "schedule_subject_title": "Физическая культура и спорт", "schedule_weekday_id": 1, "schedule_time_title": "15:10-16:30", "building_title": "Корпус 3 (Спортзал нижний)", "room_title": "Спортивный зал", "comment": "", "type": "Физвоспитание", "teacher": "Преподаватель не определён", "teacher_fullname": "Преподаватель не определён", "teacher_id": 0 }, { "index": 10, "schedule_id": 62561, "schedule_weeks": [ "", "34", "35", "36", "37", "" ], "schedule_subject_title": "Техническая и вычислительная физика", "schedule_weekday_id": 1, "schedule_time_title": "15:10-16:30", "building_title": "Корпус 1", "room_title": "1-341", "comment": "", "type": "Лабораторная работа", "teacher": "Фрик А. А. ", "teacher_fullname": "Фрик Александра Анатольевна", "teacher_id": 1414240 }, { "index": 11, "schedule_id": 62563, "schedule_weeks": [ "", "34", "35", "36", "37", "" ], "schedule_subject_title": "Техническая и вычислительная физика", "schedule_weekday_id": 1, "schedule_time_title": "15:10-16:30", "building_title": "Корпус 1", "room_title": "1-337", "comment": "", "type": "Лабораторная работа", "teacher": "Шишкунова М. А. ", "teacher_fullname": "Шишкунова Мария Андреевна", "teacher_id": 1450594 }, { "index": 27, "schedule_id": 73240, "schedule_weeks": [ "", "31", "" ], "schedule_subject_title": "Основы проектной деятельности", "schedule_weekday_id": 2, "schedule_time_title": "15:10-16:30", "building_title": "Корпус 3", "room_title": "3-202", "comment": "", "type": "Практика (семинар)", "teacher": "Арсланов А. Ф. ", "teacher_fullname": "Арсланов Альберт Фанзильевич", "teacher_id": 1596084 }, { "index": 28, "schedule_id": 73264, "schedule_weeks": [ "", "34", "" ], "schedule_subject_title": "Основы саморазвития", "schedule_weekday_id": 2, "schedule_time_title": "15:10-16:30", "building_title": "Корпус 3", "room_title": "3-202", "comment": "", "type": "Практика (семинар)", "teacher": "Арсланов А. Ф. ", "teacher_fullname": "Арсланов Альберт Фанзильевич", "teacher_id": 1596084 }, { "index": 36, "schedule_id": 75289, "schedule_weeks": [ "", "35", "37", "" ], "schedule_subject_title": "Основы компьютерного инжиниринга", "schedule_weekday_id": 3, "schedule_time_title": "15:10-16:30", "building_title": "Корпус 6", "room_title": "6-303", "comment": "", "type": "Лабораторная работа", "teacher": "Трубин В. Д. ", "teacher_fullname": "Трубин Владислав Дмитриевич", "teacher_id": 1431312 }, { "index": 12, "schedule_id": 57905, "schedule_weeks": [ "", "23", "24", "25", "26", "27", "28", "" ], "schedule_subject_title": "Авиация будущего", "schedule_weekday_id": 1, "schedule_time_title": "16:45-18:05", "building_title": "Дистанционно", "room_title": "Асинхронно", "comment": "", "type": "Лекция", "teacher": "Каменев С. И. ", "teacher_fullname": "Каменев Сергей Иванович", "teacher_id": 1393088 }, { "index": 13, "schedule_id": 62567, "schedule_weeks": [ "", "34", "35", "36", "37", "" ], "schedule_subject_title": "Техническая и вычислительная физика", "schedule_weekday_id": 1, "schedule_time_title": "16:45-18:05", "building_title": "Корпус 1", "room_title": "1-337", "comment": "", "type": "Лабораторная работа", "teacher": "Шишкунова М. А. ", "teacher_fullname": "Шишкунова Мария Андреевна", "teacher_id": 1450594 }, { "index": 14, "schedule_id": 62562, "schedule_weeks": [ "", "34", "35", "36", "37", "" ], "schedule_subject_title": "Техническая и вычислительная физика", "schedule_weekday_id": 1, "schedule_time_title": "16:45-18:05", "building_title": "Корпус 1", "room_title": "1-341", "comment": "", "type": "Лабораторная работа", "teacher": "Фрик А. А. ", "teacher_fullname": "Фрик Александра Анатольевна", "teacher_id": 1414240 }, { "index": 37, "schedule_id": 75290, "schedule_weeks": [ "", "35", "37", "" ], "schedule_subject_title": "Основы компьютерного инжиниринга", "schedule_weekday_id": 3, "schedule_time_title": "16:45-18:05", "building_title": "Корпус 6", "room_title": "6-303", "comment": "", "type": "Лабораторная работа", "teacher": "Трубин В. Д. ", "teacher_fullname": "Трубин Владислав Дмитриевич", "teacher_id": 1431312 }, { "index": 45, "schedule_id": 57995, "schedule_weeks": [ "", "22", "23", "24", "25", "26", "27", "" ], "schedule_subject_title": "Экология и устойчивое развитие (Green Class)", "schedule_weekday_id": 4, "schedule_time_title": "18:20-19:40", "building_title": "Дистанционно", "room_title": "Асинхронно", "comment": "", "type": "Лекция", "teacher": "Ганиева Е. С. ", "teacher_fullname": "Ганиева Екатерина Сергеевна", "teacher_id": 1460214 } ]
5176c8367a4759d657363e7441387874
{ "intermediate": 0.2646268308162689, "beginner": 0.5509753227233887, "expert": 0.184397891163826 }
47,397
Привет! Помоги мне переписать код так, чтобы отображался еще и вид занятия (практика, лабораторная работа и т.д." ) и преподаватель. Вот код: import requests from datetime import datetime, timedelta import pytz url = 'https://dev.uust-time.ru/api/v/742198/schedule/0/4233/semester/232?site=uust-time' headers = { 'accept': '/', 'accept-language': 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7', 'origin': 'https://uust-time.ru', 'priority': 'u=1, i', 'referer': 'https://uust-time.ru/', 'sec-ch-ua': '"Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99"', 'sec-ch-ua-mobile': '?0', 'sec-ch-ua-platform': '"Windows"', 'sec-fetch-dest': 'empty', 'sec-fetch-mode': 'cors', 'sec-fetch-site': 'same-site', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36', } response = requests.get(url, headers=headers) if response.status_code == 200: data = response.json() tz = pytz.timezone('Etc/GMT-5') now = datetime.now(tz) start_date = datetime(2023, 8, 28, tzinfo=tz) current_week_number = (now - start_date).days // 7 + 1 week_day = (now.isoweekday() % 7) print("Текущее время:", now) print("Текущая неделя семестра:", current_week_number) print("День недели:", week_day) response = data def parse_schedule(raw_data, current_week_number, week_day): suitable_lessons = [] for item in raw_data: if str(current_week_number) in item["schedule_weeks"] and item["schedule_weekday_id"] == week_day: suitable_lessons.append(item) return suitable_lessons today_lessons = parse_schedule(response, current_week_number, week_day) def find_next_lesson(lessons, now): now_time = now.time() closest_lesson = None min_diff = timedelta.max for lesson in lessons: start_time_str = lesson["schedule_time_title"].split('-')[0] start_time = datetime.strptime(start_time_str, "%H:%M").time() if start_time >= now_time and datetime.combine(now.date(), start_time) - datetime.combine(now.date(), now_time) < min_diff: min_diff = datetime.combine(now.date(), start_time) - datetime.combine(now.date(), now_time) closest_lesson = lesson return closest_lesson next_lesson = find_next_lesson(today_lessons, now) if next_lesson: print(f"Ближайшее занятие: {next_lesson['schedule_subject_title']} в {next_lesson['schedule_time_title']}, аудитория {next_lesson['room_title']}") else: print("На сегодня занятия уже закончились или нет занятий.") Вот ответ от API: [ { "index": 0, "schedule_id": 59551, "schedule_weeks": [ "", "29", "30", "32", "" ], "schedule_subject_title": "Экология и устойчивое развитие (Green Class)", "schedule_weekday_id": 1, "schedule_time_title": "08:00-09:20", "building_title": "Корпус 9", "room_title": "9-205", "comment": "", "type": "Практика (семинар)", "teacher": "Ганиева Е. С. ", "teacher_fullname": "Ганиева Екатерина Сергеевна", "teacher_id": 1460214 }, { "index": 15, "schedule_id": 73386, "schedule_weeks": [ "", "38", "39", "" ], "schedule_subject_title": "Основы компьютерного инжиниринга", "schedule_weekday_id": 2, "schedule_time_title": "08:00-09:20", "building_title": "Корпус 6", "room_title": "6-303а", "comment": "", "type": "Лабораторная работа", "teacher": "Трубин В. Д. ", "teacher_fullname": "Трубин Владислав Дмитриевич", "teacher_id": 1431312 }, { "index": 16, "schedule_id": 57914, "schedule_weeks": [ "", "21", "22", "23", "24", "25", "26", "27", "28", "29", "32", "33", "34", "35", "36", "37", "" ], "schedule_subject_title": "Техническая и вычислительная физика", "schedule_weekday_id": 2, "schedule_time_title": "08:00-09:20", "building_title": "Корпус 2", "room_title": "2-212", "comment": "", "type": "Лекция", "teacher": "Басырова Е. Р. ", "teacher_fullname": "Басырова Елена Рафаиловна", "teacher_id": 1391408 }, { "index": 29, "schedule_id": 59250, "schedule_weeks": [ "", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "34", "35", "" ], "schedule_subject_title": "Высшая математика", "schedule_weekday_id": 3, "schedule_time_title": "08:00-09:20", "building_title": "Корпус 3", "room_title": "3-202", "comment": "", "type": "Практика (семинар)", "teacher": "Нусратуллина Л. Р. ", "teacher_fullname": "Нусратуллина Лилия Ринатовна", "teacher_id": 1448012 }, { "index": 38, "schedule_id": 73322, "schedule_weeks": [ "", "35", "36", "" ], "schedule_subject_title": "Карьера: проектирование и управление", "schedule_weekday_id": 4, "schedule_time_title": "08:00-09:20", "building_title": "Корпус 5", "room_title": "5-(403+405)", "comment": "", "type": "Практика (семинар)", "teacher": "Арсланов А. Ф. ", "teacher_fullname": "Арсланов Альберт Фанзильевич", "teacher_id": 1596084 }, { "index": 49, "schedule_id": 75284, "schedule_weeks": [ "", "36", "37", "38", "39", "" ], "schedule_subject_title": "Основы компьютерного инжиниринга", "schedule_weekday_id": 6, "schedule_time_title": "08:00-09:20", "building_title": "Корпус 6", "room_title": "6-301", "comment": "", "type": "Лабораторная работа", "teacher": "Трубин В. Д. ", "teacher_fullname": "Трубин Владислав Дмитриевич", "teacher_id": 1431312 }, { "index": 54, "schedule_id": 60401, "schedule_weeks": [ "", "24", "25", "" ], "schedule_subject_title": "Человек и общество", "schedule_weekday_id": 4, "schedule_time_title": "08:00-09:20", "building_title": "Корпус 9", "room_title": "9-605", "comment": "Правоведение", "type": "Лекция", "teacher": "Иксанов Р. А. ", "teacher_id": 1448402 }, { "index": 56, "schedule_id": 66659, "schedule_weeks": [ "", "40", "" ], "schedule_subject_title": "Авиация будущего", "schedule_weekday_id": 6, "schedule_time_title": "08:00-09:20", "building_title": "Испытательный блок кафедры АД", "room_title": "2", "comment": "ЛИК", "type": "Практика (семинар)", "teacher": "Преподаватель не определён", "teacher_id": 0 }, { "index": 57, "schedule_id": 73082, "schedule_weeks": [ "", "31", "" ], "schedule_subject_title": "Основы саморазвития", "schedule_weekday_id": 6, "schedule_time_title": "08:00-09:20", "building_title": "Корпус 3", "room_title": "3-401", "comment": "", "type": "Лекция", "teacher": "Арсланов А. Ф. ", "teacher_id": 1596084 }, { "index": 58, "schedule_id": 69544, "schedule_weeks": [ "", "27", "29", "32", "33", "" ], "schedule_subject_title": "Основы саморазвития", "schedule_weekday_id": 6, "schedule_time_title": "08:00-09:20", "building_title": "Корпус 3", "room_title": "3-402", "comment": "", "type": "Лекция", "teacher": "Арсланов А. Ф. ", "teacher_id": 1596084 }, { "index": 59, "schedule_id": 73079, "schedule_weeks": [ "", "30", "" ], "schedule_subject_title": "Основы саморазвития", "schedule_weekday_id": 6, "schedule_time_title": "08:00-09:20", "building_title": "Корпус 3", "room_title": "3-415", "comment": "", "type": "Лекция", "teacher": "Арсланов А. Ф. ", "teacher_id": 1596084 }, { "index": 1, "schedule_id": 69299, "schedule_weeks": [ "", "27", "" ], "schedule_subject_title": "Человек и общество", "schedule_weekday_id": 1, "schedule_time_title": "09:35-10:55", "building_title": "Корпус 9", "room_title": "9-504", "comment": "социология", "type": "Практика (семинар)", "teacher": "Тулебаева А. А. ", "teacher_fullname": "Тулебаева Альфия Ахатовна", "teacher_id": 1391666 }, { "index": 2, "schedule_id": 68478, "schedule_weeks": [ "", "26", "" ], "schedule_subject_title": "Человек и общество", "schedule_weekday_id": 1, "schedule_time_title": "09:35-10:55", "building_title": "Корпус 9", "room_title": "9-104", "comment": "", "type": "Практика (семинар)", "teacher": "Тулебаева А. А. ", "teacher_fullname": "Тулебаева Альфия Ахатовна", "teacher_id": 1391666 }, { "index": 3, "schedule_id": 59552, "schedule_weeks": [ "", "29", "30", "32", "" ], "schedule_subject_title": "Экология и устойчивое развитие (Green Class)", "schedule_weekday_id": 1, "schedule_time_title": "09:35-10:55", "building_title": "Корпус 9", "room_title": "9-205", "comment": "", "type": "Практика (семинар)", "teacher": "Ганиева Е. С. ", "teacher_fullname": "Ганиева Екатерина Сергеевна", "teacher_id": 1460214 }, { "index": 4, "schedule_id": 72918, "schedule_weeks": [ "", "33", "" ], "schedule_subject_title": "Авиация будущего", "schedule_weekday_id": 1, "schedule_time_title": "09:35-10:55", "building_title": "Корпус 2", "room_title": "2-504", "comment": "", "type": "Практика (семинар)", "teacher": "Сахабутдинов Р. М. ", "teacher_fullname": "Сахабутдинов Ринат Масхарович", "teacher_id": 1446520 }, { "index": 17, "schedule_id": 73235, "schedule_weeks": [ "", "34", "35", "36", "37", "" ], "schedule_subject_title": "Основы проектной деятельности", "schedule_weekday_id": 2, "schedule_time_title": "09:35-10:55", "building_title": "Корпус 3", "room_title": "3-202", "comment": "", "type": "Практика (семинар)", "teacher": "Арсланов А. Ф. ", "teacher_fullname": "Арсланов Альберт Фанзильевич", "teacher_id": 1596084 }, { "index": 18, "schedule_id": 73387, "schedule_weeks": [ "", "38", "39", "" ], "schedule_subject_title": "Основы компьютерного инжиниринга", "schedule_weekday_id": 2, "schedule_time_title": "09:35-10:55", "building_title": "Корпус 6", "room_title": "6-303а", "comment": "", "type": "Лабораторная работа", "teacher": "Трубин В. Д. ", "teacher_fullname": "Трубин Владислав Дмитриевич", "teacher_id": 1431312 }, { "index": 19, "schedule_id": 71803, "schedule_weeks": [ "", "33", "" ], "schedule_subject_title": "Авиация будущего", "schedule_weekday_id": 2, "schedule_time_title": "09:35-10:55", "building_title": "Корпус 2", "room_title": "2-120", "comment": "", "type": "Практика (семинар)", "teacher": "Каменев С. И. ", "teacher_fullname": "Каменев Сергей Иванович", "teacher_id": 1393088 }, { "index": 20, "schedule_id": 57912, "schedule_weeks": [ "", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "" ], "schedule_subject_title": "Высшая математика", "schedule_weekday_id": 2, "schedule_time_title": "09:35-10:55", "building_title": "Корпус 7", "room_title": "7-401", "comment": "", "type": "Лекция", "teacher": "Нусратуллина Л. Р. ", "teacher_fullname": "Нусратуллина Лилия Ринатовна", "teacher_id": 1448012 }, { "index": 30, "schedule_id": 59255, "schedule_weeks": [ "", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "34", "35", "" ], "schedule_subject_title": "Высшая математика", "schedule_weekday_id": 3, "schedule_time_title": "09:35-10:55", "building_title": "Корпус 3", "room_title": "3-202", "comment": "", "type": "Практика (семинар)", "teacher": "Нусратуллина Л. Р. ", "teacher_fullname": "Нусратуллина Лилия Ринатовна", "teacher_id": 1448012 }, { "index": 46, "schedule_id": 57923, "schedule_weeks": [ "", "21", "24", "25", "27", "29", "30", "31", "32", "33", "34", "35", "" ], "schedule_subject_title": "Основы проектной деятельности", "schedule_weekday_id": 5, "schedule_time_title": "09:35-10:55", "building_title": "Корпус 7", "room_title": "7-406", "comment": "", "type": "Лекция", "teacher": "Матягина Т. В. ", "teacher_fullname": "Матягина Татьяна Владимировна", "teacher_id": 1392900 }, { "index": 50, "schedule_id": 75285, "schedule_weeks": [ "", "36", "37", "38", "39", "" ], "schedule_subject_title": "Основы компьютерного инжиниринга", "schedule_weekday_id": 6, "schedule_time_title": "09:35-10:55", "building_title": "Корпус 6", "room_title": "6-301", "comment": "", "type": "Лабораторная работа", "teacher": "Трубин В. Д. ", "teacher_fullname": "Трубин Владислав Дмитриевич", "teacher_id": 1431312 }, { "index": 51, "schedule_id": 57931, "schedule_weeks": [ "", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "" ], "schedule_subject_title": "История России", "schedule_weekday_id": 6, "schedule_time_title": "09:35-10:55", "building_title": "Корпус 9", "room_title": "9-501", "comment": "25,26,27 недели в ауд. 7-201", "type": "Лекция", "teacher": "Зарипов А. Я. ", "teacher_fullname": "Зарипов Айрат Янсурович", "teacher_id": 1393146 }, { "index": 55, "schedule_id": 58347, "schedule_weeks": [ "", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "38", "" ], "schedule_subject_title": "Физическая культура и спорт", "schedule_weekday_id": 4, "schedule_time_title": "09:35-10:55", "building_title": "Корпус 3 (Спортзал нижний)", "room_title": "Спортивный зал", "comment": "", "type": "Физвоспитание", "teacher": "Преподаватель не определён", "teacher_id": 0 }, { "index": 5, "schedule_id": 57904, "schedule_weeks": [ "", "22", "" ], "schedule_subject_title": "Авиация будущего", "schedule_weekday_id": 1, "schedule_time_title": "11:35-12:55", "building_title": "Корпус 7", "room_title": "7-204", "comment": "", "type": "Лекция", "teacher": "Каменев С. И. ", "teacher_fullname": "Каменев Сергей Иванович", "teacher_id": 1393088 }, { "index": 6, "schedule_id": 59553, "schedule_weeks": [ "", "33", "34", "35", "" ], "schedule_subject_title": "Экология и устойчивое развитие (Green Class)", "schedule_weekday_id": 1, "schedule_time_title": "11:35-12:55", "building_title": "Корпус 9", "room_title": "9-301", "comment": "", "type": "Практика (семинар)", "teacher": "Ганиева Е. С. ", "teacher_fullname": "Ганиева Екатерина Сергеевна", "teacher_id": 1460214 }, { "index": 7, "schedule_id": 69302, "schedule_weeks": [ "", "27", "" ], "schedule_subject_title": "Человек и общество", "schedule_weekday_id": 1, "schedule_time_title": "11:35-12:55", "building_title": "Корпус 9", "room_title": "9-504", "comment": "социология", "type": "Практика (семинар)", "teacher": "Тулебаева А. А. ", "teacher_fullname": "Тулебаева Альфия Ахатовна", "teacher_id": 1391666 }, { "index": 21, "schedule_id": 73242, "schedule_weeks": [ "", "35", "36", "37", "" ], "schedule_subject_title": "Основы проектной деятельности", "schedule_weekday_id": 2, "schedule_time_title": "11:35-12:55", "building_title": "Корпус 3", "room_title": "3-202", "comment": "", "type": "Практика (семинар)", "teacher": "Арсланов А. Ф. ", "teacher_fullname": "Арсланов Альберт Фанзильевич", "teacher_id": 1596084 }, { "index": 22, "schedule_id": 73265, "schedule_weeks": [ "", "38", "39", "" ], "schedule_subject_title": "Основы саморазвития", "schedule_weekday_id": 2, "schedule_time_title": "11:35-12:55", "building_title": "Корпус 5", "room_title": "5-404", "comment": "", "type": "Практика (семинар)", "teacher": "Арсланов А. Ф. ", "teacher_fullname": "Арсланов Альберт Фанзильевич", "teacher_id": 1596084 }, { "index": 23, "schedule_id": 65259, "schedule_weeks": [ "", "28", "29", "30", "31", "32", "33", "34", "" ], "schedule_subject_title": "Экономическая и финансовая грамотность", "schedule_weekday_id": 2, "schedule_time_title": "11:35-12:55", "building_title": "Корпус 9", "room_title": "9-507", "comment": "", "type": "Практика (семинар)", "teacher": "Ханова О. Ю. ", "teacher_fullname": "Ханова Оксана Юрьевна", "teacher_id": 1392468 }, { "index": 31, "schedule_id": 59468, "schedule_weeks": [ "", "22", "23", "25", "26", "27", "28", "29", "31", "32", "34", "35", "37", "38", "" ], "schedule_subject_title": "Техническая и вычислительная физика", "schedule_weekday_id": 3, "schedule_time_title": "11:35-12:55", "building_title": "Корпус 7", "room_title": "7-305", "comment": "", "type": "Практика (семинар)", "teacher": "Басырова Е. Р. ", "teacher_fullname": "Басырова Елена Рафаиловна", "teacher_id": 1391408 }, { "index": 39, "schedule_id": 73377, "schedule_weeks": [ "", "31", "33", "35", "39", "40", "41", "" ], "schedule_subject_title": "Основы компьютерного инжиниринга", "schedule_weekday_id": 4, "schedule_time_title": "11:35-12:55", "building_title": "Корпус 6", "room_title": "6-309", "comment": "", "type": "Лабораторная работа", "teacher": "Трубин В. Д. ", "teacher_fullname": "Трубин Владислав Дмитриевич", "teacher_id": 1431312 }, { "index": 40, "schedule_id": 57910, "schedule_weeks": [ "", "21", "23", "24", "25", "26", "27", "28", "29", "" ], "schedule_subject_title": "Экономическая и финансовая грамотность", "schedule_weekday_id": 4, "schedule_time_title": "11:35-12:55", "building_title": "Корпус 9", "room_title": "9-501", "comment": "23 неделя ауд. 7-201, 29 нед. ауд. 7-201", "type": "Лекция", "teacher": "Ханова О. Ю. ", "teacher_fullname": "Ханова Оксана Юрьевна", "teacher_id": 1392468 }, { "index": 47, "schedule_id": 57928, "schedule_weeks": [ "", "21", "22", "23", "24", "25", "27", "29", "30", "31", "32", "" ], "schedule_subject_title": "Карьера: проектирование и управление", "schedule_weekday_id": 5, "schedule_time_title": "11:35-12:55", "building_title": "Корпус 3", "room_title": "3-401", "comment": "", "type": "Лекция", "teacher": "Арсланов А. Ф. ", "teacher_fullname": "Арсланов Альберт Фанзильевич", "teacher_id": 1596084 }, { "index": 48, "schedule_id": 74540, "schedule_weeks": [ "", "36", "37", "" ], "schedule_subject_title": "История России", "schedule_weekday_id": 5, "schedule_time_title": "11:35-12:55", "building_title": "Корпус 9", "room_title": "9-103", "comment": "", "type": "Практика (семинар)", "teacher": "Зарипов А. Я. ", "teacher_fullname": "Зарипов Айрат Янсурович", "teacher_id": 1393146 }, { "index": 52, "schedule_id": 74544, "schedule_weeks": [ "", "32", "33", "34", "35", "" ], "schedule_subject_title": "Человек и общество", "schedule_weekday_id": 6, "schedule_time_title": "11:35-12:55", "building_title": "Корпус 9", "room_title": "9-407", "comment": "Правоведение", "type": "Практика (семинар)", "teacher": "Иксанов Р. А. ", "teacher_fullname": "Иксанов Радмир Аузагиевич", "teacher_id": 1448402 }, { "index": 53, "schedule_id": 60390, "schedule_weeks": [ "", "23", "24", "25", "26", "" ], "schedule_subject_title": "Человек и общество", "schedule_weekday_id": 1, "schedule_time_title": "11:35-12:55", "building_title": "Корпус 9", "room_title": "9-605", "comment": "Социология", "type": "Лекция", "teacher": "Тулебаева А. А. ", "teacher_id": 1391666 }, { "index": 8, "schedule_id": 60845, "schedule_weeks": [ "", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "" ], "schedule_subject_title": "Иностранный язык", "schedule_weekday_id": 1, "schedule_time_title": "13:10-14:30", "building_title": "Корпус 1", "room_title": "1-303", "comment": "", "type": "Практика (семинар)", "teacher": "Преподаватель не определён", "teacher_fullname": "Преподаватель не определён", "teacher_id": 0 }, { "index": 24, "schedule_id": 73267, "schedule_weeks": [ "", "38", "39", "" ], "schedule_subject_title": "Основы саморазвития", "schedule_weekday_id": 2, "schedule_time_title": "13:10-14:30", "building_title": "Корпус 5", "room_title": "5-404", "comment": "", "type": "Практика (семинар)", "teacher": "Арсланов А. Ф. ", "teacher_fullname": "Арсланов Альберт Фанзильевич", "teacher_id": 1596084 }, { "index": 25, "schedule_id": 73239, "schedule_weeks": [ "", "31", "32", "33", "34", "" ], "schedule_subject_title": "Основы проектной деятельности", "schedule_weekday_id": 2, "schedule_time_title": "13:10-14:30", "building_title": "Корпус 3", "room_title": "3-202", "comment": "", "type": "Практика (семинар)", "teacher": "Арсланов А. Ф. ", "teacher_fullname": "Арсланов Альберт Фанзильевич", "teacher_id": 1596084 }, { "index": 26, "schedule_id": 73263, "schedule_weeks": [ "", "35", "36", "37", "" ], "schedule_subject_title": "Основы саморазвития", "schedule_weekday_id": 2, "schedule_time_title": "13:10-14:30", "building_title": "Корпус 3", "room_title": "3-202", "comment": "", "type": "Практика (семинар)", "teacher": "Арсланов А. Ф. ", "teacher_fullname": "Арсланов Альберт Фанзильевич", "teacher_id": 1596084 }, { "index": 32, "schedule_id": 58161, "schedule_weeks": [ "", "23", "24", "25", "" ], "schedule_subject_title": "История России", "schedule_weekday_id": 3, "schedule_time_title": "13:10-14:30", "building_title": "Корпус 9", "room_title": "9-501", "comment": "23 нед. ауд. 7-406", "type": "Лекция", "teacher": "Зарипов А. Я. ", "teacher_fullname": "Зарипов Айрат Янсурович", "teacher_id": 1393146 }, { "index": 33, "schedule_id": 57993, "schedule_weeks": [ "", "22", "" ], "schedule_subject_title": "Экология и устойчивое развитие (Green Class)", "schedule_weekday_id": 3, "schedule_time_title": "13:10-14:30", "building_title": "Корпус 2", "room_title": "2-218", "comment": "", "type": "Лекция", "teacher": "Ганиева Е. С. ", "teacher_fullname": "Ганиева Екатерина Сергеевна", "teacher_id": 1460214 }, { "index": 34, "schedule_id": 73328, "schedule_weeks": [ "", "35", "37", "" ], "schedule_subject_title": "Карьера: проектирование и управление", "schedule_weekday_id": 3, "schedule_time_title": "13:10-14:30", "building_title": "Корпус 5", "room_title": "5-404", "comment": "", "type": "Практика (семинар)", "teacher": "Арсланов А. Ф. ", "teacher_fullname": "Арсланов Альберт Фанзильевич", "teacher_id": 1596084 }, { "index": 35, "schedule_id": 67596, "schedule_weeks": [ "", "26", "27", "" ], "schedule_subject_title": "Человек и общество", "schedule_weekday_id": 3, "schedule_time_title": "13:10-14:30", "building_title": "Корпус 7", "room_title": "7-406", "comment": "", "type": "Лекция", "teacher": "Иксанов Р. А. ", "teacher_fullname": "Иксанов Радмир Аузагиевич", "teacher_id": 1448402 }, { "index": 41, "schedule_id": 64536, "schedule_weeks": [ "", "28", "30", "32", "34", "36", "38", "" ], "schedule_subject_title": "История России", "schedule_weekday_id": 4, "schedule_time_title": "13:10-14:30", "building_title": "Корпус 7", "room_title": "7-407", "comment": "", "type": "Практика (семинар)", "teacher": "Зарипов А. Я. ", "teacher_fullname": "Зарипов Айрат Янсурович", "teacher_id": 1393146 }, { "index": 42, "schedule_id": 73383, "schedule_weeks": [ "", "31", "33", "35", "39", "40", "41", "" ], "schedule_subject_title": "Основы компьютерного инжиниринга", "schedule_weekday_id": 4, "schedule_time_title": "13:10-14:30", "building_title": "Корпус 6", "room_title": "6-309", "comment": "", "type": "Лабораторная работа", "teacher": "Трубин В. Д. ", "teacher_fullname": "Трубин Владислав Дмитриевич", "teacher_id": 1431312 }, { "index": 43, "schedule_id": 58388, "schedule_weeks": [ "", "21", "22", "23", "" ], "schedule_subject_title": "Основы компьютерного инжиниринга", "schedule_weekday_id": 4, "schedule_time_title": "13:10-14:30", "building_title": "Корпус 9", "room_title": "9-202", "comment": "", "type": "Лекция", "teacher": "Соколова А. В. ", "teacher_fullname": "Соколова Анна Васильевна", "teacher_id": 1392622 }, { "index": 44, "schedule_id": 58389, "schedule_weeks": [ "", "24", "25", "26", "" ], "schedule_subject_title": "Основы компьютерного инжиниринга", "schedule_weekday_id": 4, "schedule_time_title": "13:10-14:30", "building_title": "Корпус 9", "room_title": "9-202", "comment": "", "type": "Лекция", "teacher": "Филосова Е. И. ", "teacher_fullname": "Филосова Елена Ивановна", "teacher_id": 1392490 }, { "index": 9, "schedule_id": 60843, "schedule_weeks": [ "", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "" ], "schedule_subject_title": "Физическая культура и спорт", "schedule_weekday_id": 1, "schedule_time_title": "15:10-16:30", "building_title": "Корпус 3 (Спортзал нижний)", "room_title": "Спортивный зал", "comment": "", "type": "Физвоспитание", "teacher": "Преподаватель не определён", "teacher_fullname": "Преподаватель не определён", "teacher_id": 0 }, { "index": 10, "schedule_id": 62561, "schedule_weeks": [ "", "34", "35", "36", "37", "" ], "schedule_subject_title": "Техническая и вычислительная физика", "schedule_weekday_id": 1, "schedule_time_title": "15:10-16:30", "building_title": "Корпус 1", "room_title": "1-341", "comment": "", "type": "Лабораторная работа", "teacher": "Фрик А. А. ", "teacher_fullname": "Фрик Александра Анатольевна", "teacher_id": 1414240 }, { "index": 11, "schedule_id": 62563, "schedule_weeks": [ "", "34", "35", "36", "37", "" ], "schedule_subject_title": "Техническая и вычислительная физика", "schedule_weekday_id": 1, "schedule_time_title": "15:10-16:30", "building_title": "Корпус 1", "room_title": "1-337", "comment": "", "type": "Лабораторная работа", "teacher": "Шишкунова М. А. ", "teacher_fullname": "Шишкунова Мария Андреевна", "teacher_id": 1450594 }, { "index": 27, "schedule_id": 73240, "schedule_weeks": [ "", "31", "" ], "schedule_subject_title": "Основы проектной деятельности", "schedule_weekday_id": 2, "schedule_time_title": "15:10-16:30", "building_title": "Корпус 3", "room_title": "3-202", "comment": "", "type": "Практика (семинар)", "teacher": "Арсланов А. Ф. ", "teacher_fullname": "Арсланов Альберт Фанзильевич", "teacher_id": 1596084 }, { "index": 28, "schedule_id": 73264, "schedule_weeks": [ "", "34", "" ], "schedule_subject_title": "Основы саморазвития", "schedule_weekday_id": 2, "schedule_time_title": "15:10-16:30", "building_title": "Корпус 3", "room_title": "3-202", "comment": "", "type": "Практика (семинар)", "teacher": "Арсланов А. Ф. ", "teacher_fullname": "Арсланов Альберт Фанзильевич", "teacher_id": 1596084 }, { "index": 36, "schedule_id": 75289, "schedule_weeks": [ "", "35", "37", "" ], "schedule_subject_title": "Основы компьютерного инжиниринга", "schedule_weekday_id": 3, "schedule_time_title": "15:10-16:30", "building_title": "Корпус 6", "room_title": "6-303", "comment": "", "type": "Лабораторная работа", "teacher": "Трубин В. Д. ", "teacher_fullname": "Трубин Владислав Дмитриевич", "teacher_id": 1431312 }, { "index": 12, "schedule_id": 57905, "schedule_weeks": [ "", "23", "24", "25", "26", "27", "28", "" ], "schedule_subject_title": "Авиация будущего", "schedule_weekday_id": 1, "schedule_time_title": "16:45-18:05", "building_title": "Дистанционно", "room_title": "Асинхронно", "comment": "", "type": "Лекция", "teacher": "Каменев С. И. ", "teacher_fullname": "Каменев Сергей Иванович", "teacher_id": 1393088 }, { "index": 13, "schedule_id": 62567, "schedule_weeks": [ "", "34", "35", "36", "37", "" ], "schedule_subject_title": "Техническая и вычислительная физика", "schedule_weekday_id": 1, "schedule_time_title": "16:45-18:05", "building_title": "Корпус 1", "room_title": "1-337", "comment": "", "type": "Лабораторная работа", "teacher": "Шишкунова М. А. ", "teacher_fullname": "Шишкунова Мария Андреевна", "teacher_id": 1450594 }, { "index": 14, "schedule_id": 62562, "schedule_weeks": [ "", "34", "35", "36", "37", "" ], "schedule_subject_title": "Техническая и вычислительная физика", "schedule_weekday_id": 1, "schedule_time_title": "16:45-18:05", "building_title": "Корпус 1", "room_title": "1-341", "comment": "", "type": "Лабораторная работа", "teacher": "Фрик А. А. ", "teacher_fullname": "Фрик Александра Анатольевна", "teacher_id": 1414240 }, { "index": 37, "schedule_id": 75290, "schedule_weeks": [ "", "35", "37", "" ], "schedule_subject_title": "Основы компьютерного инжиниринга", "schedule_weekday_id": 3, "schedule_time_title": "16:45-18:05", "building_title": "Корпус 6", "room_title": "6-303", "comment": "", "type": "Лабораторная работа", "teacher": "Трубин В. Д. ", "teacher_fullname": "Трубин Владислав Дмитриевич", "teacher_id": 1431312 }, { "index": 45, "schedule_id": 57995, "schedule_weeks": [ "", "22", "23", "24", "25", "26", "27", "" ], "schedule_subject_title": "Экология и устойчивое развитие (Green Class)", "schedule_weekday_id": 4, "schedule_time_title": "18:20-19:40", "building_title": "Дистанционно", "room_title": "Асинхронно", "comment": "", "type": "Лекция", "teacher": "Ганиева Е. С. ", "teacher_fullname": "Ганиева Екатерина Сергеевна", "teacher_id": 1460214 } ]
edee399c1aeab5f6e3a9a5c99ae1a992
{ "intermediate": 0.35738784074783325, "beginner": 0.43791770935058594, "expert": 0.2046944499015808 }
47,398
Convert the following MATLAB code to python code function[]= plot_spectrogram_automated(x, output_folder, fs, ds, N) % Downsample the signal %x1 = lowpass(x,pi/ds); x1=downsample(x,ds); fs = fs / ds; % Set window length (in samples) L = N; % Loop through the signal with overlap i = 1; while (i + L <= length(x)) % Extract segment of the signal xx = x1(i:i+L-1); % Compute spectrogram [S, F, T] = spectrogram(xx, 2^7, 2^6, 2^7, fs); % Plot and save cropped spectrogram h = figure; imagesc(T, F, 10*log10(abs(S))); % Plot in dB scale axis off; % Turn off axes set(gca,'Position',[0 0 1 1]); % Set axes position to fill the entire figure colormap jet; %colorbar; filename = sprintf('%s/spectrogram_%d.png', output_folder, i); saveas(h, filename); close(h); % Increment index with overlap i = i + 5000; end end
372675c2909e1e135e90733e44046d8f
{ "intermediate": 0.3996613025665283, "beginner": 0.35665246844291687, "expert": 0.243686243891716 }
47,399
I want to fine-tune a sentence embedding model on my own dataset. The datasets consists of 1000 (Query, Answer) pairs. I want to use the MultipleNegativesRankingLoss. Do this in Python
e685786779f7b703757b14ab52080f65
{ "intermediate": 0.31268438696861267, "beginner": 0.1283799111843109, "expert": 0.5589357018470764 }
47,400
can i call multiple model.fit( at once togheter in a jupyter notebook
00f72d122d8b882c44fd83190faf5b59
{ "intermediate": 0.32542043924331665, "beginner": 0.2724650204181671, "expert": 0.40211451053619385 }
47,401
is it possible to camm multiple model.fit in a jupyter notebook at the same time?
b65e2b3aec1a0b48242af61bf68dddb3
{ "intermediate": 0.3187093138694763, "beginner": 0.12670810520648956, "expert": 0.5545825362205505 }
47,402
def find_volume_patterns(data, pattern): conditions = pattern.split(',') volumes = data['Volume'].values opens = data['Open'].values closes = data['Close'].values highs = data['High'].values lows = data['Low'].values variable_mapping = { 'cv': volumes, 'pv': np.roll(volumes, 1), 'pv1': np.roll(volumes, 2), 'pv2': np.roll(volumes, 3), 'pv3': np.roll(volumes, 4), 'pv4': np.roll(volumes, 5), 'pv5': np.roll(volumes, 6), 'pv6': np.roll(volumes, 7), 'pv7': np.roll(volumes, 8), 'pv8': np.roll(volumes, 9), 'pv9': np.roll(volumes, 10), 'pv10': np.roll(volumes, 11), 'pv11': np.roll(volumes, 12), 'pv12': np.roll(volumes, 13), 'fv1': np.roll(volumes, -1), 'fv2': np.roll(volumes, -2), 'fv3': np.roll(volumes, -3), 'fv4': np.roll(volumes, -4), 'fv5': np.roll(volumes, -5), 'co': opens, 'cc': closes, 'fo1': np.roll(opens, -1), 'fc1': np.roll(closes, -1), 'fo2': np.roll(opens, -2), 'fc2': np.roll(closes, -2), 'fo3': np.roll(opens, -3), 'fc3': np.roll(closes, -3), 'fo4': np.roll(opens, -4), 'fc4': np.roll(closes, -4), 'fo5': np.roll(opens, -5), 'fc5': np.roll(closes, -5), 'po': np.roll(opens, 1), 'po1': np.roll(opens, 2), 'po2': np.roll(opens, 3), 'po3': np.roll(opens, 4), 'po4': np.roll(opens, 5), 'po5': np.roll(opens, 6), 'po6': np.roll(opens, 7), 'po7': np.roll(opens, 8), 'po8': np.roll(opens, 9), 'po9': np.roll(opens, 10), 'po10': np.roll(opens, 11), 'po11': np.roll(opens, 12), 'po12': np.roll(opens, 13), 'pc': np.roll(closes, 1), 'pc1': np.roll(closes, 2), 'pc2': np.roll(closes, 3), 'pc3': np.roll(closes, 4), 'pc4': np.roll(closes, 5), 'pc5': np.roll(closes, 6), 'pc6': np.roll(closes, 7), 'pc7': np.roll(closes, 8), 'pc8': np.roll(closes, 9), 'pc9': np.roll(closes, 10), 'pc10': np.roll(closes, 11), 'pc11': np.roll(closes, 12), 'pc12': np.roll(closes, 13), 'cl': lows, 'pl': np.roll(highs, 1), 'pl1': np.roll(highs, 2), 'pl2': np.roll(highs, 3), 'pl3': np.roll(highs, 4), 'pl4': np.roll(highs, 5), 'pl5': np.roll(highs, 6), 'pl6': np.roll(highs, 7), 'pl7': np.roll(highs, 8), 'pl8': np.roll(highs, 9), 'pl9': np.roll(highs, 10), 'pl10': np.roll(highs, 11), 'pl11': np.roll(highs, 12), 'pl12': np.roll(highs, 13), 'ch': highs, 'ph': np.roll(highs, 1), 'ph1': np.roll(highs, 2), 'ph2': np.roll(highs, 3), 'ph3': np.roll(highs, 4), 'ph4': np.roll(highs, 5), 'ph5': np.roll(highs, 6), 'ph6': np.roll(highs, 7), 'ph7': np.roll(highs, 8), 'ph8': np.roll(highs, 9), 'ph9': np.roll(highs, 10), 'ph10': np.roll(highs, 11), 'ph11': np.roll(highs, 12), 'ph12': np.roll(highs, 13), 'fl1': np.roll(lows, 1), 'fl2': np.roll(lows, 2), 'fl3': np.roll(lows, 3), 'fl4': np.roll(lows, 4), 'fl5': np.roll(lows, 5), 'fh1': np.roll(highs, 1), 'fh2': np.roll(highs, 2), 'fh3': np.roll(highs, 3), 'fh4': np.roll(highs, 4), 'fh5': np.roll(highs, 5) } condition_results = [] for condition in conditions: parts = condition.replace(" ", "").split('<') if len(parts) == 2: left_var, right_var = parts condition_result = variable_mapping[left_var] < variable_mapping[right_var] else: parts = condition.replace(" ", "").split('>') left_var, right_var = parts condition_result = variable_mapping[left_var] > variable_mapping[right_var] condition_results.append(condition_result) pattern_found = np.logical_and.reduce(condition_results) return data.index[pattern_found]
42af64869dab366a335cd771864bba53
{ "intermediate": 0.39493823051452637, "beginner": 0.4774254560470581, "expert": 0.12763632833957672 }
47,403
i have following code to train a model: from sklearn.model_selection import GridSearchCV from xgboost import XGBRegressor # Initialize the XGBoost model xgb_regressor = XGBRegressor(objective='reg:squarederror') # Wrap XGBoost model with MultiOutputRegressor multioutput_regressor = MultiOutputRegressor(xgb_regressor) # Define the parameter grid for XGBoost param_grid = { 'estimator__n_estimators': [200], # Number of trees 'estimator__learning_rate': [0.1], # Step size shrinkage used to prevent overfitting 'estimator__max_depth': [5], # Maximum depth of a tree # Add more parameters here based on your needs } # Initialize GridSearchCV grid_search = GridSearchCV(estimator=multioutput_regressor, param_grid=param_grid, cv=3, n_jobs=-1, verbose=2, scoring='neg_mean_squared_error') # Train the model using grid search to find the best hyperparameters grid_search.fit(X_train_scaled, Y_train_scaled) # Print the best parameters and the best score print(f"Best parameters: {grid_search.best_params_}") print(f"Best score: {grid_search.best_score_}")
ed006a087e6cc9eb735c53698aa002f7
{ "intermediate": 0.31823986768722534, "beginner": 0.10864321142435074, "expert": 0.5731168985366821 }
47,404
i have following code to train a model: from sklearn.model_selection import GridSearchCV from xgboost import XGBRegressor # Initialize the XGBoost model xgb_regressor = XGBRegressor(objective=‘reg:squarederror’) # Wrap XGBoost model with MultiOutputRegressor multioutput_regressor = MultiOutputRegressor(xgb_regressor) # Define the parameter grid for XGBoost param_grid = { ‘estimator__n_estimators’: [200], # Number of trees ‘estimator__learning_rate’: [0.1], # Step size shrinkage used to prevent overfitting ‘estimator__max_depth’: [5], # Maximum depth of a tree # Add more parameters here based on your needs } # Initialize GridSearchCV grid_search = GridSearchCV(estimator=multioutput_regressor, param_grid=param_grid, cv=3, n_jobs=-1, verbose=2, scoring=‘neg_mean_squared_error’) # Train the model using grid search to find the best hyperparameters grid_search.fit(X_train_scaled, Y_train_scaled) # Print the best parameters and the best score print(f"Best parameters: {grid_search.best_params_}“) print(f"Best score: {grid_search.best_score_}”) is it possible to make it run using gpu for faster processing?
baaad946d1713ea6a889ac6e32c24583
{ "intermediate": 0.31746017932891846, "beginner": 0.11588156223297119, "expert": 0.5666582584381104 }
47,405
I need help with coding
5b425ef8835b2cffb73d6af28737da68
{ "intermediate": 0.38154324889183044, "beginner": 0.4841824471950531, "expert": 0.13427431881427765 }
47,406
Write this in c++ n = 600851475143 nr = n while nr % 2 == 0: nr /= 2 while nr % 3 == 0: nr /= 3 i = 2 d = 5 while True: while nr % d == 0: nr /= d if d > nr: break d += 2 while nr % d == 0: nr /= d if d > nr: break d += 4 print(d)
f7522a4bc244d68383e92e1844213465
{ "intermediate": 0.23250322043895721, "beginner": 0.5413858890533447, "expert": 0.22611095011234283 }
47,407
Write this in c
5d8ca760eff0c000fa3ed38d5a7000e4
{ "intermediate": 0.28327837586402893, "beginner": 0.4303949177265167, "expert": 0.28632673621177673 }
47,408
Why do these two programs give different results
b444c47a532e9c1695302823ed4453c7
{ "intermediate": 0.2514728903770447, "beginner": 0.1988191455602646, "expert": 0.5497080087661743 }
47,409
for example i have this code: <div class="card-body"> <p class="card-text">...</p> </div> how can i code my custom css to fill card-text area?
c7f23c5c882c57a8ba55ccac1c19406f
{ "intermediate": 0.4957772195339203, "beginner": 0.22501708567142487, "expert": 0.2792057394981384 }
47,410
у меня есть подобного вида код "- --Decompiled Nodes-File 'Z:\decompiled nodes.dnf' automattically generatet from APE! --The Segments are the same as the areas. its very important for sorting. so please dont edit the DNF with Nodepad! --The numbers in the single segements are: -- PosX PosY PosZ LinkID NodeID PathWidth NodeType FlagInteger(UINT32) cars = { segment0 = { -2427.625, -2474.75, 35.75, 0, 0, 0, 1, 991234 -2350.25, -2575.625, 44.75, 2, 1, 0, 1, 991234 -2365.875, -2564.625, 43.875, 4, 2, 0, 1, 991234 -2379.75, -2552.625, 42.875, 6, 3, 0, 1, 991234 -2391.875, -2539, 41.875, 8, 4, 0, 1, 991234" - он продолжается и дальше, помимо segment0 там еще дохуя сегментов, помимо cars есть таблицы тоже с сегментами. но тут неправильный синтаксис для lua! напиши на python скрипт который будет делать чтобы каждая из строк внутри segment[0-63] закрывалась в фигурные скобки
a6fb69f47fa6aa779b4a7509f67905dc
{ "intermediate": 0.3694946765899658, "beginner": 0.33346879482269287, "expert": 0.2970365881919861 }
47,411
package main import ( "bytes" "encoding/binary" "encoding/json" "errors" "fmt" "io" "io/ioutil" "math" "net" "net/http" "net/url" "os" "path/filepath" "regexp" "sort" "strings" "time" "github.com/abema/go-mp4" "github.com/grafov/m3u8" ) const ( defaultId = "0" prefetchKey = "skd://itunes.apple.com/P000000000/s1/e1" ) var ( forbiddenNames = regexp.MustCompile(`[/\\<>:"|?*]`) ) type SampleInfo struct { data []byte duration uint32 descIndex uint32 } type SongInfo struct { r io.ReadSeeker alacParam *Alac samples []SampleInfo } func (s *SongInfo) Duration() (ret uint64) { for i := range s.samples { ret += uint64(s.samples[i].duration) } return } func (*Alac) GetType() mp4.BoxType { return BoxTypeAlac() } func fileExists(path string) (bool, error) { f, err := os.Stat(path) if err == nil { return !f.IsDir(), nil } else if os.IsNotExist(err) { return false, nil } return false, err } func writeM4a(w *mp4.Writer, info *SongInfo, meta *AutoGenerated, data []byte, trackNum, trackTotal int) error { index := trackNum - 1 { // ftyp box, err := w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeFtyp()}) if err != nil { return err } _, err = mp4.Marshal(w, &mp4.Ftyp{ MajorBrand: [4]byte{'M', '4', 'A', ' '}, MinorVersion: 0, CompatibleBrands: []mp4.CompatibleBrandElem{ {CompatibleBrand: [4]byte{'M', '4', 'A', ' '}}, {CompatibleBrand: [4]byte{'m', 'p', '4', '2'}}, {CompatibleBrand: mp4.BrandISOM()}, {CompatibleBrand: [4]byte{0, 0, 0, 0}}, }, }, box.Context) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } const chunkSize uint32 = 5 duration := info.Duration() numSamples := uint32(len(info.samples)) var stco *mp4.BoxInfo { // moov _, err := w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeMoov()}) if err != nil { return err } box, err := mp4.ExtractBox(info.r, nil, mp4.BoxPath{mp4.BoxTypeMoov()}) if err != nil { return err } moovOri := box[0] { // mvhd _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeMvhd()}) if err != nil { return err } oriBox, err := mp4.ExtractBoxWithPayload(info.r, moovOri, mp4.BoxPath{mp4.BoxTypeMvhd()}) if err != nil { return err } mvhd := oriBox[0].Payload.(*mp4.Mvhd) if mvhd.Version == 0 { mvhd.DurationV0 = uint32(duration) } else { mvhd.DurationV1 = duration } _, err = mp4.Marshal(w, mvhd, oriBox[0].Info.Context) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } { // trak _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeTrak()}) if err != nil { return err } box, err := mp4.ExtractBox(info.r, moovOri, mp4.BoxPath{mp4.BoxTypeTrak()}) if err != nil { return err } trakOri := box[0] { // tkhd _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeTkhd()}) if err != nil { return err } oriBox, err := mp4.ExtractBoxWithPayload(info.r, trakOri, mp4.BoxPath{mp4.BoxTypeTkhd()}) if err != nil { return err } tkhd := oriBox[0].Payload.(*mp4.Tkhd) if tkhd.Version == 0 { tkhd.DurationV0 = uint32(duration) } else { tkhd.DurationV1 = duration } tkhd.SetFlags(0x7) _, err = mp4.Marshal(w, tkhd, oriBox[0].Info.Context) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } { // mdia _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeMdia()}) if err != nil { return err } box, err := mp4.ExtractBox(info.r, trakOri, mp4.BoxPath{mp4.BoxTypeMdia()}) if err != nil { return err } mdiaOri := box[0] { // mdhd _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeMdhd()}) if err != nil { return err } oriBox, err := mp4.ExtractBoxWithPayload(info.r, mdiaOri, mp4.BoxPath{mp4.BoxTypeMdhd()}) if err != nil { return err } mdhd := oriBox[0].Payload.(*mp4.Mdhd) if mdhd.Version == 0 { mdhd.DurationV0 = uint32(duration) } else { mdhd.DurationV1 = duration } _, err = mp4.Marshal(w, mdhd, oriBox[0].Info.Context) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } { // hdlr oriBox, err := mp4.ExtractBox(info.r, mdiaOri, mp4.BoxPath{mp4.BoxTypeHdlr()}) if err != nil { return err } err = w.CopyBox(info.r, oriBox[0]) if err != nil { return err } } { // minf _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeMinf()}) if err != nil { return err } box, err := mp4.ExtractBox(info.r, mdiaOri, mp4.BoxPath{mp4.BoxTypeMinf()}) if err != nil { return err } minfOri := box[0] { // smhd, dinf boxes, err := mp4.ExtractBoxes(info.r, minfOri, []mp4.BoxPath{ {mp4.BoxTypeSmhd()}, {mp4.BoxTypeDinf()}, }) if err != nil { return err } for _, b := range boxes { err = w.CopyBox(info.r, b) if err != nil { return err } } } { // stbl _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeStbl()}) if err != nil { return err } { // stsd box, err := w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeStsd()}) if err != nil { return err } _, err = mp4.Marshal(w, &mp4.Stsd{EntryCount: 1}, box.Context) if err != nil { return err } { // alac _, err = w.StartBox(&mp4.BoxInfo{Type: BoxTypeAlac()}) if err != nil { return err } _, err = w.Write([]byte{ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}) if err != nil { return err } err = binary.Write(w, binary.BigEndian, uint16(info.alacParam.NumChannels)) if err != nil { return err } err = binary.Write(w, binary.BigEndian, uint16(info.alacParam.BitDepth)) if err != nil { return err } _, err = w.Write([]byte{0, 0}) if err != nil { return err } err = binary.Write(w, binary.BigEndian, info.alacParam.SampleRate) if err != nil { return err } _, err = w.Write([]byte{0, 0}) if err != nil { return err } box, err := w.StartBox(&mp4.BoxInfo{Type: BoxTypeAlac()}) if err != nil { return err } _, err = mp4.Marshal(w, info.alacParam, box.Context) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } _, err = w.EndBox() if err != nil { return err } } { // stts box, err := w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeStts()}) if err != nil { return err } var stts mp4.Stts for _, sample := range info.samples { if len(stts.Entries) != 0 { last := &stts.Entries[len(stts.Entries)-1] if last.SampleDelta == sample.duration { last.SampleCount++ continue } } stts.Entries = append(stts.Entries, mp4.SttsEntry{ SampleCount: 1, SampleDelta: sample.duration, }) } stts.EntryCount = uint32(len(stts.Entries)) _, err = mp4.Marshal(w, &stts, box.Context) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } { // stsc box, err := w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeStsc()}) if err != nil { return err } if numSamples%chunkSize == 0 { _, err = mp4.Marshal(w, &mp4.Stsc{ EntryCount: 1, Entries: []mp4.StscEntry{ { FirstChunk: 1, SamplesPerChunk: chunkSize, SampleDescriptionIndex: 1, }, }, }, box.Context) } else { _, err = mp4.Marshal(w, &mp4.Stsc{ EntryCount: 2, Entries: []mp4.StscEntry{ { FirstChunk: 1, SamplesPerChunk: chunkSize, SampleDescriptionIndex: 1, }, { FirstChunk: numSamples/chunkSize + 1, SamplesPerChunk: numSamples % chunkSize, SampleDescriptionIndex: 1, }, }, }, box.Context) } _, err = w.EndBox() if err != nil { return err } } { // stsz box, err := w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeStsz()}) if err != nil { return err } stsz := mp4.Stsz{SampleCount: numSamples} for _, sample := range info.samples { stsz.EntrySize = append(stsz.EntrySize, uint32(len(sample.data))) } _, err = mp4.Marshal(w, &stsz, box.Context) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } { // stco box, err := w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeStco()}) if err != nil { return err } l := (numSamples + chunkSize - 1) / chunkSize _, err = mp4.Marshal(w, &mp4.Stco{ EntryCount: l, ChunkOffset: make([]uint32, l), }, box.Context) stco, err = w.EndBox() if err != nil { return err } } _, err = w.EndBox() if err != nil { return err } } _, err = w.EndBox() if err != nil { return err } } _, err = w.EndBox() if err != nil { return err } } _, err = w.EndBox() if err != nil { return err } } { // udta ctx := mp4.Context{UnderUdta: true} _, err := w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeUdta(), Context: ctx}) if err != nil { return err } { // meta ctx.UnderIlstMeta = true _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeMeta(), Context: ctx}) if err != nil { return err } _, err = mp4.Marshal(w, &mp4.Meta{}, ctx) if err != nil { return err } { // hdlr _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeHdlr(), Context: ctx}) if err != nil { return err } _, err = mp4.Marshal(w, &mp4.Hdlr{ HandlerType: [4]byte{'m', 'd', 'i', 'r'}, Reserved: [3]uint32{0x6170706c, 0, 0}, }, ctx) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } { // ilst ctx.UnderIlst = true _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeIlst(), Context: ctx}) if err != nil { return err } marshalData := func(val interface{}) error { _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeData()}) if err != nil { return err } var boxData mp4.Data switch v := val.(type) { case string: boxData.DataType = mp4.DataTypeStringUTF8 boxData.Data = []byte(v) case uint8: boxData.DataType = mp4.DataTypeSignedIntBigEndian boxData.Data = []byte{v} case uint32: boxData.DataType = mp4.DataTypeSignedIntBigEndian boxData.Data = make([]byte, 4) binary.BigEndian.PutUint32(boxData.Data, v) case []byte: boxData.DataType = mp4.DataTypeBinary boxData.Data = v default: panic("unsupported value") } _, err = mp4.Marshal(w, &boxData, ctx) if err != nil { return err } _, err = w.EndBox() return err } addMeta := func(tag mp4.BoxType, val interface{}) error { _, err = w.StartBox(&mp4.BoxInfo{Type: tag}) if err != nil { return err } err = marshalData(val) if err != nil { return err } _, err = w.EndBox() return err } addExtendedMeta := func(name string, val interface{}) error { ctx.UnderIlstFreeMeta = true _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxType{'-', '-', '-', '-'}, Context: ctx}) if err != nil { return err } { _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxType{'m', 'e', 'a', 'n'}, Context: ctx}) if err != nil { return err } _, err = w.Write([]byte{0, 0, 0, 0}) if err != nil { return err } _, err = io.WriteString(w, "com.apple.iTunes") if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } { _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxType{'n', 'a', 'm', 'e'}, Context: ctx}) if err != nil { return err } _, err = w.Write([]byte{0, 0, 0, 0}) if err != nil { return err } _, err = io.WriteString(w, name) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } err = marshalData(val) if err != nil { return err } ctx.UnderIlstFreeMeta = false _, err = w.EndBox() return err } err = addMeta(mp4.BoxType{'\251', 'n', 'a', 'm'}, meta.Data[0].Relationships.Tracks.Data[index].Attributes.Name) if err != nil { return err } err = addMeta(mp4.BoxType{'\251', 'a', 'l', 'b'}, meta.Data[0].Attributes.Name) if err != nil { return err } err = addMeta(mp4.BoxType{'\251', 'A', 'R', 'T'}, meta.Data[0].Relationships.Tracks.Data[index].Attributes.ArtistName) if err != nil { return err } err = addMeta(mp4.BoxType{'\251', 'w', 'r', 't'}, meta.Data[0].Relationships.Tracks.Data[index].Attributes.ComposerName) if err != nil { return err } err = addMeta(mp4.BoxType{'\251', 'd', 'a', 'y'}, strings.Split(meta.Data[0].Attributes.ReleaseDate, "-")[0]) if err != nil { return err } // cnID, err := strconv.ParseUint(meta.Data[0].Relationships.Tracks.Data[index].ID, 10, 32) // if err != nil { // return err // } // err = addMeta(mp4.BoxType{'c', 'n', 'I', 'D'}, uint32(cnID)) // if err != nil { // return err // } err = addExtendedMeta("ISRC", meta.Data[0].Relationships.Tracks.Data[index].Attributes.Isrc) if err != nil { return err } if len(meta.Data[0].Relationships.Tracks.Data[index].Attributes.GenreNames) > 0 { err = addMeta(mp4.BoxType{'\251', 'g', 'e', 'n'}, meta.Data[0].Relationships.Tracks.Data[index].Attributes.GenreNames[0]) if err != nil { return err } } if len(meta.Data) > 0 { album := meta.Data[0] err = addMeta(mp4.BoxType{'a', 'A', 'R', 'T'}, album.Attributes.ArtistName) if err != nil { return err } err = addMeta(mp4.BoxType{'c', 'p', 'r', 't'}, album.Attributes.Copyright) if err != nil { return err } var isCpil uint8 if album.Attributes.IsCompilation { isCpil = 1 } err = addMeta(mp4.BoxType{'c', 'p', 'i', 'l'}, isCpil) if err != nil { return err } err = addExtendedMeta("LABEL", album.Attributes.RecordLabel) if err != nil { return err } err = addExtendedMeta("UPC", album.Attributes.Upc) if err != nil { return err } // plID, err := strconv.ParseUint(album.ID, 10, 32) // if err != nil { // return err // } // err = addMeta(mp4.BoxType{'p', 'l', 'I', 'D'}, uint32(plID)) // if err != nil { // return err // } } // if len(meta.Data[0].Relationships.Artists.Data) > 0 { // atID, err := strconv.ParseUint(meta.Data[0].Relationships.Artists.Data[index].ID, 10, 32) // if err != nil { // return err // } // err = addMeta(mp4.BoxType{'a', 't', 'I', 'D'}, uint32(atID)) // if err != nil { // return err // } // } trkn := make([]byte, 8) binary.BigEndian.PutUint32(trkn, uint32(trackNum)) binary.BigEndian.PutUint16(trkn[4:], uint16(trackTotal)) err = addMeta(mp4.BoxType{'t', 'r', 'k', 'n'}, trkn) if err != nil { return err } // disk := make([]byte, 8) // binary.BigEndian.PutUint32(disk, uint32(meta.Attributes.DiscNumber)) // err = addMeta(mp4.BoxType{'d', 'i', 's', 'k'}, disk) // if err != nil { // return err // } ctx.UnderIlst = false _, err = w.EndBox() if err != nil { return err } } ctx.UnderIlstMeta = false _, err = w.EndBox() if err != nil { return err } } ctx.UnderUdta = false _, err = w.EndBox() if err != nil { return err } } _, err = w.EndBox() if err != nil { return err } } { box, err := w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeMdat()}) if err != nil { return err } _, err = mp4.Marshal(w, &mp4.Mdat{Data: data}, box.Context) if err != nil { return err } mdat, err := w.EndBox() var realStco mp4.Stco offset := mdat.Offset + mdat.HeaderSize for i := uint32(0); i < numSamples; i++ { if i%chunkSize == 0 { realStco.EntryCount++ realStco.ChunkOffset = append(realStco.ChunkOffset, uint32(offset)) } offset += uint64(len(info.samples[i].data)) } _, err = stco.SeekToPayload(w) if err != nil { return err } _, err = mp4.Marshal(w, &realStco, box.Context) if err != nil { return err } } return nil } func decryptSong(info *SongInfo, keys []string, manifest *AutoGenerated, filename string, trackNum, trackTotal int) error { //fmt.Printf("%d-bit / %d Hz\n", info.bitDepth, info.bitRate) conn, err := net.Dial("tcp", "127.0.0.1:10020") if err != nil { return err } defer conn.Close() var decrypted []byte var lastIndex uint32 = math.MaxUint8 fmt.Println("Decrypt start.") for _, sp := range info.samples { if lastIndex != sp.descIndex { if len(decrypted) != 0 { _, err := conn.Write([]byte{0, 0, 0, 0}) if err != nil { return err } } keyUri := keys[sp.descIndex] id := manifest.Data[0].Relationships.Tracks.Data[trackNum-1].ID if keyUri == prefetchKey { id = defaultId } _, err := conn.Write([]byte{byte(len(id))}) if err != nil { return err } _, err = io.WriteString(conn, id) if err != nil { return err } _, err = conn.Write([]byte{byte(len(keyUri))}) if err != nil { return err } _, err = io.WriteString(conn, keyUri) if err != nil { return err } } lastIndex = sp.descIndex err := binary.Write(conn, binary.LittleEndian, uint32(len(sp.data))) if err != nil { return err } _, err = conn.Write(sp.data) if err != nil { return err } de := make([]byte, len(sp.data)) _, err = io.ReadFull(conn, de) if err != nil { return err } decrypted = append(decrypted, de...) } _, _ = conn.Write([]byte{0, 0, 0, 0, 0}) fmt.Println("Decrypt finished.") create, err := os.Create(filename) if err != nil { return err } defer create.Close() return writeM4a(mp4.NewWriter(create), info, manifest, decrypted, trackNum, trackTotal) } func checkUrl(url string) (string, string) { pat := regexp.MustCompile(`^(?:https:\/\/(?:beta\.music|music)\.apple\.com\/(\w{2})(?:\/album|\/album\/.+))\/(?:id)?(\d[^\D]+)(?:$|\?)`) matches := pat.FindAllStringSubmatch(url, -1) if matches == nil { return "", "" } else { return matches[0][1], matches[0][2] } } func getMeta(albumId string, token string, storefront string) (*AutoGenerated, error) { req, err := http.NewRequest("GET", fmt.Sprintf("https://amp-api.music.apple.com/v1/catalog/%s/albums/%s", storefront, albumId), nil) if err != nil { return nil, err } req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token)) req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36") req.Header.Set("Origin", "https://music.apple.com") query := url.Values{} query.Set("omit[resource]", "autos") query.Set("include", "tracks,artists,record-labels") query.Set("include[songs]", "artists") query.Set("fields[artists]", "name") query.Set("fields[albums:albums]", "artistName,artwork,name,releaseDate,url") query.Set("fields[record-labels]", "name") // query.Set("l", "en-gb") req.URL.RawQuery = query.Encode() do, err := http.DefaultClient.Do(req) if err != nil { return nil, err } defer do.Body.Close() if do.StatusCode != http.StatusOK { return nil, errors.New(do.Status) } obj := new(AutoGenerated) err = json.NewDecoder(do.Body).Decode(&obj) if err != nil { return nil, err } return obj, nil } func writeCover(sanAlbumFolder, url string) error { covPath := filepath.Join(sanAlbumFolder, "cover.jpg") exists, err := fileExists(covPath) if err != nil { fmt.Println("Failed to check if cover exists.") return err } if exists { return nil } url = strings.Replace(url, "{w}x{h}", "1200x12000", 1) req, err := http.NewRequest("GET", url, nil) if err != nil { return err } req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36") do, err := http.DefaultClient.Do(req) if err != nil { return err } defer do.Body.Close() if do.StatusCode != http.StatusOK { errors.New(do.Status) } f, err := os.Create(covPath) if err != nil { return err } defer f.Close() _, err = io.Copy(f, do.Body) if err != nil { return err } return nil } func rip(albumId string, token string, storefront string) error { meta, err := getMeta(albumId, token, storefront) if err != nil { fmt.Println("Failed to get album metadata.\n") return err } albumFolder := fmt.Sprintf("%s - %s", meta.Data[0].Attributes.ArtistName, meta.Data[0].Attributes.Name) sanAlbumFolder := filepath.Join("AM-DL downloads", forbiddenNames.ReplaceAllString(albumFolder, "_")) os.MkdirAll(sanAlbumFolder, os.ModePerm) fmt.Println(albumFolder) err = writeCover(sanAlbumFolder, meta.Data[0].Attributes.Artwork.URL) if err != nil { fmt.Println("Failed to write cover.") } trackTotal := len(meta.Data[0].Relationships.Tracks.Data) for trackNum, track := range meta.Data[0].Relationships.Tracks.Data { trackNum++ fmt.Printf("Track %d of %d:\n", trackNum, trackTotal) manifest, err := getInfoFromAdam(track.ID, token, storefront) if err != nil { fmt.Println("Failed to get manifest.\n", err) continue } if manifest.Attributes.ExtendedAssetUrls.EnhancedHls == "" { fmt.Println("Unavailable in ALAC.") continue } filename := fmt.Sprintf("%02d. %s.m4a", trackNum, forbiddenNames.ReplaceAllString(track.Attributes.Name, "_")) trackPath := filepath.Join(sanAlbumFolder, filename) exists, err := fileExists(trackPath) if err != nil { fmt.Println("Failed to check if track exists.") } if exists { fmt.Println("Track already exists locally.") continue } trackUrl, keys, err := extractMedia(manifest.Attributes.ExtendedAssetUrls.EnhancedHls) if err != nil { fmt.Println("Failed to extract info from manifest.\n", err) continue } info, err := extractSong(trackUrl) if err != nil { fmt.Println("Failed to extract track.", err) continue } samplesOk := true for samplesOk { for _, i := range info.samples { if int(i.descIndex) >= len(keys) { fmt.Println("Decryption size mismatch.") samplesOk = false } } break } if !samplesOk { continue } err = decryptSong(info, keys, meta, trackPath, trackNum, trackTotal) if err != nil { fmt.Println("Failed to decrypt track.\n", err) continue } } return err } func main() { token, err := getToken() if err != nil { fmt.Println("Failed to get token.") return } albumTotal := len(os.Args[1:]) for albumNum, url := range os.Args[1:] { fmt.Printf("Album %d of %d:\n", albumNum+1, albumTotal) storefront, albumId := checkUrl(url) if albumId == "" { fmt.Printf("Invalid URL: %s\n", url) continue } err := rip(albumId, token, storefront) if err != nil { fmt.Println("Album failed.") fmt.Println(err) } } } func extractMedia(b string) (string, []string, error) { masterUrl, err := url.Parse(b) if err != nil { return "", nil, err } resp, err := http.Get(b) if err != nil { return "", nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return "", nil, errors.New(resp.Status) } body, err := io.ReadAll(resp.Body) if err != nil { return "", nil, err } masterString := string(body) from, listType, err := m3u8.DecodeFrom(strings.NewReader(masterString), true) if err != nil || listType != m3u8.MASTER { return "", nil, errors.New("m3u8 not of master type") } master := from.(*m3u8.MasterPlaylist) var streamUrl *url.URL sort.Slice(master.Variants, func(i, j int) bool { return master.Variants[i].AverageBandwidth > master.Variants[j].AverageBandwidth }) for _, variant := range master.Variants { if variant.Codecs == "alac" { split := strings.Split(variant.Audio, "-") length := len(split) fmt.Printf("%s-bit / %s Hz\n", split[length-1], split[length-2]) streamUrlTemp, err := masterUrl.Parse(variant.URI) if err != nil { panic(err) } streamUrl = streamUrlTemp break } } if streamUrl == nil { return "", nil, errors.New("no alac codec found") } var keys []string keys = append(keys, prefetchKey) streamUrl.Path = strings.TrimSuffix(streamUrl.Path, ".m3u8") + "_m.mp4" regex := regexp.MustCompile(`"(skd?://[^"]*)"`) matches := regex.FindAllStringSubmatch(masterString, -1) for _, match := range matches { if strings.HasSuffix(match[1], "c23") || strings.HasSuffix(match[1], "c6") { keys = append(keys, match[1]) } } return streamUrl.String(), keys, nil } func extractSong(url string) (*SongInfo, error) { fmt.Println("Downloading...") track, err := http.Get(url) if err != nil { return nil, err } defer track.Body.Close() if track.StatusCode != http.StatusOK { return nil, errors.New(track.Status) } rawSong, err := ioutil.ReadAll(track.Body) if err != nil { return nil, err } fmt.Println("Downloaded.") f := bytes.NewReader(rawSong) trex, err := mp4.ExtractBoxWithPayload(f, nil, []mp4.BoxType{ mp4.BoxTypeMoov(), mp4.BoxTypeMvex(), mp4.BoxTypeTrex(), }) if err != nil || len(trex) != 1 { return nil, err } trexPay := trex[0].Payload.(*mp4.Trex) stbl, err := mp4.ExtractBox(f, nil, []mp4.BoxType{ mp4.BoxTypeMoov(), mp4.BoxTypeTrak(), mp4.BoxTypeMdia(), mp4.BoxTypeMinf(), mp4.BoxTypeStbl(), }) if err != nil || len(stbl) != 1 { return nil, err } enca, err := mp4.ExtractBoxWithPayload(f, stbl[0], []mp4.BoxType{ mp4.BoxTypeStsd(), mp4.BoxTypeEnca(), }) if err != nil { return nil, err } aalac, err := mp4.ExtractBoxWithPayload(f, &enca[0].Info, []mp4.BoxType{BoxTypeAlac()}) if err != nil || len(aalac) != 1 { return nil, err } extracted := &SongInfo{ r: f, alacParam: aalac[0].Payload.(*Alac), } moofs, err := mp4.ExtractBox(f, nil, []mp4.BoxType{ mp4.BoxTypeMoof(), }) if err != nil || len(moofs) <= 0 { return nil, err } mdats, err := mp4.ExtractBoxWithPayload(f, nil, []mp4.BoxType{ mp4.BoxTypeMdat(), }) if err != nil || len(mdats) != len(moofs) { return nil, err } for i, moof := range moofs { tfhd, err := mp4.ExtractBoxWithPayload(f, moof, []mp4.BoxType{ mp4.BoxTypeTraf(), mp4.BoxTypeTfhd(), }) if err != nil || len(tfhd) != 1 { return nil, err } tfhdPay := tfhd[0].Payload.(*mp4.Tfhd) index := tfhdPay.SampleDescriptionIndex if index != 0 { index-- } truns, err := mp4.ExtractBoxWithPayload(f, moof, []mp4.BoxType{ mp4.BoxTypeTraf(), mp4.BoxTypeTrun(), }) if err != nil || len(truns) <= 0 { return nil, err } mdat := mdats[i].Payload.(*mp4.Mdat).Data for _, t := range truns { for _, en := range t.Payload.(*mp4.Trun).Entries { info := SampleInfo{descIndex: index} switch { case t.Payload.CheckFlag(0x200): info.data = mdat[:en.SampleSize] mdat = mdat[en.SampleSize:] case tfhdPay.CheckFlag(0x10): info.data = mdat[:tfhdPay.DefaultSampleSize] mdat = mdat[tfhdPay.DefaultSampleSize:] default: info.data = mdat[:trexPay.DefaultSampleSize] mdat = mdat[trexPay.DefaultSampleSize:] } switch { case t.Payload.CheckFlag(0x100): info.duration = en.SampleDuration case tfhdPay.CheckFlag(0x8): info.duration = tfhdPay.DefaultSampleDuration default: info.duration = trexPay.DefaultSampleDuration } extracted.samples = append(extracted.samples, info) } } if len(mdat) != 0 { return nil, errors.New("offset mismatch") } } return extracted, nil } func init() { mp4.AddBoxDef((*Alac)(nil)) } func BoxTypeAlac() mp4.BoxType { return mp4.StrToBoxType("alac") } type Alac struct { mp4.FullBox `mp4:"extend"` FrameLength uint32 `mp4:"size=32"` CompatibleVersion uint8 `mp4:"size=8"` BitDepth uint8 `mp4:"size=8"` Pb uint8 `mp4:"size=8"` Mb uint8 `mp4:"size=8"` Kb uint8 `mp4:"size=8"` NumChannels uint8 `mp4:"size=8"` MaxRun uint16 `mp4:"size=16"` MaxFrameBytes uint32 `mp4:"size=32"` AvgBitRate uint32 `mp4:"size=32"` SampleRate uint32 `mp4:"size=32"` } func getInfoFromAdam(adamId string, token string, storefront string) (*SongData, error) { request, err := http.NewRequest("GET", fmt.Sprintf("https://amp-api.music.apple.com/v1/catalog/%s/songs/%s", storefront, adamId), nil) if err != nil { return nil, err } query := url.Values{} query.Set("extend", "extendedAssetUrls") query.Set("include", "albums") request.URL.RawQuery = query.Encode() request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token)) request.Header.Set("User-Agent", "iTunes/12.11.3 (Windows; Microsoft Windows 10 x64 Professional Edition (Build 19041); x64) AppleWebKit/7611.1022.4001.1 (dt:2)") request.Header.Set("Origin", "https://music.apple.com") do, err := http.DefaultClient.Do(request) if err != nil { return nil, err } defer do.Body.Close() if do.StatusCode != http.StatusOK { return nil, errors.New(do.Status) } obj := new(ApiResult) err = json.NewDecoder(do.Body).Decode(&obj) if err != nil { return nil, err } for _, d := range obj.Data { if d.ID == adamId { return &d, nil } } return nil, nil } func getToken() (string, error) { req, err := http.NewRequest("GET", "https://beta.music.apple.com", nil) if err != nil { return "", err } resp, err := http.DefaultClient.Do(req) if err != nil { return "", err } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { return "", err } regex := regexp.MustCompile(`/assets/index-legacy-[^/]+\.js`) indexJsUri := regex.FindString(string(body)) req, err = http.NewRequest("GET", "https://beta.music.apple.com"+indexJsUri, nil) if err != nil { return "", err } resp, err = http.DefaultClient.Do(req) if err != nil { return "", err } defer resp.Body.Close() body, err = io.ReadAll(resp.Body) if err != nil { return "", err } regex = regexp.MustCompile(`eyJh([^"]*)`) token := regex.FindString(string(body)) return token, nil } type ApiResult struct { Data []SongData `json:"data"` } type SongAttributes struct { ArtistName string `json:"artistName"` DiscNumber int `json:"discNumber"` GenreNames []string `json:"genreNames"` ExtendedAssetUrls struct { EnhancedHls string `json:"enhancedHls"` } `json:"extendedAssetUrls"` IsMasteredForItunes bool `json:"isMasteredForItunes"` ReleaseDate string `json:"releaseDate"` Name string `json:"name"` Isrc string `json:"isrc"` AlbumName string `json:"albumName"` TrackNumber int `json:"trackNumber"` ComposerName string `json:"composerName"` } type AlbumAttributes struct { ArtistName string `json:"artistName"` IsSingle bool `json:"isSingle"` IsComplete bool `json:"isComplete"` GenreNames []string `json:"genreNames"` TrackCount int `json:"trackCount"` IsMasteredForItunes bool `json:"isMasteredForItunes"` ReleaseDate string `json:"releaseDate"` Name string `json:"name"` RecordLabel string `json:"recordLabel"` Upc string `json:"upc"` Copyright string `json:"copyright"` IsCompilation bool `json:"isCompilation"` } type SongData struct { ID string `json:"id"` Attributes SongAttributes `json:"attributes"` Relationships struct { Albums struct { Data []struct { ID string `json:"id"` Type string `json:"type"` Href string `json:"href"` Attributes AlbumAttributes `json:"attributes"` } `json:"data"` } `json:"albums"` Artists struct { Href string `json:"href"` Data []struct { ID string `json:"id"` Type string `json:"type"` Href string `json:"href"` } `json:"data"` } `json:"artists"` } `json:"relationships"` } type SongResult struct { Artwork struct { Width int `json:"width"` URL string `json:"url"` Height int `json:"height"` TextColor3 string `json:"textColor3"` TextColor2 string `json:"textColor2"` TextColor4 string `json:"textColor4"` HasAlpha bool `json:"hasAlpha"` TextColor1 string `json:"textColor1"` BgColor string `json:"bgColor"` HasP3 bool `json:"hasP3"` SupportsLayeredImage bool `json:"supportsLayeredImage"` } `json:"artwork"` ArtistName string `json:"artistName"` CollectionID string `json:"collectionId"` DiscNumber int `json:"discNumber"` GenreNames []string `json:"genreNames"` ID string `json:"id"` DurationInMillis int `json:"durationInMillis"` ReleaseDate string `json:"releaseDate"` ContentRatingsBySystem struct { } `json:"contentRatingsBySystem"` Name string `json:"name"` Composer struct { Name string `json:"name"` URL string `json:"url"` } `json:"composer"` EditorialArtwork struct { } `json:"editorialArtwork"` CollectionName string `json:"collectionName"` AssetUrls struct { Plus string `json:"plus"` Lightweight string `json:"lightweight"` SuperLightweight string `json:"superLightweight"` LightweightPlus string `json:"lightweightPlus"` EnhancedHls string `json:"enhancedHls"` } `json:"assetUrls"` AudioTraits []string `json:"audioTraits"` Kind string `json:"kind"` Copyright string `json:"copyright"` ArtistID string `json:"artistId"` Genres []struct { GenreID string `json:"genreId"` Name string `json:"name"` URL string `json:"url"` MediaType string `json:"mediaType"` } `json:"genres"` TrackNumber int `json:"trackNumber"` AudioLocale string `json:"audioLocale"` Offers []struct { ActionText struct { Short string `json:"short"` Medium string `json:"medium"` Long string `json:"long"` Downloaded string `json:"downloaded"` Downloading string `json:"downloading"` } `json:"actionText"` Type string `json:"type"` PriceFormatted string `json:"priceFormatted"` Price float64 `json:"price"` BuyParams string `json:"buyParams"` Variant string `json:"variant,omitempty"` Assets []struct { Flavor string `json:"flavor"` Preview struct { Duration int `json:"duration"` URL string `json:"url"` } `json:"preview"` Size int `json:"size"` Duration int `json:"duration"` } `json:"assets"` } `json:"offers"` } type iTunesLookup struct { Results map[string]SongResult `json:"results"` } type Meta struct { Context string `json:"@context"` Type string `json:"@type"` Name string `json:"name"` Description string `json:"description"` Tracks []struct { Type string `json:"@type"` Name string `json:"name"` Audio struct { Type string `json:"@type"` } `json:"audio"` Offers struct { Type string `json:"@type"` Category string `json:"category"` Price int `json:"price"` } `json:"offers"` Duration string `json:"duration"` } `json:"tracks"` Citation []interface{} `json:"citation"` WorkExample []struct { Type string `json:"@type"` Name string `json:"name"` URL string `json:"url"` Audio struct { Type string `json:"@type"` } `json:"audio"` Offers struct { Type string `json:"@type"` Category string `json:"category"` Price int `json:"price"` } `json:"offers"` Duration string `json:"duration"` } `json:"workExample"` Genre []string `json:"genre"` DatePublished time.Time `json:"datePublished"` ByArtist struct { Type string `json:"@type"` URL string `json:"url"` Name string `json:"name"` } `json:"byArtist"` } type AutoGenerated struct { Data []struct { ID string `json:"id"` Type string `json:"type"` Href string `json:"href"` Attributes struct { Artwork struct { Width int `json:"width"` Height int `json:"height"` URL string `json:"url"` BgColor string `json:"bgColor"` TextColor1 string `json:"textColor1"` TextColor2 string `json:"textColor2"` TextColor3 string `json:"textColor3"` TextColor4 string `json:"textColor4"` } `json:"artwork"` ArtistName string `json:"artistName"` IsSingle bool `json:"isSingle"` URL string `json:"url"` IsComplete bool `json:"isComplete"` GenreNames []string `json:"genreNames"` TrackCount int `json:"trackCount"` IsMasteredForItunes bool `json:"isMasteredForItunes"` ReleaseDate string `json:"releaseDate"` Name string `json:"name"` RecordLabel string `json:"recordLabel"` Upc string `json:"upc"` AudioTraits []string `json:"audioTraits"` Copyright string `json:"copyright"` PlayParams struct { ID string `json:"id"` Kind string `json:"kind"` } `json:"playParams"` IsCompilation bool `json:"isCompilation"` } `json:"attributes"` Relationships struct { RecordLabels struct { Href string `json:"href"` Data []interface{} `json:"data"` } `json:"record-labels"` Artists struct { Href string `json:"href"` Data []struct { ID string `json:"id"` Type string `json:"type"` Href string `json:"href"` Attributes struct { Name string `json:"name"` } `json:"attributes"` } `json:"data"` } `json:"artists"` Tracks struct { Href string `json:"href"` Data []struct { ID string `json:"id"` Type string `json:"type"` Href string `json:"href"` Attributes struct { Previews []struct { URL string `json:"url"` } `json:"previews"` Artwork struct { Width int `json:"width"` Height int `json:"height"` URL string `json:"url"` BgColor string `json:"bgColor"` TextColor1 string `json:"textColor1"` TextColor2 string `json:"textColor2"` TextColor3 string `json:"textColor3"` TextColor4 string `json:"textColor4"` } `json:"artwork"` ArtistName string `json:"artistName"` URL string `json:"url"` DiscNumber int `json:"discNumber"` GenreNames []string `json:"genreNames"` HasTimeSyncedLyrics bool `json:"hasTimeSyncedLyrics"` IsMasteredForItunes bool `json:"isMasteredForItunes"` DurationInMillis int `json:"durationInMillis"` ReleaseDate string `json:"releaseDate"` Name string `json:"name"` Isrc string `json:"isrc"` AudioTraits []string `json:"audioTraits"` HasLyrics bool `json:"hasLyrics"` AlbumName string `json:"albumName"` PlayParams struct { ID string `json:"id"` Kind string `json:"kind"` } `json:"playParams"` TrackNumber int `json:"trackNumber"` AudioLocale string `json:"audioLocale"` ComposerName string `json:"composerName"` } `json:"attributes"` Relationships struct { Artists struct { Href string `json:"href"` Data []struct { ID string `json:"id"` Type string `json:"type"` Href string `json:"href"` Attributes struct { Name string `json:"name"` } `json:"attributes"` } `json:"data"` } `json:"artists"` } `json:"relationships"` } `json:"data"` } `json:"tracks"` } `json:"relationships"` } `json:"data"` } add explicit tag tagging and mention[E] to the track name having index# and track name mention here[E}
ba88bf4fc30a7842daa056fe02f8f53b
{ "intermediate": 0.33890464901924133, "beginner": 0.44517913460731506, "expert": 0.21591626107692719 }
47,412
почему не работает код import torch def target_function(x): return 2**x * torch.sin(2**-x) class RegressionNet(torch.nn.Module): def __init__(self, n_hidden_neurons): super().__init__() self.fc1 = torch.nn.Linear(1, n_hidden_neurons) self.act1 = torch.nn.Sigmoid() self.fc2 = torch.nn.Linear(n_hidden_neurons, n_hidden_neurons) #self.act2 = torch.nn.Tanh() #self.fc3 = torch.nn.Linear(n_hidden_neurons, 1) # your code here net = RegressionNet(50) # ------Dataset preparation start--------: x_train = torch.linspace(-10, 5, 100) y_train = target_function(x_train) noise = torch.randn(y_train.shape) / 20. y_train = y_train + noise x_train.unsqueeze_(1) y_train.unsqueeze_(1) x_validation = torch.linspace(-10, 5, 100) y_validation = target_function(x_validation) x_validation.unsqueeze_(1) y_validation.unsqueeze_(1) # ------Dataset preparation end--------: optimizer = torch.optim.Adam(net.parameters(), lr=0.001) def loss(pred, target): squares = abs(pred - target) return squares.mean() for epoch_index in range(1000): optimizer.zero_grad() y_pred = net.forward(x_train) loss_value = loss(y_pred, y_train) loss_val.backward() optimizer.step() # Проверка осуществляется вызовом кода: # def metric(pred, target): # return (pred - target).abs().mean() # # print(metric(net.forward(x_validation), y_validation).item()) # (раскомментируйте, если решаете задание локально) def predict(net, x, y): y_pred = net.forward(x) plt.plot(x.numpy(), y.numpy(), 'o', label='Groud truth') plt.plot(x.numpy(), y_pred.data.numpy(), 'o', c='r', label='Prediction'); plt.legend(loc='upper left') plt.xlabel('$x$') plt.ylabel('$y$') predict(net, x_validation, y_validation)
4980622e196c7aa1ce333f4234092f83
{ "intermediate": 0.2897595167160034, "beginner": 0.3925633728504181, "expert": 0.31767702102661133 }
47,413
If you want to select two columns and remove duplicates in one column, you should use the GROUP BY clause instead. can you give me an example of this, related to SQL
529efb0a8a2c6ec633bcde00d0382a35
{ "intermediate": 0.31913965940475464, "beginner": 0.3774992823600769, "expert": 0.30336108803749084 }
47,414
package main import ( “bytes” “encoding/binary” “encoding/json” “errors” “fmt” “io” “io/ioutil” “math” “net” “net/http” “net/url” “os” “path/filepath” “regexp” “sort” “strings” “time” “github.com/abema/go-mp4” “github.com/grafov/m3u8” ) const ( defaultId = “0” prefetchKey = “skd://itunes.apple.com/P000000000/s1/e1” ) var ( forbiddenNames = regexp.MustCompile([/\\&lt;&gt;:"|?*]) ) type SampleInfo struct { data []byte duration uint32 descIndex uint32 } type SongInfo struct { r io.ReadSeeker alacParam *Alac samples []SampleInfo } func (s *SongInfo) Duration() (ret uint64) { for i := range s.samples { ret += uint64(s.samples[i].duration) } return } func (*Alac) GetType() mp4.BoxType { return BoxTypeAlac() } func fileExists(path string) (bool, error) { f, err := os.Stat(path) if err == nil { return !f.IsDir(), nil } else if os.IsNotExist(err) { return false, nil } return false, err } func writeM4a(w *mp4.Writer, info *SongInfo, meta *AutoGenerated, data []byte, trackNum, trackTotal int) error { index := trackNum - 1 { // ftyp box, err := w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeFtyp()}) if err != nil { return err } _, err = mp4.Marshal(w, &mp4.Ftyp{ MajorBrand: [4]byte{‘M’, ‘4’, ‘A’, ’ ‘}, MinorVersion: 0, CompatibleBrands: []mp4.CompatibleBrandElem{ {CompatibleBrand: [4]byte{‘M’, ‘4’, ‘A’, ’ ‘}}, {CompatibleBrand: [4]byte{‘m’, ‘p’, ‘4’, ‘2’}}, {CompatibleBrand: mp4.BrandISOM()}, {CompatibleBrand: [4]byte{0, 0, 0, 0}}, }, }, box.Context) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } const chunkSize uint32 = 5 duration := info.Duration() numSamples := uint32(len(info.samples)) var stco *mp4.BoxInfo { // moov _, err := w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeMoov()}) if err != nil { return err } box, err := mp4.ExtractBox(info.r, nil, mp4.BoxPath{mp4.BoxTypeMoov()}) if err != nil { return err } moovOri := box[0] { // mvhd _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeMvhd()}) if err != nil { return err } oriBox, err := mp4.ExtractBoxWithPayload(info.r, moovOri, mp4.BoxPath{mp4.BoxTypeMvhd()}) if err != nil { return err } mvhd := oriBox[0].Payload.(*mp4.Mvhd) if mvhd.Version == 0 { mvhd.DurationV0 = uint32(duration) } else { mvhd.DurationV1 = duration } _, err = mp4.Marshal(w, mvhd, oriBox[0].Info.Context) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } { // trak _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeTrak()}) if err != nil { return err } box, err := mp4.ExtractBox(info.r, moovOri, mp4.BoxPath{mp4.BoxTypeTrak()}) if err != nil { return err } trakOri := box[0] { // tkhd _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeTkhd()}) if err != nil { return err } oriBox, err := mp4.ExtractBoxWithPayload(info.r, trakOri, mp4.BoxPath{mp4.BoxTypeTkhd()}) if err != nil { return err } tkhd := oriBox[0].Payload.(*mp4.Tkhd) if tkhd.Version == 0 { tkhd.DurationV0 = uint32(duration) } else { tkhd.DurationV1 = duration } tkhd.SetFlags(0x7) _, err = mp4.Marshal(w, tkhd, oriBox[0].Info.Context) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } { // mdia _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeMdia()}) if err != nil { return err } box, err := mp4.ExtractBox(info.r, trakOri, mp4.BoxPath{mp4.BoxTypeMdia()}) if err != nil { return err } mdiaOri := box[0] { // mdhd _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeMdhd()}) if err != nil { return err } oriBox, err := mp4.ExtractBoxWithPayload(info.r, mdiaOri, mp4.BoxPath{mp4.BoxTypeMdhd()}) if err != nil { return err } mdhd := oriBox[0].Payload.(*mp4.Mdhd) if mdhd.Version == 0 { mdhd.DurationV0 = uint32(duration) } else { mdhd.DurationV1 = duration } _, err = mp4.Marshal(w, mdhd, oriBox[0].Info.Context) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } { // hdlr oriBox, err := mp4.ExtractBox(info.r, mdiaOri, mp4.BoxPath{mp4.BoxTypeHdlr()}) if err != nil { return err } err = w.CopyBox(info.r, oriBox[0]) if err != nil { return err } } { // minf _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeMinf()}) if err != nil { return err } box, err := mp4.ExtractBox(info.r, mdiaOri, mp4.BoxPath{mp4.BoxTypeMinf()}) if err != nil { return err } minfOri := box[0] { // smhd, dinf boxes, err := mp4.ExtractBoxes(info.r, minfOri, []mp4.BoxPath{ {mp4.BoxTypeSmhd()}, {mp4.BoxTypeDinf()}, }) if err != nil { return err } for _, b := range boxes { err = w.CopyBox(info.r, b) if err != nil { return err } } } { // stbl _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeStbl()}) if err != nil { return err } { // stsd box, err := w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeStsd()}) if err != nil { return err } _, err = mp4.Marshal(w, &mp4.Stsd{EntryCount: 1}, box.Context) if err != nil { return err } { // alac _, err = w.StartBox(&mp4.BoxInfo{Type: BoxTypeAlac()}) if err != nil { return err } _, err = w.Write([]byte{ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}) if err != nil { return err } err = binary.Write(w, binary.BigEndian, uint16(info.alacParam.NumChannels)) if err != nil { return err } err = binary.Write(w, binary.BigEndian, uint16(info.alacParam.BitDepth)) if err != nil { return err } _, err = w.Write([]byte{0, 0}) if err != nil { return err } err = binary.Write(w, binary.BigEndian, info.alacParam.SampleRate) if err != nil { return err } _, err = w.Write([]byte{0, 0}) if err != nil { return err } box, err := w.StartBox(&mp4.BoxInfo{Type: BoxTypeAlac()}) if err != nil { return err } _, err = mp4.Marshal(w, info.alacParam, box.Context) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } _, err = w.EndBox() if err != nil { return err } } { // stts box, err := w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeStts()}) if err != nil { return err } var stts mp4.Stts for _, sample := range info.samples { if len(stts.Entries) != 0 { last := &stts.Entries[len(stts.Entries)-1] if last.SampleDelta == sample.duration { last.SampleCount++ continue } } stts.Entries = append(stts.Entries, mp4.SttsEntry{ SampleCount: 1, SampleDelta: sample.duration, }) } stts.EntryCount = uint32(len(stts.Entries)) _, err = mp4.Marshal(w, &stts, box.Context) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } { // stsc box, err := w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeStsc()}) if err != nil { return err } if numSamples%chunkSize == 0 { _, err = mp4.Marshal(w, &mp4.Stsc{ EntryCount: 1, Entries: []mp4.StscEntry{ { FirstChunk: 1, SamplesPerChunk: chunkSize, SampleDescriptionIndex: 1, }, }, }, box.Context) } else { _, err = mp4.Marshal(w, &mp4.Stsc{ EntryCount: 2, Entries: []mp4.StscEntry{ { FirstChunk: 1, SamplesPerChunk: chunkSize, SampleDescriptionIndex: 1, }, { FirstChunk: numSamples/chunkSize + 1, SamplesPerChunk: numSamples % chunkSize, SampleDescriptionIndex: 1, }, }, }, box.Context) } _, err = w.EndBox() if err != nil { return err } } { // stsz box, err := w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeStsz()}) if err != nil { return err } stsz := mp4.Stsz{SampleCount: numSamples} for _, sample := range info.samples { stsz.EntrySize = append(stsz.EntrySize, uint32(len(sample.data))) } _, err = mp4.Marshal(w, &stsz, box.Context) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } { // stco box, err := w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeStco()}) if err != nil { return err } l := (numSamples + chunkSize - 1) / chunkSize _, err = mp4.Marshal(w, &mp4.Stco{ EntryCount: l, ChunkOffset: make([]uint32, l), }, box.Context) stco, err = w.EndBox() if err != nil { return err } } _, err = w.EndBox() if err != nil { return err } } _, err = w.EndBox() if err != nil { return err } } _, err = w.EndBox() if err != nil { return err } } _, err = w.EndBox() if err != nil { return err } } { // udta ctx := mp4.Context{UnderUdta: true} _, err := w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeUdta(), Context: ctx}) if err != nil { return err } { // meta ctx.UnderIlstMeta = true _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeMeta(), Context: ctx}) if err != nil { return err } _, err = mp4.Marshal(w, &mp4.Meta{}, ctx) if err != nil { return err } { // hdlr _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeHdlr(), Context: ctx}) if err != nil { return err } _, err = mp4.Marshal(w, &mp4.Hdlr{ HandlerType: [4]byte{‘m’, ‘d’, ‘i’, ‘r’}, Reserved: [3]uint32{0x6170706c, 0, 0}, }, ctx) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } { // ilst ctx.UnderIlst = true _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeIlst(), Context: ctx}) if err != nil { return err } marshalData := func(val interface{}) error { _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeData()}) if err != nil { return err } var boxData mp4.Data switch v := val.(type) { case string: boxData.DataType = mp4.DataTypeStringUTF8 boxData.Data = []byte(v) case uint8: boxData.DataType = mp4.DataTypeSignedIntBigEndian boxData.Data = []byte{v} case uint32: boxData.DataType = mp4.DataTypeSignedIntBigEndian boxData.Data = make([]byte, 4) binary.BigEndian.PutUint32(boxData.Data, v) case []byte: boxData.DataType = mp4.DataTypeBinary boxData.Data = v default: panic(“unsupported value”) } _, err = mp4.Marshal(w, &boxData, ctx) if err != nil { return err } _, err = w.EndBox() return err } addMeta := func(tag mp4.BoxType, val interface{}) error { _, err = w.StartBox(&mp4.BoxInfo{Type: tag}) if err != nil { return err } err = marshalData(val) if err != nil { return err } _, err = w.EndBox() return err } addExtendedMeta := func(name string, val interface{}) error { ctx.UnderIlstFreeMeta = true _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxType{’-’, ‘-’, ‘-’, ‘-’}, Context: ctx}) if err != nil { return err } { _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxType{‘m’, ‘e’, ‘a’, ‘n’}, Context: ctx}) if err != nil { return err } _, err = w.Write([]byte{0, 0, 0, 0}) if err != nil { return err } _, err = io.WriteString(w, “com.apple.iTunes”) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } { _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxType{‘n’, ‘a’, ‘m’, ‘e’}, Context: ctx}) if err != nil { return err } _, err = w.Write([]byte{0, 0, 0, 0}) if err != nil { return err } _, err = io.WriteString(w, name) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } err = marshalData(val) if err != nil { return err } ctx.UnderIlstFreeMeta = false _, err = w.EndBox() return err } err = addMeta(mp4.BoxType{‘\251’, ‘n’, ‘a’, ‘m’}, meta.Data[0].Relationships.Tracks.Data[index].Attributes.Name) if err != nil { return err } err = addMeta(mp4.BoxType{‘\251’, ‘a’, ‘l’, ‘b’}, meta.Data[0].Attributes.Name) if err != nil { return err } err = addMeta(mp4.BoxType{‘\251’, ‘A’, ‘R’, ‘T’}, meta.Data[0].Relationships.Tracks.Data[index].Attributes.ArtistName) if err != nil { return err } err = addMeta(mp4.BoxType{‘\251’, ‘w’, ‘r’, ‘t’}, meta.Data[0].Relationships.Tracks.Data[index].Attributes.ComposerName) if err != nil { return err } err = addMeta(mp4.BoxType{‘\251’, ‘d’, ‘a’, ‘y’}, strings.Split(meta.Data[0].Attributes.ReleaseDate, “-”)[0]) if err != nil { return err } // cnID, err := strconv.ParseUint(meta.Data[0].Relationships.Tracks.Data[index].ID, 10, 32) // if err != nil { // return err // } // err = addMeta(mp4.BoxType{‘c’, ‘n’, ‘I’, ‘D’}, uint32(cnID)) // if err != nil { // return err // } err = addExtendedMeta(“ISRC”, meta.Data[0].Relationships.Tracks.Data[index].Attributes.Isrc) if err != nil { return err } if len(meta.Data[0].Relationships.Tracks.Data[index].Attributes.GenreNames) > 0 { err = addMeta(mp4.BoxType{‘\251’, ‘g’, ‘e’, ‘n’}, meta.Data[0].Relationships.Tracks.Data[index].Attributes.GenreNames[0]) if err != nil { return err } } if len(meta.Data) > 0 { album := meta.Data[0] err = addMeta(mp4.BoxType{‘a’, ‘A’, ‘R’, ‘T’}, album.Attributes.ArtistName) if err != nil { return err } err = addMeta(mp4.BoxType{‘c’, ‘p’, ‘r’, ‘t’}, album.Attributes.Copyright) if err != nil { return err } var isCpil uint8 if album.Attributes.IsCompilation { isCpil = 1 } err = addMeta(mp4.BoxType{‘c’, ‘p’, ‘i’, ‘l’}, isCpil) if err != nil { return err } err = addExtendedMeta(“LABEL”, album.Attributes.RecordLabel) if err != nil { return err } err = addExtendedMeta(“UPC”, album.Attributes.Upc) if err != nil { return err } // plID, err := strconv.ParseUint(album.ID, 10, 32) // if err != nil { // return err // } // err = addMeta(mp4.BoxType{‘p’, ‘l’, ‘I’, ‘D’}, uint32(plID)) // if err != nil { // return err // } } // if len(meta.Data[0].Relationships.Artists.Data) > 0 { // atID, err := strconv.ParseUint(meta.Data[0].Relationships.Artists.Data[index].ID, 10, 32) // if err != nil { // return err // } // err = addMeta(mp4.BoxType{‘a’, ‘t’, ‘I’, ‘D’}, uint32(atID)) // if err != nil { // return err // } // } trkn := make([]byte, 8) binary.BigEndian.PutUint32(trkn, uint32(trackNum)) binary.BigEndian.PutUint16(trkn[4:], uint16(trackTotal)) err = addMeta(mp4.BoxType{‘t’, ‘r’, ‘k’, ‘n’}, trkn) if err != nil { return err } // disk := make([]byte, 8) // binary.BigEndian.PutUint32(disk, uint32(meta.Attributes.DiscNumber)) // err = addMeta(mp4.BoxType{‘d’, ‘i’, ‘s’, ‘k’}, disk) // if err != nil { // return err // } ctx.UnderIlst = false _, err = w.EndBox() if err != nil { return err } } ctx.UnderIlstMeta = false _, err = w.EndBox() if err != nil { return err } } ctx.UnderUdta = false _, err = w.EndBox() if err != nil { return err } } _, err = w.EndBox() if err != nil { return err } } { box, err := w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeMdat()}) if err != nil { return err } _, err = mp4.Marshal(w, &mp4.Mdat{Data: data}, box.Context) if err != nil { return err } mdat, err := w.EndBox() var realStco mp4.Stco offset := mdat.Offset + mdat.HeaderSize for i := uint32(0); i < numSamples; i++ { if i%chunkSize == 0 { realStco.EntryCount++ realStco.ChunkOffset = append(realStco.ChunkOffset, uint32(offset)) } offset += uint64(len(info.samples[i].data)) } _, err = stco.SeekToPayload(w) if err != nil { return err } _, err = mp4.Marshal(w, &realStco, box.Context) if err != nil { return err } } return nil } func decryptSong(info *SongInfo, keys []string, manifest *AutoGenerated, filename string, trackNum, trackTotal int) error { //fmt.Printf(“%d-bit / %d Hz\n”, info.bitDepth, info.bitRate) conn, err := net.Dial(“tcp”, “127.0.0.1:10020”) if err != nil { return err } defer conn.Close() var decrypted []byte var lastIndex uint32 = math.MaxUint8 fmt.Println(“Decrypt start.”) for _, sp := range info.samples { if lastIndex != sp.descIndex { if len(decrypted) != 0 { _, err := conn.Write([]byte{0, 0, 0, 0}) if err != nil { return err } } keyUri := keys[sp.descIndex] id := manifest.Data[0].Relationships.Tracks.Data[trackNum-1].ID if keyUri == prefetchKey { id = defaultId } _, err := conn.Write([]byte{byte(len(id))}) if err != nil { return err } _, err = io.WriteString(conn, id) if err != nil { return err } _, err = conn.Write([]byte{byte(len(keyUri))}) if err != nil { return err } _, err = io.WriteString(conn, keyUri) if err != nil { return err } } lastIndex = sp.descIndex err := binary.Write(conn, binary.LittleEndian, uint32(len(sp.data))) if err != nil { return err } _, err = conn.Write(sp.data) if err != nil { return err } de := make([]byte, len(sp.data)) _, err = io.ReadFull(conn, de) if err != nil { return err } decrypted = append(decrypted, de…) } , _ = conn.Write([]byte{0, 0, 0, 0, 0}) fmt.Println(“Decrypt finished.”) create, err := os.Create(filename) if err != nil { return err } defer create.Close() return writeM4a(mp4.NewWriter(create), info, manifest, decrypted, trackNum, trackTotal) } func checkUrl(url string) (string, string) { pat := regexp.MustCompile(^(?:https:\/\/(?:beta\.music|music)\.apple\.com\/(\w{2})(?:\/album|\/album\/.+))\/(?:id)?(\d[^\D]+)(?:$|\?)) matches := pat.FindAllStringSubmatch(url, -1) if matches == nil { return “”, “” } else { return matches[0][1], matches[0][2] } } func getMeta(albumId string, token string, storefront string) (*AutoGenerated, error) { req, err := http.NewRequest(“GET”, fmt.Sprintf(“https://amp-api.music.apple.com/v1/catalog/%s/albums/%s”, storefront, albumId), nil) if err != nil { return nil, err } req.Header.Set(“Authorization”, fmt.Sprintf(“Bearer %s”, token)) req.Header.Set(“User-Agent”, “Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36”) req.Header.Set(“Origin”, “https://music.apple.com”) query := url.Values{} query.Set(“omit[resource]”, “autos”) query.Set(“include”, “tracks,artists,record-labels”) query.Set(“include[songs]”, “artists”) query.Set(“fields[artists]”, “name”) query.Set(“fields[albums:albums]”, “artistName,artwork,name,releaseDate,url”) query.Set(“fields[record-labels]”, “name”) // query.Set(“l”, “en-gb”) req.URL.RawQuery = query.Encode() do, err := http.DefaultClient.Do(req) if err != nil { return nil, err } defer do.Body.Close() if do.StatusCode != http.StatusOK { return nil, errors.New(do.Status) } obj := new(AutoGenerated) err = json.NewDecoder(do.Body).Decode(&obj) if err != nil { return nil, err } return obj, nil } func writeCover(sanAlbumFolder, url string) error { covPath := filepath.Join(sanAlbumFolder, “cover.jpg”) exists, err := fileExists(covPath) if err != nil { fmt.Println(“Failed to check if cover exists.”) return err } if exists { return nil } url = strings.Replace(url, “{w}x{h}”, “1200x12000”, 1) req, err := http.NewRequest(“GET”, url, nil) if err != nil { return err } req.Header.Set(“User-Agent”, “Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36”) do, err := http.DefaultClient.Do(req) if err != nil { return err } defer do.Body.Close() if do.StatusCode != http.StatusOK { errors.New(do.Status) } f, err := os.Create(covPath) if err != nil { return err } defer f.Close() , err = io.Copy(f, do.Body) if err != nil { return err } return nil } func rip(albumId string, token string, storefront string) error { meta, err := getMeta(albumId, token, storefront) if err != nil { fmt.Println(“Failed to get album metadata.\n”) return err } albumFolder := fmt.Sprintf(“%s - %s”, meta.Data[0].Attributes.ArtistName, meta.Data[0].Attributes.Name) sanAlbumFolder := filepath.Join(“AM-DL downloads”, forbiddenNames.ReplaceAllString(albumFolder, "“)) os.MkdirAll(sanAlbumFolder, os.ModePerm) fmt.Println(albumFolder) err = writeCover(sanAlbumFolder, meta.Data[0].Attributes.Artwork.URL) if err != nil { fmt.Println(“Failed to write cover.”) } trackTotal := len(meta.Data[0].Relationships.Tracks.Data) for trackNum, track := range meta.Data[0].Relationships.Tracks.Data { trackNum++ fmt.Printf(“Track %d of %d:\n”, trackNum, trackTotal) manifest, err := getInfoFromAdam(track.ID, token, storefront) if err != nil { fmt.Println(“Failed to get manifest.\n”, err) continue } if manifest.Attributes.ExtendedAssetUrls.EnhancedHls == “” { fmt.Println(“Unavailable in ALAC.”) continue } filename := fmt.Sprintf(”%02d. %s.m4a", trackNum, forbiddenNames.ReplaceAllString(track.Attributes.Name, "“)) trackPath := filepath.Join(sanAlbumFolder, filename) exists, err := fileExists(trackPath) if err != nil { fmt.Println(“Failed to check if track exists.”) } if exists { fmt.Println(“Track already exists locally.”) continue } trackUrl, keys, err := extractMedia(manifest.Attributes.ExtendedAssetUrls.EnhancedHls) if err != nil { fmt.Println(“Failed to extract info from manifest.\n”, err) continue } info, err := extractSong(trackUrl) if err != nil { fmt.Println(“Failed to extract track.”, err) continue } samplesOk := true for samplesOk { for _, i := range info.samples { if int(i.descIndex) >= len(keys) { fmt.Println(“Decryption size mismatch.”) samplesOk = false } } break } if !samplesOk { continue } err = decryptSong(info, keys, meta, trackPath, trackNum, trackTotal) if err != nil { fmt.Println(“Failed to decrypt track.\n”, err) continue } } return err } func main() { token, err := getToken() if err != nil { fmt.Println(“Failed to get token.”) return } albumTotal := len(os.Args[1:]) for albumNum, url := range os.Args[1:] { fmt.Printf(“Album %d of %d:\n”, albumNum+1, albumTotal) storefront, albumId := checkUrl(url) if albumId == “” { fmt.Printf(“Invalid URL: %s\n”, url) continue } err := rip(albumId, token, storefront) if err != nil { fmt.Println(“Album failed.”) fmt.Println(err) } } } func extractMedia(b string) (string, []string, error) { masterUrl, err := url.Parse(b) if err != nil { return “”, nil, err } resp, err := http.Get(b) if err != nil { return “”, nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return “”, nil, errors.New(resp.Status) } body, err := io.ReadAll(resp.Body) if err != nil { return “”, nil, err } masterString := string(body) from, listType, err := m3u8.DecodeFrom(strings.NewReader(masterString), true) if err != nil || listType != m3u8.MASTER { return “”, nil, errors.New(“m3u8 not of master type”) } master := from.(*m3u8.MasterPlaylist) var streamUrl *url.URL sort.Slice(master.Variants, func(i, j int) bool { return master.Variants[i].AverageBandwidth > master.Variants[j].AverageBandwidth }) for _, variant := range master.Variants { if variant.Codecs == “alac” { split := strings.Split(variant.Audio, “-”) length := len(split) fmt.Printf(”%s-bit / %s Hz\n", split[length-1], split[length-2]) streamUrlTemp, err := masterUrl.Parse(variant.URI) if err != nil { panic(err) } streamUrl = streamUrlTemp break } } if streamUrl == nil { return “”, nil, errors.New(“no alac codec found”) } var keys []string keys = append(keys, prefetchKey) streamUrl.Path = strings.TrimSuffix(streamUrl.Path, “.m3u8”) + “_m.mp4” regex := regexp.MustCompile("(skd?://[^"]*)") matches := regex.FindAllStringSubmatch(masterString, -1) for _, match := range matches { if strings.HasSuffix(match[1], “c23”) || strings.HasSuffix(match[1], “c6”) { keys = append(keys, match[1]) } } return streamUrl.String(), keys, nil } func extractSong(url string) (*SongInfo, error) { fmt.Println(“Downloading…”) track, err := http.Get(url) if err != nil { return nil, err } defer track.Body.Close() if track.StatusCode != http.StatusOK { return nil, errors.New(track.Status) } rawSong, err := ioutil.ReadAll(track.Body) if err != nil { return nil, err } fmt.Println(“Downloaded.”) f := bytes.NewReader(rawSong) trex, err := mp4.ExtractBoxWithPayload(f, nil, []mp4.BoxType{ mp4.BoxTypeMoov(), mp4.BoxTypeMvex(), mp4.BoxTypeTrex(), }) if err != nil || len(trex) != 1 { return nil, err } trexPay := trex[0].Payload.(*mp4.Trex) stbl, err := mp4.ExtractBox(f, nil, []mp4.BoxType{ mp4.BoxTypeMoov(), mp4.BoxTypeTrak(), mp4.BoxTypeMdia(), mp4.BoxTypeMinf(), mp4.BoxTypeStbl(), }) if err != nil || len(stbl) != 1 { return nil, err } enca, err := mp4.ExtractBoxWithPayload(f, stbl[0], []mp4.BoxType{ mp4.BoxTypeStsd(), mp4.BoxTypeEnca(), }) if err != nil { return nil, err } aalac, err := mp4.ExtractBoxWithPayload(f, &enca[0].Info, []mp4.BoxType{BoxTypeAlac()}) if err != nil || len(aalac) != 1 { return nil, err } extracted := &SongInfo{ r: f, alacParam: aalac[0].Payload.(*Alac), } moofs, err := mp4.ExtractBox(f, nil, []mp4.BoxType{ mp4.BoxTypeMoof(), }) if err != nil || len(moofs) <= 0 { return nil, err } mdats, err := mp4.ExtractBoxWithPayload(f, nil, []mp4.BoxType{ mp4.BoxTypeMdat(), }) if err != nil || len(mdats) != len(moofs) { return nil, err } for i, moof := range moofs { tfhd, err := mp4.ExtractBoxWithPayload(f, moof, []mp4.BoxType{ mp4.BoxTypeTraf(), mp4.BoxTypeTfhd(), }) if err != nil || len(tfhd) != 1 { return nil, err } tfhdPay := tfhd[0].Payload.(*mp4.Tfhd) index := tfhdPay.SampleDescriptionIndex if index != 0 { index– } truns, err := mp4.ExtractBoxWithPayload(f, moof, []mp4.BoxType{ mp4.BoxTypeTraf(), mp4.BoxTypeTrun(), }) if err != nil || len(truns) <= 0 { return nil, err } mdat := mdats[i].Payload.(*mp4.Mdat).Data for _, t := range truns { for _, en := range t.Payload.(*mp4.Trun).Entries { info := SampleInfo{descIndex: index} switch { case t.Payload.CheckFlag(0x200): info.data = mdat[:en.SampleSize] mdat = mdat[en.SampleSize:] case tfhdPay.CheckFlag(0x10): info.data = mdat[:tfhdPay.DefaultSampleSize] mdat = mdat[tfhdPay.DefaultSampleSize:] default: info.data = mdat[:trexPay.DefaultSampleSize] mdat = mdat[trexPay.DefaultSampleSize:] } switch { case t.Payload.CheckFlag(0x100): info.duration = en.SampleDuration case tfhdPay.CheckFlag(0x8): info.duration = tfhdPay.DefaultSampleDuration default: info.duration = trexPay.DefaultSampleDuration } extracted.samples = append(extracted.samples, info) } } if len(mdat) != 0 { return nil, errors.New(“offset mismatch”) } } return extracted, nil } func init() { mp4.AddBoxDef((*Alac)(nil)) } func BoxTypeAlac() mp4.BoxType { return mp4.StrToBoxType(“alac”) } type Alac struct { mp4.FullBox mp4:"extend" FrameLength uint32 mp4:"size=32" CompatibleVersion uint8 mp4:"size=8" BitDepth uint8 mp4:"size=8" Pb uint8 mp4:"size=8" Mb uint8 mp4:"size=8" Kb uint8 mp4:"size=8" NumChannels uint8 mp4:"size=8" MaxRun uint16 mp4:"size=16" MaxFrameBytes uint32 mp4:"size=32" AvgBitRate uint32 mp4:"size=32" SampleRate uint32 mp4:"size=32" } func getInfoFromAdam(adamId string, token string, storefront string) (*SongData, error) { request, err := http.NewRequest(“GET”, fmt.Sprintf(“https://amp-api.music.apple.com/v1/catalog/%s/songs/%s”, storefront, adamId), nil) if err != nil { return nil, err } query := url.Values{} query.Set(“extend”, “extendedAssetUrls”) query.Set(“include”, “albums”) request.URL.RawQuery = query.Encode() request.Header.Set(“Authorization”, fmt.Sprintf(“Bearer %s”, token)) request.Header.Set(“User-Agent”, “iTunes/12.11.3 (Windows; Microsoft Windows 10 x64 Professional Edition (Build 19041); x64) AppleWebKit/7611.1022.4001.1 (dt:2)”) request.Header.Set(“Origin”, “https://music.apple.com”) do, err := http.DefaultClient.Do(request) if err != nil { return nil, err } defer do.Body.Close() if do.StatusCode != http.StatusOK { return nil, errors.New(do.Status) } obj := new(ApiResult) err = json.NewDecoder(do.Body).Decode(&obj) if err != nil { return nil, err } for _, d := range obj.Data { if d.ID == adamId { return &d, nil } } return nil, nil } func getToken() (string, error) { req, err := http.NewRequest(“GET”, “https://beta.music.apple.com”, nil) if err != nil { return “”, err } resp, err := http.DefaultClient.Do(req) if err != nil { return “”, err } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { return “”, err } regex := regexp.MustCompile(/assets/index-legacy-[^/]+\.js) indexJsUri := regex.FindString(string(body)) req, err = http.NewRequest(“GET”, “https://beta.music.apple.com”+indexJsUri, nil) if err != nil { return “”, err } resp, err = http.DefaultClient.Do(req) if err != nil { return “”, err } defer resp.Body.Close() body, err = io.ReadAll(resp.Body) if err != nil { return “”, err } regex = regexp.MustCompile(eyJh([^"]*)) token := regex.FindString(string(body)) return token, nil } type ApiResult struct { Data []SongData json:"data" } type SongAttributes struct { ArtistName string json:"artistName" DiscNumber int json:"discNumber" GenreNames []string json:"genreNames" ExtendedAssetUrls struct { EnhancedHls string json:"enhancedHls" } json:"extendedAssetUrls" IsMasteredForItunes bool json:"isMasteredForItunes" ReleaseDate string json:"releaseDate" Name string json:"name" Isrc string json:"isrc" AlbumName string json:"albumName" TrackNumber int json:"trackNumber" ComposerName string json:"composerName" } type AlbumAttributes struct { ArtistName string json:"artistName" IsSingle bool json:"isSingle" IsComplete bool json:"isComplete" GenreNames []string json:"genreNames" TrackCount int json:"trackCount" IsMasteredForItunes bool json:"isMasteredForItunes" ReleaseDate string json:"releaseDate" Name string json:"name" RecordLabel string json:"recordLabel" Upc string json:"upc" Copyright string json:"copyright" IsCompilation bool json:"isCompilation" } type SongData struct { ID string json:"id" Attributes SongAttributes json:"attributes" Relationships struct { Albums struct { Data []struct { ID string json:"id" Type string json:"type" Href string json:"href" Attributes AlbumAttributes json:"attributes" } json:"data" } json:"albums" Artists struct { Href string json:"href" Data []struct { ID string json:"id" Type string json:"type" Href string json:"href" } json:"data" } json:"artists" } json:"relationships" } type SongResult struct { Artwork struct { Width int json:"width" URL string json:"url" Height int json:"height" TextColor3 string json:"textColor3" TextColor2 string json:"textColor2" TextColor4 string json:"textColor4" HasAlpha bool json:"hasAlpha" TextColor1 string json:"textColor1" BgColor string json:"bgColor" HasP3 bool json:"hasP3" SupportsLayeredImage bool json:"supportsLayeredImage" } json:"artwork" ArtistName string json:"artistName" CollectionID string json:"collectionId" DiscNumber int json:"discNumber" GenreNames []string json:"genreNames" ID string json:"id" DurationInMillis int json:"durationInMillis" ReleaseDate string json:"releaseDate" ContentRatingsBySystem struct { } json:"contentRatingsBySystem" Name string json:"name" Composer struct { Name string json:"name" URL string json:"url" } json:"composer" EditorialArtwork struct { } json:"editorialArtwork" CollectionName string json:"collectionName" AssetUrls struct { Plus string json:"plus" Lightweight string json:"lightweight" SuperLightweight string json:"superLightweight" LightweightPlus string json:"lightweightPlus" EnhancedHls string json:"enhancedHls" } json:"assetUrls" AudioTraits []string json:"audioTraits" Kind string json:"kind" Copyright string json:"copyright" ArtistID string json:"artistId" Genres []struct { GenreID string json:"genreId" Name string json:"name" URL string json:"url" MediaType string json:"mediaType" } json:"genres" TrackNumber int json:"trackNumber" AudioLocale string json:"audioLocale" Offers []struct { ActionText struct { Short string json:"short" Medium string json:"medium" Long string json:"long" Downloaded string json:"downloaded" Downloading string json:"downloading" } json:"actionText" Type string json:"type" PriceFormatted string json:"priceFormatted" Price float64 json:"price" BuyParams string json:"buyParams" Variant string json:"variant,omitempty" Assets []struct { Flavor string json:"flavor" Preview struct { Duration int json:"duration" URL string json:"url" } json:"preview" Size int json:"size" Duration int json:"duration" } json:"assets" } json:"offers" } type iTunesLookup struct { Results map[string]SongResult json:"results" } type Meta struct { Context string json:"@context" Type string json:"@type" Name string json:"name" Description string json:"description" Tracks []struct { Type string json:"@type" Name string json:"name" Audio struct { Type string json:"@type" } json:"audio" Offers struct { Type string json:"@type" Category string json:"category" Price int json:"price" } json:"offers" Duration string json:"duration" } json:"tracks" Citation []interface{} json:"citation" WorkExample []struct { Type string json:"@type" Name string json:"name" URL string json:"url" Audio struct { Type string json:"@type" } json:"audio" Offers struct { Type string json:"@type" Category string json:"category" Price int json:"price" } json:"offers" Duration string json:"duration" } json:"workExample" Genre []string json:"genre" DatePublished time.Time json:"datePublished" ByArtist struct { Type string json:"@type" URL string json:"url" Name string json:"name" } json:"byArtist" } type AutoGenerated struct { Data []struct { ID string json:"id" Type string json:"type" Href string json:"href" Attributes struct { Artwork struct { Width int json:"width" Height int json:"height" URL string json:"url" BgColor string json:"bgColor" TextColor1 string json:"textColor1" TextColor2 string json:"textColor2" TextColor3 string json:"textColor3" TextColor4 string json:"textColor4" } json:"artwork" ArtistName string json:"artistName" IsSingle bool json:"isSingle" URL string json:"url" IsComplete bool json:"isComplete" GenreNames []string json:"genreNames" TrackCount int json:"trackCount" IsMasteredForItunes bool json:"isMasteredForItunes" ReleaseDate string json:"releaseDate" Name string json:"name" RecordLabel string json:"recordLabel" Upc string json:"upc" AudioTraits []string json:"audioTraits" Copyright string json:"copyright" PlayParams struct { ID string json:"id" Kind string json:"kind" } json:"playParams" IsCompilation bool json:"isCompilation" } json:"attributes" Relationships struct { RecordLabels struct { Href string json:"href" Data []interface{} json:"data" } json:"record-labels" Artists struct { Href string json:"href" Data []struct { ID string json:"id" Type string json:"type" Href string json:"href" Attributes struct { Name string json:"name" } json:"attributes" } json:"data" } json:"artists" Tracks struct { Href string json:"href" Data []struct { ID string json:"id" Type string json:"type" Href string json:"href" Attributes struct { Previews []struct { URL string json:"url" } json:"previews" Artwork struct { Width int json:"width" Height int json:"height" URL string json:"url" BgColor string json:"bgColor" TextColor1 string json:"textColor1" TextColor2 string json:"textColor2" TextColor3 string json:"textColor3" TextColor4 string json:"textColor4" } json:"artwork" ArtistName string json:"artistName" URL string json:"url" DiscNumber int json:"discNumber" GenreNames []string json:"genreNames" HasTimeSyncedLyrics bool json:"hasTimeSyncedLyrics" IsMasteredForItunes bool json:"isMasteredForItunes" DurationInMillis int json:"durationInMillis" ReleaseDate string json:"releaseDate" Name string json:"name" Isrc string json:"isrc" AudioTraits []string json:"audioTraits" HasLyrics bool json:"hasLyrics" AlbumName string json:"albumName" PlayParams struct { ID string json:"id" Kind string json:"kind" } json:"playParams" TrackNumber int json:"trackNumber" AudioLocale string json:"audioLocale" ComposerName string json:"composerName" } json:"attributes" Relationships struct { Artists struct { Href string json:"href" Data []struct { ID string json:"id" Type string json:"type" Href string json:"href" Attributes struct { Name string json:"name" } json:"attributes" } json:"data" } json:"artists" } json:"relationships" } json:"data" } json:"tracks" } json:"relationships" } json:"data" } add explicit tag tagging and mention[E] to the track name having index# and track name mention here[E}
d4b44b153a0de9a4ba4a9f25102e8e43
{ "intermediate": 0.3162858188152313, "beginner": 0.41927504539489746, "expert": 0.26443925499916077 }
47,415
extends CharacterBody3D const SPEED = 3.0 const RUN_SPEED = 6.0 const JUMP_VELOCITY = 4.5 @onready var camera_point = $camera_point # Get the gravity from the project settings to be synced with RigidBody nodes. var gravity = ProjectSettings.get_setting("physics/3d/default_gravity") @onready var animation_player = $Visuals/player/AnimationPlayer @onready var visuals = $Visuals var walking = false var running = false func _ready(): animation_player.set_blend_time("idle", "walk", 0.2) animation_player.set_blend_time("walk", "idle", 0.2) animation_player.set_blend_time("idle", "run", 0.2) animation_player.set_blend_time("run", "idle", 0.2) animation_player.set_blend_time("walk", "run", 0.2) animation_player.set_blend_time("run", "walk", 0.2) animation_player.set_blend_time("idle", "mma kick", 0.2) animation_player.set_blend_time("walk", "mma kick", 0.2) animation_player.set_blend_time("run", "mma kick", 0.2) animation_player.set_blend_time("mma kick", "idle", 0.2) animation_player.set_blend_time("mma kick", "walk", 0.2) animation_player.set_blend_time("mma kick", "run", 0.2) # Optionally, sync animations with physics process for smoother transitions animation_player.playback_process_mode = AnimationPlayer.ANIMATION_PROCESS_PHYSICS var _was_on_floor_last_frame = false var _snapped_to_stairs_last_frame = false func _snap_down_to_stairs_check(): var did_snap = false if not is_on_floor() and velocity.y <= 0 and (_was_on_floor_last_frame or _snapped_to_stairs_last_frame) and $StairsBelowRayCast3D.is_colliding(): var body_test_params = PhysicsTestMotionParameters3D.new() var body_test_result = PhysicsTestMotionResult3D.new() var max_step_down = -0.5 body_test_params.from = self.global_transform body_test_params.motion = Vector3(0, max_step_down, 0) if PhysicsServer3D.body_test_motion(self.get_rid(), body_test_params, body_test_result): var translate_y = body_test_result.get_travel().y self.position.y += translate_y apply_floor_snap() did_snap = true _snapped_to_stairs_last_frame = did_snap _was_on_floor_last_frame = is_on_floor() func _physics_process(delta): # Add the gravity. if not is_on_floor(): velocity.y -= gravity * delta # Handle jump. if Input.is_action_just_pressed("ui_accept") and is_on_floor(): velocity.y = JUMP_VELOCITY # Get the input direction and handle the movement/deceleration. var input_dir = Input.get_vector("left", "right", "forward", "backward") var direction = (transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized() # Check for running if Input.is_action_pressed("run"): running = true else: running = false if direction: if running: velocity.x = direction.x * RUN_SPEED velocity.z = direction.z * RUN_SPEED else: velocity.x = direction.x * SPEED velocity.z = direction.z * SPEED visuals.look_at(direction + position) if !walking: walking = true if running: animation_player.play("run") else: animation_player.play("walk") else: velocity.x = move_toward(velocity.x, 0, SPEED) velocity.z = move_toward(velocity.z, 0, SPEED) if walking: walking = false animation_player.play("idle") # Check for "mma kick" animation if Input.is_action_just_pressed("mma kick"): animation_player.play("mma kick") animation_player.queue("") # Clear any queued animations move_and_slide() _snap_down_to_stairs_check() i did logifor s player to go down stairs but now how do i go up
65ef4f017806b47f301a5c1613bb62bc
{ "intermediate": 0.34904980659484863, "beginner": 0.42916420102119446, "expert": 0.2217859923839569 }
47,416
package main import ( "bytes" "encoding/binary" "encoding/json" "errors" "fmt" "io" "io/ioutil" "math" "net" "net/http" "net/url" "os" "path/filepath" "regexp" "sort" "strings" "time" "github.com/abema/go-mp4" "github.com/grafov/m3u8" ) const ( defaultId = "0" prefetchKey = "skd://itunes.apple.com/P000000000/s1/e1" ) var ( forbiddenNames = regexp.MustCompile(`[/\\<>:"|?*]`) ) type SampleInfo struct { data []byte duration uint32 descIndex uint32 } type SongInfo struct { r io.ReadSeeker alacParam *Alac samples []SampleInfo } func (s *SongInfo) Duration() (ret uint64) { for i := range s.samples { ret += uint64(s.samples[i].duration) } return } func (*Alac) GetType() mp4.BoxType { return BoxTypeAlac() } func fileExists(path string) (bool, error) { f, err := os.Stat(path) if err == nil { return !f.IsDir(), nil } else if os.IsNotExist(err) { return false, nil } return false, err } func writeM4a(w *mp4.Writer, info *SongInfo, meta *AutoGenerated, data []byte, trackNum, trackTotal int) error { index := trackNum - 1 { // ftyp box, err := w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeFtyp()}) if err != nil { return err } _, err = mp4.Marshal(w, &mp4.Ftyp{ MajorBrand: [4]byte{'M', '4', 'A', ' '}, MinorVersion: 0, CompatibleBrands: []mp4.CompatibleBrandElem{ {CompatibleBrand: [4]byte{'M', '4', 'A', ' '}}, {CompatibleBrand: [4]byte{'m', 'p', '4', '2'}}, {CompatibleBrand: mp4.BrandISOM()}, {CompatibleBrand: [4]byte{0, 0, 0, 0}}, }, }, box.Context) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } const chunkSize uint32 = 5 duration := info.Duration() numSamples := uint32(len(info.samples)) var stco *mp4.BoxInfo { // moov _, err := w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeMoov()}) if err != nil { return err } box, err := mp4.ExtractBox(info.r, nil, mp4.BoxPath{mp4.BoxTypeMoov()}) if err != nil { return err } moovOri := box[0] { // mvhd _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeMvhd()}) if err != nil { return err } oriBox, err := mp4.ExtractBoxWithPayload(info.r, moovOri, mp4.BoxPath{mp4.BoxTypeMvhd()}) if err != nil { return err } mvhd := oriBox[0].Payload.(*mp4.Mvhd) if mvhd.Version == 0 { mvhd.DurationV0 = uint32(duration) } else { mvhd.DurationV1 = duration } _, err = mp4.Marshal(w, mvhd, oriBox[0].Info.Context) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } { // trak _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeTrak()}) if err != nil { return err } box, err := mp4.ExtractBox(info.r, moovOri, mp4.BoxPath{mp4.BoxTypeTrak()}) if err != nil { return err } trakOri := box[0] { // tkhd _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeTkhd()}) if err != nil { return err } oriBox, err := mp4.ExtractBoxWithPayload(info.r, trakOri, mp4.BoxPath{mp4.BoxTypeTkhd()}) if err != nil { return err } tkhd := oriBox[0].Payload.(*mp4.Tkhd) if tkhd.Version == 0 { tkhd.DurationV0 = uint32(duration) } else { tkhd.DurationV1 = duration } tkhd.SetFlags(0x7) _, err = mp4.Marshal(w, tkhd, oriBox[0].Info.Context) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } { // mdia _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeMdia()}) if err != nil { return err } box, err := mp4.ExtractBox(info.r, trakOri, mp4.BoxPath{mp4.BoxTypeMdia()}) if err != nil { return err } mdiaOri := box[0] { // mdhd _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeMdhd()}) if err != nil { return err } oriBox, err := mp4.ExtractBoxWithPayload(info.r, mdiaOri, mp4.BoxPath{mp4.BoxTypeMdhd()}) if err != nil { return err } mdhd := oriBox[0].Payload.(*mp4.Mdhd) if mdhd.Version == 0 { mdhd.DurationV0 = uint32(duration) } else { mdhd.DurationV1 = duration } _, err = mp4.Marshal(w, mdhd, oriBox[0].Info.Context) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } { // hdlr oriBox, err := mp4.ExtractBox(info.r, mdiaOri, mp4.BoxPath{mp4.BoxTypeHdlr()}) if err != nil { return err } err = w.CopyBox(info.r, oriBox[0]) if err != nil { return err } } { // minf _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeMinf()}) if err != nil { return err } box, err := mp4.ExtractBox(info.r, mdiaOri, mp4.BoxPath{mp4.BoxTypeMinf()}) if err != nil { return err } minfOri := box[0] { // smhd, dinf boxes, err := mp4.ExtractBoxes(info.r, minfOri, []mp4.BoxPath{ {mp4.BoxTypeSmhd()}, {mp4.BoxTypeDinf()}, }) if err != nil { return err } for _, b := range boxes { err = w.CopyBox(info.r, b) if err != nil { return err } } } { // stbl _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeStbl()}) if err != nil { return err } { // stsd box, err := w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeStsd()}) if err != nil { return err } _, err = mp4.Marshal(w, &mp4.Stsd{EntryCount: 1}, box.Context) if err != nil { return err } { // alac _, err = w.StartBox(&mp4.BoxInfo{Type: BoxTypeAlac()}) if err != nil { return err } _, err = w.Write([]byte{ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}) if err != nil { return err } err = binary.Write(w, binary.BigEndian, uint16(info.alacParam.NumChannels)) if err != nil { return err } err = binary.Write(w, binary.BigEndian, uint16(info.alacParam.BitDepth)) if err != nil { return err } _, err = w.Write([]byte{0, 0}) if err != nil { return err } err = binary.Write(w, binary.BigEndian, info.alacParam.SampleRate) if err != nil { return err } _, err = w.Write([]byte{0, 0}) if err != nil { return err } box, err := w.StartBox(&mp4.BoxInfo{Type: BoxTypeAlac()}) if err != nil { return err } _, err = mp4.Marshal(w, info.alacParam, box.Context) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } _, err = w.EndBox() if err != nil { return err } } { // stts box, err := w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeStts()}) if err != nil { return err } var stts mp4.Stts for _, sample := range info.samples { if len(stts.Entries) != 0 { last := &stts.Entries[len(stts.Entries)-1] if last.SampleDelta == sample.duration { last.SampleCount++ continue } } stts.Entries = append(stts.Entries, mp4.SttsEntry{ SampleCount: 1, SampleDelta: sample.duration, }) } stts.EntryCount = uint32(len(stts.Entries)) _, err = mp4.Marshal(w, &stts, box.Context) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } { // stsc box, err := w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeStsc()}) if err != nil { return err } if numSamples%chunkSize == 0 { _, err = mp4.Marshal(w, &mp4.Stsc{ EntryCount: 1, Entries: []mp4.StscEntry{ { FirstChunk: 1, SamplesPerChunk: chunkSize, SampleDescriptionIndex: 1, }, }, }, box.Context) } else { _, err = mp4.Marshal(w, &mp4.Stsc{ EntryCount: 2, Entries: []mp4.StscEntry{ { FirstChunk: 1, SamplesPerChunk: chunkSize, SampleDescriptionIndex: 1, }, { FirstChunk: numSamples/chunkSize + 1, SamplesPerChunk: numSamples % chunkSize, SampleDescriptionIndex: 1, }, }, }, box.Context) } _, err = w.EndBox() if err != nil { return err } } { // stsz box, err := w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeStsz()}) if err != nil { return err } stsz := mp4.Stsz{SampleCount: numSamples} for _, sample := range info.samples { stsz.EntrySize = append(stsz.EntrySize, uint32(len(sample.data))) } _, err = mp4.Marshal(w, &stsz, box.Context) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } { // stco box, err := w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeStco()}) if err != nil { return err } l := (numSamples + chunkSize - 1) / chunkSize _, err = mp4.Marshal(w, &mp4.Stco{ EntryCount: l, ChunkOffset: make([]uint32, l), }, box.Context) stco, err = w.EndBox() if err != nil { return err } } _, err = w.EndBox() if err != nil { return err } } _, err = w.EndBox() if err != nil { return err } } _, err = w.EndBox() if err != nil { return err } } _, err = w.EndBox() if err != nil { return err } } { // udta ctx := mp4.Context{UnderUdta: true} _, err := w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeUdta(), Context: ctx}) if err != nil { return err } { // meta ctx.UnderIlstMeta = true _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeMeta(), Context: ctx}) if err != nil { return err } _, err = mp4.Marshal(w, &mp4.Meta{}, ctx) if err != nil { return err } { // hdlr _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeHdlr(), Context: ctx}) if err != nil { return err } _, err = mp4.Marshal(w, &mp4.Hdlr{ HandlerType: [4]byte{'m', 'd', 'i', 'r'}, Reserved: [3]uint32{0x6170706c, 0, 0}, }, ctx) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } { // ilst ctx.UnderIlst = true _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeIlst(), Context: ctx}) if err != nil { return err } marshalData := func(val interface{}) error { _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeData()}) if err != nil { return err } var boxData mp4.Data switch v := val.(type) { case string: boxData.DataType = mp4.DataTypeStringUTF8 boxData.Data = []byte(v) case uint8: boxData.DataType = mp4.DataTypeSignedIntBigEndian boxData.Data = []byte{v} case uint32: boxData.DataType = mp4.DataTypeSignedIntBigEndian boxData.Data = make([]byte, 4) binary.BigEndian.PutUint32(boxData.Data, v) case []byte: boxData.DataType = mp4.DataTypeBinary boxData.Data = v default: panic("unsupported value") } _, err = mp4.Marshal(w, &boxData, ctx) if err != nil { return err } _, err = w.EndBox() return err } addMeta := func(tag mp4.BoxType, val interface{}) error { _, err = w.StartBox(&mp4.BoxInfo{Type: tag}) if err != nil { return err } err = marshalData(val) if err != nil { return err } _, err = w.EndBox() return err } addExtendedMeta := func(name string, val interface{}) error { ctx.UnderIlstFreeMeta = true _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxType{'-', '-', '-', '-'}, Context: ctx}) if err != nil { return err } { _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxType{'m', 'e', 'a', 'n'}, Context: ctx}) if err != nil { return err } _, err = w.Write([]byte{0, 0, 0, 0}) if err != nil { return err } _, err = io.WriteString(w, "com.apple.iTunes") if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } { _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxType{'n', 'a', 'm', 'e'}, Context: ctx}) if err != nil { return err } _, err = w.Write([]byte{0, 0, 0, 0}) if err != nil { return err } _, err = io.WriteString(w, name) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } err = marshalData(val) if err != nil { return err } ctx.UnderIlstFreeMeta = false _, err = w.EndBox() return err } err = addMeta(mp4.BoxType{'\251', 'n', 'a', 'm'}, meta.Data[0].Relationships.Tracks.Data[index].Attributes.Name) if err != nil { return err } err = addMeta(mp4.BoxType{'\251', 'a', 'l', 'b'}, meta.Data[0].Attributes.Name) if err != nil { return err } err = addMeta(mp4.BoxType{'\251', 'A', 'R', 'T'}, meta.Data[0].Relationships.Tracks.Data[index].Attributes.ArtistName) if err != nil { return err } err = addMeta(mp4.BoxType{'\251', 'w', 'r', 't'}, meta.Data[0].Relationships.Tracks.Data[index].Attributes.ComposerName) if err != nil { return err } err = addMeta(mp4.BoxType{'\251', 'd', 'a', 'y'}, strings.Split(meta.Data[0].Attributes.ReleaseDate, "-")[0]) if err != nil { return err } // cnID, err := strconv.ParseUint(meta.Data[0].Relationships.Tracks.Data[index].ID, 10, 32) // if err != nil { // return err // } // err = addMeta(mp4.BoxType{'c', 'n', 'I', 'D'}, uint32(cnID)) // if err != nil { // return err // } err = addExtendedMeta("ISRC", meta.Data[0].Relationships.Tracks.Data[index].Attributes.Isrc) if err != nil { return err } if len(meta.Data[0].Relationships.Tracks.Data[index].Attributes.GenreNames) > 0 { err = addMeta(mp4.BoxType{'\251', 'g', 'e', 'n'}, meta.Data[0].Relationships.Tracks.Data[index].Attributes.GenreNames[0]) if err != nil { return err } } if len(meta.Data) > 0 { album := meta.Data[0] err = addMeta(mp4.BoxType{'a', 'A', 'R', 'T'}, album.Attributes.ArtistName) if err != nil { return err } err = addMeta(mp4.BoxType{'c', 'p', 'r', 't'}, album.Attributes.Copyright) if err != nil { return err } var isCpil uint8 if album.Attributes.IsCompilation { isCpil = 1 } err = addMeta(mp4.BoxType{'c', 'p', 'i', 'l'}, isCpil) if err != nil { return err } err = addExtendedMeta("LABEL", album.Attributes.RecordLabel) if err != nil { return err } err = addExtendedMeta("UPC", album.Attributes.Upc) if err != nil { return err } // plID, err := strconv.ParseUint(album.ID, 10, 32) // if err != nil { // return err // } // err = addMeta(mp4.BoxType{'p', 'l', 'I', 'D'}, uint32(plID)) // if err != nil { // return err // } } // if len(meta.Data[0].Relationships.Artists.Data) > 0 { // atID, err := strconv.ParseUint(meta.Data[0].Relationships.Artists.Data[index].ID, 10, 32) // if err != nil { // return err // } // err = addMeta(mp4.BoxType{'a', 't', 'I', 'D'}, uint32(atID)) // if err != nil { // return err // } // } trkn := make([]byte, 8) binary.BigEndian.PutUint32(trkn, uint32(trackNum)) binary.BigEndian.PutUint16(trkn[4:], uint16(trackTotal)) err = addMeta(mp4.BoxType{'t', 'r', 'k', 'n'}, trkn) if err != nil { return err } // disk := make([]byte, 8) // binary.BigEndian.PutUint32(disk, uint32(meta.Attributes.DiscNumber)) // err = addMeta(mp4.BoxType{'d', 'i', 's', 'k'}, disk) // if err != nil { // return err // } ctx.UnderIlst = false _, err = w.EndBox() if err != nil { return err } } ctx.UnderIlstMeta = false _, err = w.EndBox() if err != nil { return err } } ctx.UnderUdta = false _, err = w.EndBox() if err != nil { return err } } _, err = w.EndBox() if err != nil { return err } } { box, err := w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeMdat()}) if err != nil { return err } _, err = mp4.Marshal(w, &mp4.Mdat{Data: data}, box.Context) if err != nil { return err } mdat, err := w.EndBox() var realStco mp4.Stco offset := mdat.Offset + mdat.HeaderSize for i := uint32(0); i < numSamples; i++ { if i%chunkSize == 0 { realStco.EntryCount++ realStco.ChunkOffset = append(realStco.ChunkOffset, uint32(offset)) } offset += uint64(len(info.samples[i].data)) } _, err = stco.SeekToPayload(w) if err != nil { return err } _, err = mp4.Marshal(w, &realStco, box.Context) if err != nil { return err } } return nil } func decryptSong(info *SongInfo, keys []string, manifest *AutoGenerated, filename string, trackNum, trackTotal int) error { //fmt.Printf("%d-bit / %d Hz\n", info.bitDepth, info.bitRate) conn, err := net.Dial("tcp", "127.0.0.1:10020") if err != nil { return err } defer conn.Close() var decrypted []byte var lastIndex uint32 = math.MaxUint8 fmt.Println("Decrypt start.") for _, sp := range info.samples { if lastIndex != sp.descIndex { if len(decrypted) != 0 { _, err := conn.Write([]byte{0, 0, 0, 0}) if err != nil { return err } } keyUri := keys[sp.descIndex] id := manifest.Data[0].Relationships.Tracks.Data[trackNum-1].ID if keyUri == prefetchKey { id = defaultId } _, err := conn.Write([]byte{byte(len(id))}) if err != nil { return err } _, err = io.WriteString(conn, id) if err != nil { return err } _, err = conn.Write([]byte{byte(len(keyUri))}) if err != nil { return err } _, err = io.WriteString(conn, keyUri) if err != nil { return err } } lastIndex = sp.descIndex err := binary.Write(conn, binary.LittleEndian, uint32(len(sp.data))) if err != nil { return err } _, err = conn.Write(sp.data) if err != nil { return err } de := make([]byte, len(sp.data)) _, err = io.ReadFull(conn, de) if err != nil { return err } decrypted = append(decrypted, de...) } _, _ = conn.Write([]byte{0, 0, 0, 0, 0}) fmt.Println("Decrypt finished.") create, err := os.Create(filename) if err != nil { return err } defer create.Close() return writeM4a(mp4.NewWriter(create), info, manifest, decrypted, trackNum, trackTotal) } func checkUrl(url string) (string, string) { pat := regexp.MustCompile(`^(?:https:\/\/(?:beta\.music|music)\.apple\.com\/(\w{2})(?:\/album|\/album\/.+))\/(?:id)?(\d[^\D]+)(?:$|\?)`) matches := pat.FindAllStringSubmatch(url, -1) if matches == nil { return "", "" } else { return matches[0][1], matches[0][2] } } func getMeta(albumId string, token string, storefront string) (*AutoGenerated, error) { req, err := http.NewRequest("GET", fmt.Sprintf("https://amp-api.music.apple.com/v1/catalog/%s/albums/%s", storefront, albumId), nil) if err != nil { return nil, err } req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token)) req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36") req.Header.Set("Origin", "https://music.apple.com") query := url.Values{} query.Set("omit[resource]", "autos") query.Set("include", "tracks,artists,record-labels") query.Set("include[songs]", "artists") query.Set("fields[artists]", "name") query.Set("fields[albums:albums]", "artistName,artwork,name,releaseDate,url") query.Set("fields[record-labels]", "name") // query.Set("l", "en-gb") req.URL.RawQuery = query.Encode() do, err := http.DefaultClient.Do(req) if err != nil { return nil, err } defer do.Body.Close() if do.StatusCode != http.StatusOK { return nil, errors.New(do.Status) } obj := new(AutoGenerated) err = json.NewDecoder(do.Body).Decode(&obj) if err != nil { return nil, err } return obj, nil } func writeCover(sanAlbumFolder, url string) error { covPath := filepath.Join(sanAlbumFolder, "cover.jpg") exists, err := fileExists(covPath) if err != nil { fmt.Println("Failed to check if cover exists.") return err } if exists { return nil } url = strings.Replace(url, "{w}x{h}", "1200x12000", 1) req, err := http.NewRequest("GET", url, nil) if err != nil { return err } req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36") do, err := http.DefaultClient.Do(req) if err != nil { return err } defer do.Body.Close() if do.StatusCode != http.StatusOK { errors.New(do.Status) } f, err := os.Create(covPath) if err != nil { return err } defer f.Close() _, err = io.Copy(f, do.Body) if err != nil { return err } return nil } func rip(albumId string, token string, storefront string) error { meta, err := getMeta(albumId, token, storefront) if err != nil { fmt.Println("Failed to get album metadata.\n") return err } albumFolder := fmt.Sprintf("%s - %s", meta.Data[0].Attributes.ArtistName, meta.Data[0].Attributes.Name) sanAlbumFolder := filepath.Join("AM-DL downloads", forbiddenNames.ReplaceAllString(albumFolder, "_")) os.MkdirAll(sanAlbumFolder, os.ModePerm) fmt.Println(albumFolder) err = writeCover(sanAlbumFolder, meta.Data[0].Attributes.Artwork.URL) if err != nil { fmt.Println("Failed to write cover.") } trackTotal := len(meta.Data[0].Relationships.Tracks.Data) for trackNum, track := range meta.Data[0].Relationships.Tracks.Data { trackNum++ explicitTag := "" if track.Attributes.IsExplicit { explicitTag = " [E]" } fmt.Printf("Track %d of %d:\n", trackNum, trackTotal) manifest, err := getInfoFromAdam(track.ID, token, storefront) if err != nil { fmt.Println("Failed to get manifest.\n", err) continue } if manifest.Attributes.ExtendedAssetUrls.EnhancedHls == "" { fmt.Println("Unavailable in ALAC.") continue } filename := fmt.Sprintf("%02d. %s.m4a", trackNum, forbiddenNames.ReplaceAllString(track.Attributes.Name, "_"), explicitTag) trackPath := filepath.Join(sanAlbumFolder, filename) exists, err := fileExists(trackPath) if err != nil { fmt.Println("Failed to check if track exists.") } if exists { fmt.Println("Track already exists locally.") continue } trackUrl, keys, err := extractMedia(manifest.Attributes.ExtendedAssetUrls.EnhancedHls) if err != nil { fmt.Println("Failed to extract info from manifest.\n", err) continue } info, err := extractSong(trackUrl) if err != nil { fmt.Println("Failed to extract track.", err) continue } samplesOk := true for samplesOk { for _, i := range info.samples { if int(i.descIndex) >= len(keys) { fmt.Println("Decryption size mismatch.") samplesOk = false } } break } if !samplesOk { continue } err = decryptSong(info, keys, meta, trackPath, trackNum, trackTotal) if err != nil { fmt.Println("Failed to decrypt track.\n", err) continue } } return err } func main() { token, err := getToken() if err != nil { fmt.Println("Failed to get token.") return } albumTotal := len(os.Args[1:]) for albumNum, url := range os.Args[1:] { fmt.Printf("Album %d of %d:\n", albumNum+1, albumTotal) storefront, albumId := checkUrl(url) if albumId == "" { fmt.Printf("Invalid URL: %s\n", url) continue } err := rip(albumId, token, storefront) if err != nil { fmt.Println("Album failed.") fmt.Println(err) } } } func extractMedia(b string) (string, []string, error) { masterUrl, err := url.Parse(b) if err != nil { return "", nil, err } resp, err := http.Get(b) if err != nil { return "", nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return "", nil, errors.New(resp.Status) } body, err := io.ReadAll(resp.Body) if err != nil { return "", nil, err } masterString := string(body) from, listType, err := m3u8.DecodeFrom(strings.NewReader(masterString), true) if err != nil || listType != m3u8.MASTER { return "", nil, errors.New("m3u8 not of master type") } master := from.(*m3u8.MasterPlaylist) var streamUrl *url.URL sort.Slice(master.Variants, func(i, j int) bool { return master.Variants[i].AverageBandwidth > master.Variants[j].AverageBandwidth }) for _, variant := range master.Variants { if variant.Codecs == "alac" { split := strings.Split(variant.Audio, "-") length := len(split) fmt.Printf("%s-bit / %s Hz\n", split[length-1], split[length-2]) streamUrlTemp, err := masterUrl.Parse(variant.URI) if err != nil { panic(err) } streamUrl = streamUrlTemp break } } if streamUrl == nil { return "", nil, errors.New("no alac codec found") } var keys []string keys = append(keys, prefetchKey) streamUrl.Path = strings.TrimSuffix(streamUrl.Path, ".m3u8") + "_m.mp4" regex := regexp.MustCompile(`"(skd?://[^"]*)"`) matches := regex.FindAllStringSubmatch(masterString, -1) for _, match := range matches { if strings.HasSuffix(match[1], "c23") || strings.HasSuffix(match[1], "c6") { keys = append(keys, match[1]) } } return streamUrl.String(), keys, nil } func extractSong(url string) (*SongInfo, error) { fmt.Println("Downloading...") track, err := http.Get(url) if err != nil { return nil, err } defer track.Body.Close() if track.StatusCode != http.StatusOK { return nil, errors.New(track.Status) } rawSong, err := ioutil.ReadAll(track.Body) if err != nil { return nil, err } fmt.Println("Downloaded.") f := bytes.NewReader(rawSong) trex, err := mp4.ExtractBoxWithPayload(f, nil, []mp4.BoxType{ mp4.BoxTypeMoov(), mp4.BoxTypeMvex(), mp4.BoxTypeTrex(), }) if err != nil || len(trex) != 1 { return nil, err } trexPay := trex[0].Payload.(*mp4.Trex) stbl, err := mp4.ExtractBox(f, nil, []mp4.BoxType{ mp4.BoxTypeMoov(), mp4.BoxTypeTrak(), mp4.BoxTypeMdia(), mp4.BoxTypeMinf(), mp4.BoxTypeStbl(), }) if err != nil || len(stbl) != 1 { return nil, err } enca, err := mp4.ExtractBoxWithPayload(f, stbl[0], []mp4.BoxType{ mp4.BoxTypeStsd(), mp4.BoxTypeEnca(), }) if err != nil { return nil, err } aalac, err := mp4.ExtractBoxWithPayload(f, &enca[0].Info, []mp4.BoxType{BoxTypeAlac()}) if err != nil || len(aalac) != 1 { return nil, err } extracted := &SongInfo{ r: f, alacParam: aalac[0].Payload.(*Alac), } moofs, err := mp4.ExtractBox(f, nil, []mp4.BoxType{ mp4.BoxTypeMoof(), }) if err != nil || len(moofs) <= 0 { return nil, err } mdats, err := mp4.ExtractBoxWithPayload(f, nil, []mp4.BoxType{ mp4.BoxTypeMdat(), }) if err != nil || len(mdats) != len(moofs) { return nil, err } for i, moof := range moofs { tfhd, err := mp4.ExtractBoxWithPayload(f, moof, []mp4.BoxType{ mp4.BoxTypeTraf(), mp4.BoxTypeTfhd(), }) if err != nil || len(tfhd) != 1 { return nil, err } tfhdPay := tfhd[0].Payload.(*mp4.Tfhd) index := tfhdPay.SampleDescriptionIndex if index != 0 { index-- } truns, err := mp4.ExtractBoxWithPayload(f, moof, []mp4.BoxType{ mp4.BoxTypeTraf(), mp4.BoxTypeTrun(), }) if err != nil || len(truns) <= 0 { return nil, err } mdat := mdats[i].Payload.(*mp4.Mdat).Data for _, t := range truns { for _, en := range t.Payload.(*mp4.Trun).Entries { info := SampleInfo{descIndex: index} switch { case t.Payload.CheckFlag(0x200): info.data = mdat[:en.SampleSize] mdat = mdat[en.SampleSize:] case tfhdPay.CheckFlag(0x10): info.data = mdat[:tfhdPay.DefaultSampleSize] mdat = mdat[tfhdPay.DefaultSampleSize:] default: info.data = mdat[:trexPay.DefaultSampleSize] mdat = mdat[trexPay.DefaultSampleSize:] } switch { case t.Payload.CheckFlag(0x100): info.duration = en.SampleDuration case tfhdPay.CheckFlag(0x8): info.duration = tfhdPay.DefaultSampleDuration default: info.duration = trexPay.DefaultSampleDuration } extracted.samples = append(extracted.samples, info) } } if len(mdat) != 0 { return nil, errors.New("offset mismatch") } } return extracted, nil } func init() { mp4.AddBoxDef((*Alac)(nil)) } func BoxTypeAlac() mp4.BoxType { return mp4.StrToBoxType("alac") } type Alac struct { mp4.FullBox `mp4:"extend"` FrameLength uint32 `mp4:"size=32"` CompatibleVersion uint8 `mp4:"size=8"` BitDepth uint8 `mp4:"size=8"` Pb uint8 `mp4:"size=8"` Mb uint8 `mp4:"size=8"` Kb uint8 `mp4:"size=8"` NumChannels uint8 `mp4:"size=8"` MaxRun uint16 `mp4:"size=16"` MaxFrameBytes uint32 `mp4:"size=32"` AvgBitRate uint32 `mp4:"size=32"` SampleRate uint32 `mp4:"size=32"` } func getInfoFromAdam(adamId string, token string, storefront string) (*SongData, error) { request, err := http.NewRequest("GET", fmt.Sprintf("https://amp-api.music.apple.com/v1/catalog/%s/songs/%s", storefront, adamId), nil) if err != nil { return nil, err } query := url.Values{} query.Set("extend", "extendedAssetUrls") query.Set("include", "albums") request.URL.RawQuery = query.Encode() request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token)) request.Header.Set("User-Agent", "iTunes/12.11.3 (Windows; Microsoft Windows 10 x64 Professional Edition (Build 19041); x64) AppleWebKit/7611.1022.4001.1 (dt:2)") request.Header.Set("Origin", "https://music.apple.com") do, err := http.DefaultClient.Do(request) if err != nil { return nil, err } defer do.Body.Close() if do.StatusCode != http.StatusOK { return nil, errors.New(do.Status) } obj := new(ApiResult) err = json.NewDecoder(do.Body).Decode(&obj) if err != nil { return nil, err } for _, d := range obj.Data { if d.ID == adamId { return &d, nil } } return nil, nil } func getToken() (string, error) { req, err := http.NewRequest("GET", "https://beta.music.apple.com", nil) if err != nil { return "", err } resp, err := http.DefaultClient.Do(req) if err != nil { return "", err } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { return "", err } regex := regexp.MustCompile(`/assets/index-legacy-[^/]+\.js`) indexJsUri := regex.FindString(string(body)) req, err = http.NewRequest("GET", "https://beta.music.apple.com"+indexJsUri, nil) if err != nil { return "", err } resp, err = http.DefaultClient.Do(req) if err != nil { return "", err } defer resp.Body.Close() body, err = io.ReadAll(resp.Body) if err != nil { return "", err } regex = regexp.MustCompile(`eyJh([^"]*)`) token := regex.FindString(string(body)) return token, nil } type ApiResult struct { Data []SongData `json:"data"` } type SongAttributes struct { ArtistName string `json:"artistName"` DiscNumber int `json:"discNumber"` GenreNames []string `json:"genreNames"` ExtendedAssetUrls struct { EnhancedHls string `json:"enhancedHls"` } `json:"extendedAssetUrls"` IsMasteredForItunes bool `json:"isMasteredForItunes"` ReleaseDate string `json:"releaseDate"` Name string `json:"name"` Isrc string `json:"isrc"` AlbumName string `json:"albumName"` TrackNumber int `json:"trackNumber"` ComposerName string `json:"composerName"` IsExplicit bool `json:"isExplicit"` } type AlbumAttributes struct { ArtistName string `json:"artistName"` IsSingle bool `json:"isSingle"` IsComplete bool `json:"isComplete"` GenreNames []string `json:"genreNames"` TrackCount int `json:"trackCount"` IsMasteredForItunes bool `json:"isMasteredForItunes"` ReleaseDate string `json:"releaseDate"` Name string `json:"name"` RecordLabel string `json:"recordLabel"` Upc string `json:"upc"` Copyright string `json:"copyright"` IsCompilation bool `json:"isCompilation"` IsExplicit bool `json:"isExplicit"` } type SongData struct { ID string `json:"id"` Attributes SongAttributes `json:"attributes"` Relationships struct { Albums struct { Data []struct { ID string `json:"id"` Type string `json:"type"` Href string `json:"href"` Attributes AlbumAttributes `json:"attributes"` } `json:"data"` } `json:"albums"` Artists struct { Href string `json:"href"` Data []struct { ID string `json:"id"` Type string `json:"type"` Href string `json:"href"` } `json:"data"` } `json:"artists"` } `json:"relationships"` } type SongResult struct { Artwork struct { Width int `json:"width"` URL string `json:"url"` Height int `json:"height"` TextColor3 string `json:"textColor3"` TextColor2 string `json:"textColor2"` TextColor4 string `json:"textColor4"` HasAlpha bool `json:"hasAlpha"` TextColor1 string `json:"textColor1"` BgColor string `json:"bgColor"` HasP3 bool `json:"hasP3"` SupportsLayeredImage bool `json:"supportsLayeredImage"` } `json:"artwork"` ArtistName string `json:"artistName"` CollectionID string `json:"collectionId"` DiscNumber int `json:"discNumber"` GenreNames []string `json:"genreNames"` ID string `json:"id"` DurationInMillis int `json:"durationInMillis"` ReleaseDate string `json:"releaseDate"` ContentRatingsBySystem struct { } `json:"contentRatingsBySystem"` Name string `json:"name"` Composer struct { Name string `json:"name"` URL string `json:"url"` } `json:"composer"` EditorialArtwork struct { } `json:"editorialArtwork"` CollectionName string `json:"collectionName"` AssetUrls struct { Plus string `json:"plus"` Lightweight string `json:"lightweight"` SuperLightweight string `json:"superLightweight"` LightweightPlus string `json:"lightweightPlus"` EnhancedHls string `json:"enhancedHls"` } `json:"assetUrls"` AudioTraits []string `json:"audioTraits"` Kind string `json:"kind"` Copyright string `json:"copyright"` ArtistID string `json:"artistId"` Genres []struct { GenreID string `json:"genreId"` Name string `json:"name"` URL string `json:"url"` MediaType string `json:"mediaType"` } `json:"genres"` TrackNumber int `json:"trackNumber"` AudioLocale string `json:"audioLocale"` Offers []struct { ActionText struct { Short string `json:"short"` Medium string `json:"medium"` Long string `json:"long"` Downloaded string `json:"downloaded"` Downloading string `json:"downloading"` } `json:"actionText"` Type string `json:"type"` PriceFormatted string `json:"priceFormatted"` Price float64 `json:"price"` BuyParams string `json:"buyParams"` Variant string `json:"variant,omitempty"` Assets []struct { Flavor string `json:"flavor"` Preview struct { Duration int `json:"duration"` URL string `json:"url"` } `json:"preview"` Size int `json:"size"` Duration int `json:"duration"` } `json:"assets"` } `json:"offers"` } type iTunesLookup struct { Results map[string]SongResult `json:"results"` } type Meta struct { Context string `json:"@context"` Type string `json:"@type"` Name string `json:"name"` Description string `json:"description"` Tracks []struct { Type string `json:"@type"` Name string `json:"name"` Audio struct { Type string `json:"@type"` } `json:"audio"` Offers struct { Type string `json:"@type"` Category string `json:"category"` Price int `json:"price"` } `json:"offers"` Duration string `json:"duration"` } `json:"tracks"` Citation []interface{} `json:"citation"` WorkExample []struct { Type string `json:"@type"` Name string `json:"name"` URL string `json:"url"` Audio struct { Type string `json:"@type"` } `json:"audio"` Offers struct { Type string `json:"@type"` Category string `json:"category"` Price int `json:"price"` } `json:"offers"` Duration string `json:"duration"` } `json:"workExample"` Genre []string `json:"genre"` DatePublished time.Time `json:"datePublished"` ByArtist struct { Type string `json:"@type"` URL string `json:"url"` Name string `json:"name"` } `json:"byArtist"` } type AutoGenerated struct { Data []struct { ID string `json:"id"` Type string `json:"type"` Href string `json:"href"` Attributes struct { Artwork struct { Width int `json:"width"` Height int `json:"height"` URL string `json:"url"` BgColor string `json:"bgColor"` TextColor1 string `json:"textColor1"` TextColor2 string `json:"textColor2"` TextColor3 string `json:"textColor3"` TextColor4 string `json:"textColor4"` } `json:"artwork"` ArtistName string `json:"artistName"` IsSingle bool `json:"isSingle"` URL string `json:"url"` IsComplete bool `json:"isComplete"` GenreNames []string `json:"genreNames"` TrackCount int `json:"trackCount"` IsMasteredForItunes bool `json:"isMasteredForItunes"` ReleaseDate string `json:"releaseDate"` IsExplicit bool `json:"isExplicit"` Name string `json:"name"` RecordLabel string `json:"recordLabel"` Upc string `json:"upc"` AudioTraits []string `json:"audioTraits"` Copyright string `json:"copyright"` PlayParams struct { ID string `json:"id"` Kind string `json:"kind"` } `json:"playParams"` IsCompilation bool `json:"isCompilation"` } `json:"attributes"` Relationships struct { RecordLabels struct { Href string `json:"href"` Data []interface{} `json:"data"` } `json:"record-labels"` Artists struct { Href string `json:"href"` Data []struct { ID string `json:"id"` Type string `json:"type"` Href string `json:"href"` Attributes struct { Name string `json:"name"` } `json:"attributes"` } `json:"data"` } `json:"artists"` Tracks struct { Href string `json:"href"` Data []struct { ID string `json:"id"` Type string `json:"type"` Href string `json:"href"` Attributes struct { Previews []struct { URL string `json:"url"` } `json:"previews"` Artwork struct { Width int `json:"width"` Height int `json:"height"` URL string `json:"url"` BgColor string `json:"bgColor"` TextColor1 string `json:"textColor1"` TextColor2 string `json:"textColor2"` TextColor3 string `json:"textColor3"` TextColor4 string `json:"textColor4"` } `json:"artwork"` ArtistName string `json:"artistName"` URL string `json:"url"` DiscNumber int `json:"discNumber"` GenreNames []string `json:"genreNames"` HasTimeSyncedLyrics bool `json:"hasTimeSyncedLyrics"` IsMasteredForItunes bool `json:"isMasteredForItunes"` DurationInMillis int `json:"durationInMillis"` ReleaseDate string `json:"releaseDate"` IsExplicit bool `json:"isExplicit"` Name string `json:"name"` Isrc string `json:"isrc"` AudioTraits []string `json:"audioTraits"` HasLyrics bool `json:"hasLyrics"` AlbumName string `json:"albumName"` PlayParams struct { ID string `json:"id"` Kind string `json:"kind"` } `json:"playParams"` TrackNumber int `json:"trackNumber"` AudioLocale string `json:"audioLocale"` ComposerName string `json:"composerName"` } `json:"attributes"` Relationships struct { Artists struct { Href string `json:"href"` Data []struct { ID string `json:"id"` Type string `json:"type"` Href string `json:"href"` Attributes struct { Name string `json:"name"` } `json:"attributes"` } `json:"data"` } `json:"artists"` } `json:"relationships"` } `json:"data"` } `json:"tracks"` } `json:"relationships"` } `json:"data"` } i have added explicit but output is : 02. .m4a%!(EXTRA string=Champagne Problems)
52a7a710d8bab95ba4a26eba78b46377
{ "intermediate": 0.33890464901924133, "beginner": 0.44517913460731506, "expert": 0.21591626107692719 }
47,417
python is example of:
f926e4e52bc25442cc0f331ada660856
{ "intermediate": 0.3263927698135376, "beginner": 0.3451583683490753, "expert": 0.3284488618373871 }
47,418
package main import ( "bytes" "encoding/binary" "encoding/json" "errors" "fmt" "io" "io/ioutil" "math" "net" "net/http" "net/url" "os" "path/filepath" "regexp" "sort" "strings" "time" "github.com/abema/go-mp4" "github.com/grafov/m3u8" ) const ( defaultId = "0" prefetchKey = "skd://itunes.apple.com/P000000000/s1/e1" ) var ( forbiddenNames = regexp.MustCompile(`[/\\<>:"|?*]`) ) type SampleInfo struct { data []byte duration uint32 descIndex uint32 } type SongInfo struct { r io.ReadSeeker alacParam *Alac samples []SampleInfo } func (s *SongInfo) Duration() (ret uint64) { for i := range s.samples { ret += uint64(s.samples[i].duration) } return } func (*Alac) GetType() mp4.BoxType { return BoxTypeAlac() } func fileExists(path string) (bool, error) { f, err := os.Stat(path) if err == nil { return !f.IsDir(), nil } else if os.IsNotExist(err) { return false, nil } return false, err } func writeM4a(w *mp4.Writer, info *SongInfo, meta *AutoGenerated, data []byte, trackNum, trackTotal int) error { index := trackNum - 1 { // ftyp box, err := w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeFtyp()}) if err != nil { return err } _, err = mp4.Marshal(w, &mp4.Ftyp{ MajorBrand: [4]byte{'M', '4', 'A', ' '}, MinorVersion: 0, CompatibleBrands: []mp4.CompatibleBrandElem{ {CompatibleBrand: [4]byte{'M', '4', 'A', ' '}}, {CompatibleBrand: [4]byte{'m', 'p', '4', '2'}}, {CompatibleBrand: mp4.BrandISOM()}, {CompatibleBrand: [4]byte{0, 0, 0, 0}}, }, }, box.Context) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } const chunkSize uint32 = 5 duration := info.Duration() numSamples := uint32(len(info.samples)) var stco *mp4.BoxInfo { // moov _, err := w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeMoov()}) if err != nil { return err } box, err := mp4.ExtractBox(info.r, nil, mp4.BoxPath{mp4.BoxTypeMoov()}) if err != nil { return err } moovOri := box[0] { // mvhd _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeMvhd()}) if err != nil { return err } oriBox, err := mp4.ExtractBoxWithPayload(info.r, moovOri, mp4.BoxPath{mp4.BoxTypeMvhd()}) if err != nil { return err } mvhd := oriBox[0].Payload.(*mp4.Mvhd) if mvhd.Version == 0 { mvhd.DurationV0 = uint32(duration) } else { mvhd.DurationV1 = duration } _, err = mp4.Marshal(w, mvhd, oriBox[0].Info.Context) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } { // trak _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeTrak()}) if err != nil { return err } box, err := mp4.ExtractBox(info.r, moovOri, mp4.BoxPath{mp4.BoxTypeTrak()}) if err != nil { return err } trakOri := box[0] { // tkhd _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeTkhd()}) if err != nil { return err } oriBox, err := mp4.ExtractBoxWithPayload(info.r, trakOri, mp4.BoxPath{mp4.BoxTypeTkhd()}) if err != nil { return err } tkhd := oriBox[0].Payload.(*mp4.Tkhd) if tkhd.Version == 0 { tkhd.DurationV0 = uint32(duration) } else { tkhd.DurationV1 = duration } tkhd.SetFlags(0x7) _, err = mp4.Marshal(w, tkhd, oriBox[0].Info.Context) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } { // mdia _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeMdia()}) if err != nil { return err } box, err := mp4.ExtractBox(info.r, trakOri, mp4.BoxPath{mp4.BoxTypeMdia()}) if err != nil { return err } mdiaOri := box[0] { // mdhd _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeMdhd()}) if err != nil { return err } oriBox, err := mp4.ExtractBoxWithPayload(info.r, mdiaOri, mp4.BoxPath{mp4.BoxTypeMdhd()}) if err != nil { return err } mdhd := oriBox[0].Payload.(*mp4.Mdhd) if mdhd.Version == 0 { mdhd.DurationV0 = uint32(duration) } else { mdhd.DurationV1 = duration } _, err = mp4.Marshal(w, mdhd, oriBox[0].Info.Context) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } { // hdlr oriBox, err := mp4.ExtractBox(info.r, mdiaOri, mp4.BoxPath{mp4.BoxTypeHdlr()}) if err != nil { return err } err = w.CopyBox(info.r, oriBox[0]) if err != nil { return err } } { // minf _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeMinf()}) if err != nil { return err } box, err := mp4.ExtractBox(info.r, mdiaOri, mp4.BoxPath{mp4.BoxTypeMinf()}) if err != nil { return err } minfOri := box[0] { // smhd, dinf boxes, err := mp4.ExtractBoxes(info.r, minfOri, []mp4.BoxPath{ {mp4.BoxTypeSmhd()}, {mp4.BoxTypeDinf()}, }) if err != nil { return err } for _, b := range boxes { err = w.CopyBox(info.r, b) if err != nil { return err } } } { // stbl _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeStbl()}) if err != nil { return err } { // stsd box, err := w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeStsd()}) if err != nil { return err } _, err = mp4.Marshal(w, &mp4.Stsd{EntryCount: 1}, box.Context) if err != nil { return err } { // alac _, err = w.StartBox(&mp4.BoxInfo{Type: BoxTypeAlac()}) if err != nil { return err } _, err = w.Write([]byte{ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}) if err != nil { return err } err = binary.Write(w, binary.BigEndian, uint16(info.alacParam.NumChannels)) if err != nil { return err } err = binary.Write(w, binary.BigEndian, uint16(info.alacParam.BitDepth)) if err != nil { return err } _, err = w.Write([]byte{0, 0}) if err != nil { return err } err = binary.Write(w, binary.BigEndian, info.alacParam.SampleRate) if err != nil { return err } _, err = w.Write([]byte{0, 0}) if err != nil { return err } box, err := w.StartBox(&mp4.BoxInfo{Type: BoxTypeAlac()}) if err != nil { return err } _, err = mp4.Marshal(w, info.alacParam, box.Context) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } _, err = w.EndBox() if err != nil { return err } } { // stts box, err := w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeStts()}) if err != nil { return err } var stts mp4.Stts for _, sample := range info.samples { if len(stts.Entries) != 0 { last := &stts.Entries[len(stts.Entries)-1] if last.SampleDelta == sample.duration { last.SampleCount++ continue } } stts.Entries = append(stts.Entries, mp4.SttsEntry{ SampleCount: 1, SampleDelta: sample.duration, }) } stts.EntryCount = uint32(len(stts.Entries)) _, err = mp4.Marshal(w, &stts, box.Context) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } { // stsc box, err := w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeStsc()}) if err != nil { return err } if numSamples%chunkSize == 0 { _, err = mp4.Marshal(w, &mp4.Stsc{ EntryCount: 1, Entries: []mp4.StscEntry{ { FirstChunk: 1, SamplesPerChunk: chunkSize, SampleDescriptionIndex: 1, }, }, }, box.Context) } else { _, err = mp4.Marshal(w, &mp4.Stsc{ EntryCount: 2, Entries: []mp4.StscEntry{ { FirstChunk: 1, SamplesPerChunk: chunkSize, SampleDescriptionIndex: 1, }, { FirstChunk: numSamples/chunkSize + 1, SamplesPerChunk: numSamples % chunkSize, SampleDescriptionIndex: 1, }, }, }, box.Context) } _, err = w.EndBox() if err != nil { return err } } { // stsz box, err := w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeStsz()}) if err != nil { return err } stsz := mp4.Stsz{SampleCount: numSamples} for _, sample := range info.samples { stsz.EntrySize = append(stsz.EntrySize, uint32(len(sample.data))) } _, err = mp4.Marshal(w, &stsz, box.Context) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } { // stco box, err := w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeStco()}) if err != nil { return err } l := (numSamples + chunkSize - 1) / chunkSize _, err = mp4.Marshal(w, &mp4.Stco{ EntryCount: l, ChunkOffset: make([]uint32, l), }, box.Context) stco, err = w.EndBox() if err != nil { return err } } _, err = w.EndBox() if err != nil { return err } } _, err = w.EndBox() if err != nil { return err } } _, err = w.EndBox() if err != nil { return err } } _, err = w.EndBox() if err != nil { return err } } { // udta ctx := mp4.Context{UnderUdta: true} _, err := w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeUdta(), Context: ctx}) if err != nil { return err } { // meta ctx.UnderIlstMeta = true _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeMeta(), Context: ctx}) if err != nil { return err } _, err = mp4.Marshal(w, &mp4.Meta{}, ctx) if err != nil { return err } { // hdlr _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeHdlr(), Context: ctx}) if err != nil { return err } _, err = mp4.Marshal(w, &mp4.Hdlr{ HandlerType: [4]byte{'m', 'd', 'i', 'r'}, Reserved: [3]uint32{0x6170706c, 0, 0}, }, ctx) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } { // ilst ctx.UnderIlst = true _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeIlst(), Context: ctx}) if err != nil { return err } marshalData := func(val interface{}) error { _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeData()}) if err != nil { return err } var boxData mp4.Data switch v := val.(type) { case string: boxData.DataType = mp4.DataTypeStringUTF8 boxData.Data = []byte(v) case uint8: boxData.DataType = mp4.DataTypeSignedIntBigEndian boxData.Data = []byte{v} case uint32: boxData.DataType = mp4.DataTypeSignedIntBigEndian boxData.Data = make([]byte, 4) binary.BigEndian.PutUint32(boxData.Data, v) case []byte: boxData.DataType = mp4.DataTypeBinary boxData.Data = v default: panic("unsupported value") } _, err = mp4.Marshal(w, &boxData, ctx) if err != nil { return err } _, err = w.EndBox() return err } addMeta := func(tag mp4.BoxType, val interface{}) error { _, err = w.StartBox(&mp4.BoxInfo{Type: tag}) if err != nil { return err } err = marshalData(val) if err != nil { return err } _, err = w.EndBox() return err } addExtendedMeta := func(name string, val interface{}) error { ctx.UnderIlstFreeMeta = true _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxType{'-', '-', '-', '-'}, Context: ctx}) if err != nil { return err } { _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxType{'m', 'e', 'a', 'n'}, Context: ctx}) if err != nil { return err } _, err = w.Write([]byte{0, 0, 0, 0}) if err != nil { return err } _, err = io.WriteString(w, "com.apple.iTunes") if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } { _, err = w.StartBox(&mp4.BoxInfo{Type: mp4.BoxType{'n', 'a', 'm', 'e'}, Context: ctx}) if err != nil { return err } _, err = w.Write([]byte{0, 0, 0, 0}) if err != nil { return err } _, err = io.WriteString(w, name) if err != nil { return err } _, err = w.EndBox() if err != nil { return err } } err = marshalData(val) if err != nil { return err } ctx.UnderIlstFreeMeta = false _, err = w.EndBox() return err } err = addMeta(mp4.BoxType{'\251', 'n', 'a', 'm'}, meta.Data[0].Relationships.Tracks.Data[index].Attributes.Name) if err != nil { return err } err = addMeta(mp4.BoxType{'\251', 'a', 'l', 'b'}, meta.Data[0].Attributes.Name) if err != nil { return err } err = addMeta(mp4.BoxType{'\251', 'A', 'R', 'T'}, meta.Data[0].Relationships.Tracks.Data[index].Attributes.ArtistName) if err != nil { return err } err = addMeta(mp4.BoxType{'\251', 'w', 'r', 't'}, meta.Data[0].Relationships.Tracks.Data[index].Attributes.ComposerName) if err != nil { return err } err = addMeta(mp4.BoxType{'\251', 'd', 'a', 'y'}, strings.Split(meta.Data[0].Attributes.ReleaseDate, "-")[0]) if err != nil { return err } // cnID, err := strconv.ParseUint(meta.Data[0].Relationships.Tracks.Data[index].ID, 10, 32) // if err != nil { // return err // } // err = addMeta(mp4.BoxType{'c', 'n', 'I', 'D'}, uint32(cnID)) // if err != nil { // return err // } err = addExtendedMeta("ISRC", meta.Data[0].Relationships.Tracks.Data[index].Attributes.Isrc) if err != nil { return err } if len(meta.Data[0].Relationships.Tracks.Data[index].Attributes.GenreNames) > 0 { err = addMeta(mp4.BoxType{'\251', 'g', 'e', 'n'}, meta.Data[0].Relationships.Tracks.Data[index].Attributes.GenreNames[0]) if err != nil { return err } } if len(meta.Data) > 0 { album := meta.Data[0] err = addMeta(mp4.BoxType{'a', 'A', 'R', 'T'}, album.Attributes.ArtistName) if err != nil { return err } err = addMeta(mp4.BoxType{'c', 'p', 'r', 't'}, album.Attributes.Copyright) if err != nil { return err } var isCpil uint8 if album.Attributes.IsCompilation { isCpil = 1 } err = addMeta(mp4.BoxType{'c', 'p', 'i', 'l'}, isCpil) if err != nil { return err } err = addExtendedMeta("LABEL", album.Attributes.RecordLabel) if err != nil { return err } err = addExtendedMeta("UPC", album.Attributes.Upc) if err != nil { return err } // plID, err := strconv.ParseUint(album.ID, 10, 32) // if err != nil { // return err // } // err = addMeta(mp4.BoxType{'p', 'l', 'I', 'D'}, uint32(plID)) // if err != nil { // return err // } } // if len(meta.Data[0].Relationships.Artists.Data) > 0 { // atID, err := strconv.ParseUint(meta.Data[0].Relationships.Artists.Data[index].ID, 10, 32) // if err != nil { // return err // } // err = addMeta(mp4.BoxType{'a', 't', 'I', 'D'}, uint32(atID)) // if err != nil { // return err // } // } trkn := make([]byte, 8) binary.BigEndian.PutUint32(trkn, uint32(trackNum)) binary.BigEndian.PutUint16(trkn[4:], uint16(trackTotal)) err = addMeta(mp4.BoxType{'t', 'r', 'k', 'n'}, trkn) if err != nil { return err } // disk := make([]byte, 8) // binary.BigEndian.PutUint32(disk, uint32(meta.Attributes.DiscNumber)) // err = addMeta(mp4.BoxType{'d', 'i', 's', 'k'}, disk) // if err != nil { // return err // } ctx.UnderIlst = false _, err = w.EndBox() if err != nil { return err } } ctx.UnderIlstMeta = false _, err = w.EndBox() if err != nil { return err } } ctx.UnderUdta = false _, err = w.EndBox() if err != nil { return err } } _, err = w.EndBox() if err != nil { return err } } { box, err := w.StartBox(&mp4.BoxInfo{Type: mp4.BoxTypeMdat()}) if err != nil { return err } _, err = mp4.Marshal(w, &mp4.Mdat{Data: data}, box.Context) if err != nil { return err } mdat, err := w.EndBox() var realStco mp4.Stco offset := mdat.Offset + mdat.HeaderSize for i := uint32(0); i < numSamples; i++ { if i%chunkSize == 0 { realStco.EntryCount++ realStco.ChunkOffset = append(realStco.ChunkOffset, uint32(offset)) } offset += uint64(len(info.samples[i].data)) } _, err = stco.SeekToPayload(w) if err != nil { return err } _, err = mp4.Marshal(w, &realStco, box.Context) if err != nil { return err } } return nil } func decryptSong(info *SongInfo, keys []string, manifest *AutoGenerated, filename string, trackNum, trackTotal int) error { //fmt.Printf("%d-bit / %d Hz\n", info.bitDepth, info.bitRate) conn, err := net.Dial("tcp", "127.0.0.1:10020") if err != nil { return err } defer conn.Close() var decrypted []byte var lastIndex uint32 = math.MaxUint8 fmt.Println("Decrypt start.") for _, sp := range info.samples { if lastIndex != sp.descIndex { if len(decrypted) != 0 { _, err := conn.Write([]byte{0, 0, 0, 0}) if err != nil { return err } } keyUri := keys[sp.descIndex] id := manifest.Data[0].Relationships.Tracks.Data[trackNum-1].ID if keyUri == prefetchKey { id = defaultId } _, err := conn.Write([]byte{byte(len(id))}) if err != nil { return err } _, err = io.WriteString(conn, id) if err != nil { return err } _, err = conn.Write([]byte{byte(len(keyUri))}) if err != nil { return err } _, err = io.WriteString(conn, keyUri) if err != nil { return err } } lastIndex = sp.descIndex err := binary.Write(conn, binary.LittleEndian, uint32(len(sp.data))) if err != nil { return err } _, err = conn.Write(sp.data) if err != nil { return err } de := make([]byte, len(sp.data)) _, err = io.ReadFull(conn, de) if err != nil { return err } decrypted = append(decrypted, de...) } _, _ = conn.Write([]byte{0, 0, 0, 0, 0}) fmt.Println("Decrypt finished.") create, err := os.Create(filename) if err != nil { return err } defer create.Close() return writeM4a(mp4.NewWriter(create), info, manifest, decrypted, trackNum, trackTotal) } func checkUrl(url string) (string, string) { pat := regexp.MustCompile(`^(?:https:\/\/(?:beta\.music|music)\.apple\.com\/(\w{2})(?:\/album|\/album\/.+))\/(?:id)?(\d[^\D]+)(?:$|\?)`) matches := pat.FindAllStringSubmatch(url, -1) if matches == nil { return "", "" } else { return matches[0][1], matches[0][2] } } func getMeta(albumId string, token string, storefront string) (*AutoGenerated, error) { req, err := http.NewRequest("GET", fmt.Sprintf("https://amp-api.music.apple.com/v1/catalog/%s/albums/%s", storefront, albumId), nil) if err != nil { return nil, err } req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token)) req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36") req.Header.Set("Origin", "https://music.apple.com") query := url.Values{} query.Set("omit[resource]", "autos") query.Set("include", "tracks,artists,record-labels") query.Set("include[songs]", "artists") query.Set("fields[artists]", "name") query.Set("fields[albums:albums]", "artistName,artwork,name,releaseDate,url") query.Set("fields[record-labels]", "name") // query.Set("l", "en-gb") req.URL.RawQuery = query.Encode() do, err := http.DefaultClient.Do(req) if err != nil { return nil, err } defer do.Body.Close() if do.StatusCode != http.StatusOK { return nil, errors.New(do.Status) } obj := new(AutoGenerated) err = json.NewDecoder(do.Body).Decode(&obj) if err != nil { return nil, err } return obj, nil } func writeCover(sanAlbumFolder, url string) error { covPath := filepath.Join(sanAlbumFolder, "cover.jpg") exists, err := fileExists(covPath) if err != nil { fmt.Println("Failed to check if cover exists.") return err } if exists { return nil } url = strings.Replace(url, "{w}x{h}", "1200x12000", 1) req, err := http.NewRequest("GET", url, nil) if err != nil { return err } req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36") do, err := http.DefaultClient.Do(req) if err != nil { return err } defer do.Body.Close() if do.StatusCode != http.StatusOK { errors.New(do.Status) } f, err := os.Create(covPath) if err != nil { return err } defer f.Close() _, err = io.Copy(f, do.Body) if err != nil { return err } return nil } func rip(albumId string, token string, storefront string) error { meta, err := getMeta(albumId, token, storefront) if err != nil { fmt.Println("Failed to get album metadata.\n") return err } albumFolder := fmt.Sprintf("%s - %s", meta.Data[0].Attributes.ArtistName, meta.Data[0].Attributes.Name) sanAlbumFolder := filepath.Join("AM-DL downloads", forbiddenNames.ReplaceAllString(albumFolder, "_")) os.MkdirAll(sanAlbumFolder, os.ModePerm) fmt.Println(albumFolder) err = writeCover(sanAlbumFolder, meta.Data[0].Attributes.Artwork.URL) if err != nil { fmt.Println("Failed to write cover.") } trackTotal := len(meta.Data[0].Relationships.Tracks.Data) for trackNum, track := range meta.Data[0].Relationships.Tracks.Data { trackNum++ fmt.Printf("Track %d of %d:\n", trackNum, trackTotal) manifest, err := getInfoFromAdam(track.ID, token, storefront) if err != nil { fmt.Println("Failed to get manifest.\n", err) continue } if manifest.Attributes.ExtendedAssetUrls.EnhancedHls == "" { fmt.Println("Unavailable in ALAC.") continue } explicitTag := "" if track.Attributes.IsExplicit { explicitTag = " [E]" } fmt.Println("IsExplicit:", track.Attributes.IsExplicit) fmt.Printf("Track: %s, IsExplicit: %v\n", track.Attributes.Name, track.Attributes.IsExplicit) filename := fmt.Sprintf("%02d. %s%s.m4a", trackNum, forbiddenNames.ReplaceAllString(track.Attributes.Name, "_"), explicitTag) trackPath := filepath.Join(sanAlbumFolder, filename) exists, err := fileExists(trackPath) if err != nil { fmt.Println("Failed to check if track exists.") } if exists { fmt.Println("Track already exists locally.") continue } trackUrl, keys, err := extractMedia(manifest.Attributes.ExtendedAssetUrls.EnhancedHls) if err != nil { fmt.Println("Failed to extract info from manifest.\n", err) continue } info, err := extractSong(trackUrl) if err != nil { fmt.Println("Failed to extract track.", err) continue } samplesOk := true for samplesOk { for _, i := range info.samples { if int(i.descIndex) >= len(keys) { fmt.Println("Decryption size mismatch.") samplesOk = false } } break } if !samplesOk { continue } err = decryptSong(info, keys, meta, trackPath, trackNum, trackTotal) if err != nil { fmt.Println("Failed to decrypt track.\n", err) continue } } return err } func main() { token, err := getToken() if err != nil { fmt.Println("Failed to get token.") return } albumTotal := len(os.Args[1:]) for albumNum, url := range os.Args[1:] { fmt.Printf("Album %d of %d:\n", albumNum+1, albumTotal) storefront, albumId := checkUrl(url) if albumId == "" { fmt.Printf("Invalid URL: %s\n", url) continue } err := rip(albumId, token, storefront) if err != nil { fmt.Println("Album failed.") fmt.Println(err) } } } func extractMedia(b string) (string, []string, error) { masterUrl, err := url.Parse(b) if err != nil { return "", nil, err } resp, err := http.Get(b) if err != nil { return "", nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return "", nil, errors.New(resp.Status) } body, err := io.ReadAll(resp.Body) if err != nil { return "", nil, err } masterString := string(body) from, listType, err := m3u8.DecodeFrom(strings.NewReader(masterString), true) if err != nil || listType != m3u8.MASTER { return "", nil, errors.New("m3u8 not of master type") } master := from.(*m3u8.MasterPlaylist) var streamUrl *url.URL sort.Slice(master.Variants, func(i, j int) bool { return master.Variants[i].AverageBandwidth > master.Variants[j].AverageBandwidth }) for _, variant := range master.Variants { if variant.Codecs == "alac" { split := strings.Split(variant.Audio, "-") length := len(split) fmt.Printf("%s-bit / %s Hz\n", split[length-1], split[length-2]) streamUrlTemp, err := masterUrl.Parse(variant.URI) if err != nil { panic(err) } streamUrl = streamUrlTemp break } } if streamUrl == nil { return "", nil, errors.New("no alac codec found") } var keys []string keys = append(keys, prefetchKey) streamUrl.Path = strings.TrimSuffix(streamUrl.Path, ".m3u8") + "_m.mp4" regex := regexp.MustCompile(`"(skd?://[^"]*)"`) matches := regex.FindAllStringSubmatch(masterString, -1) for _, match := range matches { if strings.HasSuffix(match[1], "c23") || strings.HasSuffix(match[1], "c6") { keys = append(keys, match[1]) } } return streamUrl.String(), keys, nil } func extractSong(url string) (*SongInfo, error) { fmt.Println("Downloading...") track, err := http.Get(url) if err != nil { return nil, err } defer track.Body.Close() if track.StatusCode != http.StatusOK { return nil, errors.New(track.Status) } rawSong, err := ioutil.ReadAll(track.Body) if err != nil { return nil, err } fmt.Println("Downloaded.") f := bytes.NewReader(rawSong) trex, err := mp4.ExtractBoxWithPayload(f, nil, []mp4.BoxType{ mp4.BoxTypeMoov(), mp4.BoxTypeMvex(), mp4.BoxTypeTrex(), }) if err != nil || len(trex) != 1 { return nil, err } trexPay := trex[0].Payload.(*mp4.Trex) stbl, err := mp4.ExtractBox(f, nil, []mp4.BoxType{ mp4.BoxTypeMoov(), mp4.BoxTypeTrak(), mp4.BoxTypeMdia(), mp4.BoxTypeMinf(), mp4.BoxTypeStbl(), }) if err != nil || len(stbl) != 1 { return nil, err } enca, err := mp4.ExtractBoxWithPayload(f, stbl[0], []mp4.BoxType{ mp4.BoxTypeStsd(), mp4.BoxTypeEnca(), }) if err != nil { return nil, err } aalac, err := mp4.ExtractBoxWithPayload(f, &enca[0].Info, []mp4.BoxType{BoxTypeAlac()}) if err != nil || len(aalac) != 1 { return nil, err } extracted := &SongInfo{ r: f, alacParam: aalac[0].Payload.(*Alac), } moofs, err := mp4.ExtractBox(f, nil, []mp4.BoxType{ mp4.BoxTypeMoof(), }) if err != nil || len(moofs) <= 0 { return nil, err } mdats, err := mp4.ExtractBoxWithPayload(f, nil, []mp4.BoxType{ mp4.BoxTypeMdat(), }) if err != nil || len(mdats) != len(moofs) { return nil, err } for i, moof := range moofs { tfhd, err := mp4.ExtractBoxWithPayload(f, moof, []mp4.BoxType{ mp4.BoxTypeTraf(), mp4.BoxTypeTfhd(), }) if err != nil || len(tfhd) != 1 { return nil, err } tfhdPay := tfhd[0].Payload.(*mp4.Tfhd) index := tfhdPay.SampleDescriptionIndex if index != 0 { index-- } truns, err := mp4.ExtractBoxWithPayload(f, moof, []mp4.BoxType{ mp4.BoxTypeTraf(), mp4.BoxTypeTrun(), }) if err != nil || len(truns) <= 0 { return nil, err } mdat := mdats[i].Payload.(*mp4.Mdat).Data for _, t := range truns { for _, en := range t.Payload.(*mp4.Trun).Entries { info := SampleInfo{descIndex: index} switch { case t.Payload.CheckFlag(0x200): info.data = mdat[:en.SampleSize] mdat = mdat[en.SampleSize:] case tfhdPay.CheckFlag(0x10): info.data = mdat[:tfhdPay.DefaultSampleSize] mdat = mdat[tfhdPay.DefaultSampleSize:] default: info.data = mdat[:trexPay.DefaultSampleSize] mdat = mdat[trexPay.DefaultSampleSize:] } switch { case t.Payload.CheckFlag(0x100): info.duration = en.SampleDuration case tfhdPay.CheckFlag(0x8): info.duration = tfhdPay.DefaultSampleDuration default: info.duration = trexPay.DefaultSampleDuration } extracted.samples = append(extracted.samples, info) } } if len(mdat) != 0 { return nil, errors.New("offset mismatch") } } return extracted, nil } func init() { mp4.AddBoxDef((*Alac)(nil)) } func BoxTypeAlac() mp4.BoxType { return mp4.StrToBoxType("alac") } type Alac struct { mp4.FullBox `mp4:"extend"` FrameLength uint32 `mp4:"size=32"` CompatibleVersion uint8 `mp4:"size=8"` BitDepth uint8 `mp4:"size=8"` Pb uint8 `mp4:"size=8"` Mb uint8 `mp4:"size=8"` Kb uint8 `mp4:"size=8"` NumChannels uint8 `mp4:"size=8"` MaxRun uint16 `mp4:"size=16"` MaxFrameBytes uint32 `mp4:"size=32"` AvgBitRate uint32 `mp4:"size=32"` SampleRate uint32 `mp4:"size=32"` } func getInfoFromAdam(adamId string, token string, storefront string) (*SongData, error) { request, err := http.NewRequest("GET", fmt.Sprintf("https://amp-api.music.apple.com/v1/catalog/%s/songs/%s", storefront, adamId), nil) if err != nil { return nil, err } query := url.Values{} query.Set("extend", "extendedAssetUrls") query.Set("include", "albums") request.URL.RawQuery = query.Encode() request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token)) request.Header.Set("User-Agent", "iTunes/12.11.3 (Windows; Microsoft Windows 10 x64 Professional Edition (Build 19041); x64) AppleWebKit/7611.1022.4001.1 (dt:2)") request.Header.Set("Origin", "https://music.apple.com") do, err := http.DefaultClient.Do(request) if err != nil { return nil, err } defer do.Body.Close() if do.StatusCode != http.StatusOK { return nil, errors.New(do.Status) } obj := new(ApiResult) err = json.NewDecoder(do.Body).Decode(&obj) if err != nil { return nil, err } for _, d := range obj.Data { if d.ID == adamId { return &d, nil } } return nil, nil } func getToken() (string, error) { req, err := http.NewRequest("GET", "https://beta.music.apple.com", nil) if err != nil { return "", err } resp, err := http.DefaultClient.Do(req) if err != nil { return "", err } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { return "", err } regex := regexp.MustCompile(`/assets/index-legacy-[^/]+\.js`) indexJsUri := regex.FindString(string(body)) req, err = http.NewRequest("GET", "https://beta.music.apple.com"+indexJsUri, nil) if err != nil { return "", err } resp, err = http.DefaultClient.Do(req) if err != nil { return "", err } defer resp.Body.Close() body, err = io.ReadAll(resp.Body) if err != nil { return "", err } regex = regexp.MustCompile(`eyJh([^"]*)`) token := regex.FindString(string(body)) return token, nil } type ApiResult struct { Data []SongData `json:"data"` } type SongAttributes struct { ArtistName string `json:"artistName"` DiscNumber int `json:"discNumber"` GenreNames []string `json:"genreNames"` ExtendedAssetUrls struct { EnhancedHls string `json:"enhancedHls"` } `json:"extendedAssetUrls"` IsMasteredForItunes bool `json:"isMasteredForItunes"` ReleaseDate string `json:"releaseDate"` Name string `json:"name"` Isrc string `json:"isrc"` AlbumName string `json:"albumName"` TrackNumber int `json:"trackNumber"` ComposerName string `json:"composerName"` IsExplicit bool `json:"isExplicit"` } type AlbumAttributes struct { ArtistName string `json:"artistName"` IsSingle bool `json:"isSingle"` IsComplete bool `json:"isComplete"` GenreNames []string `json:"genreNames"` TrackCount int `json:"trackCount"` IsMasteredForItunes bool `json:"isMasteredForItunes"` ReleaseDate string `json:"releaseDate"` Name string `json:"name"` RecordLabel string `json:"recordLabel"` Upc string `json:"upc"` Copyright string `json:"copyright"` IsCompilation bool `json:"isCompilation"` IsExplicit bool `json:"isExplicit"` } type SongData struct { ID string `json:"id"` Attributes SongAttributes `json:"attributes"` Relationships struct { Albums struct { Data []struct { ID string `json:"id"` Type string `json:"type"` Href string `json:"href"` Attributes AlbumAttributes `json:"attributes"` } `json:"data"` } `json:"albums"` Artists struct { Href string `json:"href"` Data []struct { ID string `json:"id"` Type string `json:"type"` Href string `json:"href"` } `json:"data"` } `json:"artists"` } `json:"relationships"` } type SongResult struct { Artwork struct { Width int `json:"width"` URL string `json:"url"` Height int `json:"height"` TextColor3 string `json:"textColor3"` TextColor2 string `json:"textColor2"` TextColor4 string `json:"textColor4"` HasAlpha bool `json:"hasAlpha"` TextColor1 string `json:"textColor1"` BgColor string `json:"bgColor"` HasP3 bool `json:"hasP3"` SupportsLayeredImage bool `json:"supportsLayeredImage"` } `json:"artwork"` ArtistName string `json:"artistName"` CollectionID string `json:"collectionId"` DiscNumber int `json:"discNumber"` GenreNames []string `json:"genreNames"` ID string `json:"id"` DurationInMillis int `json:"durationInMillis"` ReleaseDate string `json:"releaseDate"` ContentRatingsBySystem struct { } `json:"contentRatingsBySystem"` Name string `json:"name"` Composer struct { Name string `json:"name"` URL string `json:"url"` } `json:"composer"` EditorialArtwork struct { } `json:"editorialArtwork"` CollectionName string `json:"collectionName"` AssetUrls struct { Plus string `json:"plus"` Lightweight string `json:"lightweight"` SuperLightweight string `json:"superLightweight"` LightweightPlus string `json:"lightweightPlus"` EnhancedHls string `json:"enhancedHls"` } `json:"assetUrls"` AudioTraits []string `json:"audioTraits"` Kind string `json:"kind"` Copyright string `json:"copyright"` ArtistID string `json:"artistId"` Genres []struct { GenreID string `json:"genreId"` Name string `json:"name"` URL string `json:"url"` MediaType string `json:"mediaType"` } `json:"genres"` TrackNumber int `json:"trackNumber"` AudioLocale string `json:"audioLocale"` Offers []struct { ActionText struct { Short string `json:"short"` Medium string `json:"medium"` Long string `json:"long"` Downloaded string `json:"downloaded"` Downloading string `json:"downloading"` } `json:"actionText"` Type string `json:"type"` PriceFormatted string `json:"priceFormatted"` Price float64 `json:"price"` BuyParams string `json:"buyParams"` Variant string `json:"variant,omitempty"` Assets []struct { Flavor string `json:"flavor"` Preview struct { Duration int `json:"duration"` URL string `json:"url"` } `json:"preview"` Size int `json:"size"` Duration int `json:"duration"` } `json:"assets"` } `json:"offers"` } type iTunesLookup struct { Results map[string]SongResult `json:"results"` } type Meta struct { Context string `json:"@context"` Type string `json:"@type"` Name string `json:"name"` Description string `json:"description"` Tracks []struct { Type string `json:"@type"` Name string `json:"name"` Audio struct { Type string `json:"@type"` } `json:"audio"` Offers struct { Type string `json:"@type"` Category string `json:"category"` Price int `json:"price"` } `json:"offers"` Duration string `json:"duration"` } `json:"tracks"` Citation []interface{} `json:"citation"` WorkExample []struct { Type string `json:"@type"` Name string `json:"name"` URL string `json:"url"` Audio struct { Type string `json:"@type"` } `json:"audio"` Offers struct { Type string `json:"@type"` Category string `json:"category"` Price int `json:"price"` } `json:"offers"` Duration string `json:"duration"` } `json:"workExample"` Genre []string `json:"genre"` DatePublished time.Time `json:"datePublished"` ByArtist struct { Type string `json:"@type"` URL string `json:"url"` Name string `json:"name"` } `json:"byArtist"` } type AutoGenerated struct { Data []struct { ID string `json:"id"` Type string `json:"type"` Href string `json:"href"` Attributes struct { Artwork struct { Width int `json:"width"` Height int `json:"height"` URL string `json:"url"` BgColor string `json:"bgColor"` TextColor1 string `json:"textColor1"` TextColor2 string `json:"textColor2"` TextColor3 string `json:"textColor3"` TextColor4 string `json:"textColor4"` } `json:"artwork"` ArtistName string `json:"artistName"` IsSingle bool `json:"isSingle"` URL string `json:"url"` IsComplete bool `json:"isComplete"` GenreNames []string `json:"genreNames"` TrackCount int `json:"trackCount"` IsMasteredForItunes bool `json:"isMasteredForItunes"` ReleaseDate string `json:"releaseDate"` IsExplicit bool `json:"isExplicit"` Name string `json:"name"` RecordLabel string `json:"recordLabel"` Upc string `json:"upc"` AudioTraits []string `json:"audioTraits"` Copyright string `json:"copyright"` PlayParams struct { ID string `json:"id"` Kind string `json:"kind"` } `json:"playParams"` IsCompilation bool `json:"isCompilation"` } `json:"attributes"` Relationships struct { RecordLabels struct { Href string `json:"href"` Data []interface{} `json:"data"` } `json:"record-labels"` Artists struct { Href string `json:"href"` Data []struct { ID string `json:"id"` Type string `json:"type"` Href string `json:"href"` Attributes struct { Name string `json:"name"` } `json:"attributes"` } `json:"data"` } `json:"artists"` Tracks struct { Href string `json:"href"` Data []struct { ID string `json:"id"` Type string `json:"type"` Href string `json:"href"` Attributes struct { Previews []struct { URL string `json:"url"` } `json:"previews"` Artwork struct { Width int `json:"width"` Height int `json:"height"` URL string `json:"url"` BgColor string `json:"bgColor"` TextColor1 string `json:"textColor1"` TextColor2 string `json:"textColor2"` TextColor3 string `json:"textColor3"` TextColor4 string `json:"textColor4"` } `json:"artwork"` ArtistName string `json:"artistName"` URL string `json:"url"` DiscNumber int `json:"discNumber"` GenreNames []string `json:"genreNames"` HasTimeSyncedLyrics bool `json:"hasTimeSyncedLyrics"` IsMasteredForItunes bool `json:"isMasteredForItunes"` DurationInMillis int `json:"durationInMillis"` ReleaseDate string `json:"releaseDate"` IsExplicit bool `json:"isExplicit"` Name string `json:"name"` Isrc string `json:"isrc"` AudioTraits []string `json:"audioTraits"` HasLyrics bool `json:"hasLyrics"` AlbumName string `json:"albumName"` PlayParams struct { ID string `json:"id"` Kind string `json:"kind"` } `json:"playParams"` TrackNumber int `json:"trackNumber"` AudioLocale string `json:"audioLocale"` ComposerName string `json:"composerName"` } `json:"attributes"` Relationships struct { Artists struct { Href string `json:"href"` Data []struct { ID string `json:"id"` Type string `json:"type"` Href string `json:"href"` Attributes struct { Name string `json:"name"` } `json:"attributes"` } `json:"data"` } `json:"artists"` } `json:"relationships"` } `json:"data"` } `json:"tracks"` } `json:"relationships"` } `json:"data"` } if albumId == "" { fmt.Printf("Invalid URL: %s\n", url) continue } i think this is the URL write this URL to save in album_link.txt in the album folder
8769315d9c181e8a67ac3d04d6629bdc
{ "intermediate": 0.33890464901924133, "beginner": 0.44517913460731506, "expert": 0.21591626107692719 }
47,419
Python how to create windows application contains two input fields for integers and one label for calculation output using at python
0a60afd59730c4659c8b0fee1c043fc2
{ "intermediate": 0.3652837574481964, "beginner": 0.2472068965435028, "expert": 0.3875093460083008 }
47,420
Я подключен с 2 айпи: Windows IP Configuration Unknown adapter ProtonVPN: Connection-specific DNS Suffix . : IPv4 Address. . . . . . . . . . . : 10.2.0.2 Subnet Mask . . . . . . . . . . . : 255.255.255.255 Default Gateway . . . . . . . . . : 0.0.0.0 Ethernet adapter Ethernet: Connection-specific DNS Suffix . : IPv4 Address. . . . . . . . . . . : 77.91.68.163 Subnet Mask . . . . . . . . . . . : 255.255.255.255 Default Gateway . . . . . . . . . : 10.0.0.1 Как узнать, с какого айпи у меня запускается бот в телеграм? Есть ли возможность
09619e41e58c7fd6d53149ea297eba60
{ "intermediate": 0.3472144901752472, "beginner": 0.29010844230651855, "expert": 0.3626769781112671 }
47,421
Python Tkinter entry get input value
c6bff9b6e5494be2bb2d7547837539a1
{ "intermediate": 0.3235275447368622, "beginner": 0.3048194646835327, "expert": 0.3716529309749603 }
47,422
在DATA: MAX_SAMPLE_INTERVAL: 100 MEAN: - 0.485 - 0.456 - 0.406 SEARCH: CENTER_JITTER: 3 FACTOR: 4.0 SCALE_JITTER: 0.25 SIZE: 256 NUMBER: 1 STD: - 0.229 - 0.224 - 0.225 TEMPLATE: CENTER_JITTER: 0 FACTOR: 2.0 SCALE_JITTER: 0 SIZE: 128 TRAIN: DATASETS_NAME: - COESOT DATASETS_RATIO: - 1 SAMPLE_PER_EPOCH: 60000 VAL: DATASETS_NAME: - COESOT_VAL DATASETS_RATIO: - 1 SAMPLE_PER_EPOCH: 5000 MODEL: PRETRAIN_FILE: "mae_pretrain_vit_base.pth" EXTRA_MERGER: False RETURN_INTER: False BACKBONE: TYPE: vit_base_patch16_224_ce STRIDE: 16 CE_LOC: [3, 6, 9] CE_KEEP_RATIO: [1, 1, 1] CE_TEMPLATE_RANGE: 'CTR_POINT' HEAD: TYPE: CENTER NUM_CHANNELS: 256 TRAIN: BACKBONE_MULTIPLIER: 0.1 DROP_PATH_RATE: 0.1 CE_START_EPOCH: 0 # candidate elimination start epoch 20 CE_WARM_EPOCH: 0 # candidate elimination warm up epoch 50 BATCH_SIZE: 32 EPOCH: 60 GIOU_WEIGHT: 1 # 2.0 L1_WEIGHT: 14 # 5.0 FOCAL_WEIGHT: 1.0 # 1.5 GRAD_CLIP_NORM: 0.1 LR: 0.000005 LR_DROP_EPOCH: 30 NUM_WORKER: 8 OPTIMIZER: ADAMW PRINT_INTERVAL: 50 SCHEDULER: TYPE: step DECAY_RATE: 0.1 # TYPE: Mstep # MILESTONES: [40, 60] # GAMMA: 0.1 VAL_EPOCH_INTERVAL: 2 # 目前出现了过拟合,所以考虑减小验证间隔,精确过拟合位置 WEIGHT_DECAY: 0.0001 AMP: False TEST: EPOCH: 50 SEARCH_FACTOR: 4.0 SEARCH_SIZE: 256 TEMPLATE_FACTOR: 2.0 TEMPLATE_SIZE: 128 中,我们想把LR策略改为mstep,然后在30和50epoch处衰减学习率
3c0f1e2371b2c49d1df8a485a8efcc4a
{ "intermediate": 0.27101200819015503, "beginner": 0.4550015926361084, "expert": 0.2739863097667694 }
47,423
Rename dui70 to dui71 and hex edit VAN.dll to reflect this
6a5ac9d1acd2d6a9c4e2cd127900d843
{ "intermediate": 0.4048098027706146, "beginner": 0.26850104331970215, "expert": 0.3266892433166504 }
47,424
I have this table in latex: \begin{table}[h] \centering \begin{tabular}{@{}ll@{}} \toprule Total parties & 8 \\ Total manifestos & 40 \\ Time & 09/1998 - 09/2021 \\ Total quasi-sentences & 88694 \\ \bottomrule \end{tabular} \caption{Statistics and additional information about the subset.} \label{table:subsetStatistics} \end{table} What can I improve?
cc2712eb71a86b16fa1fdde61c4a0b5e
{ "intermediate": 0.37903255224227905, "beginner": 0.29381129145622253, "expert": 0.327156126499176 }
47,425
where is my camera folder with vrchat?
b57b96faa2a287095dd576f31901c38f
{ "intermediate": 0.46469932794570923, "beginner": 0.25599604845046997, "expert": 0.2793046236038208 }
47,426
I have this function: def get_full_sentence(manifesto_chunks): """ Concatenates political statements to full sentences. """ i = 0 while i < len(manifesto_chunks) - 1: if not manifesto_chunks[i]['text'][-1] in '.!?': manifesto_chunks[i]['text'] += ' ' + manifesto_chunks[i+1]['text'] manifesto_chunks[i]['cmp_code'] += '+' + manifesto_chunks[i+1]['cmp_code'] del manifesto_chunks[i+1] else: i += 1 return manifesto_chunks No the problem is that there a cases in the data which are complete sentences but just dont end with an sentence ending symbol. These are in the result super long of course. I want to end the concatenation for a given chunk when it exceeds 2000 characters
7667a39175639cb5b878b3d940b6e45f
{ "intermediate": 0.3711610734462738, "beginner": 0.40029382705688477, "expert": 0.22854508459568024 }
47,427
I have unreal engine 5 project and I cant compile my .h file in visual studio code: PS C:\Users\Prohor\Documents\Unreal Projects\Card_Game> cd "c:\Users\Prohor\Documents\Unreal Projects\Card_Game\Source\Card_Game\Public\" ; if ($?) { g++ BlankTile.h -o BlankTile } ; if ($?) { .\BlankTile } BlankTile.h:3:9: warning: #pragma once in main file #pragma once ^~~~ BlankTile.h:5:10: fatal error: CoreMinimal.h: No such file or directory #include "CoreMinimal.h" ^~~~~~~~~~~~~~~ compilation terminated.
312ed46511e87775f1e1bfa125c611b6
{ "intermediate": 0.3822592794895172, "beginner": 0.3130076825618744, "expert": 0.3047330677509308 }
47,428
Fix issue and show fixed code: Make the enclosing method "static" or remove this set.
4d571ec1253c6d5e76035ab4e3a43b04
{ "intermediate": 0.3633768558502197, "beginner": 0.2542203962802887, "expert": 0.3824027478694916 }
47,429
i want to remove all columns in my csv file except the columns that name are exactly "close' "high' "low" give proper pyhton code
a62a8bb0bfd6f01e19ac4b8fc308dd28
{ "intermediate": 0.3725118339061737, "beginner": 0.34213635325431824, "expert": 0.28535181283950806 }
47,430
What is the simplest, most elegant way of getting Python 3.10 to return current date in dd-mm-yyyy format?
72b8ac182d4beeff073eadf98da80cc1
{ "intermediate": 0.5476338267326355, "beginner": 0.18427741527557373, "expert": 0.268088698387146 }
47,431
User profile photo How I can decode Json to Java object without using any external library? Give me code, please, do not use javax.json
f276db896d675fa442244bfc94432e57
{ "intermediate": 0.7766585946083069, "beginner": 0.10541480779647827, "expert": 0.11792662739753723 }
47,432
iv trained a model on my dataset like: from sklearn.model_selection import GridSearchCV from xgboost import XGBRegressor # Initialize the XGBoost model xgb_regressor = XGBRegressor(objective='reg:squarederror', tree_method='gpu_hist') # Wrap XGBoost model with MultiOutputRegressor multioutput_regressor = MultiOutputRegressor(xgb_regressor) # Define the parameter grid for XGBoost param_grid = { 'estimator__n_estimators': [400,800], # Number of trees 'estimator__learning_rate': [0.2,2], # Step size shrinkage used to prevent overfitting 'estimator__max_depth': [8,16], # Maximum depth of a tree # Add more parameters here based on your needs } # Initialize GridSearchCV grid_search = GridSearchCV(estimator=multioutput_regressor, param_grid=param_grid, cv=3, n_jobs=-1, verbose=2, scoring='neg_mean_absolute_error') # Train the model using grid search to find the best hyperparameters grid_search.fit(X_train_scaled, Y_train_scaled) # Print the best parameters and the best score print(f"Best parameters: {grid_search.best_params_}") print(f"Best score: {grid_search.best_score_}") how can i see mae of model performance on test and dev set?
239b456616ec821a86cf2639a8e1f8b0
{ "intermediate": 0.29363322257995605, "beginner": 0.13446001708507538, "expert": 0.5719068050384521 }
47,433
GIVE THIS PROGRAME LIKE A TEMPLATE (TABLE)" ### Weekly Planning Table | Week | Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday | |------|-----------------|------------------------|----------------|-------------------------|-------------------|---------------------|---------------------------------| | 1 | Technique | Strength & Condition | Sparring | Rest/Active Recovery | Speed & Reflexes | Endurance & Cardio | Review & Meditation | | 2 | Advanced Drills | Strength & Plyometrics | Advanced Sparring | Rest/Active Recovery | Agility & Reflexes | Extended Endurance | Rest & Mental Training | | 3 | Intensive Drills| High-Intensity Training| Intensive Sparring | Rest/Active Recovery | High-Speed Agility | Cardio Peak | Technique Review & Strategies | | 4 | Speed Tactics | Tactical Sparring | Mental Training| Strategy & Light Activity | Mental Prep | Rest | Rest & Mental Focus | ### Monthly Planning Table | Week & Focus | Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday | |-------------------------|-----------------|------------------------|----------------|-------------------------|-------------------|---------------------|-----------------------| | Week 1:<br>Foundation & Technique | Warm-up, Poomsae | Circuit training | Sparring drills | Active Recovery | Speed drills | Cardio drills | Review, Meditation | | Week 2:<br>Intensity Increase | Technique, Advanced | Strength, Plyometrics | Advanced Sparring | Active Recovery | Speed, Agility | Extended Cardio | Rest, Mental Training| | Week 3:<br>Application & Strategy| Intense Drills | High-Intensity Train | Intensive Sparring | Active Recovery | High-Speed Agility | Peak Cardio | Light Review, Strategy| | Week 4:<br>Taper & Mental Prep | Speed Tactics | Tactical Sparring | Mental Training | Strategy & Light Act | Mental Prep | Rest | Rest & Mental Focus | - Note: “Active Recovery” recommended activities include light jogging, yoga, or swimming. - “Rest & Mental Focus” includes activities like meditation, visualization technique practices, and calming exercises to prepare mentally for competition."
19c59db0bd2082b3276f541c48229151
{ "intermediate": 0.30721449851989746, "beginner": 0.3819156289100647, "expert": 0.31086987257003784 }
47,434
<!DOCTYPE html> <html lang="ru"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Сайт продаж товаров</title> <link rel="stylesheet" href="style.css"> </head> <body> <h1>Продажа товаров</h1> <section id="upload-form"> <h2>Загрузить товар</h2> <input type="file" id="file-input" accept="image/*"> <button id="upload-button">Загрузить</button> </section> <section id="posts"> <h2>Товары</h2> <ul id="post-list"></ul> </section> <script src="script.js"></script> </body> </html> const fileInput = document.getElementById('file-input'); const uploadButton = document.getElementById('upload-button'); const postList = document.getElementById('post-list'); uploadButton.addEventListener('click', () => { const file = fileInput.files[0]; if (file) { const reader = new FileReader(); reader.onload = (event) => { const img = document.createElement('img'); img.src = event.target.result; img.classList.add('post'); const post = document.createElement('li'); post.appendChild(img); postList.appendChild(post); }; reader.readAsDataURL(file); } }); body { font-family: sans-serif; } #upload-form { margin-bottom: 20px; } #upload-button { padding: 10px 20px; background-color: #007bff; color: white; border: none; cursor: pointer; } #posts { list-style: none; padding: 0; } #post-list { display: flex; flex-wrap: wrap; justify-content: space-between; } .post { width: 250px; margin-bottom: 20px; border: 1px solid #ccc; padding: 10px; } .post img { width: 100%; height: auto; margin-bottom: 10px; } Улучши логику данного сайта и добавь в код нововведений важных для сайта продаж собственных товаров пользователей. Ответь в виде кода!
9e0619dcf957b9ea142be3162668d643
{ "intermediate": 0.27273401618003845, "beginner": 0.534659206867218, "expert": 0.19260677695274353 }
47,435
give me meta data using these tags, top 10 android gacha games, top android gacha games 2023,top android gacha games 2024,best android gacha games 2024top,10, android,gacha,games,top 10,top 10 andriod,top android games gacha,top 5 gacha games android,top gacha android games,top gacha games for android,top 10 gacha games for android,top gacha game mobile,new mobile releases,new turn based gacha games,best new mobile gacha games,best gacha android,upcoming gacha games,best upcoming gacha games,best gacha game mobile,top new gacha games,top android games gacha,best new gacha games,top gacha games,upcoming mobile games,gacha games ios,best gacha games,gacha games for android,new gacha game,top game gacha,best gacha game,new gacha games,gacha games android,gacha games mobile,mobile gacha games,top 10 phone games,gacha game,gacha games,free android games
96c2d017b2e2068dfc6cec15e3c9cf7e
{ "intermediate": 0.24414537847042084, "beginner": 0.37684059143066406, "expert": 0.3790139853954315 }
47,436
connecting to wiregaurd via gnome settings doesnt do anything. it shows that it is "connected" but in reality it is not connected
d680dbe680418a85d573a03905a142ce
{ "intermediate": 0.45283612608909607, "beginner": 0.29632240533828735, "expert": 0.2508414089679718 }
47,437
i want to make ai that predicts next game state of cs:go game, i want something like llm, state is [65,256] where 65 is max player count and 256 is state for each player, how to do that? and can i then change model behavior to predict is player cheater on not
404ba89fd4b6188ba8249dedde35bba0
{ "intermediate": 0.21302062273025513, "beginner": 0.06800743192434311, "expert": 0.7189719080924988 }
47,438
Im using stm32cubeide hal drivers with a stm32f03 and I want a single conversion done by the adc but it has to be timed right to the last microsecond. After I output something on a pin, delay 5 microseconds I want to read a single analog input with a 5 microsecond sample time.
ef3a6bb4d7829e6949f40d5bd13e3857
{ "intermediate": 0.48158782720565796, "beginner": 0.2093157321214676, "expert": 0.30909639596939087 }
47,439
I have the following error. What must i do? ../../../../../src/osd/winui/mui_util.cpp: In function 'DWORD win_get_current_directory_utf8(DWORD, char*)': ../../../../../src/osd/winui/mui_util.cpp:831:16: warning: 'char* strncpy(char*, const char*, size_t)' destination unchanged after copying no bytes [-Wstringop-truncation] 831 | strncpy(buffer, utf8_buffer, bufferlength); | ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This is the function with the error: DWORD win_get_current_directory_utf8(DWORD bufferlength, char* buffer) { DWORD result = 0; TCHAR* t_buffer = NULL; if( bufferlength > 0 ) { t_buffer = (TCHAR*)malloc((bufferlength * sizeof(TCHAR)) + 1); if( !t_buffer ) return result; } result = GetCurrentDirectory(bufferlength, t_buffer); char* utf8_buffer = NULL; if( bufferlength > 0 ) { utf8_buffer = ui_utf8_from_wstring(t_buffer); if( !utf8_buffer ) { free(t_buffer); return result; } } strncpy(buffer, utf8_buffer, bufferlength); if( utf8_buffer ) free(utf8_buffer); if( t_buffer ) free(t_buffer); return result; } ---
c74c52fbf780869c63e835cbcd3a31b7
{ "intermediate": 0.4572531580924988, "beginner": 0.3512939214706421, "expert": 0.19145293533802032 }
47,440
i'll send you blogger template code, i want you to clean it, upgrad it, and remove unused codes and change it to RTL to support arabic
f86028d8862a3a0a2190599480c4bc4f
{ "intermediate": 0.30940744280815125, "beginner": 0.33698874711990356, "expert": 0.3536038100719452 }
47,441
JsonSerializer.Deserialize<Dictionary<string, List<JsonElement>>>(json) сгенерируй конфиг
f6970477d19906996cf7e83be4e499dd
{ "intermediate": 0.44407373666763306, "beginner": 0.2859173119068146, "expert": 0.27000898122787476 }
47,442
do you know what lotto 649 is
628e7a57bd3dcfc71205ee09022e39c8
{ "intermediate": 0.33458399772644043, "beginner": 0.3639419674873352, "expert": 0.30147409439086914 }
47,443
hi, please recommend the best performers similar to antent
c93280f1c6a33e3027db9609d9c88dda
{ "intermediate": 0.32639485597610474, "beginner": 0.2180691361427307, "expert": 0.45553600788116455 }
47,444
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NotImplementedException: The method or operation is not implemented. at TestModule.TestItem.Buy(ILKPlayer player, TestConfig config) in C:\Users\zoro8\RiderProjects\LK\TestModule\TestModule.cs:line 29 at LKCoreApi.LKItemPrefab`1.Buy(ILKPlayer player, ItemConfig config) in C:\Users\zoro8\RiderProjects\LK\LKCoreApi\LKItemPrefab.cs:line 7 at LK.LKPlugin.OnBuyItem(LkPlayer player, LKItem registeredItem) in C:\Users\zoro8\RiderProjects\LK\LK\LKPlugin.cs:line 80 at LK.LKPlugin.<>c__DisplayClass20_0.<OnSelectProductItem>b__0(CCSPlayerController _, ChatMenuOption _) in C:\Users\zoro8\RiderProjects\LK\LK\LKPlugin.cs:line 74 at CounterStrikeSharp.API.Modules.Menu.BaseMenuInstance.OnKeyPress(CCSPlayerController player, Int32 key) in E:\github\CounterStrikeSharp\managed\CounterStrikeSharp.API\Modules\Menu\BaseMenu.cs:line 132 at CounterStrikeSharp.API.Modules.Menu.MenuManager.OnKeyPress(CCSPlayerController player, Int32 key) in E:\github\CounterStrikeSharp\managed\CounterStrikeSharp.API\Modules\Menu\MenuManager.cs:line 72 at CounterStrikeSharp.API.Core.Application.<>c.<Start>b__16_0(CCSPlayerController player, CommandInfo info) in E:\github\CounterStrikeSharp\managed\CounterStrikeSharp.API\Core\Application.cs:line 101 at CounterStrikeSharp.API.Core.Commands.CommandManager.HandleCommandInternal(Int32 playerSlot, IntPtr commandInfo) in E:\github\CounterStrikeSharp\managed\CounterStrikeSharp.API\Core\Commands\CommandManager.cs:line 159 at InvokeStub_Action`2.Invoke(Object, Span`1) at System.Reflection.MethodBaseInvoker.InvokeWithFewArgs(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) --- End of inner exception stack trace --- at System.Reflection.MethodBaseInvoker.InvokeWithFewArgs(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at System.Delegate.DynamicInvokeImpl(Object[] args) at CounterStrikeSharp.API.Core.FunctionReference.<CreateWrappedCallback>b__18_0(fxScriptContext* context) in E:\github\CounterStrikeSharp\managed\CounterStrikeSharp.API\Core\FunctionReference.cs:line 100 В чем ошибка? public class TestItem : LKItemPrefab<TestConfig> { public override bool Buy(ILKPlayer player, TestConfig config) { Server.PrintToChatAll(config.Duration.ToString()); return true; } public override string Name => "123"; } public abstract class LKItemPrefab<T> : ILKItemPrefab where T : ItemConfig { public bool Buy(ILKPlayer player, ItemConfig config) => Buy(player, (T)config); public abstract bool Buy(ILKPlayer player, T config); public abstract string Name { get; } } public interface ILKItemPrefab { bool Buy(ILKPlayer player, ItemConfig config); string Name { get; } }
7b5476711e648971f12c18df611cd482
{ "intermediate": 0.335682213306427, "beginner": 0.4030071794986725, "expert": 0.26131054759025574 }
47,445
I want to visualize my sentence embedding model from Hugging Face. How can I do this? I also have metadata
f5200d65736f9e62f4bd61166600d1eb
{ "intermediate": 0.35245540738105774, "beginner": 0.1733688861131668, "expert": 0.4741757810115814 }
47,446
corrige : import 'package:flutter/material.dart'; import 'package:quizz_app/data/questions_example.dart'; import 'package:quizz_app/screens/result_screen.dart'; import 'package:quizz_app/ui/shared/color.dart'; import 'package:quizz_app/widgets/quizz_widget.dart'; import 'package:quizz_app/model/question_model.dart'; class QuizzScreen extends StatefulWidget { const QuizzScreen({Key? key}) : super(key: key); @override _QuizzScreenState createState() => _QuizzScreenState(); } class _QuizzScreenState extends State<QuizzScreen> { int question_pos = 0; int score = 0; bool btnPressed = false; PageController? _controller; String btnText = "Next Question"; bool answered = false; @override void initState() { // TODO: implement initState super.initState(); _controller = PageController(initialPage: 0); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: AppColor.pripmaryColor, body: Padding( padding: const EdgeInsets.all(18.0), child: PageView.builder( controller: _controller!, onPageChanged: (page) { if (page == questions.length - 1) { setState(() { btnText = "See Results"; }); } setState(() { answered = false; }); }, physics: new NeverScrollableScrollPhysics(), itemBuilder: (context, index) { return Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ SizedBox( width: double.infinity, child: Text( "Question ${index + 1}/10", textAlign: TextAlign.start, style: TextStyle( color: Colors.white, fontSize: 28.0, ), ), ), Divider( color: Colors.white, ), SizedBox( height: 10.0, ), SizedBox( width: double.infinity, height: 200.0, child: Text( "${questions[index].question}", style: TextStyle( color: Colors.white, fontSize: 22.0, ), ), ), for (int i = 0; i < questions[index].answers!.length; i++) Container( width: double.infinity, height: 50.0, margin: EdgeInsets.only( bottom: 20.0, left: 12.0, right: 12.0), child: RawMaterialButton( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8.0), ), fillColor: btnPressed ? questions[index].answers!.values.toList()[i] ? Colors.green : Colors.red : AppColor.secondaryColor, onPressed: !answered ? () { if (questions[index] .answers! .values .toList()[i]) { score++; print("yes"); } else { print("no"); } setState(() { btnPressed = true; answered = true; }); } : null, child: Text(questions[index].answers!.keys.toList()[i], style: TextStyle( color: Colors.white, fontSize: 18.0, )), ), ), SizedBox( height: 40.0, ), RawMaterialButton( onPressed: () { if (_controller!.page?.toInt() == questions.length - 1) { Navigator.push( context, MaterialPageRoute( builder: (context) => ResultScreen(score))); } else { _controller!.nextPage( duration: Duration(milliseconds: 250), curve: Curves.easeInExpo); setState(() { btnPressed = false; }); } }, shape: StadiumBorder(), fillColor: Colors.blue, padding: EdgeInsets.all(18.0), elevation: 0.0, child: Text( btnText, style: TextStyle(color: Colors.white), ), ) ], ); }, itemCount: questions.length, )), ); } } voici le probleme : Installed new service worker. ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════ The following assertion was thrown during layout: A RenderFlex overflowed by 38 pixels on the bottom. The relevant error-causing widget was: Column Column:/lib/screens/quizz_screen.dart:49:22 The overflowing RenderFlex has an orientation of Axis.vertical. The edge of the RenderFlex that is overflowing has been marked in the rendering with a yellow and black striped pattern. This is usually caused by the contents being too big for the RenderFlex. Consider applying a flex factor (e.g. using an Expanded widget) to force the children of the RenderFlex to fit within the available space instead of being sized to their natural size. This is considered an error condition because it indicates that there is content that cannot be seen. If the content is legitimately bigger than the available space, consider clipping it with a ClipRect widget before putting it in the flex, or using a scrollable container rather than a Flex, like a ListView. The specific RenderFlex in question is: RenderFlex#35fad OVERFLOWING: creator: Column ← RepaintBoundary ← IndexedSemantics ← _SelectionKeepAlive ← NotificationListener ← KeepAlive ← AutomaticKeepAlive ← KeyedSubtree ← _SliverFillViewportRenderObjectWidget ← _SliverFractionalPadding ← SliverFillViewport ← Viewport ← ⋯ parentData: (can use size) constraints: BoxConstraints(w=324.0, h=604.0) size: Size(324.0, 604.0) direction: vertical mainAxisAlignment: center mainAxisSize: max crossAxisAlignment: center verticalDirection: down ◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤ ════════════════════════════════════════════════════════════════════════════════════════════════════ no
b244b1eefdc4b914e4dbacf4b309d083
{ "intermediate": 0.5208637714385986, "beginner": 0.3506898283958435, "expert": 0.12844635546207428 }
47,447
hi
833133a62e0f38a77ab26ae3ed24fc04
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
47,448
In Python, what is the simplest way to count the how many times an item is repeated in a two-dimensional list?
292e6ab57306827aae15e080ec7b59cd
{ "intermediate": 0.29266273975372314, "beginner": 0.17272847890853882, "expert": 0.5346087217330933 }
47,449
select employee_id, salary from employees group by salary; is this sql query incorrect
816014e973955bf4c7aeb8252f98958c
{ "intermediate": 0.3480879068374634, "beginner": 0.2926092743873596, "expert": 0.3593028485774994 }
47,450
struct UserNotLoggedInError : public std::runtime_error { UserNotLoggedInError(const char* what) : std::runtime_error(what) {} }; explains how to class this
49765a2d42c42772580e2525aeceed43
{ "intermediate": 0.22746030986309052, "beginner": 0.6602882742881775, "expert": 0.11225142329931259 }
47,451
import os import pandas as pd from pdb2sql import interface from pdb2sql import pdb2sql from Bio import pairwise2 from Bio.pairwise2 import format_alignment # Read the CSV file triplet_complex_df = pd.read_csv('triplet_complex.csv') # Define the Google Drive folder google_drive_folder = '/content/drive/MyDrive/pdb_files/' # Iterate over each entry for index, row in triplet_complex_df.iterrows(): # Assuming 'Entry ID' is the column name containing the IDs entry_id = row['Entry ID'] # Form the PDB file name pdb_file_path = os.path.join(google_drive_folder, f"{entry_id}.pdb") # Call pdb2sql with the PDB file name pdb_db = pdb2sql(pdb_file_path) db = interface(pdb_db) # Get contact residues itf_residue_pair = db.get_contact_residues(cutoff=3, return_contact_pairs=True) print("Interface residue pairs for Entry ID:", entry_id) print(itf_residue_pair) # Define the file name for each entry output_file = f"interface_residue_pairs_{entry_id}.txt" with open(output_file, "w") as file: for key, value in itf_residue_pair.items(): # Convert key and value to strings key_str = str(key) value_str = str(value) # Calculate alignment similarity score alignments = pairwise2.align.globalxx(key_str, value_str) alignment = alignments[0] score = alignment[2] file.write(f"{key_str} -> {value_str} -> Similarity Score: {score}\n") print(f"Output saved to {output_file}") Now generate Euclidean distance between each residue pair instead of alignment similarity score and save the text files into google_drive_folder = '/content/drive/MyDrive/ALLtxt_files/'
dff9f6cdcc82fcdc6a96b6167221da7f
{ "intermediate": 0.6116306781768799, "beginner": 0.17240068316459656, "expert": 0.21596871316432953 }
47,452
Give me examples of set time out funtions in javascript
80ebada616891863c77e04fc1d490ff7
{ "intermediate": 0.40203535556793213, "beginner": 0.36249592900276184, "expert": 0.23546867072582245 }
47,453
i have following code to train a lstm model: # %% [markdown] # <a href="https://colab.research.google.com/github/034adarsh/Stock-Price-Prediction-Using-LSTM/blob/main/LSTM_Improved_model(diff_dataset).ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # %% [markdown] # # Import all the required libraries # # --- # # # %% import pandas as pd import datetime as dt from datetime import date import numpy as np import tensorflow as tf # %% [markdown] # # Define start day to fetch the dataset from the yahoo finance library # # --- # # # %% data = pd.read_csv(r'C:\Users\arisa\Desktop\ddd\Binance_AVAXUSDT_d.csv') df=data df.head() # %% df = df[["Open", "High", "Low", "Close","volume_base", "volume_crypto", "tradecount","y1","y2","y3"]] data = data[["Open", "High", "Low", "Close","volume_base", "volume_crypto", "tradecount","y1","y2","y3"]] df.head() # %% [markdown] # Visualizing Closing Price # %% import matplotlib.pyplot as plt plt.figure(figsize=(12, 6)) plt.plot(df['Close']) plt.title("TCS India Stock Price") plt.xlabel("Date") plt.ylabel("Price (INR)") plt.grid(True) plt.show() # %% df # %% [markdown] # # Plotting moving averages of 100 day # # --- # # # %% ma100 = df.Close.rolling(100).mean() ma100 # %% plt.figure(figsize = (12,6)) plt.plot(df.Close) plt.plot(ma100, 'r') plt.grid(True) plt.title('Graph Of Moving Averages Of 100 Days') # %% [markdown] # # Defining 200 days moving averages and plotting comparision graph with 100 days moving averages # # --- # # # %% ma200 = df.Close.rolling(200).mean() ma200 # %% plt.figure(figsize = (12,6)) plt.plot(df.Close) plt.plot(ma100, 'r') plt.plot(ma200, 'g') plt.grid(True) plt.title('Comparision Of 100 Days And 200 Days Moving Averages') # %% df.shape # %% [markdown] # # Spliting the dataset into training (70%) and testing (30%) set # %% # Splitting data into training and testing train = pd.DataFrame(data[0:int(len(data)*0.70)]) test = pd.DataFrame(data[int(len(data)*0.70): int(len(data))]) print(train.shape) print(test.shape) # %% train.head() # %% test.head() # %% [markdown] # # Using MinMax scaler for normalization of the dataset # # --- # # # %% from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler(feature_range=(0,1)) # %% train_close = train.iloc[:, 4:5].values test_close = test.iloc[:, 4:5].values # %% data_training_array = scaler.fit_transform(train_close) data_training_array # %% x_train = [] y_train = [] for i in range(100, data_training_array.shape[0]): x_train.append(data_training_array[i-100: i]) y_train.append(data_training_array[i, 0]) x_train, y_train = np.array(x_train), np.array(y_train) # %% x_train.shape # %% [markdown] # # ML Model (LSTM) # # --- # # # %% from tensorflow.keras.layers import Dense, Dropout, LSTM from tensorflow.keras.models import Sequential # %% model = Sequential() model.add(LSTM(units = 50, activation = 'tanh', return_sequences=True ,input_shape = (x_train.shape[1], 1))) model.add(Dropout(0.2)) model.add(LSTM(units = 60, activation = 'tanh', return_sequences=True)) model.add(Dropout(0.3)) model.add(LSTM(units = 80, activation = 'tanh', return_sequences=True)) model.add(Dropout(0.4)) model.add(LSTM(units = 120, activation = 'tanh')) model.add(Dropout(0.5)) model.add(Dense(units = 1)) # %% model.summary() # %% [markdown] # # Training the model # # --- # # # %% import tensorflow as tf model.compile(optimizer = 'adam', loss = 'mean_squared_error', metrics=[tf.keras.metrics.MeanAbsoluteError()]) model.fit(x_train, y_train,epochs = 100) # %% model.save('keras_model.h5') # %% test_close.shape # %% past_100_days = pd.DataFrame(train_close[-100:]) # %% test_df = pd.DataFrame(test_close) # %% [markdown] # **Defining the final dataset for testing by including last 100 coloums of the training dataset to get the prediction from the 1st column of the testing dataset.** # # --- # # %% final_df = past_100_days._append(test_df, ignore_index = True) # %% final_df.head() # %% input_data = scaler.fit_transform(final_df) input_data # %% input_data.shape # %% [markdown] # # Testing the model # # --- # # # %% x_test = [] y_test = [] for i in range(100, input_data.shape[0]): x_test.append(input_data[i-100: i]) y_test.append(input_data[i, 0]) # %% x_test, y_test = np.array(x_test), np.array(y_test) print(x_test.shape) print(y_test.shape) # %% [markdown] # # Making prediction and plotting the graph of predicted vs actual values # # --- # # # %% # Making predictions y_pred = model.predict(x_test) # %% y_pred.shape # %% y_test # %% y_pred # %% scaler.scale_ # %% scale_factor = 1/0.00041967 y_pred = y_pred * scale_factor y_test = y_test * scale_factor # %% plt.figure(figsize = (12,6)) plt.plot(y_test, 'b', label = "Original Price") plt.plot(y_pred, 'r', label = "Predicted Price") plt.xlabel('Time') plt.ylabel('Price') plt.legend() plt.grid(True) plt.show() # %% [markdown] # # Model evaluation # %% [markdown] # Calculation of mean absolute error # %% from sklearn.metrics import mean_absolute_error mae = mean_absolute_error(y_test, y_pred) mae_percentage = (mae / np.mean(y_test)) * 100 print("Mean absolute error on test set: {:.2f}%".format(mae_percentage)) # %% [markdown] # Calculation of R2 score # %% from sklearn.metrics import r2_score # Actual values actual = y_test # Predicted values predicted = y_pred # Calculate the R2 score r2 = r2_score(actual, predicted) print("R2 score:", r2) # %% # Plotting the R2 score fig, ax = plt.subplots() ax.barh(0, r2, color='skyblue') ax.set_xlim([-1, 1]) ax.set_yticks([]) ax.set_xlabel('R2 Score') ax.set_title('R2 Score') # Adding the R2 score value on the bar ax.text(r2, 0, f'{r2:.2f}', va='center', color='black') plt.show() # %% plt.scatter(actual, predicted) plt.plot([min(actual), max(actual)], [min(predicted), max(predicted)], 'r--') plt.xlabel('Actual Values') plt.ylabel('Predicted Values') plt.title(f'R2 Score: {r2:.2f}') plt.show() make proper changes so the model uses "Open", "High", "Low", "Close","volume_base", "volume_crypto", "tradecount" instead of just using "Close" and also predicts "y1","y2","y3" instead of just Close price
82791bfbc0a98f712f5eefe62c3a5824
{ "intermediate": 0.4338858425617218, "beginner": 0.26664653420448303, "expert": 0.29946762323379517 }
47,454
please give me meta data with these tags warren buffett's timeless strategy,investor weekly,value investing,financial education,investment strategies,warren buffett investment strategy,warren buffett advice,warren buffett investing,warren buffett investment,warren buffett wisdom,stock market investing,warren buffett motivation,investment
2379a985b82c6a91aa45a825ea262cf0
{ "intermediate": 0.3512565791606903, "beginner": 0.37326544523239136, "expert": 0.2754780352115631 }
47,455
Write a script of a simple Discord bot using discord.py
06151abaf99ce5b56656f8ea2e2f114c
{ "intermediate": 0.3454936444759369, "beginner": 0.2567283809185028, "expert": 0.3977779150009155 }
47,456
how can i create a grid of 50 meter by 50 meter squares in geojson for a leaflet.js map
ac34483c2438f1e3a0188bb92cab8be5
{ "intermediate": 0.381401002407074, "beginner": 0.21092477440834045, "expert": 0.4076741933822632 }
47,457
please explain this google colab error: ""NameError Traceback (most recent call last) <ipython-input-1-06d1f3208168> in <cell line: 16>() 14 15 # Convert to fp16 ---> 16 fp16 = f"{MODEL_NAME}/{MODEL_NAME.lower()}.fp16.bin" 17 get_ipython().system('python llama.cpp/convert.py {MODEL_NAME} --outtype f16 --outfile {fp16}') 18 NameError: name 'MODEL_NAME' is not defined ""
992411a9d7a394fb2a4bc5cad5062ce3
{ "intermediate": 0.46745553612709045, "beginner": 0.3224641978740692, "expert": 0.21008028090000153 }
47,458
var a,b,s:array[0..1000001] of int64; n,d:longint; kq:int64; procedure nhapdl; var i:longint; begin assign(input,'bai5.inp'); reset(input); assign(output,'bai5.out'); rewrite(output); readln(d,n); s[0]:=1; for i:=1 to n do begin read(a[i]); b[i]:=(a[i]+b[i-1]) mod d; inc(s[b[i]]); end; end; procedure cach1; var i,j:longint; begin kq:=0; for i:=1 to n do for j:=i to n do if (b[j]-b[i-1]) mod d =0 then inc(kq); write(kq); end; procedure cach2; var i,j:longint; begin kq:=0; for i:=0 to d-1 do kq:=kq+(s[i]*(s[i]-1) div 2); write(kq); end; begin nhapdl; //cach1; //writeln; cach2; close(input); close(output); end. c++
b5f2889ccd41380be78c538a8f317ec3
{ "intermediate": 0.3372705280780792, "beginner": 0.33667173981666565, "expert": 0.3260577917098999 }
47,459
#include <bits/stdc++.h> #include <vector> #include <queue> using namespace std; void add_edge(vector<vector<int>> &adj, int u, int v) { adj[u].push_back(v); adj[v].push_back(u); } void empty_vis(vector<int> &vis) { fill(vis.begin(), vis.end(), 0); } bool is_vis_full(vector<int> &vis) { return all_of(vis.begin(), vis.end(), [](int x) { return x == 1; }); } void bfs(vector<vector<int>> &adj, int start, vector<int> &vis1, vector<int> &vis2) { queue<int> myqueue; vis2[start] = true; vis1[start] = true; myqueue.push(start); while (!myqueue.empty()) { int curr = myqueue.front(); myqueue.pop(); for (int neighbour : adj[curr]) { if (!vis2[neighbour]) { vis2[neighbour] = true; vis1[neighbour] = true; myqueue.push(neighbour); } } } } int find_last_node(vector<int> &vis) { for (int i = vis.size() - 1; i >= 0; i--) { if (vis[i] == 1) return i; } return -1; } int find_start_node(vector<int> &vis) { for (int i = 0; i < vis.size(); i++) { if (vis[i] == 0) return i; } return -1; } int main() { int vertices, edges; cin >> vertices >> edges; vector<vector<int>> adj(vertices); vector<int> vis1(vertices); empty_vis(vis1); vector<int> vis2(vertices); empty_vis(vis2); int cnt = 0; vector<vector<int>> arr; for (int i = 0; i < edges; i++) { int u, v; cin >> u >> v; add_edge(adj, u, v); } while (!is_vis_full(vis1)) { int start = find_start_node(vis1); bfs(adj, start, vis1, vis2); int end = find_last_node(vis2); if (start != -1 && end != -1) { arr.push_back({start, end}); cnt++; add_edge(adj, start, end); } empty_vis(vis1); empty_vis(vis2); } cout << cnt << "\n"; for (const auto &pair : arr) { cout << pair[0] << " " << pair[1] << "\n"; } return 0; } Statement You're given the buildings and the layout of roads between the buildings. Each existing pathway connects two distinct buildings bidirectionally, and there can be at most one pathway between any two buildings. Your objective is to determine the minimum number of new pathways needed to ensure anyone can travel between any two buildings in the Vindhya complex. Additionally, you need to specify which specific new pathways should be constructed. Input Format The first line will contain the two space-separated integers: the number of buildings and the total number of pathways. lines follow, the will contain two space separated integers: and indicating that the road connects the buildings and Output Format In the first line output the minimum number of roads that need to be added. Then, in separate new lines, print the two buildings and , the buildings which your new road connects. If there are multiple solutions, print any of them.
99bef5d623f30f0f3b919c80c54c5f21
{ "intermediate": 0.3204505741596222, "beginner": 0.5018317699432373, "expert": 0.1777176856994629 }
47,460
in servicenow, i wrote a script include that gets the duplicate from alm_asset table and use it on reports to show, but reports shows duplicate data. can you tell me how to fix this issue. i provide my script include below. var getDuplicates = CLass.create(); getDuplicates.prototype = Object.extendsObject(AbstractAjaxProcessor, { getDuplicatesSerialNumber: function( ) var dupRecords = []; var gaDupCheck = new GlideAggregate('alm_asset'); //gaDupCheck.addEncodedQuery('install_status!=7'); gaDupCheck.addQuery('install_status','!=',7); gaDupCheck.addAggregate('COUNT', 'serial_number' ); gaDupCheck.addNotNullQuery('serial_number'); gaDupCheck.groupBy('serial_number'); gaDupCheck.addHaving('COUNT', '>', 1); gaDupCheck.query(); while (gaDupCheck.next()) { dupRecords.push(gaDupCheck['serial_number'].toString()); } return dupRecords; ),
ba04da9d66b37668824bd92106405bce
{ "intermediate": 0.5755259394645691, "beginner": 0.24741403758525848, "expert": 0.17705997824668884 }
47,461
in this javascript for leaflet.js why am I getting the error ' clickedFeature.getBounds is not a function' when I try to add a marker to the map - 'var map = L.tileLayer('', { maxZoom: 20, subdomains: ['mt0', 'mt1', 'mt2', 'mt3'] }); // initialize the map on the "map" div with a given center and zoom var map = L.map('map', { layers: [map] }).setView([-5.0750, 19.4250], 13); // Flag to track grid click event state (combined for roads and parks) var gridClickEnabled = false; function houseSquareClick(e) { if (gridClickEnabled) { var clickedFeature = e.target.feature; // Access the feature object from the event var center = clickedFeature.getBounds().getCenter(); // Get center coordinates var marker = L.marker(center).addTo(map); // Create and add marker to the center } } // Function to handle square click and update color for parks function parkSquareClick(e) { if (gridClickEnabled) { var clickedSquare = e.target.feature; clickedSquare.properties = {fillColor: 'green', fillOpacity: 1 }; // Change color to green e.target.setStyle(clickedSquare.properties); // Update style on map } } // Function to handle square click and update color for roads (optional) function squareClick(e) { if (gridClickEnabled) { var clickedSquare = e.target.feature; clickedSquare.properties = {fillColor: 'black', fillOpacity: 1 }; // Change color to black e.target.setStyle(clickedSquare.properties); // Update style on map } } // Get references to the button elements var parksButton = document.getElementById("parksButton"); var roadsButton = document.getElementById("roadsButton"); var housesButton = document.getElementById("housesButton"); // Function to toggle grid click event based on button function toggleGridClick(featureType) { // Renamed for clarity // Update gridClickEnabled based on button click, but only if different from current state if (featureType === "parks") { gridClickEnabled = !gridClickEnabled || featureType !== "roads" || featureType !== "houses"; // Handle all three features } else if (featureType === "roads") { gridClickEnabled = !gridClickEnabled || featureType !== "parks" || featureType !== "houses"; // Handle all three features } else if (featureType === "houses") { // New feature type for houses gridClickEnabled = !gridClickEnabled || featureType !== "parks" || featureType !== "roads"; // Handle all three features } map.eachLayer(function(layer) { // Check for existing square grid layer if (layer.feature && layer.feature.geometry.type === 'Polygon') { layer.off('click'); // Remove all click listeners before adding a new one if (gridClickEnabled) { if (featureType === "parks") { layer.on('click', parkSquareClick); // Add click listener for parks parksButton.innerText = "Parks On"; roadsButton.innerText = "Roads Off"; housesButton.innerText = "Houses Off"; // Update button text } else if (featureType === "roads") { // Optional for roads button layer.on('click', squareClick); // Add click listener for roads roadsButton.innerText = "Roads On"; parksButton.innerText = "Parks Off"; housesButton.innerText = "Houses Off"; // Update button text (optional) }else if (featureType === "houses") { // New click listener for houses layer.on('click', houseSquareClick); // Add click listener for houses housesButton.innerText = "Houses On"; parksButton.innerText = "Parks Off"; roadsButton.innerText = "Roads Off"; // Update button text for houses } } else { parksButton.innerText = "Parks Off"; // Update button text roadsButton.innerText = "Roads Off"; // Update button text (optional) housesButton.innerText = "Houses Off"; // Update button text (optional) } } }); } // Add click event listeners to the buttons parksButton.addEventListener("click", function() { toggleGridClick("parks"); }); roadsButton.addEventListener("click", function() { toggleGridClick("roads"); // Optional for roads button }); housesButton.addEventListener("click", function() { toggleGridClick("houses"); }); // Square Grid var bbox = [19.35, -5, 19.5, -5.15]; var cellSide = 1; var options = {units: 'kilometers'}; var squareGrid = turf.squareGrid(bbox, cellSide, options); // Add GeoJSON layer with click event handler (optional, can be removed) L.geoJSON(squareGrid, { style: function (feature) { return {weight: 1, fillOpacity: 0 }; // Initial style for squares } }).addTo(map);'
5f21235a857c1a3e5564e7395f378ade
{ "intermediate": 0.3932592272758484, "beginner": 0.40741002559661865, "expert": 0.19933079183101654 }
47,462
این کد منه <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Candlestick Chart with Dark Background</title> <script src="https://unpkg.com/lightweight-charts@3.0.0/dist/lightweight-charts.standalone.production.js"></script> <style> /* استایل نمودار */ #chart-container { width: 100%; max-width: 90%; margin: 0 auto; } </style> </head> <body> <div id="chart-container"></div> <script> document.addEventListener("DOMContentLoaded", function () { const chartContainer = document.getElementById("chart-container"); // داده‌های قیمتی (مثال) const data = [ {'open': '65027.3', 'close': '65060.7', 'high': '65094.0', 'low': '65027.2', 'volume': '30.75', 'time': 1713683100000}, {'open': '65020.6', 'close': '65026.3', 'high': '65066.7', 'low': '65000.0', 'volume': '62.00', 'time': 1713682800000}, {'open': '65051.9', 'close': '65020.6', 'high': '65071.0', 'low': '65014.7', 'volume': '55.76', 'time': 1713682500000}, {'open': '65066.5', 'close': '65051.8', 'high': '65083.9', 'low': '65050.0', 'volume': '72.57', 'time': 1713682200000}, {'open': '65073.8', 'close': '65066.4', 'high': '65116.3', 'low': '65050.0', 'volume': '49.10', 'time': 1713681900000}, {'open': '65079.6', 'close': '65073.7', 'high': '65123.8', 'low': '65070.1', 'volume': '44.89', 'time': 1713681600000}, {'open': '65107.2', 'close': '65079.7', 'high': '65150.2', 'low': '65071.9', 'volume': '40.40', 'time': 1713681300000}, {'open': '65134.4', 'close': '65108.1', 'high': '65150.1', 'low': '65092.4', 'volume': '40.99', 'time': 1713681000000}, {'open': '65142.5', 'close': '65135.3', 'high': '65167.9', 'low': '65107.7', 'volume': '73.87', 'time': 1713680700000}, {'open': '65063.7', 'close': '65143.3', 'high': '65178.2', 'low': '65029.8', 'volume': '85.38', 'time': 1713680400000}, {'open': '64983.0', 'close': '65063.6', 'high': '65073.3', 'low': '64952.9', 'volume': '57.30', 'time': 1713680100000}, {'open': '64953.6', 'close': '64982.9', 'high': '65006.9', 'low': '64953.6', 'volume': '51.59', 'time': 1713679800000}, {'open': '64986.3', 'close': '64953.4', 'high': '65045.2', 'low': '64953.2', 'volume': '55.86', 'time': 1713679500000}, {'open': '64996.2', 'close': '64986.6', 'high': '65024.2', 'low': '64900.4', 'volume': '78.30', 'time': 1713679200000}, {'open': '64980.2', 'close': '64996.3', 'high': '65028.6', 'low': '64978.9', 'volume': '58.83', 'time': 1713678900000}, {'open': '65008.7', 'close': '64980.1', 'high': '65073.7', 'low': '64980.0', 'volume': '51.49', 'time': 1713678600000}, {'open': '65046.1', 'close': '65007.8', 'high': '65063.2', 'low': '64943.9', 'volume': '103.21', 'time': 1713678300000}, ]; // ایجاد نمودار کندل استیک const chart = LightweightCharts.createChart(chartContainer, { width: chartContainer.offsetWidth, height: 900, }); chart.applyOptions({ timeScale: { timeVisible: true, secondsVisible: true, }, layout: { backgroundColor: 'rgb(17, 17, 39)', textColor: 'rgba(255, 255, 255, 0.9)', }, grid: { vertLines: { color: 'rgb(41, 44, 58)', }, horzLines: { color: 'rgb(41, 44, 58)', }, }, crosshair: { mode: LightweightCharts.CrosshairMode.Normal, }, scales: { x: { type: 'time', time: { unit: 'day' } }, y: { beginAtZero: true } }, priceScale: { borderColor: 'rgba(197, 203, 206, 0.5)', }, timeScale: { borderColor: 'rgba(197, 203, 206, 0.5)', }, watermark: { color: 'rgba(197, 203, 206, 0.5)', visible: true, text: 'dev boys chart', fontSize: 32, horzAlign: 'center', vertAlign: 'center', }, }); const candlestickSeries = chart.addCandlestickSeries(); candlestickSeries.setData(data); const entryLineSeries = chart.addLineSeries({ color: 'red', // رنگ نمایش نقطه ورود lineWidth: 4, }); entryLineSeries.setData([ { time: 1713683100000, value: 65031 }, { time: 1713305400000, value: 60031 }, // مقدار خط افقی { time: 1713251400000, value: 65031 }, // مقدار خط افقی ]); }); </script> </body> </html> میخوام با توجه به کد زیر کاری کنی که من بتونم بالای و یا پایین ی کندل byu , sell بنویسم // determining the dates for the 'buy' and 'sell' markers added below. const datesForMarkers = [data[data.length - 39], data[data.length - 19]]; let indexOfMinPrice = 0; for (let i = 1; i < datesForMarkers.length; i++) { if (datesForMarkers[i].high < datesForMarkers[indexOfMinPrice].high) { indexOfMinPrice = i; } } const markers = [ { time: data[data.length - 48].time, position: 'aboveBar', color: '#f68410', shape: 'circle', text: 'D', }, ]; for (let i = 0; i < datesForMarkers.length; i++) { if (i !== indexOfMinPrice) { markers.push({ time: datesForMarkers[i].time, position: 'aboveBar', color: '#e91e63', shape: 'arrowDown', text: 'Sell @ ' + Math.floor(datesForMarkers[i].high + 2), }); } else { markers.push({ time: datesForMarkers[i].time, position: 'belowBar', color: '#2196F3', shape: 'arrowUp', text: 'Buy @ ' + Math.floor(datesForMarkers[i].low - 2), }); } } series.setMarkers(markers); chart.timeScale().fitContent();
33ca8c1793fce4192610650649e8b3d2
{ "intermediate": 0.2489183396100998, "beginner": 0.5060988068580627, "expert": 0.2449827790260315 }
47,463
I this javascript for leaflet.js I want to add a marker to the center of a clicked grid square rather than give it a yellow fill when the housesButton is selected - 'var map = L.tileLayer('', { maxZoom: 20, subdomains: ['mt0', 'mt1', 'mt2', 'mt3'] }); // initialize the map on the "map" div with a given center and zoom var map = L.map('map', { layers: [map] }).setView([-5.0750, 19.4250], 13); // Flag to track grid click event state (combined for roads and parks) var gridClickEnabled = false; // Function to handle square click and update color for parks function houseSquareClick(e) { if (gridClickEnabled) { var clickedSquare = e.target.feature; clickedSquare.properties = {fillColor: 'yellow', fillOpacity: 1 }; // Change color to green e.target.setStyle(clickedSquare.properties); // Update style on map } } // Function to handle square click and update color for parks function parkSquareClick(e) { if (gridClickEnabled) { var clickedSquare = e.target.feature; clickedSquare.properties = {fillColor: 'green', fillOpacity: 1 }; // Change color to green e.target.setStyle(clickedSquare.properties); // Update style on map } } // Function to handle square click and update color for roads (optional) function squareClick(e) { if (gridClickEnabled) { var clickedSquare = e.target.feature; clickedSquare.properties = {fillColor: 'black', fillOpacity: 1 }; // Change color to black e.target.setStyle(clickedSquare.properties); // Update style on map } } // Get references to the button elements var parksButton = document.getElementById("parksButton"); var roadsButton = document.getElementById("roadsButton"); var housesButton = document.getElementById("housesButton"); // Function to toggle grid click event based on button function toggleGridClick(featureType) { // Renamed for clarity // Update gridClickEnabled based on button click, but only if different from current state if (featureType === "parks") { gridClickEnabled = !gridClickEnabled || featureType !== "roads" || featureType !== "houses"; // Handle all three features } else if (featureType === "roads") { gridClickEnabled = !gridClickEnabled || featureType !== "parks" || featureType !== "houses"; // Handle all three features } else if (featureType === "houses") { // New feature type for houses gridClickEnabled = !gridClickEnabled || featureType !== "parks" || featureType !== "roads"; // Handle all three features } map.eachLayer(function(layer) { // Check for existing square grid layer if (layer.feature && layer.feature.geometry.type === 'Polygon') { layer.off('click'); // Remove all click listeners before adding a new one if (gridClickEnabled) { if (featureType === "parks") { layer.on('click', parkSquareClick); // Add click listener for parks parksButton.innerText = "Parks On"; roadsButton.innerText = "Roads Off"; housesButton.innerText = "Houses Off"; // Update button text } else if (featureType === "roads") { // Optional for roads button layer.on('click', squareClick); // Add click listener for roads roadsButton.innerText = "Roads On"; parksButton.innerText = "Parks Off"; housesButton.innerText = "Houses Off"; // Update button text (optional) }else if (featureType === "houses") { // New click listener for houses layer.on('click', houseSquareClick); // Add click listener for houses housesButton.innerText = "Houses On"; parksButton.innerText = "Parks Off"; roadsButton.innerText = "Roads Off"; // Update button text for houses } } else { parksButton.innerText = "Parks Off"; // Update button text roadsButton.innerText = "Roads Off"; // Update button text (optional) housesButton.innerText = "Houses Off"; // Update button text (optional) } } }); } // Add click event listeners to the buttons parksButton.addEventListener("click", function() { toggleGridClick("parks"); }); roadsButton.addEventListener("click", function() { toggleGridClick("roads"); // Optional for roads button }); housesButton.addEventListener("click", function() { toggleGridClick("houses"); }); // Square Grid var bbox = [19.35, -5, 19.5, -5.15]; var cellSide = 1; var options = {units: 'kilometers'}; var squareGrid = turf.squareGrid(bbox, cellSide, options); // Add GeoJSON layer with click event handler (optional, can be removed) L.geoJSON(squareGrid, { style: function (feature) { return {weight: 1, fillOpacity: 0 }; // Initial style for squares } }).addTo(map); '
c9f43c4fdca0d6f0d63c3a5cc42a103b
{ "intermediate": 0.32852983474731445, "beginner": 0.5023596882820129, "expert": 0.1691104769706726 }
47,464
Make a HTML snippet with a heading 2 saying Trivia and a bullet explaining what the "Soporose" means and what it is related to in the game mode. Use code blocks. <html> <head> <link rel="stylesheet" href="style.css"> <title>Functioner 95 - Games</title> </head> <body> <header><h1>Games</h1></header> <p>Games are used to gain points. These appear in all Functioner and FunkOS systems.</p> <h1>Types of games</h1> <ul> <li><b>Hidden Logo/Functosh</b>: Functioner or FunkOS gives you points if the mouse pointer hovers over its logo or icon (depending on the line of systems you're running).</li> <li><b>Screensaver</b>: A item will appear on the screen and will go to random positions. If you manage to catch the item, you will then receive a 500 point bonus.</li> <li><b>Screensaver New</b>: Only appearing in Functioner 96 to 10.10 by the time being, in Cryp&#0321;funk and in FUNK/S. A item will be floating on the screen and bouncing. Press space if it touches the red area to receive the 500 point bonus.</li> <li><b>Searchlight</b>: Similar to Screensaver. Only appearing in FunkOS I&#11604;+ by the time being. However, the item (called Functosh in FunkOS) moves around the screen instead of randomly appearing in random positions. It also leaves a trail.</li> <li><b>Multiplayer</b>: Only appearing in FunkOS systems from Functosh System 1 to FunkOS 1&#11604;III and in FUNK/S by the time being. You are controlling the Functosh and have to defeat the opponent Functosh who blocks balls. If you shoot the ball to the opponent Functosh, you get a 500 point bonus.</li> <li><b>Screensaver Soporose</b>: A new game mode. Only appearing in Functioner 11+ by the time being. Same as Screensaver, except the item doesn't move and appears in random positions before fading out and hiding into a different position, making it hard to play the game mode. You can find information about this one in the <a href="sillythings.html">Silly things</a> page.</li> <li><b>Multiplayer Soporose</b>: Only appearing in FunkOS II+ by the time being. Same as Multiplayer, except the ball doesn't move and appears in random positions before fading out and hiding into a different position, making it hard to play the game mode, like in Screensaver Soprose. If the blue Functosh touches the ball, it will go to a different position far away from the blue Functosh.</li> </ul> <h1>Gallery</h1> <img src="games.png" height="250px"><p>The screensaver game mode in Functioner Meteor.</p><img src="games2.png" height="250px"><p>The Hidden Logo game mode in Functioner REMOTE 4.</p><img src="funkos3.png" height="250px"><p>The old screensaver game mode in FunkOS 7. You can see how system lines behave differently to others in <a href="behaviour.html">this page</a>.</p><img src="games5.png" height="250px"><p>The message that appears before the start of the Hidden Logo game mode in Functioner 80.</p><img src="games3.png" height="250px"><p>The multiplayer game mode in FunkOS I&#11604;II.</p><img src="cryptfunk2.png" height="250px"><p>The screensaver game mode in Cryp&#0321;funk (new).</p><img src="silly6.png" height="250px"><p>The Screensaver Soporose gamemode in Functioner 11.20.</p><img src="games4.png" height="250px"><p>The Multiplayer Soporose gamemode in FunkOS II.</p> <footer><p>End</p></footer> </body> </html>
f6daccd75ed382e74fe366f694f99794
{ "intermediate": 0.2933083772659302, "beginner": 0.4179682433605194, "expert": 0.288723349571228 }
47,465
Add trivia relating to the meanings of random words found in the Silly things page in the HTML. Use code blocks. <html> <head> <link rel="stylesheet" href="style.css"> <title>Functioner 95 - Silly things</title> </head> <body> <header><h1>Silly things</h1></header> <p>There are a few silly things to do with Functioner. Here are a few of them:</p> <img src="silly.png" height="250px"><p>Sometimes, there may be dead pixels on the screen, among image popups (the latter can be seen in Functioner 1 onwards, NOT DOS System).</p><img src="silly2.png" height="250px"><p>The FunkOS sometimes advertises Functioner since it has more systems.</p><img src="silly3.png" height="250px"><p>The FunkOS 8 logo has googly eyes.</p><img src="silly4.png" height="250px"><p>Functioner sometimes complains about the things it doesn't know to do.</p> <img src="silly6.png" height="250px"><p>Ever since the release of the wiki, you can find a classic mode commonly in systems after Functioner 96. Since the FunkOS I&#11604;III update, that chance is raised to high in modern systems, but if you're lucky, you will find a very updated Screensaver game mode, where the item doesn't move and appears in random positions before fading out and hiding into a different position, making it hard to play the game mode.</p><img src="silly5.png" height="250px"><p>Something similar to the last one, which was introduced during the FunkOS I&#11604; update. Since FunkOS I&#11604; and FunkOS I&#11604;II have been released, users are finding it hard to see new things. If you boot into Functioner, then you will see that Functosh is locked. Try again, it doesn't unlock, until it unlocks itself. If you press it, you will get into an old system (most specifically Functosh System 5) and instantly boot into the B OS Show or Progressbar Largehorn (Show).</p><p>However, if you are lucky enough, you may get a "searchlight" screensaver game mode in FunkOS I&#11604;+. The Functosh is now moving around and does not go in random positions. It also leaves a trail. You can find more on FunkOS I&#11604; and its aesthetics on the <a href="index.html">main page</a>.</p><img src="silly7.png" height="250px"><p>Even though Functioner REMOTE 3.6 in-game counts itself as a server system, in the Progressbar95 universe it is counted as a consumer system.</p><img src="silly8.png" height="250px"><p>Looking into the FunkOS IZ Functosh icon more closely will give you the name of the CPU, in case "N1". Inside the red Functosh sprite's costumes, if you look closer it says "O1", which stands for Opponent 1.</p><p>In FunkOS I&#1047; (new), the CPU names are "N2" and "O2", respectively.</p><img src="silly9.png" height="250px"><p>In FunkOS I&#1047; (new), the colours of the Functoshes in the Multiplayer game mode are hilariously referred to as Azure and Tomato, respectively.</p> <footer><p>End</p></footer> </body> </html>
a384d702806fa5528adc9a6dcca1295b
{ "intermediate": 0.34941962361335754, "beginner": 0.49041715264320374, "expert": 0.16016322374343872 }
47,466
Make the HTML's sentences into 1 sentence. Use code blocks. <!DOCTYPE html> <html> <head> <link rel=“stylesheet” href=“style.css”> <title>Functioner 95 - Silly things</title> </head> <body> <header><h1>Silly things</h1></header> <p>Discover quirky facts related to the amusing vocabulary within the Functioner world:</p> <!-- Trivia: Dead pixels --> <img src=“silly.png” height=“250px”> <p><strong>Dead pixels:</strong> A dead pixel is a picture element in which all three RGB (red, green, blue) sub-pixels are permanently off, making it appear as a black spot on the screen. This term humorously reminds us of the frustrations of early computer users.</p> <!-- Trivia: Image popups --> <img src=“silly2.png” height=“250px”> <p><strong>Image popups:</strong> The term “popup” dates back to the early days of web browsing, referring to unsolicited browser windows. It’s funny to see Functioner using an old annoyance for whimsical purposes.</p> <!-- Trivia: FunkOS --> <img src=“silly3.png” height=“250px”> <p><strong>FunkOS:</strong> Perhaps a playful nod to various operating systems with “OS” in their names, implying functionality but here with a ‘funky’ twist emphasizing quirkiness or odd features.</p> <!-- Trivia: Googly eyes --> <img src=“silly4.png” height=“250px”> <p><strong>Googly eyes:</strong> These are small plastic craft supplies meant to imitate eyeballs, where the pupil moves inside the larger clear sphere filled with liquid. Adding them to the FunkOS 8 logo certainly adds a lighthearted absurdity.</p> <!-- Trivia: Complains --> <img src=“silly6.png” height=“250px”> <p><strong>Complains:</strong> In anthropomorphism, objects or software “complaining” about tasks they cannot do breathes life into them, suggesting a quirky personality for Functioner.</p> <!-- Trivia: Classic mode --> <p>In gaming and software, the term “classic mode” often refers to original or traditional gameplay features, pointing to a nostalgia factor within the Functioner ecosystem.</p> <!-- Trivia: Screensaver --> <img src=“silly5.png” height=“250px”> <p><strong>Screensavers:</strong> Originally designed to prevent phosphor burn-in on CRT and plasma computer monitors by blanking the screen or filling it with moving images. The evolution into game modes showcases technological advancement with a nod to their origin.</p> <!-- Trivia: Remote 3.6 --> <img src=“silly7.png” height=“250px”> <p><strong>REMOTE 3.6:</strong> The term “server system” is a technical designation for systems primarily used for running server applications. Its classification as a “consumer system” in-game adds an amusing contradiction, considering the professional and technical connotations of the term.</p> <!-- Trivia: CPU Names --> <img src=“silly8.png” height=“250px”> <p><strong>CPU Names (“N1”, “N2”, “O1”, “O2”):</strong> These designations are typically used in computing to refer to “CPU cores” or “network operations.” By assigning simplistic labels, it playfully simplifies the complex nature of CPU architecture or network roles.</p> <!-- Trivia: Azure and Tomato --> <img src=“silly9.png” height=“250px”> <p><strong>Azure and Tomato:</strong> These color names, often found in fancier design or art contexts, are humorously applied to multiplayer game modes, poking fun at the sometimes pretentious naming of colors in technology and design.</p> <footer><p>End</p></footer> </body> </html>
b8a3cb86a7b1432cabda6decfd15a65e
{ "intermediate": 0.30400174856185913, "beginner": 0.4519963562488556, "expert": 0.24400191009044647 }
47,467
Make a trivia section in this HTML about meanings of a few words in this page. Use code blocks. <html> <head> <link rel="stylesheet" href="style.css"> <title>Functioner 95 - Silly things</title> </head> <body> <header><h1>Silly things</h1></header> <p>There are a few silly things to do with Functioner. Here are a few of them:</p> <img src="silly.png" height="250px"><p>Sometimes, there may be dead pixels on the screen, among image popups (the latter can be seen in Functioner 1 onwards, NOT DOS System).</p><img src="silly2.png" height="250px"><p>The FunkOS sometimes advertises Functioner since it has more systems.</p><img src="silly3.png" height="250px"><p>The FunkOS 8 logo has googly eyes.</p><img src="silly4.png" height="250px"><p>Functioner sometimes complains about the things it doesn't know to do.</p> <img src="silly6.png" height="250px"><p>Ever since the release of the wiki, you can find a classic mode commonly in systems after Functioner 96. Since the FunkOS I&#11604;III update, that chance is raised to high in modern systems, but if you're lucky, you will find a very updated Screensaver game mode, where the item doesn't move and appears in random positions before fading out and hiding into a different position, making it hard to play the game mode.</p><img src="silly5.png" height="250px"><p>Something similar to the last one, which was introduced during the FunkOS I&#11604; update. Since FunkOS I&#11604; and FunkOS I&#11604;II have been released, users are finding it hard to see new things. If you boot into Functioner, then you will see that Functosh is locked. Try again, it doesn't unlock, until it unlocks itself. If you press it, you will get into an old system (most specifically Functosh System 5) and instantly boot into the B OS Show or Progressbar Largehorn (Show).</p><p>However, if you are lucky enough, you may get a "searchlight" screensaver game mode in FunkOS I&#11604;+. The Functosh is now moving around and does not go in random positions. It also leaves a trail. You can find more on FunkOS I&#11604; and its aesthetics on the <a href="index.html">main page</a>.</p><img src="silly7.png" height="250px"><p>Even though Functioner REMOTE 3.6 in-game counts itself as a server system, in the Progressbar95 universe it is counted as a consumer system.</p><img src="silly8.png" height="250px"><p>Looking into the FunkOS IZ Functosh icon more closely will give you the name of the CPU, in case "N1". Inside the red Functosh sprite's costumes, if you look closer it says "O1", which stands for Opponent 1.</p><p>In FunkOS I&#1047; (new), the CPU names are "N2" and "O2", respectively.</p><img src="silly9.png" height="250px"><p>In FunkOS I&#1047; (new), the colours of the Functoshes in the Multiplayer game mode are hilariously referred to as Azure and Tomato, respectively.</p> <footer><p>End</p></footer> </body> </html>
e0e06e9c9023d58702f74330da9507ef
{ "intermediate": 0.28560569882392883, "beginner": 0.4936651289463043, "expert": 0.22072912752628326 }
47,468
Remake the text in the HTML. Use code blocks. Only provide the HTML here. <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>I9K - Inter9000 Returns</title> <link href="/style.css" rel="stylesheet" type="text/css"> <link rel="shortcut icon" type="image/ico" href="/favicon.ico"> </head> <body> <header> <img src="/logo.png" height="100px" alt="Logo"> <div class="nav-links"> <a href="index.html">Home</a> &nbsp;&nbsp; <a href="gallery.html">Gallery</a> &nbsp;&nbsp; <a href="blog.html">Blog</a> &nbsp;&nbsp; <a href="index.html">Soon</a> &nbsp;&nbsp; </div> </header> <!--<p> I9K is a website that was created in April 2023 as <a href="https://i4k.neocities.org">Inter4000</a>, or I4K. It aims to provide high-quality content and resources to the I9K community and is powered by the company who also powers C159 and the pBar 63 homepage: <a href="https://iserver.neocities.org">iServer</a>. I9K is based on Clippy 159's site, and made after few more sites like <a href="https://ptfifou2.neocities.org">PTFiFOU</a>, <a href="https://i8kreturns.neocities.org">I8K Returns</a> and <a href="https://i8k.neocities.org">I8K</a>. </p> <p>Also, I do Functioner 95. You can see its wiki <a href="/Functioner/index.html">here</a> or explore the Functionnet <a href="/Functionnet/index.html">here</a>.</p> <p>Functioner 95 (Public RC) can be downloaded here: <a href="https://file.io/Zp4mgmP1zGdT">https://file.io/Zp4mgmP1zGdT</a>. You have until 14 July to download it.</p> I make stuff and I am also managing Progresswire Coo right now.--> <div class="content"> <h2>About I9K</h2> <p>I9K (or Inter9000 Returns) is a website that I created in April 2023, otherwise known as I4K before May 2023. Right now, I am working on it, and this website is powered by iServer (which is actually a seperate site of Clippy 159). Also, I am working on Functioner 95, which you can see <a href="/Functioner/index.html">here</a>.</p> <h2>A random list</h2> <ul> <li>Pull</li> <li>Tug</li> <li>Sub</li> <li>Woof</li> <li>Glan</li> </ul> <h2>Some facts that I did not mention in my about</h2> <ul> <li>iServer is also the server that powers Clippy 159's homepage (or C159).</li> <li>iServer is also the server that powers pBar 64 usingchipper's homepage (or the pBar 63 homepage).</li> <li>You can explore the Functionnet <a href="/Functionnet/index.html">here</a>.</li> <li>This was made after various sites, such as: <ul> <li><a href="https://ptfifou2.neocities.org">PTFiFOU 2</a></li> <li><a href="https://i8kreturns.neocities.org">I8K Returns</a></li> <li><a href="https://i8k.neocities.org">I8K</a></li> </ul></li> <li>I am also managing Progresswire Coo, which you can see <a href="https://prgrswr381937.ichi.city">here</a>.</li> </ul> <h2>Links not in other pages</h2> <p>These links are:</p> <ul> <li><a href="/i4f/index.html">I4F</a></li> <li><a href="my.html">My knowledge</a></li> <li><a href="weirdstuff.html">Weird Stuff</a></li> <li><a href="testbuild.html">Test build</a></li> <li>More to come soon...</li> </ul> <h2>Join Us Today</h2> <p> Even if you are not part of the I9K community, you can join us for new people. </p> <p>I am also on Linktree as Inter4000 and Progresswire Coo (which you will see a link to download Progresswire Coo), go here for more: <a href="https://linktr.ee/i4kthetf1thingy">https://linktr.ee/i4kthetf1thingy</a></p> </div> <footer> <h1>More websites to discover</h1> <p>I don't know.</p> <small>No more left. Comment for suggestions.</small> <small>This website is not affiliated with ClippyBuji, LLC or Omarkee, LLC in any way.</small> </footer> </body> </html>
74c6570aedf3b5cadbaffab694b429ac
{ "intermediate": 0.2817091941833496, "beginner": 0.5508615970611572, "expert": 0.16742916405200958 }
47,469
can you change the marker in this function '// Function to handle square click and add a marker at the center for houses function houseSquareClick(e) {  if (gridClickEnabled) {   var clickedSquare = e.target.feature;       // Get the center of the clicked square   var centerCoords = turf.centroid(clickedSquare);       // Get the bounding box of the clicked square   var bbox = e.target.getBounds();       // Get the southwest and northeast corners of the bounding box in pixel equivalents   var swPixel = map.latLngToContainerPoint(bbox.getSouthWest());   var nePixel = map.latLngToContainerPoint(bbox.getNorthEast());       // Calculate the width and height of the bounding box in pixels   var bboxWidth = Math.abs(nePixel.x - swPixel.x);   var bboxHeight = Math.abs(nePixel.y - swPixel.y);       // Define the custom marker icon with the calculated size   var customIcon = L.icon({    iconUrl: 'https://cdn.glitch.global/12fb2e80-41df-442d-8bf7-be84a3d85f59/_abb407dd-c75d-4d25-93bb-f07f25229da1.jpeg?v=1713688035687',    iconSize: [bboxWidth, bboxHeight], // Set size based on bounding box    iconAnchor: [bboxWidth / 2, bboxHeight / 2] // Adjust anchor point if needed   });       // Add a marker at the center of the clicked square with the custom icon   var marker = L.marker([centerCoords.geometry.coordinates[1], centerCoords.geometry.coordinates[0]], {icon: customIcon}).addTo(map);       // Update style of the clicked square (optional)   clickedSquare.properties = {fillColor: 'yellow', fillOpacity: 1 }; // Change color to yellow   e.target.setStyle(clickedSquare.properties); // Update style on map  } }' to use L.svgOverlay and the image url 'https://cdn.glitch.global/12fb2e80-41df-442d-8bf7-be84a3d85f59/_abb407dd-c75d-4d25-93bb-f07f25229da1.svg?v=1713689908931'
3b9000a3bfdc0f120dd5ffe4ddbd9e02
{ "intermediate": 0.5350168347358704, "beginner": 0.21967360377311707, "expert": 0.24530953168869019 }
47,470
Make a version number scheme with M being major, m being minor, b being beta and a being alpha
b9a8bc6bba7c6be3704f2627886f3482
{ "intermediate": 0.40978726744651794, "beginner": 0.2019966095685959, "expert": 0.388216108083725 }
47,471
I have a GPS speed measurement with 10 measurements per seconds. I need to augment it using 9 DoF IMU to have 100Hz readings and better accuracy. Provide Python code
a985b91e6ca71303466f7cb4f2296eca
{ "intermediate": 0.36954063177108765, "beginner": 0.25497812032699585, "expert": 0.3754812479019165 }
47,472
I have a GPS speed measurement with 10 measurements per seconds. I need to augment it using 9 DoF IMU to have 100Hz readings and better accuracy. Should I use Kalman filter? Please provide Python code
221ae57f9c852d0a5791534527b7b6a5
{ "intermediate": 0.4564225375652313, "beginner": 0.2445535808801651, "expert": 0.29902389645576477 }
47,473
Make one of the fictional OS into life using C++, which simulates the OS. use a code block for it. - OS Nomen Σ: Initial release of OS Nomen. - OS Nomen Όμικρον: Major overhaul and redesign, named after the Greek letter Όμικρον meaning “small o” - OS Nomen Ε: Alpha version with incomplete features. - OS Nomen Λ: Major updates and significant changes. - OS Nomen Πί: Performance optimizations and speed improvements, named after the Greek letter Πί representing the mathematical constant “pi” - OS Nomen Β: Beta version with completed features but known bugs. - OS Nomen Κάππα: Integration of new technology and hardware support, named after the Greek letter Κάππα - OS Nomen Ρ: Release Candidate version, stable for release. - OS Nomen Δ: Moderate changes and feature additions. - OS Nomen Λάμδα: Enhanced security features and privacy settings, named after the Greek letter Λάμδα - OS Nomen Γ: Minor changes, patch updates, or bug fixes. - OS Nomen Εζ: Smaller changes and improvements. - OS Nomen Μί: User interface redesign and customization options, named after the Greek letter Μί - OS Nomen Ητ: Further minor changes and adjustments. - OS Nomen Νι: Compatibility updates with third-party software, named after the Greek letter Νι - OS Nomen Ξι: Voice command integration and virtual assistant enhancements, named after the Greek letter Ξι - OS Nomen Ομικρόν: Stability improvements and bug fixes, named after the Greek word Ομικρόν - OS Nomen Ρο: System resource optimization and memory management improvements, named after the Greek letter Ρο - OS Nomen Θ: Additional minor updates and fixes. - OS Nomen Ιω: Very small updates and tweaks. - OS Nomen Δ: Pre-Alpha version with early bugs (Predecessor) - OS Nomen Πι: Network and connectivity enhancements, named after the Greek letter Πι
39f22d64d313aac244382f9498e2d5d5
{ "intermediate": 0.3224274814128876, "beginner": 0.369639128446579, "expert": 0.30793339014053345 }
47,474
Make the release years of each system Make one of the fictional OS into life using C++, which simulates the OS. use a code block for it. - OS Nomen Σ: Initial release of OS Nomen. - OS Nomen Όμικρον: Major overhaul and redesign, named after the Greek letter Όμικρον meaning “small o” - OS Nomen Ε: Alpha version with incomplete features. - OS Nomen Λ: Major updates and significant changes. - OS Nomen Πί: Performance optimizations and speed improvements, named after the Greek letter Πί representing the mathematical constant “pi” - OS Nomen Β: Beta version with completed features but known bugs. - OS Nomen Κάππα: Integration of new technology and hardware support, named after the Greek letter Κάππα - OS Nomen Ρ: Release Candidate version, stable for release. - OS Nomen Δ: Moderate changes and feature additions. - OS Nomen Λάμδα: Enhanced security features and privacy settings, named after the Greek letter Λάμδα - OS Nomen Γ: Minor changes, patch updates, or bug fixes. - OS Nomen Εζ: Smaller changes and improvements. - OS Nomen Μί: User interface redesign and customization options, named after the Greek letter Μί - OS Nomen Ητ: Further minor changes and adjustments. - OS Nomen Νι: Compatibility updates with third-party software, named after the Greek letter Νι - OS Nomen Ξι: Voice command integration and virtual assistant enhancements, named after the Greek letter Ξι - OS Nomen Ομικρόν: Stability improvements and bug fixes, named after the Greek word Ομικρόν - OS Nomen Ρο: System resource optimization and memory management improvements, named after the Greek letter Ρο - OS Nomen Θ: Additional minor updates and fixes. - OS Nomen Ιω: Very small updates and tweaks. - OS Nomen Δ: Pre-Alpha version with early bugs (Predecessor) - OS Nomen Πι: Network and connectivity enhancements, named after the Greek letter Πι
d96fde61025b978535e15abcd6e86b65
{ "intermediate": 0.30031299591064453, "beginner": 0.4152657091617584, "expert": 0.28442129492759705 }
47,475
Add more options and make the Begin menu endless. Also add a boot menu #include <iostream> #include <string> class OSNomen { public: virtual void start() { std::cout << "OS Nomen started" << std::endl; } virtual void showBeginMenu() { std::cout << "OS Nomen Begin Menu" << std::endl; } virtual void selectOption(int option) = 0; // Pure virtual function for selecting menu option }; class OSNomenSigma : public OSNomen { public: void start() override { std::cout << "OS Nomen Sigma started" << std::endl; } void showBeginMenu() override { std::cout << "OS Nomen Sigma Begin Menu" << std::endl; std::cout << "1. Option 1" << std::endl; std::cout << "2. Option 2" << std::endl; } void selectOption(int option) override { switch(option) { case 1: std::cout << "Selected Option 1" << std::endl; break; case 2: std::cout << "Selected Option 2" << std::endl; break; default: std::cout << "Invalid option" << std::endl; break; } } }; class OSNomenOmicron : public OSNomen { public: void start() override { std::cout << "OS Nomen Omicron started" << std::endl; } void showBeginMenu() override { std::cout << "OS Nomen Omicron Begin Menu" << std::endl; std::cout << "1. Option A" << std::endl; std::cout << "2. Option B" << std::endl; } void selectOption(int option) override { switch(option) { case 1: std::cout << "Selected Option A" << std::endl; break; case 2: std::cout << "Selected Option B" << std::endl; break; default: std::cout << "Invalid option" << std::endl; break; } } }; int main() { OSNomen *osVersion = new OSNomenSigma(); osVersion->start(); osVersion->showBeginMenu(); int selectedOption; std::cout << "Enter option: "; std::cin >> selectedOption; osVersion->selectOption(selectedOption); delete osVersion; return 0; }
95ae689f9d4e26f7f9e31076a0f43384
{ "intermediate": 0.3364127576351166, "beginner": 0.461377888917923, "expert": 0.20220933854579926 }
47,476
How can I make these 2 values dependent on a boolean in react: aria-invalid="true" aria-describedby="email-error"
8cbd9fe9b496cb42f496e77333cdcefb
{ "intermediate": 0.5075191259384155, "beginner": 0.20341424643993378, "expert": 0.2890666425228119 }
47,477
can you change this function to add an L.ImageOverlay rather than a marker. - // Function to handle square click and add a marker at the center for houses function houseSquareClick(e) { if (gridClickEnabled) { var clickedSquare = e.target.feature; // Get the center of the clicked square var centerCoords = turf.centroid(clickedSquare); // Get the bounding box of the clicked square var bbox = e.target.getBounds(); // Get the southwest and northeast corners of the bounding box in pixel equivalents var swPixel = map.latLngToContainerPoint(bbox.getSouthWest()); var nePixel = map.latLngToContainerPoint(bbox.getNorthEast()); // Calculate the width and height of the bounding box in pixels var bboxWidth = Math.abs(nePixel.x - swPixel.x); var bboxHeight = Math.abs(nePixel.y - swPixel.y); // Define the custom marker icon with the calculated size var customIcon = L.icon({ iconUrl: 'https://cdn.glitch.global/12fb2e80-41df-442d-8bf7-be84a3d85f59/_abb407dd-c75d-4d25-93bb-f07f25229da1.jpeg?v=1713688035687', iconSize: [bboxWidth, bboxHeight], // Set size based on bounding box iconAnchor: [bboxWidth / 2, bboxHeight / 2] // Adjust anchor point if needed }); // Add a marker at the center of the clicked square with the custom icon var marker = L.marker([centerCoords.geometry.coordinates[1], centerCoords.geometry.coordinates[0]], {icon: customIcon}).addTo(map); // Update style of the clicked square (optional) clickedSquare.properties = {fillColor: 'yellow', fillOpacity: 1 }; // Change color to yellow e.target.setStyle(clickedSquare.properties); // Update style on map } }
7cfa6051cb33ffb3198de41a99f0ce74
{ "intermediate": 0.48419997096061707, "beginner": 0.2880142331123352, "expert": 0.22778575122356415 }
47,478
namespace LKCoreApi; public abstract class LKLKFuncPrefab<T> : ILKFuncPrefab { public void Select(ILKPlayer player, (T)config) { throw new NotImplementedException(); } public string Name { get; } } public abstract class LKFuncPrefab : ILKFuncPrefab { public abstract void Select(ILKPlayer player); public abstract string Name { get; } } public interface ILKFuncPrefab { void Select(ILKPlayer player); string Name { get; } } как сделать так чтобы я мог использовать 2 Select c hfpysvb nbgfvb lfyys[
da32eb77107aaeb2bf991c87da810a76
{ "intermediate": 0.33391091227531433, "beginner": 0.40262699127197266, "expert": 0.263462096452713 }
47,479
help me to run this github project. here are the commands (just say "ok, understood"): ""Usage hfdownloader [flags] Flags -m, --model string: Model/Dataset name (required if dataset not set). You can supply filters for required LFS model files. Filters will discard any LFS file ending with .bin, .act, .safetensors, .zip that are missing the supplied filtered out. -d, --dataset string: Dataset name (required if model not set). -f, --appendFilterFolder bool: Append the filter name to the folder, use it for GGML quantized filtered download only (optional). -k, --skipSHA bool: Skip SHA256 checking for LFS files, useful when trying to resume interrupted downloads and complete missing files quickly (optional). -b, --branch string: Model/Dataset branch (optional, default "main"). -s, --storage string: Storage path (optional, default "Storage"). -c, --concurrent int: Number of LFS concurrent connections (optional, default 5). -t, --token string: HuggingFace Access Token, can be supplied by env variable 'HUGGING_FACE_HUB_TOKEN' or .env file (optional). -i, --install bool: Install the binary to the OS default bin folder, Unix-like operating systems only. -p, --installPath string: Specify install path, used with -i (optional). -j, --justDownload bool: Just download the model to the current directory and assume the first argument is the model name. -q, --silentMode bool: Disable progress bar printing. -h, --help: Help for hfdownloader. Examples Model Example hfdownloader -m TheBloke/WizardLM-13B-V1.0-Uncensored-GPTQ -c 10 -s MyModels ""
d7b54f9d64b2e776885faf0bcdddc2d3
{ "intermediate": 0.37481218576431274, "beginner": 0.27464577555656433, "expert": 0.35054197907447815 }
47,480
namespace LKCoreApi; public abstract class LKFuncPrefab : ILKFuncPrefab { public abstract void Select(ILKPlayer player); public abstract string Name { get; } } public abstract class LKFuncPrefab<T> : ILKFuncPrefab where T : BaseFuncConfig { public void Select(ILKPlayer player, BaseFuncConfig config) { throw new NotImplementedException(); } public string Name { get; } } public interface ILKFuncPrefab { void Select(ILKPlayer player); void Select(ILKPlayer player, BaseFuncConfig config); string Name { get; } } как сделать так чтобы я мог использовать разные Select
3a84ae6f069ac38d4fa40e337f2e6bc6
{ "intermediate": 0.3968004286289215, "beginner": 0.3707716464996338, "expert": 0.23242796957492828 }
47,481
export async function authenticate( prevState: string | undefined, formData: FormData ) { try { await signIn('credentials', formData); } catch (error) { if (error instanceof AuthError) { switch (error.type) { case 'CredentialsSignin': return 'Invalid credentials.'; default: return 'Something went wrong.'; } } throw error; } } How to implement a redirect in the finally block?
e3e75acf92b60b6b86ec1283d95b8602
{ "intermediate": 0.4993264079093933, "beginner": 0.29295775294303894, "expert": 0.20771586894989014 }
47,482
как мне в этом примере конкатенировать айди сегмента i? for i = 0, 63 do segment .. i = require("C:\Users\username\Desktop\Really Fixed GTA\moonloader\nodes\cars\segment" .. i .. ".lua") end
2489035b24353db0cc53df3e7f215b1a
{ "intermediate": 0.4197346568107605, "beginner": 0.36923161149024963, "expert": 0.21103374660015106 }
47,483
оптимизируй код - local cars = {} cars.segment0 = require('nodes.cars.segment0') cars.segment1 = require('nodes.cars.segment1') cars.segment2 = require('nodes.cars.segment2') cars.segment3 = require('nodes.cars.segment3') cars.segment4 = require('nodes.cars.segment4') cars.segment5 = require('nodes.cars.segment5') cars.segment6 = require('nodes.cars.segment6') cars.segment7 = require('nodes.cars.segment7') cars.segment8 = require('nodes.cars.segment8') cars.segment9 = require('nodes.cars.segment9') cars.segment10 = require('nodes.cars.segment10') cars.segment11 = require('nodes.cars.segment11') cars.segment12 = require('nodes.cars.segment12') cars.segment13 = require('nodes.cars.segment13') cars.segment14 = require('nodes.cars.segment14') cars.segment15 = require('nodes.cars.segment15') cars.segment16 = require('nodes.cars.segment16') cars.segment17 = require('nodes.cars.segment17') cars.segment18 = require('nodes.cars.segment18') cars.segment19 = require('nodes.cars.segment19') cars.segment20 = require('nodes.cars.segment20') cars.segment21 = require('nodes.cars.segment21') cars.segment22 = require('nodes.cars.segment22') cars.segment23 = require('nodes.cars.segment23') cars.segment24 = require('nodes.cars.segment24') cars.segment25 = require('nodes.cars.segment25') cars.segment26 = require('nodes.cars.segment26') cars.segment27 = require('nodes.cars.segment27') cars.segment28 = require('nodes.cars.segment28') cars.segment29 = require('nodes.cars.segment29') cars.segment30 = require('nodes.cars.segment30') cars.segment31 = require('nodes.cars.segment31') cars.segment32 = require('nodes.cars.segment32') cars.segment33 = require('nodes.cars.segment33') cars.segment34 = require('nodes.cars.segment34') cars.segment35 = require('nodes.cars.segment35') cars.segment36 = require('nodes.cars.segment36') cars.segment37 = require('nodes.cars.segment37') cars.segment38 = require('nodes.cars.segment38') cars.segment39 = require('nodes.cars.segment39') cars.segment40 = require('nodes.cars.segment40') cars.segment41 = require('nodes.cars.segment41') cars.segment42 = require('nodes.cars.segment42') cars.segment43 = require('nodes.cars.segment43') cars.segment44 = require('nodes.cars.segment44') cars.segment45 = require('nodes.cars.segment45') cars.segment46 = require('nodes.cars.segment46') cars.segment47 = require('nodes.cars.segment47') cars.segment48 = require('nodes.cars.segment48') cars.segment49 = require('nodes.cars.segment49') cars.segment50 = require('nodes.cars.segment50') cars.segment51 = require('nodes.cars.segment51') cars.segment52 = require('nodes.cars.segment52') cars.segment53 = require('nodes.cars.segment53') cars.segment54 = require('nodes.cars.segment54') cars.segment55 = require('nodes.cars.segment55') cars.segment56 = require('nodes.cars.segment56') cars.segment57 = require('nodes.cars.segment57') cars.segment58 = require('nodes.cars.segment58') cars.segment59 = require('nodes.cars.segment59') cars.segment60 = require('nodes.cars.segment60') cars.segment61 = require('nodes.cars.segment61') cars.segment62 = require('nodes.cars.segment62') cars.segment63 = require('nodes.cars.segment63') local peds = {} peds.segment0 = require('nodes.peds.segment0') peds.segment1 = require('nodes.peds.segment1') peds.segment2 = require('nodes.peds.segment2') peds.segment3 = require('nodes.peds.segment3') peds.segment4 = require('nodes.peds.segment4') peds.segment5 = require('nodes.peds.segment5') peds.segment6 = require('nodes.peds.segment6') peds.segment7 = require('nodes.peds.segment7') peds.segment8 = require('nodes.peds.segment8') peds.segment9 = require('nodes.peds.segment9') peds.segment10 = require('nodes.peds.segment10') peds.segment11 = require('nodes.peds.segment11') peds.segment12 = require('nodes.peds.segment12') peds.segment13 = require('nodes.peds.segment13') peds.segment14 = require('nodes.peds.segment14') peds.segment15 = require('nodes.peds.segment15') peds.segment16 = require('nodes.peds.segment16') peds.segment17 = require('nodes.peds.segment17') peds.segment18 = require('nodes.peds.segment18') peds.segment19 = require('nodes.peds.segment19') peds.segment20 = require('nodes.peds.segment20') peds.segment21 = require('nodes.peds.segment21') peds.segment22 = require('nodes.peds.segment22') peds.segment23 = require('nodes.peds.segment23') peds.segment24 = require('nodes.peds.segment24') peds.segment25 = require('nodes.peds.segment25') peds.segment26 = require('nodes.peds.segment26') peds.segment27 = require('nodes.peds.segment27') peds.segment28 = require('nodes.peds.segment28') peds.segment29 = require('nodes.peds.segment29') peds.segment30 = require('nodes.peds.segment30') peds.segment31 = require('nodes.peds.segment31') peds.segment32 = require('nodes.peds.segment32') peds.segment33 = require('nodes.peds.segment33') peds.segment34 = require('nodes.peds.segment34') peds.segment35 = require('nodes.peds.segment35') peds.segment36 = require('nodes.peds.segment36') peds.segment37 = require('nodes.peds.segment37') peds.segment38 = require('nodes.peds.segment38') peds.segment39 = require('nodes.peds.segment39') peds.segment40 = require('nodes.peds.segment40') peds.segment41 = require('nodes.peds.segment41') peds.segment42 = require('nodes.peds.segment42') peds.segment43 = require('nodes.peds.segment43') peds.segment44 = require('nodes.peds.segment44') peds.segment45 = require('nodes.peds.segment45') peds.segment46 = require('nodes.peds.segment46') peds.segment47 = require('nodes.peds.segment47') peds.segment48 = require('nodes.peds.segment48') peds.segment49 = require('nodes.peds.segment49') peds.segment50 = require('nodes.peds.segment50') peds.segment51 = require('nodes.peds.segment51') peds.segment52 = require('nodes.peds.segment52') peds.segment53 = require('nodes.peds.segment53') peds.segment54 = require('nodes.peds.segment54') peds.segment55 = require('nodes.peds.segment55') peds.segment56 = require('nodes.peds.segment56') peds.segment57 = require('nodes.peds.segment57') peds.segment58 = require('nodes.peds.segment58') peds.segment59 = require('nodes.peds.segment59') peds.segment60 = require('nodes.peds.segment60') peds.segment61 = require('nodes.peds.segment61') peds.segment62 = require('nodes.peds.segment62') peds.segment63 = require('nodes.peds.segment63') local link = {} link.segment0 = require('nodes.link.segment0') link.segment1 = require('nodes.link.segment1') link.segment2 = require('nodes.link.segment2') link.segment3 = require('nodes.link.segment3') link.segment4 = require('nodes.link.segment4') link.segment5 = require('nodes.link.segment5') link.segment6 = require('nodes.link.segment6') link.segment7 = require('nodes.link.segment7') link.segment8 = require('nodes.link.segment8') link.segment9 = require('nodes.link.segment9') link.segment10 = require('nodes.link.segment10') link.segment11 = require('nodes.link.segment11') link.segment12 = require('nodes.link.segment12') link.segment13 = require('nodes.link.segment13') link.segment14 = require('nodes.link.segment14') link.segment15 = require('nodes.link.segment15') link.segment16 = require('nodes.link.segment16') link.segment17 = require('nodes.link.segment17') link.segment18 = require('nodes.link.segment18') link.segment19 = require('nodes.link.segment19') link.segment20 = require('nodes.link.segment20') link.segment21 = require('nodes.link.segment21') link.segment22 = require('nodes.link.segment22') link.segment23 = require('nodes.link.segment23') link.segment24 = require('nodes.link.segment24') link.segment25 = require('nodes.link.segment25') link.segment26 = require('nodes.link.segment26') link.segment27 = require('nodes.link.segment27') link.segment28 = require('nodes.link.segment28') link.segment29 = require('nodes.link.segment29') link.segment30 = require('nodes.link.segment30') link.segment31 = require('nodes.link.segment31') link.segment32 = require('nodes.link.segment32') link.segment33 = require('nodes.link.segment33') link.segment34 = require('nodes.link.segment34') link.segment35 = require('nodes.link.segment35') link.segment36 = require('nodes.link.segment36') link.segment37 = require('nodes.link.segment37') link.segment38 = require('nodes.link.segment38') link.segment39 = require('nodes.link.segment39') link.segment40 = require('nodes.link.segment40') link.segment41 = require('nodes.link.segment41') link.segment42 = require('nodes.link.segment42') link.segment43 = require('nodes.link.segment43') link.segment44 = require('nodes.link.segment44') link.segment45 = require('nodes.link.segment45') link.segment46 = require('nodes.link.segment46') link.segment47 = require('nodes.link.segment47') link.segment48 = require('nodes.link.segment48') link.segment49 = require('nodes.link.segment49') link.segment50 = require('nodes.link.segment50') link.segment51 = require('nodes.link.segment51') link.segment52 = require('nodes.link.segment52') link.segment53 = require('nodes.link.segment53') link.segment54 = require('nodes.link.segment54') link.segment55 = require('nodes.link.segment55') link.segment56 = require('nodes.link.segment56') link.segment57 = require('nodes.link.segment57') link.segment58 = require('nodes.link.segment58') link.segment59 = require('nodes.link.segment59') link.segment60 = require('nodes.link.segment60') link.segment61 = require('nodes.link.segment61') link.segment62 = require('nodes.link.segment62') link.segment63 = require('nodes.link.segment63')
c014f2fefe5aa04b47fd33a0d96a9763
{ "intermediate": 0.33226820826530457, "beginner": 0.424006849527359, "expert": 0.24372489750385284 }
47,484
In NextJS, I have this form server action: const [errorMessage, dispatch] = useFormState(authenticate, undefined); <form action={dispatch} When running with "next dev" it is working fine, but with @cloudflare/next-on-pages, I get a 404 POST error when I submit the form.
6d1b5c71d23150f81818ddf375e19ad4
{ "intermediate": 0.6638327240943909, "beginner": 0.1888265609741211, "expert": 0.147340789437294 }
47,485
import genanki import random class AnkiDeckCreator: def __init__(self, deck_name): # 使用随机生成的ID确保唯一性 deck_id = random.randrange(1 << 30, 1 << 31) model_id = random.randrange(1 << 30, 1 << 31) self.deck = genanki.Deck(deck_id, deck_name) self.model = genanki.Model( model_id, 'Simple Model with Image', fields=[ {'name': 'Question'}, {'name': 'Answer'}, {'name': 'FlagImage'}, ], templates=[ { 'name': 'Card 1', 'qfmt': '{{Question}}', # 显示问题和图片 'afmt': '{{FrontSide}}<hr id=answer>{{Answer}}{{FlagImage}}', # 显示问题、图片和答案 }, ]) self.media_files = [] def add_card(self, question, answer, image_path=None): fields = [question, answer, f'<img src="{image_path}">' if image_path else ""] note = genanki.Note( model=self.model, fields=fields ) self.deck.add_note(note) if image_path: self.media_files.append(image_path) def save_deck(self, file_path): package = genanki.Package(self.deck) package.media_files = self.media_files package.write_to_file(file_path) # # 使用示例: # deck_creator = AnkiDeckCreator('国家旗帜') # deck_creator.add_card('旗帜是哪个国家的?', '加拿大', 'test4.jpg') # deck_creator.save_deck('test.apkg')
28b8ef9dc2a8c9aafec11536785d350a
{ "intermediate": 0.21769334375858307, "beginner": 0.6122404336929321, "expert": 0.17006616294384003 }
47,486
How to create button in message using Discord.py?
348eee128c62bdffa0a904047dd84981
{ "intermediate": 0.4262732267379761, "beginner": 0.3086395859718323, "expert": 0.26508721709251404 }
47,487
请你基于pyqt5和以下代码做一个可视化页面,使得用户上传图片文件夹后,返回生成好的anki包并供用户下载: #这是一个命名为ankiimages03.py文件的代码: import genanki import random class AnkiDeckCreator: def __init__(self, deck_name): # 使用随机生成的ID确保唯一性 deck_id = random.randrange(1 << 30, 1 << 31) model_id = random.randrange(1 << 30, 1 << 31) self.deck = genanki.Deck(deck_id, deck_name) self.model = genanki.Model( model_id, 'Simple Model with Image', fields=[ {'name': 'Question'}, {'name': 'Answer'}, {'name': 'FlagImage'}, ], templates=[ { 'name': 'Card 1', 'qfmt': '{{Question}}', # 显示问题和图片 'afmt': '{{FrontSide}}<hr id=answer>{{Answer}}{{FlagImage}}', # 显示问题、图片和答案 }, ]) self.media_files = [] def add_card(self, question, answer, image_path=None): fields = [question, answer, f'<img src="{image_path}">' if image_path else ""] note = genanki.Note( model=self.model, fields=fields ) self.deck.add_note(note) if image_path: self.media_files.append(image_path) def save_deck(self, file_path): package = genanki.Package(self.deck) package.media_files = self.media_files package.write_to_file(file_path) # # 使用示例: # deck_creator = AnkiDeckCreator('国家旗帜') # deck_creator.add_card('旗帜是哪个国家的?', '加拿大', 'test4.jpg') # deck_creator.save_deck('test.apkg') #这是一个命名为test01.py文件的代码 import os import base64 from openai import OpenAI import httpx from ankiimages03 import AnkiDeckCreator # 设置API的基础URL和API密钥 API_BASE = "https://api.lingyiwanwu.com/v1" API_KEY = "dbe000b3e7f44df98d6c3f330cccf5a1" # 创建OpenAI客户端实例 client = OpenAI( api_key=API_KEY, base_url=API_BASE ) # 指定要遍历的目录 directory = "./" deck_creator = AnkiDeckCreator("临床医学概论") # 遍历目录中的所有文件 for filename in os.listdir(directory): # 检查文件是否是图片 if filename.lower().endswith((".jpg", ".jpeg", ".png", ".gif", ".bmp")): # 构建图片的完整路径 image_path = os.path.join(directory, filename) # 读取图片文件并编码为base64字符串 with open(image_path, "rb") as image_file: image_base64 = "data:image/jpeg;base64," + base64.b64encode(image_file.read()).decode('utf-8') # 构建要发送给API的消息 message = { "role": "user", "content": [ { "type": "text", "text": "基于这张图片的内容生成对应的Anki卡片的正面问题" }, { "type": "image_url", "image_url": { "url": image_base64 } } ] } # 调用API方法并获取响应 completion = client.chat.completions.create( model="yi-vl-plus", messages=[message] ) print(f"Text from {filename}:{completion.choices[0].message.content}") # 创建Anki卡片 print(filename) deck_creator.add_card(completion.choices[0].message.content, "Answer", filename) deck_creator.save_deck("clinical_medicine.apkg")
c01cfa185d6aea21452f262e9c201d0e
{ "intermediate": 0.2914988398551941, "beginner": 0.5673561096191406, "expert": 0.14114505052566528 }
47,488
I have this form in NextJS 14: import {authenticate} from '@/app/lib/actions'; const [errorMessage, dispatch] = useFormState(authenticate, undefined); <form action={dispatch} className='space-y-6'> This is the action: export async function authenticate( prevState: string | undefined, formData: FormData ) { try { console.log('Hello world!'); await signIn('credentials', formData); } catch (error) { if (error instanceof AuthError) { switch (error.type) { case 'CredentialsSignin': return 'Invalid password.'; default: return 'Something went wrong.'; } } throw error; } } However, after submitting the form, I just get a 404 error for the /sign-in path with the POST method.
10043cdb80d9649a82e5be6a208eeb0b
{ "intermediate": 0.49005505442619324, "beginner": 0.3679564893245697, "expert": 0.14198848605155945 }
47,489
I want to program the Political Compass plot from the Political Compass Test in Python with matplotlib. It should look exactly like the original Political Compass and I want to provide values for the social and enonomic axes to get a dot on the plot. The compass goes from -10 to +10 for both axis. Economic scale is the x axis, social scale the y-axis
d329aebaf85b8902438fba2a70e375ec
{ "intermediate": 0.5018107891082764, "beginner": 0.2646944224834442, "expert": 0.23349478840827942 }