prompt_id
int64
0
941
project
stringclasses
24 values
module
stringlengths
7
49
class
stringlengths
0
32
method
stringlengths
2
37
focal_method_txt
stringlengths
43
41.5k
focal_method_lines
listlengths
2
2
in_stack
bool
2 classes
globals
listlengths
0
16
type_context
stringlengths
79
41.9k
has_branch
bool
2 classes
total_branches
int64
0
3
845
typesystem
typesystem.json_schema
all_of_from_json_schema
def all_of_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field: all_of = [from_json_schema(item, definitions=definitions) for item in data["allOf"]] kwargs = {"all_of": all_of, "default": data.get("default", NO_DEFAULT)} return AllOf(**kwargs)
[ 351, 354 ]
false
[ "TYPE_CONSTRAINTS", "definitions", "JSONSchema" ]
import re import typing from typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf from typesystem.fields import ( NO_DEFAULT, Any, Array, Boolean, Choice, Const, Decimal, Field, Float, Integer, Number, Object, String, Union, ) from typesystem.sch...
false
0
846
typesystem
typesystem.json_schema
any_of_from_json_schema
def any_of_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field: any_of = [from_json_schema(item, definitions=definitions) for item in data["anyOf"]] kwargs = {"any_of": any_of, "default": data.get("default", NO_DEFAULT)} return Union(**kwargs)
[ 357, 360 ]
false
[ "TYPE_CONSTRAINTS", "definitions", "JSONSchema" ]
import re import typing from typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf from typesystem.fields import ( NO_DEFAULT, Any, Array, Boolean, Choice, Const, Decimal, Field, Float, Integer, Number, Object, String, Union, ) from typesystem.sch...
false
0
847
typesystem
typesystem.json_schema
one_of_from_json_schema
def one_of_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field: one_of = [from_json_schema(item, definitions=definitions) for item in data["oneOf"]] kwargs = {"one_of": one_of, "default": data.get("default", NO_DEFAULT)} return OneOf(**kwargs)
[ 363, 366 ]
false
[ "TYPE_CONSTRAINTS", "definitions", "JSONSchema" ]
import re import typing from typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf from typesystem.fields import ( NO_DEFAULT, Any, Array, Boolean, Choice, Const, Decimal, Field, Float, Integer, Number, Object, String, Union, ) from typesystem.sch...
false
0
848
typesystem
typesystem.json_schema
not_from_json_schema
def not_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field: negated = from_json_schema(data["not"], definitions=definitions) kwargs = {"negated": negated, "default": data.get("default", NO_DEFAULT)} return Not(**kwargs)
[ 369, 372 ]
false
[ "TYPE_CONSTRAINTS", "definitions", "JSONSchema" ]
import re import typing from typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf from typesystem.fields import ( NO_DEFAULT, Any, Array, Boolean, Choice, Const, Decimal, Field, Float, Integer, Number, Object, String, Union, ) from typesystem.sch...
false
0
849
typesystem
typesystem.json_schema
if_then_else_from_json_schema
def if_then_else_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field: if_clause = from_json_schema(data["if"], definitions=definitions) then_clause = ( from_json_schema(data["then"], definitions=definitions) if "then" in data else None ) else_clause = ( ...
[ 375, 393 ]
false
[ "TYPE_CONSTRAINTS", "definitions", "JSONSchema" ]
import re import typing from typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf from typesystem.fields import ( NO_DEFAULT, Any, Array, Boolean, Choice, Const, Decimal, Field, Float, Integer, Number, Object, String, Union, ) from typesystem.sch...
false
0
850
typesystem
typesystem.json_schema
to_json_schema
def to_json_schema( arg: typing.Union[Field, typing.Type[Schema]], _definitions: dict = None ) -> typing.Union[bool, dict]: if isinstance(arg, Any): return True elif isinstance(arg, NeverMatch): return False data: dict = {} is_root = _definitions is None definitions = {} if _de...
[ 396, 561 ]
false
[ "TYPE_CONSTRAINTS", "definitions", "JSONSchema" ]
import re import typing from typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf from typesystem.fields import ( NO_DEFAULT, Any, Array, Boolean, Choice, Const, Decimal, Field, Float, Integer, Number, Object, String, Union, ) from typesystem.sch...
true
2
851
typesystem
typesystem.schemas
set_definitions
def set_definitions(field: Field, definitions: SchemaDefinitions) -> None: """ Recursively set the definitions that string-referenced `Reference` fields should use. """ if isinstance(field, Reference) and field.definitions is None: field.definitions = definitions elif isinstance(field, A...
[ 31, 47 ]
false
[]
import typing from abc import ABCMeta from collections.abc import Mapping, MutableMapping from typesystem.base import ValidationError, ValidationResult from typesystem.fields import Array, Field, Object class SchemaDefinitions(MutableMapping): def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:...
true
2
852
typesystem
typesystem.schemas
SchemaDefinitions
__setitem__
def __setitem__(self, key: typing.Any, value: typing.Any) -> None: assert ( key not in self._definitions ), r"Definition for {key!r} has already been set." self._definitions[key] = value
[ 21, 25 ]
false
[]
import typing from abc import ABCMeta from collections.abc import Mapping, MutableMapping from typesystem.base import ValidationError, ValidationResult from typesystem.fields import Array, Field, Object class SchemaDefinitions(MutableMapping): def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:...
false
0
853
typesystem
typesystem.schemas
SchemaMetaclass
__new__
def __new__( cls: type, name: str, bases: typing.Sequence[type], attrs: dict, definitions: SchemaDefinitions = None, ) -> type: fields: typing.Dict[str, Field] = {} for key, value in list(attrs.items()): if isinstance(value, Field): ...
[ 51, 88 ]
false
[]
import typing from abc import ABCMeta from collections.abc import Mapping, MutableMapping from typesystem.base import ValidationError, ValidationResult from typesystem.fields import Array, Field, Object class SchemaDefinitions(MutableMapping): def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:...
true
2
854
typesystem
typesystem.schemas
Schema
__init__
def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: if args: assert len(args) == 1 assert not kwargs item = args[0] if isinstance(item, dict): for key in self.fields.keys(): if key in item: ...
[ 94, 130 ]
false
[]
import typing from abc import ABCMeta from collections.abc import Mapping, MutableMapping from typesystem.base import ValidationError, ValidationResult from typesystem.fields import Array, Field, Object class Schema(Mapping, metaclass=SchemaMetaclass): fields: typing.Dict[str, Field] = {} def __init__(self...
true
2
855
typesystem
typesystem.schemas
Schema
__eq__
def __eq__(self, other: typing.Any) -> bool: if not isinstance(other, self.__class__): return False for key in self.fields.keys(): if getattr(self, key) != getattr(other, key): return False return True
[ 165, 172 ]
false
[]
import typing from abc import ABCMeta from collections.abc import Mapping, MutableMapping from typesystem.base import ValidationError, ValidationResult from typesystem.fields import Array, Field, Object class Schema(Mapping, metaclass=SchemaMetaclass): fields: typing.Dict[str, Field] = {} def __init__(self...
true
2
856
typesystem
typesystem.schemas
Schema
__getitem__
def __getitem__(self, key: typing.Any) -> typing.Any: try: field = self.fields[key] value = getattr(self, key) except (KeyError, AttributeError): raise KeyError(key) from None else: return field.serialize(value)
[ 174, 181 ]
false
[]
import typing from abc import ABCMeta from collections.abc import Mapping, MutableMapping from typesystem.base import ValidationError, ValidationResult from typesystem.fields import Array, Field, Object class Schema(Mapping, metaclass=SchemaMetaclass): fields: typing.Dict[str, Field] = {} def __init__(self...
false
0
857
typesystem
typesystem.schemas
Schema
__iter__
def __iter__(self) -> typing.Iterator[str]: for key in self.fields: if hasattr(self, key): yield key
[ 183, 186 ]
false
[]
import typing from abc import ABCMeta from collections.abc import Mapping, MutableMapping from typesystem.base import ValidationError, ValidationResult from typesystem.fields import Array, Field, Object class Schema(Mapping, metaclass=SchemaMetaclass): fields: typing.Dict[str, Field] = {} def __init__(self...
true
2
858
typesystem
typesystem.schemas
Schema
__len__
def __len__(self) -> int: return len([key for key in self.fields if hasattr(self, key)])
[ 188, 189 ]
false
[]
import typing from abc import ABCMeta from collections.abc import Mapping, MutableMapping from typesystem.base import ValidationError, ValidationResult from typesystem.fields import Array, Field, Object class Schema(Mapping, metaclass=SchemaMetaclass): fields: typing.Dict[str, Field] = {} def __init__(self...
false
0
859
typesystem
typesystem.schemas
Schema
__repr__
def __repr__(self) -> str: class_name = self.__class__.__name__ arguments = { key: getattr(self, key) for key in self.fields.keys() if hasattr(self, key) } argument_str = ", ".join( [f"{key}={value!r}" for key, value in arguments.items()] ) spa...
[ 191, 200 ]
false
[]
import typing from abc import ABCMeta from collections.abc import Mapping, MutableMapping from typesystem.base import ValidationError, ValidationResult from typesystem.fields import Array, Field, Object class Schema(Mapping, metaclass=SchemaMetaclass): fields: typing.Dict[str, Field] = {} def __init__(self...
false
0
860
typesystem
typesystem.schemas
Reference
__init__
def __init__( self, to: typing.Union[str, typing.Type[Schema]], definitions: typing.Mapping = None, **kwargs: typing.Any, ) -> None: super().__init__(**kwargs) self.to = to self.definitions = definitions if isinstance(to, str): self._ta...
[ 206, 219 ]
false
[]
import typing from abc import ABCMeta from collections.abc import Mapping, MutableMapping from typesystem.base import ValidationError, ValidationResult from typesystem.fields import Array, Field, Object class Schema(Mapping, metaclass=SchemaMetaclass): fields: typing.Dict[str, Field] = {} def __init__(self...
true
2
861
typesystem
typesystem.schemas
Reference
validate
def validate(self, value: typing.Any, *, strict: bool = False) -> typing.Any: if value is None and self.allow_null: return None elif value is None: raise self.validation_error("null") return self.target.validate(value, strict=strict)
[ 236, 241 ]
false
[]
import typing from abc import ABCMeta from collections.abc import Mapping, MutableMapping from typesystem.base import ValidationError, ValidationResult from typesystem.fields import Array, Field, Object class Reference(Field): errors = {"null": "May not be null."} def __init__( self, to: ty...
true
2
862
typesystem
typesystem.schemas
Reference
serialize
def serialize(self, obj: typing.Any) -> typing.Any: if obj is None: return None return dict(obj)
[ 243, 246 ]
false
[]
import typing from abc import ABCMeta from collections.abc import Mapping, MutableMapping from typesystem.base import ValidationError, ValidationResult from typesystem.fields import Array, Field, Object class Reference(Field): errors = {"null": "May not be null."} def __init__( self, to: ty...
true
2
863
typesystem
typesystem.tokenize.positional_validation
validate_with_positions
def validate_with_positions( *, token: Token, validator: typing.Union[Field, typing.Type[Schema]] ) -> typing.Any: try: return validator.validate(token.value) except ValidationError as error: messages = [] for message in error.messages(): if message.code == "required": ...
[ 8, 35 ]
false
[]
import typing from typesystem.base import Message, ValidationError from typesystem.fields import Field from typesystem.schemas import Schema from typesystem.tokenize.tokens import Token def validate_with_positions( *, token: Token, validator: typing.Union[Field, typing.Type[Schema]] ) -> typing.Any: try: ...
true
2
864
typesystem
typesystem.tokenize.tokenize_json
tokenize_json
def tokenize_json(content: typing.Union[str, bytes]) -> Token: if isinstance(content, bytes): content = content.decode("utf-8", "ignore") if not content.strip(): # Handle the empty string case explicitly for clear error messaging. position = Position(column_no=1, line_no=1, char_index=0...
[ 164, 179 ]
false
[ "FLAGS", "WHITESPACE", "WHITESPACE_STR", "NUMBER_RE" ]
import re import typing from json.decoder import JSONDecodeError, JSONDecoder, scanstring from typesystem.base import Message, ParseError, Position, ValidationError from typesystem.fields import Field from typesystem.schemas import Schema from typesystem.tokenize.positional_validation import validate_with_positions fro...
true
2
865
typesystem
typesystem.tokenize.tokenize_json
validate_json
def validate_json( content: typing.Union[str, bytes], validator: typing.Union[Field, typing.Type[Schema]], ) -> typing.Any: """ Parse and validate a JSON string, returning positionally marked error messages on parse or validation failures. content - A JSON string or bytestring. validator - ...
[ 182, 196 ]
false
[ "FLAGS", "WHITESPACE", "WHITESPACE_STR", "NUMBER_RE" ]
import re import typing from json.decoder import JSONDecodeError, JSONDecoder, scanstring from typesystem.base import Message, ParseError, Position, ValidationError from typesystem.fields import Field from typesystem.schemas import Schema from typesystem.tokenize.positional_validation import validate_with_positions fro...
false
0
866
typesystem
typesystem.tokenize.tokenize_yaml
tokenize_yaml
def tokenize_yaml(content: typing.Union[str, bytes]) -> Token: assert yaml is not None, "'pyyaml' must be installed." if isinstance(content, bytes): str_content = content.decode("utf-8", "ignore") else: str_content = content if not str_content.strip(): # Handle the empty string...
[ 24, 108 ]
false
[]
import typing from typesystem.base import Message, ParseError, Position, ValidationError from typesystem.fields import Field from typesystem.schemas import Schema from typesystem.tokenize.positional_validation import validate_with_positions from typesystem.tokenize.tokens import DictToken, ListToken, ScalarToken, Token...
true
2
867
typesystem
typesystem.tokenize.tokenize_yaml
validate_yaml
def validate_yaml( content: typing.Union[str, bytes], validator: typing.Union[Field, typing.Type[Schema]], ) -> typing.Any: """ Parse and validate a YAML string, returning positionally marked error messages on parse or validation failures. content - A YAML string or bytestring. validator - ...
[ 111, 127 ]
false
[]
import typing from typesystem.base import Message, ParseError, Position, ValidationError from typesystem.fields import Field from typesystem.schemas import Schema from typesystem.tokenize.positional_validation import validate_with_positions from typesystem.tokenize.tokens import DictToken, ListToken, ScalarToken, Token...
false
0
868
typesystem
typesystem.tokenize.tokens
Token
__init__
def __init__( self, value: typing.Any, start_index: int, end_index: int, content: str = "" ) -> None: self._value = value self._start_index = start_index self._end_index = end_index self._content = content
[ 6, 12 ]
false
[]
import typing from typesystem.base import Position class Token: def __init__( self, value: typing.Any, start_index: int, end_index: int, content: str = "" ) -> None: self._value = value self._start_index = start_index self._end_index = end_index self._content = conten...
false
0
869
typesystem
typesystem.tokenize.tokens
Token
lookup
def lookup(self, index: list) -> "Token": """ Given an index, lookup a child token within this structure. """ token = self for key in index: token = token._get_child_token(key) return token
[ 39, 46 ]
false
[]
import typing from typesystem.base import Position class Token: def __init__( self, value: typing.Any, start_index: int, end_index: int, content: str = "" ) -> None: self._value = value self._start_index = start_index self._end_index = end_index self._content = conten...
true
2
870
typesystem
typesystem.tokenize.tokens
Token
lookup_key
def lookup_key(self, index: list) -> "Token": """ Given an index, lookup a token for a dictionary key within this structure. """ token = self.lookup(index[:-1]) return token._get_key_token(index[-1])
[ 48, 53 ]
false
[]
import typing from typesystem.base import Position class Token: def __init__( self, value: typing.Any, start_index: int, end_index: int, content: str = "" ) -> None: self._value = value self._start_index = start_index self._end_index = end_index self._content = conten...
false
0
871
typesystem
typesystem.tokenize.tokens
Token
__repr__
def __repr__(self) -> str: return "%s(%s)" % (self.__class__.__name__, repr(self.string))
[ 62, 63 ]
false
[]
import typing from typesystem.base import Position class Token: def __init__( self, value: typing.Any, start_index: int, end_index: int, content: str = "" ) -> None: self._value = value self._start_index = start_index self._end_index = end_index self._content = conten...
false
0
872
typesystem
typesystem.tokenize.tokens
Token
__eq__
def __eq__(self, other: typing.Any) -> bool: return isinstance(other, Token) and ( self._get_value() == other._get_value() and self._start_index == other._start_index and self._end_index == other._end_index )
[ 65, 66 ]
false
[]
import typing from typesystem.base import Position class Token: def __init__( self, value: typing.Any, start_index: int, end_index: int, content: str = "" ) -> None: self._value = value self._start_index = start_index self._end_index = end_index self._content = conten...
false
0
873
typesystem
typesystem.tokenize.tokens
ScalarToken
__hash__
def __hash__(self) -> typing.Any: return hash(self._value)
[ 74, 75 ]
false
[]
import typing from typesystem.base import Position class ScalarToken(Token): def __hash__(self) -> typing.Any: return hash(self._value)
false
0
874
typesystem
typesystem.tokenize.tokens
DictToken
__init__
def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: super().__init__(*args, **kwargs) self._child_keys = {k._value: k for k in self._value.keys()} self._child_tokens = {k._value: v for k, v in self._value.items()}
[ 82, 85 ]
false
[]
import typing from typesystem.base import Position class DictToken(Token): def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: super().__init__(*args, **kwargs) self._child_keys = {k._value: k for k in self._value.keys()} self._child_tokens = {k._value: v for k, v in sel...
false
0
875
youtube_dl
youtube_dl.aes
aes_ctr_decrypt
def aes_ctr_decrypt(data, key, counter): """ Decrypt with aes in counter mode @param {int[]} data cipher @param {int[]} key 16/24/32-Byte cipher key @param {instance} counter Instance whose next_value function (@returns {int[]} 16-Byte block) returns ...
[ 10, 33 ]
false
[ "BLOCK_SIZE_BYTES", "RCON", "SBOX", "SBOX_INV", "MIX_COLUMN_MATRIX", "MIX_COLUMN_MATRIX_INV", "RIJNDAEL_EXP_TABLE", "RIJNDAEL_LOG_TABLE", "__all__" ]
from math import ceil from .compat import compat_b64decode from .utils import bytes_to_intlist, intlist_to_bytes BLOCK_SIZE_BYTES = 16 RCON = (0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36) SBOX = (0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, ...
true
2
876
youtube_dl
youtube_dl.aes
aes_cbc_decrypt
def aes_cbc_decrypt(data, key, iv): """ Decrypt with aes in CBC mode @param {int[]} data cipher @param {int[]} key 16/24/32-Byte cipher key @param {int[]} iv 16-Byte IV @returns {int[]} decrypted data """ expanded_key = key_expansion(key) block_coun...
[ 36, 59 ]
false
[ "BLOCK_SIZE_BYTES", "RCON", "SBOX", "SBOX_INV", "MIX_COLUMN_MATRIX", "MIX_COLUMN_MATRIX_INV", "RIJNDAEL_EXP_TABLE", "RIJNDAEL_LOG_TABLE", "__all__" ]
from math import ceil from .compat import compat_b64decode from .utils import bytes_to_intlist, intlist_to_bytes BLOCK_SIZE_BYTES = 16 RCON = (0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36) SBOX = (0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, ...
true
2
877
youtube_dl
youtube_dl.aes
aes_cbc_encrypt
def aes_cbc_encrypt(data, key, iv): """ Encrypt with aes in CBC mode. Using PKCS#7 padding @param {int[]} data cleartext @param {int[]} key 16/24/32-Byte cipher key @param {int[]} iv 16-Byte IV @returns {int[]} encrypted data """ expanded_key = key_expa...
[ 62, 87 ]
false
[ "BLOCK_SIZE_BYTES", "RCON", "SBOX", "SBOX_INV", "MIX_COLUMN_MATRIX", "MIX_COLUMN_MATRIX_INV", "RIJNDAEL_EXP_TABLE", "RIJNDAEL_LOG_TABLE", "__all__" ]
from math import ceil from .compat import compat_b64decode from .utils import bytes_to_intlist, intlist_to_bytes BLOCK_SIZE_BYTES = 16 RCON = (0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36) SBOX = (0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, ...
true
2
878
youtube_dl
youtube_dl.aes
key_expansion
def key_expansion(data): """ Generate key schedule @param {int[]} data 16/24/32-Byte cipher key @returns {int[]} 176/208/240-Byte expanded key """ data = data[:] # copy rcon_iteration = 1 key_size_bytes = len(data) expanded_key_size_bytes = (key_size_bytes // 4 + 7) * BLOCK_SI...
[ 90, 122 ]
false
[ "BLOCK_SIZE_BYTES", "RCON", "SBOX", "SBOX_INV", "MIX_COLUMN_MATRIX", "MIX_COLUMN_MATRIX_INV", "RIJNDAEL_EXP_TABLE", "RIJNDAEL_LOG_TABLE", "__all__" ]
from math import ceil from .compat import compat_b64decode from .utils import bytes_to_intlist, intlist_to_bytes BLOCK_SIZE_BYTES = 16 RCON = (0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36) SBOX = (0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, ...
true
2
879
youtube_dl
youtube_dl.aes
aes_encrypt
def aes_encrypt(data, expanded_key): """ Encrypt one block with aes @param {int[]} data 16-Byte state @param {int[]} expanded_key 176/208/240-Byte expanded key @returns {int[]} 16-Byte cipher """ rounds = len(expanded_key) // BLOCK_SIZE_BYTES - 1 data = xor(data, ...
[ 125, 143 ]
false
[ "BLOCK_SIZE_BYTES", "RCON", "SBOX", "SBOX_INV", "MIX_COLUMN_MATRIX", "MIX_COLUMN_MATRIX_INV", "RIJNDAEL_EXP_TABLE", "RIJNDAEL_LOG_TABLE", "__all__" ]
from math import ceil from .compat import compat_b64decode from .utils import bytes_to_intlist, intlist_to_bytes BLOCK_SIZE_BYTES = 16 RCON = (0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36) SBOX = (0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, ...
true
2
880
youtube_dl
youtube_dl.aes
aes_decrypt
def aes_decrypt(data, expanded_key): """ Decrypt one block with aes @param {int[]} data 16-Byte cipher @param {int[]} expanded_key 176/208/240-Byte expanded key @returns {int[]} 16-Byte state """ rounds = len(expanded_key) // BLOCK_SIZE_BYTES - 1 for i in range(ro...
[ 146, 164 ]
false
[ "BLOCK_SIZE_BYTES", "RCON", "SBOX", "SBOX_INV", "MIX_COLUMN_MATRIX", "MIX_COLUMN_MATRIX_INV", "RIJNDAEL_EXP_TABLE", "RIJNDAEL_LOG_TABLE", "__all__" ]
from math import ceil from .compat import compat_b64decode from .utils import bytes_to_intlist, intlist_to_bytes BLOCK_SIZE_BYTES = 16 RCON = (0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36) SBOX = (0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, ...
true
2
881
youtube_dl
youtube_dl.aes
aes_decrypt_text
def aes_decrypt_text(data, password, key_size_bytes): """ Decrypt text - The first 8 Bytes of decoded 'data' are the 8 high Bytes of the counter - The cipher key is retrieved by encrypting the first 16 Byte of 'password' with the first 'key_size_bytes' Bytes from 'password' (if necessary filled wi...
[ 167, 202 ]
false
[ "BLOCK_SIZE_BYTES", "RCON", "SBOX", "SBOX_INV", "MIX_COLUMN_MATRIX", "MIX_COLUMN_MATRIX_INV", "RIJNDAEL_EXP_TABLE", "RIJNDAEL_LOG_TABLE", "__all__" ]
from math import ceil from .compat import compat_b64decode from .utils import bytes_to_intlist, intlist_to_bytes BLOCK_SIZE_BYTES = 16 RCON = (0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36) SBOX = (0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, ...
false
0
882
youtube_dl
youtube_dl.aes
key_schedule_core
def key_schedule_core(data, rcon_iteration): data = rotate(data) data = sub_bytes(data) data[0] = data[0] ^ RCON[rcon_iteration] return data
[ 292, 297 ]
false
[ "BLOCK_SIZE_BYTES", "RCON", "SBOX", "SBOX_INV", "MIX_COLUMN_MATRIX", "MIX_COLUMN_MATRIX_INV", "RIJNDAEL_EXP_TABLE", "RIJNDAEL_LOG_TABLE", "__all__" ]
from math import ceil from .compat import compat_b64decode from .utils import bytes_to_intlist, intlist_to_bytes BLOCK_SIZE_BYTES = 16 RCON = (0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36) SBOX = (0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, ...
false
0
883
youtube_dl
youtube_dl.aes
rijndael_mul
def rijndael_mul(a, b): if(a == 0 or b == 0): return 0 return RIJNDAEL_EXP_TABLE[(RIJNDAEL_LOG_TABLE[a] + RIJNDAEL_LOG_TABLE[b]) % 0xFF]
[ 304, 307 ]
false
[ "BLOCK_SIZE_BYTES", "RCON", "SBOX", "SBOX_INV", "MIX_COLUMN_MATRIX", "MIX_COLUMN_MATRIX_INV", "RIJNDAEL_EXP_TABLE", "RIJNDAEL_LOG_TABLE", "__all__" ]
from math import ceil from .compat import compat_b64decode from .utils import bytes_to_intlist, intlist_to_bytes BLOCK_SIZE_BYTES = 16 RCON = (0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36) SBOX = (0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, ...
true
2
884
youtube_dl
youtube_dl.aes
inc
def inc(data): data = data[:] # copy for i in range(len(data) - 1, -1, -1): if data[i] == 255: data[i] = 0 else: data[i] = data[i] + 1 break return data
[ 349, 357 ]
false
[ "BLOCK_SIZE_BYTES", "RCON", "SBOX", "SBOX_INV", "MIX_COLUMN_MATRIX", "MIX_COLUMN_MATRIX_INV", "RIJNDAEL_EXP_TABLE", "RIJNDAEL_LOG_TABLE", "__all__" ]
from math import ceil from .compat import compat_b64decode from .utils import bytes_to_intlist, intlist_to_bytes BLOCK_SIZE_BYTES = 16 RCON = (0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36) SBOX = (0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, ...
true
2
885
youtube_dl
youtube_dl.downloader.common
FileDownloader
format_seconds
@staticmethod def format_seconds(seconds): (mins, secs) = divmod(seconds, 60) (hours, mins) = divmod(mins, 60) if hours > 99: return '--:--:--' if hours == 0: return '%02d:%02d' % (mins, secs) else: return '%02d:%02d:%02d' % (hours, min...
[ 68, 76 ]
false
[]
import os import re import sys import time import random from ..compat import compat_os_name from ..utils import ( decodeArgument, encodeFilename, error_to_compat_str, format_bytes, shell_quote, timeconvert, ) class FileDownloader(object): _TEST_FILE_SIZE = 10241 params = None ...
true
2
886
youtube_dl
youtube_dl.downloader.common
FileDownloader
calc_percent
@staticmethod def calc_percent(byte_counter, data_len): if data_len is None: return None return float(byte_counter) / float(data_len) * 100.0
[ 79, 82 ]
false
[]
import os import re import sys import time import random from ..compat import compat_os_name from ..utils import ( decodeArgument, encodeFilename, error_to_compat_str, format_bytes, shell_quote, timeconvert, ) class FileDownloader(object): _TEST_FILE_SIZE = 10241 params = None ...
true
2
887
youtube_dl
youtube_dl.downloader.common
FileDownloader
format_percent
@staticmethod def format_percent(percent): if percent is None: return '---.-%' return '%6s' % ('%3.1f%%' % percent)
[ 85, 88 ]
false
[]
import os import re import sys import time import random from ..compat import compat_os_name from ..utils import ( decodeArgument, encodeFilename, error_to_compat_str, format_bytes, shell_quote, timeconvert, ) class FileDownloader(object): _TEST_FILE_SIZE = 10241 params = None ...
true
2
888
youtube_dl
youtube_dl.downloader.common
FileDownloader
calc_eta
@staticmethod def calc_eta(start, now, total, current): if total is None: return None if now is None: now = time.time() dif = now - start if current == 0 or dif < 0.001: # One millisecond return None rate = float(current) / dif ...
[ 91, 100 ]
false
[]
import os import re import sys import time import random from ..compat import compat_os_name from ..utils import ( decodeArgument, encodeFilename, error_to_compat_str, format_bytes, shell_quote, timeconvert, ) class FileDownloader(object): _TEST_FILE_SIZE = 10241 params = None ...
true
2
889
youtube_dl
youtube_dl.downloader.common
FileDownloader
calc_speed
@staticmethod def calc_speed(start, now, bytes): dif = now - start if bytes == 0 or dif < 0.001: # One millisecond return None return float(bytes) / dif
[ 109, 113 ]
false
[]
import os import re import sys import time import random from ..compat import compat_os_name from ..utils import ( decodeArgument, encodeFilename, error_to_compat_str, format_bytes, shell_quote, timeconvert, ) class FileDownloader(object): _TEST_FILE_SIZE = 10241 params = None ...
true
2
890
youtube_dl
youtube_dl.downloader.common
FileDownloader
format_retries
@staticmethod def format_retries(retries): return 'inf' if retries == float('inf') else '%.0f' % retries
[ 122, 123 ]
false
[]
import os import re import sys import time import random from ..compat import compat_os_name from ..utils import ( decodeArgument, encodeFilename, error_to_compat_str, format_bytes, shell_quote, timeconvert, ) class FileDownloader(object): _TEST_FILE_SIZE = 10241 params = None ...
false
0
891
youtube_dl
youtube_dl.downloader.common
FileDownloader
best_block_size
@staticmethod def best_block_size(elapsed_time, bytes): new_min = max(bytes / 2.0, 1.0) new_max = min(max(bytes * 2.0, 1.0), 4194304) # Do not surpass 4 MB if elapsed_time < 0.001: return int(new_max) rate = bytes / elapsed_time if rate > new_max: ...
[ 126, 136 ]
false
[]
import os import re import sys import time import random from ..compat import compat_os_name from ..utils import ( decodeArgument, encodeFilename, error_to_compat_str, format_bytes, shell_quote, timeconvert, ) class FileDownloader(object): _TEST_FILE_SIZE = 10241 params = None ...
true
2
892
youtube_dl
youtube_dl.downloader.common
FileDownloader
parse_bytes
@staticmethod def parse_bytes(bytestr): """Parse a string indicating a byte quantity into an integer.""" matchobj = re.match(r'(?i)^(\d+(?:\.\d+)?)([kMGTPEZY]?)$', bytestr) if matchobj is None: return None number = float(matchobj.group(1)) multiplier = 1024.0 ...
[ 139, 146 ]
false
[]
import os import re import sys import time import random from ..compat import compat_os_name from ..utils import ( decodeArgument, encodeFilename, error_to_compat_str, format_bytes, shell_quote, timeconvert, ) class FileDownloader(object): _TEST_FILE_SIZE = 10241 params = None ...
true
2
893
youtube_dl
youtube_dl.downloader.common
FileDownloader
slow_down
def slow_down(self, start_time, now, byte_counter): """Sleep if the download speed is over the rate limit.""" rate_limit = self.params.get('ratelimit') if rate_limit is None or byte_counter == 0: return if now is None: now = time.time() elapsed = now -...
[ 166, 180 ]
false
[]
import os import re import sys import time import random from ..compat import compat_os_name from ..utils import ( decodeArgument, encodeFilename, error_to_compat_str, format_bytes, shell_quote, timeconvert, ) class FileDownloader(object): _TEST_FILE_SIZE = 10241 params = None ...
true
2
894
youtube_dl
youtube_dl.downloader.common
FileDownloader
temp_name
def temp_name(self, filename): """Returns a temporary filename for the given filename.""" if self.params.get('nopart', False) or filename == '-' or \ (os.path.exists(encodeFilename(filename)) and not os.path.isfile(encodeFilename(filename))): return filename retur...
[ 182, 187 ]
false
[]
import os import re import sys import time import random from ..compat import compat_os_name from ..utils import ( decodeArgument, encodeFilename, error_to_compat_str, format_bytes, shell_quote, timeconvert, ) class FileDownloader(object): _TEST_FILE_SIZE = 10241 params = None ...
true
2
895
youtube_dl
youtube_dl.downloader.common
FileDownloader
undo_temp_name
def undo_temp_name(self, filename): if filename.endswith('.part'): return filename[:-len('.part')] return filename
[ 189, 192 ]
false
[]
import os import re import sys import time import random from ..compat import compat_os_name from ..utils import ( decodeArgument, encodeFilename, error_to_compat_str, format_bytes, shell_quote, timeconvert, ) class FileDownloader(object): _TEST_FILE_SIZE = 10241 params = None ...
true
2
896
youtube_dl
youtube_dl.downloader.common
FileDownloader
try_rename
def try_rename(self, old_filename, new_filename): try: if old_filename == new_filename: return os.rename(encodeFilename(old_filename), encodeFilename(new_filename)) except (IOError, OSError) as err: self.report_error('unable to rename file: %s' % e...
[ 197, 203 ]
false
[]
import os import re import sys import time import random from ..compat import compat_os_name from ..utils import ( decodeArgument, encodeFilename, error_to_compat_str, format_bytes, shell_quote, timeconvert, ) class FileDownloader(object): _TEST_FILE_SIZE = 10241 params = None ...
true
2
897
youtube_dl
youtube_dl.downloader.common
FileDownloader
try_utime
def try_utime(self, filename, last_modified_hdr): """Try to set the last-modified time of the given file.""" if last_modified_hdr is None: return if not os.path.isfile(encodeFilename(filename)): return timestr = last_modified_hdr if timestr is None: ...
[ 205, 224 ]
false
[]
import os import re import sys import time import random from ..compat import compat_os_name from ..utils import ( decodeArgument, encodeFilename, error_to_compat_str, format_bytes, shell_quote, timeconvert, ) class FileDownloader(object): _TEST_FILE_SIZE = 10241 params = None ...
true
2
898
youtube_dl
youtube_dl.downloader.common
FileDownloader
report_progress
def report_progress(self, s): if s['status'] == 'finished': if self.params.get('noprogress', False): self.to_screen('[download] Download completed') else: msg_template = '100%%' if s.get('total_bytes') is not None: s...
[ 247, 305 ]
false
[]
import os import re import sys import time import random from ..compat import compat_os_name from ..utils import ( decodeArgument, encodeFilename, error_to_compat_str, format_bytes, shell_quote, timeconvert, ) class FileDownloader(object): _TEST_FILE_SIZE = 10241 params = None ...
true
2
899
youtube_dl
youtube_dl.downloader.common
FileDownloader
report_file_already_downloaded
def report_file_already_downloaded(self, file_name): """Report file has already been fully downloaded.""" try: self.to_screen('[download] %s has already been downloaded' % file_name) except UnicodeEncodeError: self.to_screen('[download] The file has already been downl...
[ 317, 322 ]
false
[]
import os import re import sys import time import random from ..compat import compat_os_name from ..utils import ( decodeArgument, encodeFilename, error_to_compat_str, format_bytes, shell_quote, timeconvert, ) class FileDownloader(object): _TEST_FILE_SIZE = 10241 params = None ...
false
0
900
youtube_dl
youtube_dl.downloader.common
FileDownloader
download
def download(self, filename, info_dict): """Download to a filename using the info from info_dict Return True on success and False otherwise """ nooverwrites_and_exists = ( self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(filename)) ...
[ 328, 365 ]
false
[]
import os import re import sys import time import random from ..compat import compat_os_name from ..utils import ( decodeArgument, encodeFilename, error_to_compat_str, format_bytes, shell_quote, timeconvert, ) class FileDownloader(object): _TEST_FILE_SIZE = 10241 params = None ...
true
2
901
youtube_dl
youtube_dl.downloader.dash
DashSegmentsFD
real_download
def real_download(self, filename, info_dict): fragment_base_url = info_dict.get('fragment_base_url') fragments = info_dict['fragments'][:1] if self.params.get( 'test', False) else info_dict['fragments'] ctx = { 'filename': filename, 'total_frags': len(fra...
[ 17, 79 ]
false
[]
from .fragment import FragmentFD from ..compat import compat_urllib_error from ..utils import ( DownloadError, urljoin, ) class DashSegmentsFD(FragmentFD): FD_NAME = 'dashsegments' def real_download(self, filename, info_dict): fragment_base_url = info_dict.get('fragment_base_url') f...
true
2
902
youtube_dl
youtube_dl.downloader.f4m
build_fragments_list
def build_fragments_list(boot_info): """ Return a list of (segment, fragment) for each fragment in the video """ res = [] segment_run_table = boot_info['segments'][0] fragment_run_entry_table = boot_info['fragments'][0]['fragments'] first_frag_number = fragment_run_entry_table[0]['first'] fragme...
[ 187, 206 ]
false
[]
import io import itertools import time from .fragment import FragmentFD from ..compat import ( compat_b64decode, compat_etree_fromstring, compat_urlparse, compat_urllib_error, compat_urllib_parse_urlparse, compat_struct_pack, compat_struct_unpack, ) from ..utils import ( fix_xml_ampersan...
true
2
903
youtube_dl
youtube_dl.downloader.f4m
write_flv_header
def write_flv_header(stream): """Writes the FLV header to stream""" # FLV header stream.write(b'FLV\x01') stream.write(b'\x05') stream.write(b'\x00\x00\x00\x09') stream.write(b'\x00\x00\x00\x00')
[ 217, 223 ]
false
[]
import io import itertools import time from .fragment import FragmentFD from ..compat import ( compat_b64decode, compat_etree_fromstring, compat_urlparse, compat_urllib_error, compat_urllib_parse_urlparse, compat_struct_pack, compat_struct_unpack, ) from ..utils import ( fix_xml_ampersan...
false
0
904
youtube_dl
youtube_dl.downloader.f4m
write_metadata_tag
def write_metadata_tag(stream, metadata): """Writes optional metadata tag to stream""" SCRIPT_TAG = b'\x12' FLV_TAG_HEADER_LEN = 11 if metadata: stream.write(SCRIPT_TAG) write_unsigned_int_24(stream, len(metadata)) stream.write(b'\x00\x00\x00\x00\x00\x00\x00') stream.wri...
[ 226, 236 ]
false
[]
import io import itertools import time from .fragment import FragmentFD from ..compat import ( compat_b64decode, compat_etree_fromstring, compat_urlparse, compat_urllib_error, compat_urllib_parse_urlparse, compat_struct_pack, compat_struct_unpack, ) from ..utils import ( fix_xml_ampersan...
true
2
905
youtube_dl
youtube_dl.downloader.f4m
remove_encrypted_media
def remove_encrypted_media(media): return list(filter(lambda e: 'drmAdditionalHeaderId' not in e.attrib and 'drmAdditionalHeaderSetId' not in e.attrib, media))
[ 239, 240 ]
false
[]
import io import itertools import time from .fragment import FragmentFD from ..compat import ( compat_b64decode, compat_etree_fromstring, compat_urlparse, compat_urllib_error, compat_urllib_parse_urlparse, compat_struct_pack, compat_struct_unpack, ) from ..utils import ( fix_xml_ampersan...
false
0
906
youtube_dl
youtube_dl.downloader.f4m
get_base_url
def get_base_url(manifest): base_url = xpath_text( manifest, [_add_ns('baseURL'), _add_ns('baseURL', 2)], 'base URL', default=None) if base_url: base_url = base_url.strip() return base_url
[ 249, 255 ]
false
[]
import io import itertools import time from .fragment import FragmentFD from ..compat import ( compat_b64decode, compat_etree_fromstring, compat_urlparse, compat_urllib_error, compat_urllib_parse_urlparse, compat_struct_pack, compat_struct_unpack, ) from ..utils import ( fix_xml_ampersan...
true
2
907
youtube_dl
youtube_dl.downloader.f4m
FlvReader
read_string
def read_string(self): res = b'' while True: char = self.read_bytes(1) if char == b'\x00': break res += char return res
[ 50, 57 ]
false
[]
import io import itertools import time from .fragment import FragmentFD from ..compat import ( compat_b64decode, compat_etree_fromstring, compat_urlparse, compat_urllib_error, compat_urllib_parse_urlparse, compat_struct_pack, compat_struct_unpack, ) from ..utils import ( fix_xml_ampersan...
true
2
908
youtube_dl
youtube_dl.downloader.f4m
FlvReader
read_box_info
def read_box_info(self): """ Read a box and return the info as a tuple: (box_size, box_type, box_data) """ real_size = size = self.read_unsigned_int() box_type = self.read_bytes(4) header_end = 8 if size == 1: real_size = self.read_unsigned_long_lo...
[ 59, 69 ]
false
[]
import io import itertools import time from .fragment import FragmentFD from ..compat import ( compat_b64decode, compat_etree_fromstring, compat_urlparse, compat_urllib_error, compat_urllib_parse_urlparse, compat_struct_pack, compat_struct_unpack, ) from ..utils import ( fix_xml_ampersan...
true
2
909
youtube_dl
youtube_dl.downloader.f4m
FlvReader
read_asrt
def read_asrt(self): # version self.read_unsigned_char() # flags self.read_bytes(3) quality_entry_count = self.read_unsigned_char() # QualityEntryCount for i in range(quality_entry_count): self.read_string() segment_run_count = self.read_u...
[ 71, 88 ]
false
[]
import io import itertools import time from .fragment import FragmentFD from ..compat import ( compat_b64decode, compat_etree_fromstring, compat_urlparse, compat_urllib_error, compat_urllib_parse_urlparse, compat_struct_pack, compat_struct_unpack, ) from ..utils import ( fix_xml_ampersan...
true
2
910
youtube_dl
youtube_dl.downloader.f4m
FlvReader
read_afrt
def read_afrt(self): # version self.read_unsigned_char() # flags self.read_bytes(3) # time scale self.read_unsigned_int() quality_entry_count = self.read_unsigned_char() # QualitySegmentUrlModifiers for i in range(quality_entry_count): ...
[ 92, 122 ]
false
[]
import io import itertools import time from .fragment import FragmentFD from ..compat import ( compat_b64decode, compat_etree_fromstring, compat_urlparse, compat_urllib_error, compat_urllib_parse_urlparse, compat_struct_pack, compat_struct_unpack, ) from ..utils import ( fix_xml_ampersan...
true
2
911
youtube_dl
youtube_dl.downloader.f4m
FlvReader
read_abst
def read_abst(self): # version self.read_unsigned_char() # flags self.read_bytes(3) self.read_unsigned_int() # BootstrapinfoVersion # Profile,Live,Update,Reserved flags = self.read_unsigned_char() live = flags & 0x20 != 0 # time scale ...
[ 126, 171 ]
false
[]
import io import itertools import time from .fragment import FragmentFD from ..compat import ( compat_b64decode, compat_etree_fromstring, compat_urlparse, compat_urllib_error, compat_urllib_parse_urlparse, compat_struct_pack, compat_struct_unpack, ) from ..utils import ( fix_xml_ampersan...
true
2
912
youtube_dl
youtube_dl.downloader.f4m
FlvReader
read_bootstrap_info
def read_bootstrap_info(self): total_size, box_type, box_data = self.read_box_info() assert box_type == b'abst' return FlvReader(box_data).read_abst()
[ 177, 180 ]
false
[]
import io import itertools import time from .fragment import FragmentFD from ..compat import ( compat_b64decode, compat_etree_fromstring, compat_urlparse, compat_urllib_error, compat_urllib_parse_urlparse, compat_struct_pack, compat_struct_unpack, ) from ..utils import ( fix_xml_ampersan...
false
0
913
youtube_dl
youtube_dl.downloader.f4m
F4mFD
real_download
def real_download(self, filename, info_dict): man_url = info_dict['url'] requested_bitrate = info_dict.get('tbr') self.to_screen('[%s] Downloading f4m manifest' % self.FD_NAME) urlh = self.ydl.urlopen(self._prepare_url(info_dict, man_url)) man_url = urlh.geturl() # S...
[ 318, 437 ]
false
[]
import io import itertools import time from .fragment import FragmentFD from ..compat import ( compat_b64decode, compat_etree_fromstring, compat_urlparse, compat_urllib_error, compat_urllib_parse_urlparse, compat_struct_pack, compat_struct_unpack, ) from ..utils import ( fix_xml_ampersan...
true
2
914
youtube_dl
youtube_dl.downloader.hls
HlsFD
can_download
@staticmethod def can_download(manifest, info_dict): UNSUPPORTED_FEATURES = ( r'#EXT-X-KEY:METHOD=(?!NONE|AES-128)', # encrypted streams [1] # r'#EXT-X-BYTERANGE', # playlists composed of byte ranges of media files [2] # Live streams heuristic does not always work ...
[ 30, 57 ]
false
[]
import re import binascii from .fragment import FragmentFD from .external import FFmpegFD from ..compat import ( compat_urllib_error, compat_urlparse, compat_struct_pack, ) from ..utils import ( parse_m3u8_attributes, update_url_query, ) class HlsFD(FragmentFD): FD_NAME = 'hlsnative' @s...
false
0
915
youtube_dl
youtube_dl.downloader.hls
HlsFD
real_download
def real_download(self, filename, info_dict): man_url = info_dict['url'] self.to_screen('[%s] Downloading m3u8 manifest' % self.FD_NAME) urlh = self.ydl.urlopen(self._prepare_url(info_dict, man_url)) man_url = urlh.geturl() s = urlh.read().decode('utf-8', 'ignore') ...
[ 59, 215 ]
false
[]
import re import binascii from .fragment import FragmentFD from .external import FFmpegFD from ..compat import ( compat_urllib_error, compat_urlparse, compat_struct_pack, ) from ..utils import ( parse_m3u8_attributes, update_url_query, ) class HlsFD(FragmentFD): FD_NAME = 'hlsnative' de...
true
2
916
youtube_dl
youtube_dl.downloader.http
HttpFD
real_download
def real_download(self, filename, info_dict): url = info_dict['url'] class DownloadContext(dict): __getattr__ = dict.get __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ ctx = DownloadContext() ctx.filename = filename ctx.tmp...
[ 27, 363 ]
false
[]
import errno import os import socket import time import random import re from .common import FileDownloader from ..compat import ( compat_str, compat_urllib_error, ) from ..utils import ( ContentTooShortError, encodeFilename, int_or_none, sanitize_open, sanitized_Request, write_xattr, ...
true
2
917
youtube_dl
youtube_dl.downloader.ism
write_piff_header
def write_piff_header(stream, params): track_id = params['track_id'] fourcc = params['fourcc'] duration = params['duration'] timescale = params.get('timescale', 10000000) language = params.get('language', 'und') height = params.get('height', 0) width = params.get('width', 0) is_audio = w...
[ 42, 189 ]
false
[ "u8", "u88", "u16", "u1616", "u32", "u64", "s88", "s16", "s1616", "s32", "unity_matrix", "TRACK_ENABLED", "TRACK_IN_MOVIE", "TRACK_IN_PREVIEW", "SELF_CONTAINED" ]
import time import binascii import io from .fragment import FragmentFD from ..compat import ( compat_Struct, compat_urllib_error, ) u8 = compat_Struct('>B') u88 = compat_Struct('>Bx') u16 = compat_Struct('>H') u1616 = compat_Struct('>Hxx') u32 = compat_Struct('>I') u64 = compat_Struct('>Q') s88 = compat_Struct...
true
2
918
youtube_dl
youtube_dl.downloader.ism
extract_box_data
def extract_box_data(data, box_sequence): data_reader = io.BytesIO(data) while True: box_size = u32.unpack(data_reader.read(4))[0] box_type = data_reader.read(4) if box_type == box_sequence[0]: box_data = data_reader.read(box_size - 8) if len(box_sequence) == 1: ...
[ 192, 202 ]
false
[ "u8", "u88", "u16", "u1616", "u32", "u64", "s88", "s16", "s1616", "s32", "unity_matrix", "TRACK_ENABLED", "TRACK_IN_MOVIE", "TRACK_IN_PREVIEW", "SELF_CONTAINED" ]
import time import binascii import io from .fragment import FragmentFD from ..compat import ( compat_Struct, compat_urllib_error, ) u8 = compat_Struct('>B') u88 = compat_Struct('>Bx') u16 = compat_Struct('>H') u1616 = compat_Struct('>Hxx') u32 = compat_Struct('>I') u64 = compat_Struct('>Q') s88 = compat_Struct...
true
2
919
youtube_dl
youtube_dl.downloader.ism
IsmFD
real_download
def real_download(self, filename, info_dict): segments = info_dict['fragments'][:1] if self.params.get( 'test', False) else info_dict['fragments'] ctx = { 'filename': filename, 'total_frags': len(segments), } self._prepare_and_start_frag_download...
[ 212, 258 ]
false
[ "u8", "u88", "u16", "u1616", "u32", "u64", "s88", "s16", "s1616", "s32", "unity_matrix", "TRACK_ENABLED", "TRACK_IN_MOVIE", "TRACK_IN_PREVIEW", "SELF_CONTAINED" ]
import time import binascii import io from .fragment import FragmentFD from ..compat import ( compat_Struct, compat_urllib_error, ) u8 = compat_Struct('>B') u88 = compat_Struct('>Bx') u16 = compat_Struct('>H') u1616 = compat_Struct('>Hxx') u32 = compat_Struct('>I') u64 = compat_Struct('>Q') s88 = compat_Struct...
true
2
920
youtube_dl
youtube_dl.jsinterp
JSInterpreter
interpret_statement
def interpret_statement(self, stmt, local_vars, allow_recursion=100): if allow_recursion < 0: raise ExtractorError('Recursion limit reached') should_abort = False stmt = stmt.lstrip() stmt_m = re.match(r'var\s', stmt) if stmt_m: expr = stmt[len(stmt_m...
[ 37, 56 ]
false
[ "_OPERATORS", "_ASSIGN_OPERATORS", "_NAME_RE" ]
import json import operator import re from .utils import ( ExtractorError, remove_quotes, ) _OPERATORS = [ ('|', operator.or_), ('^', operator.xor), ('&', operator.and_), ('>>', operator.rshift), ('<<', operator.lshift), ('-', operator.sub), ('+', operator.add), ('%', operator.m...
true
2
921
youtube_dl
youtube_dl.jsinterp
JSInterpreter
interpret_expression
def interpret_expression(self, expr, local_vars, allow_recursion): expr = expr.strip() if expr == '': # Empty expression return None if expr.startswith('('): parens_count = 0 for m in re.finditer(r'[()]', expr): if m.group(0) == '(': ...
[ 58, 210 ]
false
[ "_OPERATORS", "_ASSIGN_OPERATORS", "_NAME_RE" ]
import json import operator import re from .utils import ( ExtractorError, remove_quotes, ) _OPERATORS = [ ('|', operator.or_), ('^', operator.xor), ('&', operator.and_), ('>>', operator.rshift), ('<<', operator.lshift), ('-', operator.sub), ('+', operator.add), ('%', operator.m...
true
2
922
youtube_dl
youtube_dl.jsinterp
JSInterpreter
extract_object
def extract_object(self, objname): _FUNC_NAME_RE = r'''(?:[a-zA-Z$0-9]+|"[a-zA-Z$0-9]+"|'[a-zA-Z$0-9]+')''' obj = {} obj_m = re.search( r'''(?x) (?<!this\.)%s\s*=\s*{\s* (?P<fields>(%s\s*:\s*function\s*\(.*?\)\s*{.*?}(?:,\s*)?)*) ...
[ 212, 233 ]
false
[ "_OPERATORS", "_ASSIGN_OPERATORS", "_NAME_RE" ]
import json import operator import re from .utils import ( ExtractorError, remove_quotes, ) _OPERATORS = [ ('|', operator.or_), ('^', operator.xor), ('&', operator.and_), ('>>', operator.rshift), ('<<', operator.lshift), ('-', operator.sub), ('+', operator.add), ('%', operator.m...
true
2
923
youtube_dl
youtube_dl.jsinterp
JSInterpreter
extract_function
def extract_function(self, funcname): func_m = re.search( r'''(?x) (?:function\s+%s|[{;,]\s*%s\s*=\s*function|var\s+%s\s*=\s*function)\s* \((?P<args>[^)]*)\)\s* \{(?P<code>[^}]+)\}''' % ( re.escape(funcname), re.escape(funcname), re...
[ 235, 247 ]
false
[ "_OPERATORS", "_ASSIGN_OPERATORS", "_NAME_RE" ]
import json import operator import re from .utils import ( ExtractorError, remove_quotes, ) _OPERATORS = [ ('|', operator.or_), ('^', operator.xor), ('&', operator.and_), ('>>', operator.rshift), ('<<', operator.lshift), ('-', operator.sub), ('+', operator.add), ('%', operator.m...
true
2
924
youtube_dl
youtube_dl.jsinterp
JSInterpreter
call_function
def call_function(self, funcname, *args): f = self.extract_function(funcname) return f(args)
[ 249, 251 ]
false
[ "_OPERATORS", "_ASSIGN_OPERATORS", "_NAME_RE" ]
import json import operator import re from .utils import ( ExtractorError, remove_quotes, ) _OPERATORS = [ ('|', operator.or_), ('^', operator.xor), ('&', operator.and_), ('>>', operator.rshift), ('<<', operator.lshift), ('-', operator.sub), ('+', operator.add), ('%', operator.m...
false
0
925
youtube_dl
youtube_dl.jsinterp
JSInterpreter
build_function
def build_function(self, argnames, code): def resf(args): local_vars = dict(zip(argnames, args)) for stmt in code.split(';'): res, abort = self.interpret_statement(stmt, local_vars) if abort: break return res ret...
[ 253, 261 ]
false
[ "_OPERATORS", "_ASSIGN_OPERATORS", "_NAME_RE" ]
import json import operator import re from .utils import ( ExtractorError, remove_quotes, ) _OPERATORS = [ ('|', operator.or_), ('^', operator.xor), ('&', operator.and_), ('>>', operator.rshift), ('<<', operator.lshift), ('-', operator.sub), ('+', operator.add), ('%', operator.m...
true
2
926
youtube_dl
youtube_dl.options
parseOpts
def parseOpts(overrideArguments=None): def _readOptions(filename_bytes, default=[]): try: optionf = open(filename_bytes) except IOError: return default # silently skip if file is not present try: # FIXME: https://github.com/ytdl-org/youtube-dl/commit/dfe5...
[ 40, 919 ]
false
[]
import os.path import optparse import re import sys from .downloader.external import list_external_downloaders from .compat import ( compat_expanduser, compat_get_terminal_size, compat_getenv, compat_kwargs, compat_shlex_split, ) from .utils import ( preferredencoding, write_string, ) from ....
true
2
927
youtube_dl
youtube_dl.postprocessor.common
PostProcessor
try_utime
def try_utime(self, path, atime, mtime, errnote='Cannot update utime of file'): try: os.utime(encodeFilename(path), (atime, mtime)) except Exception: self._downloader.report_warning(errnote)
[ 57, 61 ]
false
[]
import os from ..utils import ( PostProcessingError, cli_configuration_args, encodeFilename, ) class PostProcessor(object): _downloader = None def __init__(self, downloader=None): self._downloader = downloader def try_utime(self, path, atime, mtime, errnote='Cannot update utime of ...
false
0
928
youtube_dl
youtube_dl.postprocessor.metadatafromtitle
MetadataFromTitlePP
__init__
def __init__(self, downloader, titleformat): super(MetadataFromTitlePP, self).__init__(downloader) self._titleformat = titleformat self._titleregex = (self.format_to_regex(titleformat) if re.search(r'%\(\w+\)s', titleformat) else titlef...
[ 8, 11 ]
false
[]
import re from .common import PostProcessor class MetadataFromTitlePP(PostProcessor): def __init__(self, downloader, titleformat): super(MetadataFromTitlePP, self).__init__(downloader) self._titleformat = titleformat self._titleregex = (self.format_to_regex(titleformat) ...
false
0
929
youtube_dl
youtube_dl.postprocessor.metadatafromtitle
MetadataFromTitlePP
format_to_regex
def format_to_regex(self, fmt): r""" Converts a string like '%(title)s - %(artist)s' to a regex like '(?P<title>.+)\ \-\ (?P<artist>.+)' """ lastpos = 0 regex = '' # replace %(..)s with regex group and escape other string parts fo...
[ 15, 31 ]
false
[]
import re from .common import PostProcessor class MetadataFromTitlePP(PostProcessor): def __init__(self, downloader, titleformat): super(MetadataFromTitlePP, self).__init__(downloader) self._titleformat = titleformat self._titleregex = (self.format_to_regex(titleformat) ...
true
2
930
youtube_dl
youtube_dl.postprocessor.metadatafromtitle
MetadataFromTitlePP
run
def run(self, info): title = info['title'] match = re.match(self._titleregex, title) if match is None: self._downloader.to_screen( '[fromtitle] Could not interpret title of video as "%s"' % self._titleformat) return [], info for...
[ 33, 47 ]
false
[]
import re from .common import PostProcessor class MetadataFromTitlePP(PostProcessor): def __init__(self, downloader, titleformat): super(MetadataFromTitlePP, self).__init__(downloader) self._titleformat = titleformat self._titleregex = (self.format_to_regex(titleformat) ...
true
2
931
youtube_dl
youtube_dl.postprocessor.xattrpp
XAttrMetadataPP
run
def run(self, info): """ Set extended attributes on downloaded file (if xattr support is found). """ # Write the metadata to the file's xattrs self._downloader.to_screen('[metadata] Writing metadata to file\'s xattrs') filename = info['filepath'] try: xattr_map...
[ 25, 78 ]
false
[]
from .common import PostProcessor from ..compat import compat_os_name from ..utils import ( hyphenate_date, write_xattr, XAttrMetadataError, XAttrUnavailableError, ) class XAttrMetadataPP(PostProcessor): # # More info about extended attributes for media: # http://freedesktop.org/wiki/C...
true
2
932
youtube_dl
youtube_dl.socks
ProxyError
__init__
def __init__(self, code=None, msg=None): if code is not None and msg is None: msg = self.CODES.get(code) or 'unknown error' super(ProxyError, self).__init__(code, msg)
[ 60, 63 ]
false
[ "__author__", "SOCKS4_VERSION", "SOCKS4_REPLY_VERSION", "SOCKS4_DEFAULT_DSTIP", "SOCKS5_VERSION", "SOCKS5_USER_AUTH_VERSION", "SOCKS5_USER_AUTH_SUCCESS", "Proxy" ]
import collections import socket from .compat import ( compat_ord, compat_struct_pack, compat_struct_unpack, ) __author__ = 'Timo Schmid <coding@timoschmid.de>' SOCKS4_VERSION = 4 SOCKS4_REPLY_VERSION = 0x00 SOCKS4_DEFAULT_DSTIP = compat_struct_pack('!BBBB', 0, 0, 0, 0xFF) SOCKS5_VERSION = 5 SOCKS5_USER_AU...
true
2
933
youtube_dl
youtube_dl.socks
InvalidVersionError
__init__
def __init__(self, expected_version, got_version): msg = ('Invalid response version from server. Expected {0:02x} got ' '{1:02x}'.format(expected_version, got_version)) super(InvalidVersionError, self).__init__(0, msg)
[ 67, 70 ]
false
[ "__author__", "SOCKS4_VERSION", "SOCKS4_REPLY_VERSION", "SOCKS4_DEFAULT_DSTIP", "SOCKS5_VERSION", "SOCKS5_USER_AUTH_VERSION", "SOCKS5_USER_AUTH_SUCCESS", "Proxy" ]
import collections import socket from .compat import ( compat_ord, compat_struct_pack, compat_struct_unpack, ) __author__ = 'Timo Schmid <coding@timoschmid.de>' SOCKS4_VERSION = 4 SOCKS4_REPLY_VERSION = 0x00 SOCKS4_DEFAULT_DSTIP = compat_struct_pack('!BBBB', 0, 0, 0, 0xFF) SOCKS5_VERSION = 5 SOCKS5_USER_AU...
false
0
934
youtube_dl
youtube_dl.socks
sockssocket
setproxy
def setproxy(self, proxytype, addr, port, rdns=True, username=None, password=None): assert proxytype in (ProxyType.SOCKS4, ProxyType.SOCKS4A, ProxyType.SOCKS5) self._proxy = Proxy(proxytype, addr, port, username, password, rdns)
[ 115, 118 ]
false
[ "__author__", "SOCKS4_VERSION", "SOCKS4_REPLY_VERSION", "SOCKS4_DEFAULT_DSTIP", "SOCKS5_VERSION", "SOCKS5_USER_AUTH_VERSION", "SOCKS5_USER_AUTH_SUCCESS", "Proxy" ]
import collections import socket from .compat import ( compat_ord, compat_struct_pack, compat_struct_unpack, ) __author__ = 'Timo Schmid <coding@timoschmid.de>' SOCKS4_VERSION = 4 SOCKS4_REPLY_VERSION = 0x00 SOCKS4_DEFAULT_DSTIP = compat_struct_pack('!BBBB', 0, 0, 0, 0xFF) SOCKS5_VERSION = 5 SOCKS5_USER_AU...
false
0
935
youtube_dl
youtube_dl.socks
sockssocket
recvall
def recvall(self, cnt): data = b'' while len(data) < cnt: cur = self.recv(cnt - len(data)) if not cur: raise EOFError('{0} bytes missing'.format(cnt - len(data))) data += cur return data
[ 120, 127 ]
false
[ "__author__", "SOCKS4_VERSION", "SOCKS4_REPLY_VERSION", "SOCKS4_DEFAULT_DSTIP", "SOCKS5_VERSION", "SOCKS5_USER_AUTH_VERSION", "SOCKS5_USER_AUTH_SUCCESS", "Proxy" ]
import collections import socket from .compat import ( compat_ord, compat_struct_pack, compat_struct_unpack, ) __author__ = 'Timo Schmid <coding@timoschmid.de>' SOCKS4_VERSION = 4 SOCKS4_REPLY_VERSION = 0x00 SOCKS4_DEFAULT_DSTIP = compat_struct_pack('!BBBB', 0, 0, 0, 0xFF) SOCKS5_VERSION = 5 SOCKS5_USER_AU...
true
2
936
youtube_dl
youtube_dl.swfinterp
_ScopeDict
__repr__
def __repr__(self): return '%s__Scope(%s)' % ( self.avm_class.name, super(_ScopeDict, self).__repr__())
[ 59, 60 ]
false
[ "_u32", "StringClass", "ByteArrayClass", "TimerClass", "TimerEventClass", "_builtin_classes", "undefined" ]
import collections import io import zlib from .compat import ( compat_str, compat_struct_unpack, ) from .utils import ( ExtractorError, ) _u32 = _read_int StringClass = _AVMClass('(no name idx)', 'String') ByteArrayClass = _AVMClass('(no name idx)', 'ByteArray') TimerClass = _AVMClass('(no name idx)', 'Tim...
false
0
937
youtube_dl
youtube_dl.swfinterp
_AVMClass
register_methods
def register_methods(self, methods): self.method_names.update(methods.items()) self.method_idxs.update(dict( (idx, name) for name, idx in methods.items()))
[ 84, 86 ]
false
[ "_u32", "StringClass", "ByteArrayClass", "TimerClass", "TimerEventClass", "_builtin_classes", "undefined" ]
import collections import io import zlib from .compat import ( compat_str, compat_struct_unpack, ) from .utils import ( ExtractorError, ) _u32 = _read_int StringClass = _AVMClass('(no name idx)', 'String') ByteArrayClass = _AVMClass('(no name idx)', 'ByteArray') TimerClass = _AVMClass('(no name idx)', 'Tim...
false
0
938
youtube_dl
youtube_dl.swfinterp
SWFInterpreter
__init__
def __init__(self, file_contents): self._patched_functions = { (TimerClass, 'addEventListener'): lambda params: undefined, } code_tag = next(tag for tag_code, tag in _extract_tags(file_contents) if tag_code == 82) p = code_t...
[ 185, 418 ]
false
[ "_u32", "StringClass", "ByteArrayClass", "TimerClass", "TimerEventClass", "_builtin_classes", "undefined" ]
import collections import io import zlib from .compat import ( compat_str, compat_struct_unpack, ) from .utils import ( ExtractorError, ) _u32 = _read_int StringClass = _AVMClass('(no name idx)', 'String') ByteArrayClass = _AVMClass('(no name idx)', 'ByteArray') TimerClass = _AVMClass('(no name idx)', 'Tim...
true
2
939
youtube_dl
youtube_dl.swfinterp
SWFInterpreter
patch_function
def patch_function(self, avm_class, func_name, f): self._patched_functions[(avm_class, func_name)] = f
[ 420, 421 ]
false
[ "_u32", "StringClass", "ByteArrayClass", "TimerClass", "TimerEventClass", "_builtin_classes", "undefined" ]
import collections import io import zlib from .compat import ( compat_str, compat_struct_unpack, ) from .utils import ( ExtractorError, ) _u32 = _read_int StringClass = _AVMClass('(no name idx)', 'String') ByteArrayClass = _AVMClass('(no name idx)', 'ByteArray') TimerClass = _AVMClass('(no name idx)', 'Tim...
false
0
940
youtube_dl
youtube_dl.swfinterp
SWFInterpreter
extract_class
def extract_class(self, class_name, call_cinit=True): try: res = self._classes_by_name[class_name] except KeyError: raise ExtractorError('Class %r not found' % class_name) if call_cinit and hasattr(res, 'cinit_idx'): res.register_methods({'$cinit': res.ci...
[ 423, 435 ]
false
[ "_u32", "StringClass", "ByteArrayClass", "TimerClass", "TimerEventClass", "_builtin_classes", "undefined" ]
import collections import io import zlib from .compat import ( compat_str, compat_struct_unpack, ) from .utils import ( ExtractorError, ) _u32 = _read_int StringClass = _AVMClass('(no name idx)', 'String') ByteArrayClass = _AVMClass('(no name idx)', 'ByteArray') TimerClass = _AVMClass('(no name idx)', 'Tim...
true
2
941
youtube_dl
youtube_dl.swfinterp
SWFInterpreter
extract_function
def extract_function(self, avm_class, func_name): p = self._patched_functions.get((avm_class, func_name)) if p: return p if func_name in avm_class.method_pyfunctions: return avm_class.method_pyfunctions[func_name] if func_name in self._classes_by_name: ...
[ 437, 833 ]
false
[ "_u32", "StringClass", "ByteArrayClass", "TimerClass", "TimerEventClass", "_builtin_classes", "undefined" ]
import collections import io import zlib from .compat import ( compat_str, compat_struct_unpack, ) from .utils import ( ExtractorError, ) _u32 = _read_int StringClass = _AVMClass('(no name idx)', 'String') ByteArrayClass = _AVMClass('(no name idx)', 'ByteArray') TimerClass = _AVMClass('(no name idx)', 'Tim...
true
2