repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
ArchiveTeam/wpull
wpull/document/sitemap.py
SitemapReader.is_file
def is_file(cls, file): '''Return whether the file is likely a Sitemap.''' peeked_data = wpull.util.peek_file(file) if is_gzip(peeked_data): try: peeked_data = wpull.decompression.gzip_uncompress( peeked_data, truncated=True ) except zlib.error: pass peeked_data = wpull.string.printable_bytes(peeked_data) if b'<?xml' in peeked_data \ and (b'<sitemapindex' in peeked_data or b'<urlset' in peeked_data): return True
python
def is_file(cls, file): '''Return whether the file is likely a Sitemap.''' peeked_data = wpull.util.peek_file(file) if is_gzip(peeked_data): try: peeked_data = wpull.decompression.gzip_uncompress( peeked_data, truncated=True ) except zlib.error: pass peeked_data = wpull.string.printable_bytes(peeked_data) if b'<?xml' in peeked_data \ and (b'<sitemapindex' in peeked_data or b'<urlset' in peeked_data): return True
[ "def", "is_file", "(", "cls", ",", "file", ")", ":", "peeked_data", "=", "wpull", ".", "util", ".", "peek_file", "(", "file", ")", "if", "is_gzip", "(", "peeked_data", ")", ":", "try", ":", "peeked_data", "=", "wpull", ".", "decompression", ".", "gzip_...
Return whether the file is likely a Sitemap.
[ "Return", "whether", "the", "file", "is", "likely", "a", "Sitemap", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/document/sitemap.py#L44-L60
train
201,200
ArchiveTeam/wpull
wpull/url.py
normalize_hostname
def normalize_hostname(hostname): '''Normalizes a hostname so that it is ASCII and valid domain name.''' try: new_hostname = hostname.encode('idna').decode('ascii').lower() except UnicodeError as error: raise UnicodeError('Hostname {} rejected: {}'.format(hostname, error)) from error if hostname != new_hostname: # Check for round-trip. May raise UnicodeError new_hostname.encode('idna') return new_hostname
python
def normalize_hostname(hostname): '''Normalizes a hostname so that it is ASCII and valid domain name.''' try: new_hostname = hostname.encode('idna').decode('ascii').lower() except UnicodeError as error: raise UnicodeError('Hostname {} rejected: {}'.format(hostname, error)) from error if hostname != new_hostname: # Check for round-trip. May raise UnicodeError new_hostname.encode('idna') return new_hostname
[ "def", "normalize_hostname", "(", "hostname", ")", ":", "try", ":", "new_hostname", "=", "hostname", ".", "encode", "(", "'idna'", ")", ".", "decode", "(", "'ascii'", ")", ".", "lower", "(", ")", "except", "UnicodeError", "as", "error", ":", "raise", "Un...
Normalizes a hostname so that it is ASCII and valid domain name.
[ "Normalizes", "a", "hostname", "so", "that", "it", "is", "ASCII", "and", "valid", "domain", "name", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/url.py#L432-L443
train
201,201
ArchiveTeam/wpull
wpull/url.py
normalize_path
def normalize_path(path, encoding='utf-8'): '''Normalize a path string. Flattens a path by removing dot parts, percent-encodes unacceptable characters and ensures percent-encoding is uppercase. ''' if not path.startswith('/'): path = '/' + path path = percent_encode(flatten_path(path, flatten_slashes=True), encoding=encoding) return uppercase_percent_encoding(path)
python
def normalize_path(path, encoding='utf-8'): '''Normalize a path string. Flattens a path by removing dot parts, percent-encodes unacceptable characters and ensures percent-encoding is uppercase. ''' if not path.startswith('/'): path = '/' + path path = percent_encode(flatten_path(path, flatten_slashes=True), encoding=encoding) return uppercase_percent_encoding(path)
[ "def", "normalize_path", "(", "path", ",", "encoding", "=", "'utf-8'", ")", ":", "if", "not", "path", ".", "startswith", "(", "'/'", ")", ":", "path", "=", "'/'", "+", "path", "path", "=", "percent_encode", "(", "flatten_path", "(", "path", ",", "flatt...
Normalize a path string. Flattens a path by removing dot parts, percent-encodes unacceptable characters and ensures percent-encoding is uppercase.
[ "Normalize", "a", "path", "string", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/url.py#L473-L483
train
201,202
ArchiveTeam/wpull
wpull/url.py
normalize_query
def normalize_query(text, encoding='utf-8'): '''Normalize a query string. Percent-encodes unacceptable characters and ensures percent-encoding is uppercase. ''' path = percent_encode_plus(text, encoding=encoding) return uppercase_percent_encoding(path)
python
def normalize_query(text, encoding='utf-8'): '''Normalize a query string. Percent-encodes unacceptable characters and ensures percent-encoding is uppercase. ''' path = percent_encode_plus(text, encoding=encoding) return uppercase_percent_encoding(path)
[ "def", "normalize_query", "(", "text", ",", "encoding", "=", "'utf-8'", ")", ":", "path", "=", "percent_encode_plus", "(", "text", ",", "encoding", "=", "encoding", ")", "return", "uppercase_percent_encoding", "(", "path", ")" ]
Normalize a query string. Percent-encodes unacceptable characters and ensures percent-encoding is uppercase.
[ "Normalize", "a", "query", "string", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/url.py#L486-L493
train
201,203
ArchiveTeam/wpull
wpull/url.py
normalize_fragment
def normalize_fragment(text, encoding='utf-8'): '''Normalize a fragment. Percent-encodes unacceptable characters and ensures percent-encoding is uppercase. ''' path = percent_encode(text, encoding=encoding, encode_set=FRAGMENT_ENCODE_SET) return uppercase_percent_encoding(path)
python
def normalize_fragment(text, encoding='utf-8'): '''Normalize a fragment. Percent-encodes unacceptable characters and ensures percent-encoding is uppercase. ''' path = percent_encode(text, encoding=encoding, encode_set=FRAGMENT_ENCODE_SET) return uppercase_percent_encoding(path)
[ "def", "normalize_fragment", "(", "text", ",", "encoding", "=", "'utf-8'", ")", ":", "path", "=", "percent_encode", "(", "text", ",", "encoding", "=", "encoding", ",", "encode_set", "=", "FRAGMENT_ENCODE_SET", ")", "return", "uppercase_percent_encoding", "(", "p...
Normalize a fragment. Percent-encodes unacceptable characters and ensures percent-encoding is uppercase.
[ "Normalize", "a", "fragment", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/url.py#L496-L503
train
201,204
ArchiveTeam/wpull
wpull/url.py
normalize_username
def normalize_username(text, encoding='utf-8'): '''Normalize a username Percent-encodes unacceptable characters and ensures percent-encoding is uppercase. ''' path = percent_encode(text, encoding=encoding, encode_set=USERNAME_ENCODE_SET) return uppercase_percent_encoding(path)
python
def normalize_username(text, encoding='utf-8'): '''Normalize a username Percent-encodes unacceptable characters and ensures percent-encoding is uppercase. ''' path = percent_encode(text, encoding=encoding, encode_set=USERNAME_ENCODE_SET) return uppercase_percent_encoding(path)
[ "def", "normalize_username", "(", "text", ",", "encoding", "=", "'utf-8'", ")", ":", "path", "=", "percent_encode", "(", "text", ",", "encoding", "=", "encoding", ",", "encode_set", "=", "USERNAME_ENCODE_SET", ")", "return", "uppercase_percent_encoding", "(", "p...
Normalize a username Percent-encodes unacceptable characters and ensures percent-encoding is uppercase.
[ "Normalize", "a", "username" ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/url.py#L506-L513
train
201,205
ArchiveTeam/wpull
wpull/url.py
normalize_password
def normalize_password(text, encoding='utf-8'): '''Normalize a password Percent-encodes unacceptable characters and ensures percent-encoding is uppercase. ''' path = percent_encode(text, encoding=encoding, encode_set=PASSWORD_ENCODE_SET) return uppercase_percent_encoding(path)
python
def normalize_password(text, encoding='utf-8'): '''Normalize a password Percent-encodes unacceptable characters and ensures percent-encoding is uppercase. ''' path = percent_encode(text, encoding=encoding, encode_set=PASSWORD_ENCODE_SET) return uppercase_percent_encoding(path)
[ "def", "normalize_password", "(", "text", ",", "encoding", "=", "'utf-8'", ")", ":", "path", "=", "percent_encode", "(", "text", ",", "encoding", "=", "encoding", ",", "encode_set", "=", "PASSWORD_ENCODE_SET", ")", "return", "uppercase_percent_encoding", "(", "p...
Normalize a password Percent-encodes unacceptable characters and ensures percent-encoding is uppercase.
[ "Normalize", "a", "password" ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/url.py#L516-L523
train
201,206
ArchiveTeam/wpull
wpull/url.py
percent_encode
def percent_encode(text, encode_set=DEFAULT_ENCODE_SET, encoding='utf-8'): '''Percent encode text. Unlike Python's ``quote``, this function accepts a blacklist instead of a whitelist of safe characters. ''' byte_string = text.encode(encoding) try: mapping = _percent_encoder_map_cache[encode_set] except KeyError: mapping = _percent_encoder_map_cache[encode_set] = PercentEncoderMap( encode_set).__getitem__ return ''.join([mapping(char) for char in byte_string])
python
def percent_encode(text, encode_set=DEFAULT_ENCODE_SET, encoding='utf-8'): '''Percent encode text. Unlike Python's ``quote``, this function accepts a blacklist instead of a whitelist of safe characters. ''' byte_string = text.encode(encoding) try: mapping = _percent_encoder_map_cache[encode_set] except KeyError: mapping = _percent_encoder_map_cache[encode_set] = PercentEncoderMap( encode_set).__getitem__ return ''.join([mapping(char) for char in byte_string])
[ "def", "percent_encode", "(", "text", ",", "encode_set", "=", "DEFAULT_ENCODE_SET", ",", "encoding", "=", "'utf-8'", ")", ":", "byte_string", "=", "text", ".", "encode", "(", "encoding", ")", "try", ":", "mapping", "=", "_percent_encoder_map_cache", "[", "enco...
Percent encode text. Unlike Python's ``quote``, this function accepts a blacklist instead of a whitelist of safe characters.
[ "Percent", "encode", "text", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/url.py#L546-L560
train
201,207
ArchiveTeam/wpull
wpull/url.py
percent_encode_plus
def percent_encode_plus(text, encode_set=QUERY_ENCODE_SET, encoding='utf-8'): '''Percent encode text for query strings. Unlike Python's ``quote_plus``, this function accepts a blacklist instead of a whitelist of safe characters. ''' if ' ' not in text: return percent_encode(text, encode_set, encoding) else: result = percent_encode(text, encode_set, encoding) return result.replace(' ', '+')
python
def percent_encode_plus(text, encode_set=QUERY_ENCODE_SET, encoding='utf-8'): '''Percent encode text for query strings. Unlike Python's ``quote_plus``, this function accepts a blacklist instead of a whitelist of safe characters. ''' if ' ' not in text: return percent_encode(text, encode_set, encoding) else: result = percent_encode(text, encode_set, encoding) return result.replace(' ', '+')
[ "def", "percent_encode_plus", "(", "text", ",", "encode_set", "=", "QUERY_ENCODE_SET", ",", "encoding", "=", "'utf-8'", ")", ":", "if", "' '", "not", "in", "text", ":", "return", "percent_encode", "(", "text", ",", "encode_set", ",", "encoding", ")", "else",...
Percent encode text for query strings. Unlike Python's ``quote_plus``, this function accepts a blacklist instead of a whitelist of safe characters.
[ "Percent", "encode", "text", "for", "query", "strings", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/url.py#L563-L574
train
201,208
ArchiveTeam/wpull
wpull/url.py
schemes_similar
def schemes_similar(scheme1, scheme2): '''Return whether URL schemes are similar. This function considers the following schemes to be similar: * HTTP and HTTPS ''' if scheme1 == scheme2: return True if scheme1 in ('http', 'https') and scheme2 in ('http', 'https'): return True return False
python
def schemes_similar(scheme1, scheme2): '''Return whether URL schemes are similar. This function considers the following schemes to be similar: * HTTP and HTTPS ''' if scheme1 == scheme2: return True if scheme1 in ('http', 'https') and scheme2 in ('http', 'https'): return True return False
[ "def", "schemes_similar", "(", "scheme1", ",", "scheme2", ")", ":", "if", "scheme1", "==", "scheme2", ":", "return", "True", "if", "scheme1", "in", "(", "'http'", ",", "'https'", ")", "and", "scheme2", "in", "(", "'http'", ",", "'https'", ")", ":", "re...
Return whether URL schemes are similar. This function considers the following schemes to be similar: * HTTP and HTTPS
[ "Return", "whether", "URL", "schemes", "are", "similar", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/url.py#L586-L600
train
201,209
ArchiveTeam/wpull
wpull/url.py
is_subdir
def is_subdir(base_path, test_path, trailing_slash=False, wildcards=False): '''Return whether the a path is a subpath of another. Args: base_path: The base path test_path: The path which we are testing trailing_slash: If True, the trailing slash is treated with importance. For example, ``/images/`` is a directory while ``/images`` is a file. wildcards: If True, globbing wildcards are matched against paths ''' if trailing_slash: base_path = base_path.rsplit('/', 1)[0] + '/' test_path = test_path.rsplit('/', 1)[0] + '/' else: if not base_path.endswith('/'): base_path += '/' if not test_path.endswith('/'): test_path += '/' if wildcards: return fnmatch.fnmatchcase(test_path, base_path) else: return test_path.startswith(base_path)
python
def is_subdir(base_path, test_path, trailing_slash=False, wildcards=False): '''Return whether the a path is a subpath of another. Args: base_path: The base path test_path: The path which we are testing trailing_slash: If True, the trailing slash is treated with importance. For example, ``/images/`` is a directory while ``/images`` is a file. wildcards: If True, globbing wildcards are matched against paths ''' if trailing_slash: base_path = base_path.rsplit('/', 1)[0] + '/' test_path = test_path.rsplit('/', 1)[0] + '/' else: if not base_path.endswith('/'): base_path += '/' if not test_path.endswith('/'): test_path += '/' if wildcards: return fnmatch.fnmatchcase(test_path, base_path) else: return test_path.startswith(base_path)
[ "def", "is_subdir", "(", "base_path", ",", "test_path", ",", "trailing_slash", "=", "False", ",", "wildcards", "=", "False", ")", ":", "if", "trailing_slash", ":", "base_path", "=", "base_path", ".", "rsplit", "(", "'/'", ",", "1", ")", "[", "0", "]", ...
Return whether the a path is a subpath of another. Args: base_path: The base path test_path: The path which we are testing trailing_slash: If True, the trailing slash is treated with importance. For example, ``/images/`` is a directory while ``/images`` is a file. wildcards: If True, globbing wildcards are matched against paths
[ "Return", "whether", "the", "a", "path", "is", "a", "subpath", "of", "another", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/url.py#L603-L627
train
201,210
ArchiveTeam/wpull
wpull/url.py
uppercase_percent_encoding
def uppercase_percent_encoding(text): '''Uppercases percent-encoded sequences.''' if '%' not in text: return text return re.sub( r'%[a-f0-9][a-f0-9]', lambda match: match.group(0).upper(), text)
python
def uppercase_percent_encoding(text): '''Uppercases percent-encoded sequences.''' if '%' not in text: return text return re.sub( r'%[a-f0-9][a-f0-9]', lambda match: match.group(0).upper(), text)
[ "def", "uppercase_percent_encoding", "(", "text", ")", ":", "if", "'%'", "not", "in", "text", ":", "return", "text", "return", "re", ".", "sub", "(", "r'%[a-f0-9][a-f0-9]'", ",", "lambda", "match", ":", "match", ".", "group", "(", "0", ")", ".", "upper",...
Uppercases percent-encoded sequences.
[ "Uppercases", "percent", "-", "encoded", "sequences", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/url.py#L630-L638
train
201,211
ArchiveTeam/wpull
wpull/url.py
split_query
def split_query(qs, keep_blank_values=False): '''Split the query string. Note for empty values: If an equal sign (``=``) is present, the value will be an empty string (``''``). Otherwise, the value will be ``None``:: >>> list(split_query('a=&b', keep_blank_values=True)) [('a', ''), ('b', None)] No processing is done on the actual values. ''' items = [] for pair in qs.split('&'): name, delim, value = pair.partition('=') if not delim and keep_blank_values: value = None if keep_blank_values or value: items.append((name, value)) return items
python
def split_query(qs, keep_blank_values=False): '''Split the query string. Note for empty values: If an equal sign (``=``) is present, the value will be an empty string (``''``). Otherwise, the value will be ``None``:: >>> list(split_query('a=&b', keep_blank_values=True)) [('a', ''), ('b', None)] No processing is done on the actual values. ''' items = [] for pair in qs.split('&'): name, delim, value = pair.partition('=') if not delim and keep_blank_values: value = None if keep_blank_values or value: items.append((name, value)) return items
[ "def", "split_query", "(", "qs", ",", "keep_blank_values", "=", "False", ")", ":", "items", "=", "[", "]", "for", "pair", "in", "qs", ".", "split", "(", "'&'", ")", ":", "name", ",", "delim", ",", "value", "=", "pair", ".", "partition", "(", "'='",...
Split the query string. Note for empty values: If an equal sign (``=``) is present, the value will be an empty string (``''``). Otherwise, the value will be ``None``:: >>> list(split_query('a=&b', keep_blank_values=True)) [('a', ''), ('b', None)] No processing is done on the actual values.
[ "Split", "the", "query", "string", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/url.py#L641-L662
train
201,212
ArchiveTeam/wpull
wpull/url.py
query_to_map
def query_to_map(text): '''Return a key-values mapping from a query string. Plus symbols are replaced with spaces. ''' dict_obj = {} for key, value in split_query(text, True): if key not in dict_obj: dict_obj[key] = [] if value: dict_obj[key].append(value.replace('+', ' ')) else: dict_obj[key].append('') return query_to_map(text)
python
def query_to_map(text): '''Return a key-values mapping from a query string. Plus symbols are replaced with spaces. ''' dict_obj = {} for key, value in split_query(text, True): if key not in dict_obj: dict_obj[key] = [] if value: dict_obj[key].append(value.replace('+', ' ')) else: dict_obj[key].append('') return query_to_map(text)
[ "def", "query_to_map", "(", "text", ")", ":", "dict_obj", "=", "{", "}", "for", "key", ",", "value", "in", "split_query", "(", "text", ",", "True", ")", ":", "if", "key", "not", "in", "dict_obj", ":", "dict_obj", "[", "key", "]", "=", "[", "]", "...
Return a key-values mapping from a query string. Plus symbols are replaced with spaces.
[ "Return", "a", "key", "-", "values", "mapping", "from", "a", "query", "string", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/url.py#L665-L681
train
201,213
ArchiveTeam/wpull
wpull/url.py
urljoin
def urljoin(base_url, url, allow_fragments=True): '''Join URLs like ``urllib.parse.urljoin`` but allow scheme-relative URL.''' if url.startswith('//') and len(url) > 2: scheme = base_url.partition(':')[0] if scheme: return urllib.parse.urljoin( base_url, '{0}:{1}'.format(scheme, url), allow_fragments=allow_fragments ) return urllib.parse.urljoin( base_url, url, allow_fragments=allow_fragments)
python
def urljoin(base_url, url, allow_fragments=True): '''Join URLs like ``urllib.parse.urljoin`` but allow scheme-relative URL.''' if url.startswith('//') and len(url) > 2: scheme = base_url.partition(':')[0] if scheme: return urllib.parse.urljoin( base_url, '{0}:{1}'.format(scheme, url), allow_fragments=allow_fragments ) return urllib.parse.urljoin( base_url, url, allow_fragments=allow_fragments)
[ "def", "urljoin", "(", "base_url", ",", "url", ",", "allow_fragments", "=", "True", ")", ":", "if", "url", ".", "startswith", "(", "'//'", ")", "and", "len", "(", "url", ")", ">", "2", ":", "scheme", "=", "base_url", ".", "partition", "(", "':'", "...
Join URLs like ``urllib.parse.urljoin`` but allow scheme-relative URL.
[ "Join", "URLs", "like", "urllib", ".", "parse", ".", "urljoin", "but", "allow", "scheme", "-", "relative", "URL", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/url.py#L685-L697
train
201,214
ArchiveTeam/wpull
wpull/url.py
flatten_path
def flatten_path(path, flatten_slashes=False): '''Flatten an absolute URL path by removing the dot segments. :func:`urllib.parse.urljoin` has some support for removing dot segments, but it is conservative and only removes them as needed. Arguments: path (str): The URL path. flatten_slashes (bool): If True, consecutive slashes are removed. The path returned will always have a leading slash. ''' # Based on posixpath.normpath # Fast path if not path or path == '/': return '/' # Take off leading slash if path[0] == '/': path = path[1:] parts = path.split('/') new_parts = collections.deque() for part in parts: if part == '.' or (flatten_slashes and not part): continue elif part != '..': new_parts.append(part) elif new_parts: new_parts.pop() # If the filename is empty string if flatten_slashes and path.endswith('/') or not len(new_parts): new_parts.append('') # Put back leading slash new_parts.appendleft('') return '/'.join(new_parts)
python
def flatten_path(path, flatten_slashes=False): '''Flatten an absolute URL path by removing the dot segments. :func:`urllib.parse.urljoin` has some support for removing dot segments, but it is conservative and only removes them as needed. Arguments: path (str): The URL path. flatten_slashes (bool): If True, consecutive slashes are removed. The path returned will always have a leading slash. ''' # Based on posixpath.normpath # Fast path if not path or path == '/': return '/' # Take off leading slash if path[0] == '/': path = path[1:] parts = path.split('/') new_parts = collections.deque() for part in parts: if part == '.' or (flatten_slashes and not part): continue elif part != '..': new_parts.append(part) elif new_parts: new_parts.pop() # If the filename is empty string if flatten_slashes and path.endswith('/') or not len(new_parts): new_parts.append('') # Put back leading slash new_parts.appendleft('') return '/'.join(new_parts)
[ "def", "flatten_path", "(", "path", ",", "flatten_slashes", "=", "False", ")", ":", "# Based on posixpath.normpath", "# Fast path", "if", "not", "path", "or", "path", "==", "'/'", ":", "return", "'/'", "# Take off leading slash", "if", "path", "[", "0", "]", "...
Flatten an absolute URL path by removing the dot segments. :func:`urllib.parse.urljoin` has some support for removing dot segments, but it is conservative and only removes them as needed. Arguments: path (str): The URL path. flatten_slashes (bool): If True, consecutive slashes are removed. The path returned will always have a leading slash.
[ "Flatten", "an", "absolute", "URL", "path", "by", "removing", "the", "dot", "segments", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/url.py#L700-L740
train
201,215
ArchiveTeam/wpull
wpull/url.py
URLInfo.parse
def parse(cls, url, default_scheme='http', encoding='utf-8'): '''Parse a URL and return a URLInfo.''' if url is None: return None url = url.strip() if frozenset(url) & C0_CONTROL_SET: raise ValueError('URL contains control codes: {}'.format(ascii(url))) scheme, sep, remaining = url.partition(':') if not scheme: raise ValueError('URL missing scheme: {}'.format(ascii(url))) scheme = scheme.lower() if not sep and default_scheme: # Likely something like example.com/mystuff remaining = url scheme = default_scheme elif not sep: raise ValueError('URI missing colon: {}'.format(ascii(url))) if default_scheme and '.' in scheme or scheme == 'localhost': # Maybe something like example.com:8080/mystuff or # maybe localhost:8080/mystuff remaining = '{}:{}'.format(scheme, remaining) scheme = default_scheme info = URLInfo() info.encoding = encoding if scheme not in RELATIVE_SCHEME_DEFAULT_PORTS: info.raw = url info.scheme = scheme info.path = remaining return info if remaining.startswith('//'): remaining = remaining[2:] path_index = remaining.find('/') query_index = remaining.find('?') fragment_index = remaining.find('#') try: index_tuple = (path_index, query_index, fragment_index) authority_index = min(num for num in index_tuple if num >= 0) except ValueError: authority_index = len(remaining) authority = remaining[:authority_index] resource = remaining[authority_index:] try: index_tuple = (query_index, fragment_index) path_index = min(num for num in index_tuple if num >= 0) except ValueError: path_index = len(remaining) path = remaining[authority_index + 1:path_index] or '/' if fragment_index >= 0: query_index = fragment_index else: query_index = len(remaining) query = remaining[path_index + 1:query_index] fragment = remaining[query_index + 1:] userinfo, host = cls.parse_authority(authority) hostname, port = cls.parse_host(host) username, password = cls.parse_userinfo(userinfo) if not hostname: raise ValueError('Hostname is empty: {}'.format(ascii(url))) info.raw = url info.scheme = scheme info.authority = authority info.path = normalize_path(path, encoding=encoding) info.query = normalize_query(query, encoding=encoding) info.fragment = normalize_fragment(fragment, encoding=encoding) info.userinfo = userinfo info.username = percent_decode(username, encoding=encoding) info.password = percent_decode(password, encoding=encoding) info.host = host info.hostname = hostname info.port = port or RELATIVE_SCHEME_DEFAULT_PORTS[scheme] info.resource = resource return info
python
def parse(cls, url, default_scheme='http', encoding='utf-8'): '''Parse a URL and return a URLInfo.''' if url is None: return None url = url.strip() if frozenset(url) & C0_CONTROL_SET: raise ValueError('URL contains control codes: {}'.format(ascii(url))) scheme, sep, remaining = url.partition(':') if not scheme: raise ValueError('URL missing scheme: {}'.format(ascii(url))) scheme = scheme.lower() if not sep and default_scheme: # Likely something like example.com/mystuff remaining = url scheme = default_scheme elif not sep: raise ValueError('URI missing colon: {}'.format(ascii(url))) if default_scheme and '.' in scheme or scheme == 'localhost': # Maybe something like example.com:8080/mystuff or # maybe localhost:8080/mystuff remaining = '{}:{}'.format(scheme, remaining) scheme = default_scheme info = URLInfo() info.encoding = encoding if scheme not in RELATIVE_SCHEME_DEFAULT_PORTS: info.raw = url info.scheme = scheme info.path = remaining return info if remaining.startswith('//'): remaining = remaining[2:] path_index = remaining.find('/') query_index = remaining.find('?') fragment_index = remaining.find('#') try: index_tuple = (path_index, query_index, fragment_index) authority_index = min(num for num in index_tuple if num >= 0) except ValueError: authority_index = len(remaining) authority = remaining[:authority_index] resource = remaining[authority_index:] try: index_tuple = (query_index, fragment_index) path_index = min(num for num in index_tuple if num >= 0) except ValueError: path_index = len(remaining) path = remaining[authority_index + 1:path_index] or '/' if fragment_index >= 0: query_index = fragment_index else: query_index = len(remaining) query = remaining[path_index + 1:query_index] fragment = remaining[query_index + 1:] userinfo, host = cls.parse_authority(authority) hostname, port = cls.parse_host(host) username, password = cls.parse_userinfo(userinfo) if not hostname: raise ValueError('Hostname is empty: {}'.format(ascii(url))) info.raw = url info.scheme = scheme info.authority = authority info.path = normalize_path(path, encoding=encoding) info.query = normalize_query(query, encoding=encoding) info.fragment = normalize_fragment(fragment, encoding=encoding) info.userinfo = userinfo info.username = percent_decode(username, encoding=encoding) info.password = percent_decode(password, encoding=encoding) info.host = host info.hostname = hostname info.port = port or RELATIVE_SCHEME_DEFAULT_PORTS[scheme] info.resource = resource return info
[ "def", "parse", "(", "cls", ",", "url", ",", "default_scheme", "=", "'http'", ",", "encoding", "=", "'utf-8'", ")", ":", "if", "url", "is", "None", ":", "return", "None", "url", "=", "url", ".", "strip", "(", ")", "if", "frozenset", "(", "url", ")"...
Parse a URL and return a URLInfo.
[ "Parse", "a", "URL", "and", "return", "a", "URLInfo", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/url.py#L124-L219
train
201,216
ArchiveTeam/wpull
wpull/url.py
URLInfo.parse_authority
def parse_authority(cls, authority): '''Parse the authority part and return userinfo and host.''' userinfo, sep, host = authority.partition('@') if not sep: return '', userinfo else: return userinfo, host
python
def parse_authority(cls, authority): '''Parse the authority part and return userinfo and host.''' userinfo, sep, host = authority.partition('@') if not sep: return '', userinfo else: return userinfo, host
[ "def", "parse_authority", "(", "cls", ",", "authority", ")", ":", "userinfo", ",", "sep", ",", "host", "=", "authority", ".", "partition", "(", "'@'", ")", "if", "not", "sep", ":", "return", "''", ",", "userinfo", "else", ":", "return", "userinfo", ","...
Parse the authority part and return userinfo and host.
[ "Parse", "the", "authority", "part", "and", "return", "userinfo", "and", "host", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/url.py#L222-L229
train
201,217
ArchiveTeam/wpull
wpull/url.py
URLInfo.parse_userinfo
def parse_userinfo(cls, userinfo): '''Parse the userinfo and return username and password.''' username, sep, password = userinfo.partition(':') return username, password
python
def parse_userinfo(cls, userinfo): '''Parse the userinfo and return username and password.''' username, sep, password = userinfo.partition(':') return username, password
[ "def", "parse_userinfo", "(", "cls", ",", "userinfo", ")", ":", "username", ",", "sep", ",", "password", "=", "userinfo", ".", "partition", "(", "':'", ")", "return", "username", ",", "password" ]
Parse the userinfo and return username and password.
[ "Parse", "the", "userinfo", "and", "return", "username", "and", "password", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/url.py#L232-L236
train
201,218
ArchiveTeam/wpull
wpull/url.py
URLInfo.parse_host
def parse_host(cls, host): '''Parse the host and return hostname and port.''' if host.endswith(']'): return cls.parse_hostname(host), None else: hostname, sep, port = host.rpartition(':') if sep: port = int(port) if port < 0 or port > 65535: raise ValueError('Port number invalid') else: hostname = port port = None return cls.parse_hostname(hostname), port
python
def parse_host(cls, host): '''Parse the host and return hostname and port.''' if host.endswith(']'): return cls.parse_hostname(host), None else: hostname, sep, port = host.rpartition(':') if sep: port = int(port) if port < 0 or port > 65535: raise ValueError('Port number invalid') else: hostname = port port = None return cls.parse_hostname(hostname), port
[ "def", "parse_host", "(", "cls", ",", "host", ")", ":", "if", "host", ".", "endswith", "(", "']'", ")", ":", "return", "cls", ".", "parse_hostname", "(", "host", ")", ",", "None", "else", ":", "hostname", ",", "sep", ",", "port", "=", "host", ".", ...
Parse the host and return hostname and port.
[ "Parse", "the", "host", "and", "return", "hostname", "and", "port", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/url.py#L239-L254
train
201,219
ArchiveTeam/wpull
wpull/url.py
URLInfo.parse_hostname
def parse_hostname(cls, hostname): '''Parse the hostname and normalize.''' if hostname.startswith('['): return cls.parse_ipv6_hostname(hostname) else: try: new_hostname = normalize_ipv4_address(hostname) except ValueError: # _logger.debug('', exc_info=True) new_hostname = hostname new_hostname = normalize_hostname(new_hostname) if any(char in new_hostname for char in FORBIDDEN_HOSTNAME_CHARS): raise ValueError('Invalid hostname: {}' .format(ascii(hostname))) return new_hostname
python
def parse_hostname(cls, hostname): '''Parse the hostname and normalize.''' if hostname.startswith('['): return cls.parse_ipv6_hostname(hostname) else: try: new_hostname = normalize_ipv4_address(hostname) except ValueError: # _logger.debug('', exc_info=True) new_hostname = hostname new_hostname = normalize_hostname(new_hostname) if any(char in new_hostname for char in FORBIDDEN_HOSTNAME_CHARS): raise ValueError('Invalid hostname: {}' .format(ascii(hostname))) return new_hostname
[ "def", "parse_hostname", "(", "cls", ",", "hostname", ")", ":", "if", "hostname", ".", "startswith", "(", "'['", ")", ":", "return", "cls", ".", "parse_ipv6_hostname", "(", "hostname", ")", "else", ":", "try", ":", "new_hostname", "=", "normalize_ipv4_addres...
Parse the hostname and normalize.
[ "Parse", "the", "hostname", "and", "normalize", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/url.py#L257-L274
train
201,220
ArchiveTeam/wpull
wpull/url.py
URLInfo.parse_ipv6_hostname
def parse_ipv6_hostname(cls, hostname): '''Parse and normalize a IPv6 address.''' if not hostname.startswith('[') or not hostname.endswith(']'): raise ValueError('Invalid IPv6 address: {}' .format(ascii(hostname))) hostname = ipaddress.IPv6Address(hostname[1:-1]).compressed return hostname
python
def parse_ipv6_hostname(cls, hostname): '''Parse and normalize a IPv6 address.''' if not hostname.startswith('[') or not hostname.endswith(']'): raise ValueError('Invalid IPv6 address: {}' .format(ascii(hostname))) hostname = ipaddress.IPv6Address(hostname[1:-1]).compressed return hostname
[ "def", "parse_ipv6_hostname", "(", "cls", ",", "hostname", ")", ":", "if", "not", "hostname", ".", "startswith", "(", "'['", ")", "or", "not", "hostname", ".", "endswith", "(", "']'", ")", ":", "raise", "ValueError", "(", "'Invalid IPv6 address: {}'", ".", ...
Parse and normalize a IPv6 address.
[ "Parse", "and", "normalize", "a", "IPv6", "address", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/url.py#L277-L285
train
201,221
ArchiveTeam/wpull
wpull/url.py
URLInfo.to_dict
def to_dict(self): '''Return a dict of the attributes.''' return dict( raw=self.raw, scheme=self.scheme, authority=self.authority, netloc=self.authority, path=self.path, query=self.query, fragment=self.fragment, userinfo=self.userinfo, username=self.username, password=self.password, host=self.host, hostname=self.hostname, port=self.port, resource=self.resource, url=self.url, encoding=self.encoding, )
python
def to_dict(self): '''Return a dict of the attributes.''' return dict( raw=self.raw, scheme=self.scheme, authority=self.authority, netloc=self.authority, path=self.path, query=self.query, fragment=self.fragment, userinfo=self.userinfo, username=self.username, password=self.password, host=self.host, hostname=self.hostname, port=self.port, resource=self.resource, url=self.url, encoding=self.encoding, )
[ "def", "to_dict", "(", "self", ")", ":", "return", "dict", "(", "raw", "=", "self", ".", "raw", ",", "scheme", "=", "self", ".", "scheme", ",", "authority", "=", "self", ".", "authority", ",", "netloc", "=", "self", ".", "authority", ",", "path", "...
Return a dict of the attributes.
[ "Return", "a", "dict", "of", "the", "attributes", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/url.py#L330-L349
train
201,222
ArchiveTeam/wpull
wpull/url.py
URLInfo.is_port_default
def is_port_default(self): '''Return whether the URL is using the default port.''' if self.scheme in RELATIVE_SCHEME_DEFAULT_PORTS: return RELATIVE_SCHEME_DEFAULT_PORTS[self.scheme] == self.port
python
def is_port_default(self): '''Return whether the URL is using the default port.''' if self.scheme in RELATIVE_SCHEME_DEFAULT_PORTS: return RELATIVE_SCHEME_DEFAULT_PORTS[self.scheme] == self.port
[ "def", "is_port_default", "(", "self", ")", ":", "if", "self", ".", "scheme", "in", "RELATIVE_SCHEME_DEFAULT_PORTS", ":", "return", "RELATIVE_SCHEME_DEFAULT_PORTS", "[", "self", ".", "scheme", "]", "==", "self", ".", "port" ]
Return whether the URL is using the default port.
[ "Return", "whether", "the", "URL", "is", "using", "the", "default", "port", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/url.py#L351-L354
train
201,223
ArchiveTeam/wpull
wpull/url.py
URLInfo.hostname_with_port
def hostname_with_port(self): '''Return the host portion but omit default port if needed.''' default_port = RELATIVE_SCHEME_DEFAULT_PORTS.get(self.scheme) if not default_port: return '' assert '[' not in self.hostname assert ']' not in self.hostname if self.is_ipv6(): hostname = '[{}]'.format(self.hostname) else: hostname = self.hostname if default_port != self.port: return '{}:{}'.format(hostname, self.port) else: return hostname
python
def hostname_with_port(self): '''Return the host portion but omit default port if needed.''' default_port = RELATIVE_SCHEME_DEFAULT_PORTS.get(self.scheme) if not default_port: return '' assert '[' not in self.hostname assert ']' not in self.hostname if self.is_ipv6(): hostname = '[{}]'.format(self.hostname) else: hostname = self.hostname if default_port != self.port: return '{}:{}'.format(hostname, self.port) else: return hostname
[ "def", "hostname_with_port", "(", "self", ")", ":", "default_port", "=", "RELATIVE_SCHEME_DEFAULT_PORTS", ".", "get", "(", "self", ".", "scheme", ")", "if", "not", "default_port", ":", "return", "''", "assert", "'['", "not", "in", "self", ".", "hostname", "a...
Return the host portion but omit default port if needed.
[ "Return", "the", "host", "portion", "but", "omit", "default", "port", "if", "needed", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/url.py#L362-L379
train
201,224
ArchiveTeam/wpull
wpull/processor/coprocessor/proxy.py
ProxyCoprocessorSession._new_url_record
def _new_url_record(cls, request: Request) -> URLRecord: '''Return new empty URLRecord.''' url_record = URLRecord() url_record.url = request.url_info.url url_record.status = Status.in_progress url_record.try_count = 0 url_record.level = 0 return url_record
python
def _new_url_record(cls, request: Request) -> URLRecord: '''Return new empty URLRecord.''' url_record = URLRecord() url_record.url = request.url_info.url url_record.status = Status.in_progress url_record.try_count = 0 url_record.level = 0 return url_record
[ "def", "_new_url_record", "(", "cls", ",", "request", ":", "Request", ")", "->", "URLRecord", ":", "url_record", "=", "URLRecord", "(", ")", "url_record", ".", "url", "=", "request", ".", "url_info", ".", "url", "url_record", ".", "status", "=", "Status", ...
Return new empty URLRecord.
[ "Return", "new", "empty", "URLRecord", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/coprocessor/proxy.py#L93-L102
train
201,225
ArchiveTeam/wpull
wpull/processor/coprocessor/proxy.py
ProxyCoprocessorSession._server_begin_response_callback
def _server_begin_response_callback(self, response: Response): '''Pre-response callback handler.''' self._item_session.response = response if self._cookie_jar: self._cookie_jar.extract_cookies(response, self._item_session.request) action = self._result_rule.handle_pre_response(self._item_session) self._file_writer_session.process_response(response) return action == Actions.NORMAL
python
def _server_begin_response_callback(self, response: Response): '''Pre-response callback handler.''' self._item_session.response = response if self._cookie_jar: self._cookie_jar.extract_cookies(response, self._item_session.request) action = self._result_rule.handle_pre_response(self._item_session) self._file_writer_session.process_response(response) return action == Actions.NORMAL
[ "def", "_server_begin_response_callback", "(", "self", ",", "response", ":", "Response", ")", ":", "self", ".", "_item_session", ".", "response", "=", "response", "if", "self", ".", "_cookie_jar", ":", "self", ".", "_cookie_jar", ".", "extract_cookies", "(", "...
Pre-response callback handler.
[ "Pre", "-", "response", "callback", "handler", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/coprocessor/proxy.py#L129-L139
train
201,226
ArchiveTeam/wpull
wpull/processor/coprocessor/proxy.py
ProxyCoprocessorSession._server_end_response_callback
def _server_end_response_callback(self, respoonse: Response): '''Response callback handler.''' request = self._item_session.request response = self._item_session.response _logger.info(__( _('Fetched ‘{url}’: {status_code} {reason}. ' 'Length: {content_length} [{content_type}].'), url=request.url, status_code=response.status_code, reason=wpull.string.printable_str(response.reason), content_length=wpull.string.printable_str( response.fields.get('Content-Length', _('none'))), content_type=wpull.string.printable_str( response.fields.get('Content-Type', _('none'))), )) self._result_rule.handle_response(self._item_session) if response.status_code in WebProcessor.DOCUMENT_STATUS_CODES: filename = self._file_writer_session.save_document(response) self._processing_rule.scrape_document(self._item_session) self._result_rule.handle_document(self._item_session, filename) elif response.status_code in WebProcessor.NO_DOCUMENT_STATUS_CODES: self._file_writer_session.discard_document(response) self._result_rule.handle_no_document(self._item_session) else: self._file_writer_session.discard_document(response) self._result_rule.handle_document_error(self._item_session)
python
def _server_end_response_callback(self, respoonse: Response): '''Response callback handler.''' request = self._item_session.request response = self._item_session.response _logger.info(__( _('Fetched ‘{url}’: {status_code} {reason}. ' 'Length: {content_length} [{content_type}].'), url=request.url, status_code=response.status_code, reason=wpull.string.printable_str(response.reason), content_length=wpull.string.printable_str( response.fields.get('Content-Length', _('none'))), content_type=wpull.string.printable_str( response.fields.get('Content-Type', _('none'))), )) self._result_rule.handle_response(self._item_session) if response.status_code in WebProcessor.DOCUMENT_STATUS_CODES: filename = self._file_writer_session.save_document(response) self._processing_rule.scrape_document(self._item_session) self._result_rule.handle_document(self._item_session, filename) elif response.status_code in WebProcessor.NO_DOCUMENT_STATUS_CODES: self._file_writer_session.discard_document(response) self._result_rule.handle_no_document(self._item_session) else: self._file_writer_session.discard_document(response) self._result_rule.handle_document_error(self._item_session)
[ "def", "_server_end_response_callback", "(", "self", ",", "respoonse", ":", "Response", ")", ":", "request", "=", "self", ".", "_item_session", ".", "request", "response", "=", "self", ".", "_item_session", ".", "response", "_logger", ".", "info", "(", "__", ...
Response callback handler.
[ "Response", "callback", "handler", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/coprocessor/proxy.py#L141-L170
train
201,227
ArchiveTeam/wpull
wpull/protocol/ftp/client.py
Session._init_stream
def _init_stream(self): '''Create streams and commander. Coroutine. ''' assert not self._control_connection self._control_connection = yield from self._acquire_request_connection(self._request) self._control_stream = ControlStream(self._control_connection) self._commander = Commander(self._control_stream) read_callback = functools.partial(self.event_dispatcher.notify, self.Event.control_receive_data) self._control_stream.data_event_dispatcher.add_read_listener(read_callback) write_callback = functools.partial(self.event_dispatcher.notify, self.Event.control_send_data) self._control_stream.data_event_dispatcher.add_write_listener(write_callback)
python
def _init_stream(self): '''Create streams and commander. Coroutine. ''' assert not self._control_connection self._control_connection = yield from self._acquire_request_connection(self._request) self._control_stream = ControlStream(self._control_connection) self._commander = Commander(self._control_stream) read_callback = functools.partial(self.event_dispatcher.notify, self.Event.control_receive_data) self._control_stream.data_event_dispatcher.add_read_listener(read_callback) write_callback = functools.partial(self.event_dispatcher.notify, self.Event.control_send_data) self._control_stream.data_event_dispatcher.add_write_listener(write_callback)
[ "def", "_init_stream", "(", "self", ")", ":", "assert", "not", "self", ".", "_control_connection", "self", ".", "_control_connection", "=", "yield", "from", "self", ".", "_acquire_request_connection", "(", "self", ".", "_request", ")", "self", ".", "_control_str...
Create streams and commander. Coroutine.
[ "Create", "streams", "and", "commander", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/client.py#L74-L88
train
201,228
ArchiveTeam/wpull
wpull/protocol/ftp/client.py
Session._log_in
def _log_in(self): '''Connect and login. Coroutine. ''' username = self._request.url_info.username or self._request.username or 'anonymous' password = self._request.url_info.password or self._request.password or '-wpull@' cached_login = self._login_table.get(self._control_connection) if cached_login and cached_login == (username, password): _logger.debug('Reusing existing login.') return try: yield from self._commander.login(username, password) except FTPServerError as error: raise AuthenticationError('Login error: {}'.format(error)) \ from error self._login_table[self._control_connection] = (username, password)
python
def _log_in(self): '''Connect and login. Coroutine. ''' username = self._request.url_info.username or self._request.username or 'anonymous' password = self._request.url_info.password or self._request.password or '-wpull@' cached_login = self._login_table.get(self._control_connection) if cached_login and cached_login == (username, password): _logger.debug('Reusing existing login.') return try: yield from self._commander.login(username, password) except FTPServerError as error: raise AuthenticationError('Login error: {}'.format(error)) \ from error self._login_table[self._control_connection] = (username, password)
[ "def", "_log_in", "(", "self", ")", ":", "username", "=", "self", ".", "_request", ".", "url_info", ".", "username", "or", "self", ".", "_request", ".", "username", "or", "'anonymous'", "password", "=", "self", ".", "_request", ".", "url_info", ".", "pas...
Connect and login. Coroutine.
[ "Connect", "and", "login", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/client.py#L91-L111
train
201,229
ArchiveTeam/wpull
wpull/protocol/ftp/client.py
Session.start
def start(self, request: Request) -> Response: '''Start a file or directory listing download. Args: request: Request. Returns: A Response populated with the initial data connection reply. Once the response is received, call :meth:`download`. Coroutine. ''' if self._session_state != SessionState.ready: raise RuntimeError('Session not ready') response = Response() yield from self._prepare_fetch(request, response) response.file_transfer_size = yield from self._fetch_size(request) if request.restart_value: try: yield from self._commander.restart(request.restart_value) response.restart_value = request.restart_value except FTPServerError: _logger.debug('Could not restart file.', exc_info=1) yield from self._open_data_stream() command = Command('RETR', request.file_path) yield from self._begin_stream(command) self._session_state = SessionState.file_request_sent return response
python
def start(self, request: Request) -> Response: '''Start a file or directory listing download. Args: request: Request. Returns: A Response populated with the initial data connection reply. Once the response is received, call :meth:`download`. Coroutine. ''' if self._session_state != SessionState.ready: raise RuntimeError('Session not ready') response = Response() yield from self._prepare_fetch(request, response) response.file_transfer_size = yield from self._fetch_size(request) if request.restart_value: try: yield from self._commander.restart(request.restart_value) response.restart_value = request.restart_value except FTPServerError: _logger.debug('Could not restart file.', exc_info=1) yield from self._open_data_stream() command = Command('RETR', request.file_path) yield from self._begin_stream(command) self._session_state = SessionState.file_request_sent return response
[ "def", "start", "(", "self", ",", "request", ":", "Request", ")", "->", "Response", ":", "if", "self", ".", "_session_state", "!=", "SessionState", ".", "ready", ":", "raise", "RuntimeError", "(", "'Session not ready'", ")", "response", "=", "Response", "(",...
Start a file or directory listing download. Args: request: Request. Returns: A Response populated with the initial data connection reply. Once the response is received, call :meth:`download`. Coroutine.
[ "Start", "a", "file", "or", "directory", "listing", "download", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/client.py#L114-L151
train
201,230
ArchiveTeam/wpull
wpull/protocol/ftp/client.py
Session.start_listing
def start_listing(self, request: Request) -> ListingResponse: '''Fetch a file listing. Args: request: Request. Returns: A listing response populated with the initial data connection reply. Once the response is received, call :meth:`download_listing`. Coroutine. ''' if self._session_state != SessionState.ready: raise RuntimeError('Session not ready') response = ListingResponse() yield from self._prepare_fetch(request, response) yield from self._open_data_stream() mlsd_command = Command('MLSD', self._request.file_path) list_command = Command('LIST', self._request.file_path) try: yield from self._begin_stream(mlsd_command) self._listing_type = 'mlsd' except FTPServerError as error: if error.reply_code in (ReplyCodes.syntax_error_command_unrecognized, ReplyCodes.command_not_implemented): self._listing_type = None else: raise if not self._listing_type: # This code not in exception handler to avoid incorrect # exception chaining yield from self._begin_stream(list_command) self._listing_type = 'list' _logger.debug('Listing type is %s', self._listing_type) self._session_state = SessionState.directory_request_sent return response
python
def start_listing(self, request: Request) -> ListingResponse: '''Fetch a file listing. Args: request: Request. Returns: A listing response populated with the initial data connection reply. Once the response is received, call :meth:`download_listing`. Coroutine. ''' if self._session_state != SessionState.ready: raise RuntimeError('Session not ready') response = ListingResponse() yield from self._prepare_fetch(request, response) yield from self._open_data_stream() mlsd_command = Command('MLSD', self._request.file_path) list_command = Command('LIST', self._request.file_path) try: yield from self._begin_stream(mlsd_command) self._listing_type = 'mlsd' except FTPServerError as error: if error.reply_code in (ReplyCodes.syntax_error_command_unrecognized, ReplyCodes.command_not_implemented): self._listing_type = None else: raise if not self._listing_type: # This code not in exception handler to avoid incorrect # exception chaining yield from self._begin_stream(list_command) self._listing_type = 'list' _logger.debug('Listing type is %s', self._listing_type) self._session_state = SessionState.directory_request_sent return response
[ "def", "start_listing", "(", "self", ",", "request", ":", "Request", ")", "->", "ListingResponse", ":", "if", "self", ".", "_session_state", "!=", "SessionState", ".", "ready", ":", "raise", "RuntimeError", "(", "'Session not ready'", ")", "response", "=", "Li...
Fetch a file listing. Args: request: Request. Returns: A listing response populated with the initial data connection reply. Once the response is received, call :meth:`download_listing`. Coroutine.
[ "Fetch", "a", "file", "listing", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/client.py#L154-L199
train
201,231
ArchiveTeam/wpull
wpull/protocol/ftp/client.py
Session._prepare_fetch
def _prepare_fetch(self, request: Request, response: Response): '''Prepare for a fetch. Coroutine. ''' self._request = request self._response = response yield from self._init_stream() connection_closed = self._control_connection.closed() if connection_closed: self._login_table.pop(self._control_connection, None) yield from self._control_stream.reconnect() request.address = self._control_connection.address connection_reused = not connection_closed self.event_dispatcher.notify(self.Event.begin_control, request, connection_reused=connection_reused) if connection_closed: yield from self._commander.read_welcome_message() yield from self._log_in() self._response.request = request
python
def _prepare_fetch(self, request: Request, response: Response): '''Prepare for a fetch. Coroutine. ''' self._request = request self._response = response yield from self._init_stream() connection_closed = self._control_connection.closed() if connection_closed: self._login_table.pop(self._control_connection, None) yield from self._control_stream.reconnect() request.address = self._control_connection.address connection_reused = not connection_closed self.event_dispatcher.notify(self.Event.begin_control, request, connection_reused=connection_reused) if connection_closed: yield from self._commander.read_welcome_message() yield from self._log_in() self._response.request = request
[ "def", "_prepare_fetch", "(", "self", ",", "request", ":", "Request", ",", "response", ":", "Response", ")", ":", "self", ".", "_request", "=", "request", "self", ".", "_response", "=", "response", "yield", "from", "self", ".", "_init_stream", "(", ")", ...
Prepare for a fetch. Coroutine.
[ "Prepare", "for", "a", "fetch", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/client.py#L202-L228
train
201,232
ArchiveTeam/wpull
wpull/protocol/ftp/client.py
Session._begin_stream
def _begin_stream(self, command: Command): '''Start data stream transfer.''' begin_reply = yield from self._commander.begin_stream(command) self._response.reply = begin_reply self.event_dispatcher.notify(self.Event.begin_transfer, self._response)
python
def _begin_stream(self, command: Command): '''Start data stream transfer.''' begin_reply = yield from self._commander.begin_stream(command) self._response.reply = begin_reply self.event_dispatcher.notify(self.Event.begin_transfer, self._response)
[ "def", "_begin_stream", "(", "self", ",", "command", ":", "Command", ")", ":", "begin_reply", "=", "yield", "from", "self", ".", "_commander", ".", "begin_stream", "(", "command", ")", "self", ".", "_response", ".", "reply", "=", "begin_reply", "self", "."...
Start data stream transfer.
[ "Start", "data", "stream", "transfer", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/client.py#L231-L237
train
201,233
ArchiveTeam/wpull
wpull/protocol/ftp/client.py
Session.download_listing
def download_listing(self, file: Optional[IO], duration_timeout: Optional[float]=None) -> \ ListingResponse: '''Read file listings. Args: file: A file object or asyncio stream. duration_timeout: Maximum time in seconds of which the entire file must be read. Returns: A Response populated the file listings Be sure to call :meth:`start_file_listing` first. Coroutine. ''' if self._session_state != SessionState.directory_request_sent: raise RuntimeError('File request not sent') self._session_state = SessionState.file_request_sent yield from self.download(file=file, rewind=False, duration_timeout=duration_timeout) try: if self._response.body.tell() == 0: listings = () elif self._listing_type == 'mlsd': self._response.body.seek(0) machine_listings = wpull.protocol.ftp.util.parse_machine_listing( self._response.body.read().decode('utf-8', errors='surrogateescape'), convert=True, strict=False ) listings = list( wpull.protocol.ftp.util.machine_listings_to_file_entries( machine_listings )) else: self._response.body.seek(0) file = io.TextIOWrapper(self._response.body, encoding='utf-8', errors='surrogateescape') listing_parser = ListingParser(file=file) listings = list(listing_parser.parse_input()) _logger.debug('Listing detected as %s', listing_parser.type) # We don't want the file to be closed when exiting this function file.detach() except (ListingError, ValueError) as error: raise ProtocolError(*error.args) from error self._response.files = listings self._response.body.seek(0) self._session_state = SessionState.response_received return self._response
python
def download_listing(self, file: Optional[IO], duration_timeout: Optional[float]=None) -> \ ListingResponse: '''Read file listings. Args: file: A file object or asyncio stream. duration_timeout: Maximum time in seconds of which the entire file must be read. Returns: A Response populated the file listings Be sure to call :meth:`start_file_listing` first. Coroutine. ''' if self._session_state != SessionState.directory_request_sent: raise RuntimeError('File request not sent') self._session_state = SessionState.file_request_sent yield from self.download(file=file, rewind=False, duration_timeout=duration_timeout) try: if self._response.body.tell() == 0: listings = () elif self._listing_type == 'mlsd': self._response.body.seek(0) machine_listings = wpull.protocol.ftp.util.parse_machine_listing( self._response.body.read().decode('utf-8', errors='surrogateescape'), convert=True, strict=False ) listings = list( wpull.protocol.ftp.util.machine_listings_to_file_entries( machine_listings )) else: self._response.body.seek(0) file = io.TextIOWrapper(self._response.body, encoding='utf-8', errors='surrogateescape') listing_parser = ListingParser(file=file) listings = list(listing_parser.parse_input()) _logger.debug('Listing detected as %s', listing_parser.type) # We don't want the file to be closed when exiting this function file.detach() except (ListingError, ValueError) as error: raise ProtocolError(*error.args) from error self._response.files = listings self._response.body.seek(0) self._session_state = SessionState.response_received return self._response
[ "def", "download_listing", "(", "self", ",", "file", ":", "Optional", "[", "IO", "]", ",", "duration_timeout", ":", "Optional", "[", "float", "]", "=", "None", ")", "->", "ListingResponse", ":", "if", "self", ".", "_session_state", "!=", "SessionState", "....
Read file listings. Args: file: A file object or asyncio stream. duration_timeout: Maximum time in seconds of which the entire file must be read. Returns: A Response populated the file listings Be sure to call :meth:`start_file_listing` first. Coroutine.
[ "Read", "file", "listings", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/client.py#L295-L359
train
201,234
ArchiveTeam/wpull
wpull/protocol/ftp/client.py
Session._open_data_stream
def _open_data_stream(self): '''Open the data stream connection. Coroutine. ''' @asyncio.coroutine def connection_factory(address: Tuple[int, int]): self._data_connection = yield from self._acquire_connection(address[0], address[1]) return self._data_connection self._data_stream = yield from self._commander.setup_data_stream( connection_factory ) self._response.data_address = self._data_connection.address read_callback = functools.partial(self.event_dispatcher.notify, self.Event.transfer_receive_data) self._data_stream.data_event_dispatcher.add_read_listener(read_callback) write_callback = functools.partial(self.event_dispatcher.notify, self.Event.transfer_send_data) self._data_stream.data_event_dispatcher.add_write_listener(write_callback)
python
def _open_data_stream(self): '''Open the data stream connection. Coroutine. ''' @asyncio.coroutine def connection_factory(address: Tuple[int, int]): self._data_connection = yield from self._acquire_connection(address[0], address[1]) return self._data_connection self._data_stream = yield from self._commander.setup_data_stream( connection_factory ) self._response.data_address = self._data_connection.address read_callback = functools.partial(self.event_dispatcher.notify, self.Event.transfer_receive_data) self._data_stream.data_event_dispatcher.add_read_listener(read_callback) write_callback = functools.partial(self.event_dispatcher.notify, self.Event.transfer_send_data) self._data_stream.data_event_dispatcher.add_write_listener(write_callback)
[ "def", "_open_data_stream", "(", "self", ")", ":", "@", "asyncio", ".", "coroutine", "def", "connection_factory", "(", "address", ":", "Tuple", "[", "int", ",", "int", "]", ")", ":", "self", ".", "_data_connection", "=", "yield", "from", "self", ".", "_a...
Open the data stream connection. Coroutine.
[ "Open", "the", "data", "stream", "connection", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/client.py#L362-L382
train
201,235
ArchiveTeam/wpull
wpull/protocol/ftp/client.py
Session._fetch_size
def _fetch_size(self, request: Request) -> int: '''Return size of file. Coroutine. ''' try: size = yield from self._commander.size(request.file_path) return size except FTPServerError: return
python
def _fetch_size(self, request: Request) -> int: '''Return size of file. Coroutine. ''' try: size = yield from self._commander.size(request.file_path) return size except FTPServerError: return
[ "def", "_fetch_size", "(", "self", ",", "request", ":", "Request", ")", "->", "int", ":", "try", ":", "size", "=", "yield", "from", "self", ".", "_commander", ".", "size", "(", "request", ".", "file_path", ")", "return", "size", "except", "FTPServerError...
Return size of file. Coroutine.
[ "Return", "size", "of", "file", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/client.py#L385-L394
train
201,236
ArchiveTeam/wpull
wpull/scraper/util.py
parse_refresh
def parse_refresh(text): '''Parses text for HTTP Refresh URL. Returns: str, None ''' match = re.search(r'url\s*=(.+)', text, re.IGNORECASE) if match: url = match.group(1) if url.startswith('"'): url = url.strip('"') elif url.startswith("'"): url = url.strip("'") return clean_link_soup(url)
python
def parse_refresh(text): '''Parses text for HTTP Refresh URL. Returns: str, None ''' match = re.search(r'url\s*=(.+)', text, re.IGNORECASE) if match: url = match.group(1) if url.startswith('"'): url = url.strip('"') elif url.startswith("'"): url = url.strip("'") return clean_link_soup(url)
[ "def", "parse_refresh", "(", "text", ")", ":", "match", "=", "re", ".", "search", "(", "r'url\\s*=(.+)'", ",", "text", ",", "re", ".", "IGNORECASE", ")", "if", "match", ":", "url", "=", "match", ".", "group", "(", "1", ")", "if", "url", ".", "start...
Parses text for HTTP Refresh URL. Returns: str, None
[ "Parses", "text", "for", "HTTP", "Refresh", "URL", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/scraper/util.py#L19-L35
train
201,237
ArchiveTeam/wpull
wpull/scraper/util.py
is_likely_inline
def is_likely_inline(link): '''Return whether the link is likely to be inline.''' file_type = mimetypes.guess_type(link, strict=False)[0] if file_type: top_level_type, subtype = file_type.split('/', 1) return top_level_type in ('image', 'video', 'audio') or subtype == 'javascript'
python
def is_likely_inline(link): '''Return whether the link is likely to be inline.''' file_type = mimetypes.guess_type(link, strict=False)[0] if file_type: top_level_type, subtype = file_type.split('/', 1) return top_level_type in ('image', 'video', 'audio') or subtype == 'javascript'
[ "def", "is_likely_inline", "(", "link", ")", ":", "file_type", "=", "mimetypes", ".", "guess_type", "(", "link", ",", "strict", "=", "False", ")", "[", "0", "]", "if", "file_type", ":", "top_level_type", ",", "subtype", "=", "file_type", ".", "split", "(...
Return whether the link is likely to be inline.
[ "Return", "whether", "the", "link", "is", "likely", "to", "be", "inline", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/scraper/util.py#L84-L91
train
201,238
ArchiveTeam/wpull
wpull/scraper/util.py
is_likely_link
def is_likely_link(text): '''Return whether the text is likely to be a link. This function assumes that leading/trailing whitespace has already been removed. Returns: bool ''' text = text.lower() # Check for absolute or relative URLs if ( text.startswith('http://') or text.startswith('https://') or text.startswith('ftp://') or text.startswith('/') or text.startswith('//') or text.endswith('/') or text.startswith('../') ): return True # Check if it has a alphanumeric file extension and not a decimal number dummy, dot, file_extension = text.rpartition('.') if dot and file_extension and len(file_extension) <= 4: file_extension_set = frozenset(file_extension) if file_extension_set \ and file_extension_set <= ALPHANUMERIC_CHARS \ and not file_extension_set <= NUMERIC_CHARS: if file_extension in COMMON_TLD: return False file_type = mimetypes.guess_type(text, strict=False)[0] if file_type: return True else: return False
python
def is_likely_link(text): '''Return whether the text is likely to be a link. This function assumes that leading/trailing whitespace has already been removed. Returns: bool ''' text = text.lower() # Check for absolute or relative URLs if ( text.startswith('http://') or text.startswith('https://') or text.startswith('ftp://') or text.startswith('/') or text.startswith('//') or text.endswith('/') or text.startswith('../') ): return True # Check if it has a alphanumeric file extension and not a decimal number dummy, dot, file_extension = text.rpartition('.') if dot and file_extension and len(file_extension) <= 4: file_extension_set = frozenset(file_extension) if file_extension_set \ and file_extension_set <= ALPHANUMERIC_CHARS \ and not file_extension_set <= NUMERIC_CHARS: if file_extension in COMMON_TLD: return False file_type = mimetypes.guess_type(text, strict=False)[0] if file_type: return True else: return False
[ "def", "is_likely_link", "(", "text", ")", ":", "text", "=", "text", ".", "lower", "(", ")", "# Check for absolute or relative URLs", "if", "(", "text", ".", "startswith", "(", "'http://'", ")", "or", "text", ".", "startswith", "(", "'https://'", ")", "or", ...
Return whether the text is likely to be a link. This function assumes that leading/trailing whitespace has already been removed. Returns: bool
[ "Return", "whether", "the", "text", "is", "likely", "to", "be", "a", "link", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/scraper/util.py#L136-L176
train
201,239
ArchiveTeam/wpull
wpull/scraper/util.py
is_unlikely_link
def is_unlikely_link(text): '''Return whether the text is likely to cause false positives. This function assumes that leading/trailing whitespace has already been removed. Returns: bool ''' # Check for string concatenation in JavaScript if text[:1] in ',;+:' or text[-1:] in '.,;+:': return True # Check for unusual characters if re.search(r'''[\\$()'"[\]{}|<>`]''', text): return True if text[:1] == '.' \ and not text.startswith('./') \ and not text.startswith('../'): return True if text in ('/', '//'): return True if '//' in text and '://' not in text and not text.startswith('//'): return True # Forbid strings like mimetypes if text in MIMETYPES: return True tag_1, dummy, tag_2 = text.partition('.') if tag_1 in HTML_TAGS and tag_2 != 'html': return True # Forbid things where the first part of the path looks like a domain name if FIRST_PART_TLD_PATTERN.match(text): return True
python
def is_unlikely_link(text): '''Return whether the text is likely to cause false positives. This function assumes that leading/trailing whitespace has already been removed. Returns: bool ''' # Check for string concatenation in JavaScript if text[:1] in ',;+:' or text[-1:] in '.,;+:': return True # Check for unusual characters if re.search(r'''[\\$()'"[\]{}|<>`]''', text): return True if text[:1] == '.' \ and not text.startswith('./') \ and not text.startswith('../'): return True if text in ('/', '//'): return True if '//' in text and '://' not in text and not text.startswith('//'): return True # Forbid strings like mimetypes if text in MIMETYPES: return True tag_1, dummy, tag_2 = text.partition('.') if tag_1 in HTML_TAGS and tag_2 != 'html': return True # Forbid things where the first part of the path looks like a domain name if FIRST_PART_TLD_PATTERN.match(text): return True
[ "def", "is_unlikely_link", "(", "text", ")", ":", "# Check for string concatenation in JavaScript", "if", "text", "[", ":", "1", "]", "in", "',;+:'", "or", "text", "[", "-", "1", ":", "]", "in", "'.,;+:'", ":", "return", "True", "# Check for unusual characters",...
Return whether the text is likely to cause false positives. This function assumes that leading/trailing whitespace has already been removed. Returns: bool
[ "Return", "whether", "the", "text", "is", "likely", "to", "cause", "false", "positives", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/scraper/util.py#L179-L217
train
201,240
ArchiveTeam/wpull
wpull/scraper/util.py
identify_link_type
def identify_link_type(filename): '''Return link type guessed by filename extension. Returns: str: A value from :class:`.item.LinkType`. ''' mime_type = mimetypes.guess_type(filename)[0] if not mime_type: return if mime_type == 'text/css': return LinkType.css elif mime_type == 'application/javascript': return LinkType.javascript elif mime_type == 'text/html' or mime_type.endswith('xml'): return LinkType.html elif mime_type.startswith('video') or \ mime_type.startswith('image') or \ mime_type.startswith('audio') or \ mime_type.endswith('shockwave-flash'): return LinkType.media
python
def identify_link_type(filename): '''Return link type guessed by filename extension. Returns: str: A value from :class:`.item.LinkType`. ''' mime_type = mimetypes.guess_type(filename)[0] if not mime_type: return if mime_type == 'text/css': return LinkType.css elif mime_type == 'application/javascript': return LinkType.javascript elif mime_type == 'text/html' or mime_type.endswith('xml'): return LinkType.html elif mime_type.startswith('video') or \ mime_type.startswith('image') or \ mime_type.startswith('audio') or \ mime_type.endswith('shockwave-flash'): return LinkType.media
[ "def", "identify_link_type", "(", "filename", ")", ":", "mime_type", "=", "mimetypes", ".", "guess_type", "(", "filename", ")", "[", "0", "]", "if", "not", "mime_type", ":", "return", "if", "mime_type", "==", "'text/css'", ":", "return", "LinkType", ".", "...
Return link type guessed by filename extension. Returns: str: A value from :class:`.item.LinkType`.
[ "Return", "link", "type", "guessed", "by", "filename", "extension", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/scraper/util.py#L221-L242
train
201,241
ArchiveTeam/wpull
wpull/pipeline/app.py
new_encoded_stream
def new_encoded_stream(args, stream): '''Return a stream writer.''' if args.ascii_print: return wpull.util.ASCIIStreamWriter(stream) else: return stream
python
def new_encoded_stream(args, stream): '''Return a stream writer.''' if args.ascii_print: return wpull.util.ASCIIStreamWriter(stream) else: return stream
[ "def", "new_encoded_stream", "(", "args", ",", "stream", ")", ":", "if", "args", ".", "ascii_print", ":", "return", "wpull", ".", "util", ".", "ASCIIStreamWriter", "(", "stream", ")", "else", ":", "return", "stream" ]
Return a stream writer.
[ "Return", "a", "stream", "writer", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/pipeline/app.py#L41-L46
train
201,242
ArchiveTeam/wpull
wpull/network/connection.py
CloseTimer._schedule
def _schedule(self): '''Schedule check function.''' if self._running: _logger.debug('Schedule check function.') self._call_later_handle = self._event_loop.call_later( self._timeout, self._check)
python
def _schedule(self): '''Schedule check function.''' if self._running: _logger.debug('Schedule check function.') self._call_later_handle = self._event_loop.call_later( self._timeout, self._check)
[ "def", "_schedule", "(", "self", ")", ":", "if", "self", ".", "_running", ":", "_logger", ".", "debug", "(", "'Schedule check function.'", ")", "self", ".", "_call_later_handle", "=", "self", ".", "_event_loop", ".", "call_later", "(", "self", ".", "_timeout...
Schedule check function.
[ "Schedule", "check", "function", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/connection.py#L36-L41
train
201,243
ArchiveTeam/wpull
wpull/network/connection.py
CloseTimer._check
def _check(self): '''Check and close connection if needed.''' _logger.debug('Check if timeout.') self._call_later_handle = None if self._touch_time is not None: difference = self._event_loop.time() - self._touch_time _logger.debug('Time difference %s', difference) if difference > self._timeout: self._connection.close() self._timed_out = True if not self._connection.closed(): self._schedule()
python
def _check(self): '''Check and close connection if needed.''' _logger.debug('Check if timeout.') self._call_later_handle = None if self._touch_time is not None: difference = self._event_loop.time() - self._touch_time _logger.debug('Time difference %s', difference) if difference > self._timeout: self._connection.close() self._timed_out = True if not self._connection.closed(): self._schedule()
[ "def", "_check", "(", "self", ")", ":", "_logger", ".", "debug", "(", "'Check if timeout.'", ")", "self", ".", "_call_later_handle", "=", "None", "if", "self", ".", "_touch_time", "is", "not", "None", ":", "difference", "=", "self", ".", "_event_loop", "."...
Check and close connection if needed.
[ "Check", "and", "close", "connection", "if", "needed", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/connection.py#L43-L57
train
201,244
ArchiveTeam/wpull
wpull/network/connection.py
CloseTimer.close
def close(self): '''Stop running timers.''' if self._call_later_handle: self._call_later_handle.cancel() self._running = False
python
def close(self): '''Stop running timers.''' if self._call_later_handle: self._call_later_handle.cancel() self._running = False
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_call_later_handle", ":", "self", ".", "_call_later_handle", ".", "cancel", "(", ")", "self", ".", "_running", "=", "False" ]
Stop running timers.
[ "Stop", "running", "timers", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/connection.py#L59-L64
train
201,245
ArchiveTeam/wpull
wpull/network/connection.py
BaseConnection.closed
def closed(self) -> bool: '''Return whether the connection is closed.''' return not self.writer or not self.reader or self.reader.at_eof()
python
def closed(self) -> bool: '''Return whether the connection is closed.''' return not self.writer or not self.reader or self.reader.at_eof()
[ "def", "closed", "(", "self", ")", "->", "bool", ":", "return", "not", "self", ".", "writer", "or", "not", "self", ".", "reader", "or", "self", ".", "reader", ".", "at_eof", "(", ")" ]
Return whether the connection is closed.
[ "Return", "whether", "the", "connection", "is", "closed", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/connection.py#L161-L163
train
201,246
ArchiveTeam/wpull
wpull/network/connection.py
BaseConnection.connect
def connect(self): '''Establish a connection.''' _logger.debug(__('Connecting to {0}.', self._address)) if self._state != ConnectionState.ready: raise Exception('Closed connection must be reset before reusing.') if self._sock: connection_future = asyncio.open_connection( sock=self._sock, **self._connection_kwargs() ) else: # TODO: maybe we don't want to ignore flow-info and scope-id? host = self._address[0] port = self._address[1] connection_future = asyncio.open_connection( host, port, **self._connection_kwargs() ) self.reader, self.writer = yield from \ self.run_network_operation( connection_future, wait_timeout=self._connect_timeout, name='Connect') if self._timeout is not None: self._close_timer = CloseTimer(self._timeout, self) else: self._close_timer = DummyCloseTimer() self._state = ConnectionState.created _logger.debug('Connected.')
python
def connect(self): '''Establish a connection.''' _logger.debug(__('Connecting to {0}.', self._address)) if self._state != ConnectionState.ready: raise Exception('Closed connection must be reset before reusing.') if self._sock: connection_future = asyncio.open_connection( sock=self._sock, **self._connection_kwargs() ) else: # TODO: maybe we don't want to ignore flow-info and scope-id? host = self._address[0] port = self._address[1] connection_future = asyncio.open_connection( host, port, **self._connection_kwargs() ) self.reader, self.writer = yield from \ self.run_network_operation( connection_future, wait_timeout=self._connect_timeout, name='Connect') if self._timeout is not None: self._close_timer = CloseTimer(self._timeout, self) else: self._close_timer = DummyCloseTimer() self._state = ConnectionState.created _logger.debug('Connected.')
[ "def", "connect", "(", "self", ")", ":", "_logger", ".", "debug", "(", "__", "(", "'Connecting to {0}.'", ",", "self", ".", "_address", ")", ")", "if", "self", ".", "_state", "!=", "ConnectionState", ".", "ready", ":", "raise", "Exception", "(", "'Closed...
Establish a connection.
[ "Establish", "a", "connection", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/connection.py#L170-L202
train
201,247
ArchiveTeam/wpull
wpull/network/connection.py
BaseConnection.readline
def readline(self) -> bytes: '''Read a line of data.''' assert self._state == ConnectionState.created, \ 'Expect conn created. Got {}.'.format(self._state) with self._close_timer.with_timeout(): data = yield from \ self.run_network_operation( self.reader.readline(), close_timeout=self._timeout, name='Readline') return data
python
def readline(self) -> bytes: '''Read a line of data.''' assert self._state == ConnectionState.created, \ 'Expect conn created. Got {}.'.format(self._state) with self._close_timer.with_timeout(): data = yield from \ self.run_network_operation( self.reader.readline(), close_timeout=self._timeout, name='Readline') return data
[ "def", "readline", "(", "self", ")", "->", "bytes", ":", "assert", "self", ".", "_state", "==", "ConnectionState", ".", "created", ",", "'Expect conn created. Got {}.'", ".", "format", "(", "self", ".", "_state", ")", "with", "self", ".", "_close_timer", "."...
Read a line of data.
[ "Read", "a", "line", "of", "data", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/connection.py#L262-L274
train
201,248
ArchiveTeam/wpull
wpull/network/connection.py
BaseConnection.run_network_operation
def run_network_operation(self, task, wait_timeout=None, close_timeout=None, name='Network operation'): '''Run the task and raise appropriate exceptions. Coroutine. ''' if wait_timeout is not None and close_timeout is not None: raise Exception( 'Cannot use wait_timeout and close_timeout at the same time') try: if close_timeout is not None: with self._close_timer.with_timeout(): data = yield from task if self._close_timer.is_timeout(): raise NetworkTimedOut( '{name} timed out.'.format(name=name)) else: return data elif wait_timeout is not None: data = yield from asyncio.wait_for(task, wait_timeout) return data else: return (yield from task) except asyncio.TimeoutError as error: self.close() raise NetworkTimedOut( '{name} timed out.'.format(name=name)) from error except (tornado.netutil.SSLCertificateError, SSLVerificationError) \ as error: self.close() raise SSLVerificationError( '{name} certificate error: {error}' .format(name=name, error=error)) from error except AttributeError as error: self.close() raise NetworkError( '{name} network error: connection closed unexpectedly: {error}' .format(name=name, error=error)) from error except (socket.error, ssl.SSLError, OSError, IOError) as error: self.close() if isinstance(error, NetworkError): raise if error.errno == errno.ECONNREFUSED: raise ConnectionRefused( error.errno, os.strerror(error.errno)) from error # XXX: This quality case brought to you by OpenSSL and Python. # Example: _ssl.SSLError: [Errno 1] error:14094418:SSL # routines:SSL3_READ_BYTES:tlsv1 alert unknown ca error_string = str(error).lower() if 'certificate' in error_string or 'unknown ca' in error_string: raise SSLVerificationError( '{name} certificate error: {error}' .format(name=name, error=error)) from error else: if error.errno: raise NetworkError( error.errno, os.strerror(error.errno)) from error else: raise NetworkError( '{name} network error: {error}' .format(name=name, error=error)) from error
python
def run_network_operation(self, task, wait_timeout=None, close_timeout=None, name='Network operation'): '''Run the task and raise appropriate exceptions. Coroutine. ''' if wait_timeout is not None and close_timeout is not None: raise Exception( 'Cannot use wait_timeout and close_timeout at the same time') try: if close_timeout is not None: with self._close_timer.with_timeout(): data = yield from task if self._close_timer.is_timeout(): raise NetworkTimedOut( '{name} timed out.'.format(name=name)) else: return data elif wait_timeout is not None: data = yield from asyncio.wait_for(task, wait_timeout) return data else: return (yield from task) except asyncio.TimeoutError as error: self.close() raise NetworkTimedOut( '{name} timed out.'.format(name=name)) from error except (tornado.netutil.SSLCertificateError, SSLVerificationError) \ as error: self.close() raise SSLVerificationError( '{name} certificate error: {error}' .format(name=name, error=error)) from error except AttributeError as error: self.close() raise NetworkError( '{name} network error: connection closed unexpectedly: {error}' .format(name=name, error=error)) from error except (socket.error, ssl.SSLError, OSError, IOError) as error: self.close() if isinstance(error, NetworkError): raise if error.errno == errno.ECONNREFUSED: raise ConnectionRefused( error.errno, os.strerror(error.errno)) from error # XXX: This quality case brought to you by OpenSSL and Python. # Example: _ssl.SSLError: [Errno 1] error:14094418:SSL # routines:SSL3_READ_BYTES:tlsv1 alert unknown ca error_string = str(error).lower() if 'certificate' in error_string or 'unknown ca' in error_string: raise SSLVerificationError( '{name} certificate error: {error}' .format(name=name, error=error)) from error else: if error.errno: raise NetworkError( error.errno, os.strerror(error.errno)) from error else: raise NetworkError( '{name} network error: {error}' .format(name=name, error=error)) from error
[ "def", "run_network_operation", "(", "self", ",", "task", ",", "wait_timeout", "=", "None", ",", "close_timeout", "=", "None", ",", "name", "=", "'Network operation'", ")", ":", "if", "wait_timeout", "is", "not", "None", "and", "close_timeout", "is", "not", ...
Run the task and raise appropriate exceptions. Coroutine.
[ "Run", "the", "task", "and", "raise", "appropriate", "exceptions", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/connection.py#L277-L345
train
201,249
ArchiveTeam/wpull
wpull/network/connection.py
Connection.start_tls
def start_tls(self, ssl_context: Union[bool, dict, ssl.SSLContext]=True) \ -> 'SSLConnection': '''Start client TLS on this connection and return SSLConnection. Coroutine ''' sock = self.writer.get_extra_info('socket') ssl_conn = SSLConnection( self._address, ssl_context=ssl_context, hostname=self._hostname, timeout=self._timeout, connect_timeout=self._connect_timeout, bind_host=self._bind_host, bandwidth_limiter=self._bandwidth_limiter, sock=sock ) yield from ssl_conn.connect() return ssl_conn
python
def start_tls(self, ssl_context: Union[bool, dict, ssl.SSLContext]=True) \ -> 'SSLConnection': '''Start client TLS on this connection and return SSLConnection. Coroutine ''' sock = self.writer.get_extra_info('socket') ssl_conn = SSLConnection( self._address, ssl_context=ssl_context, hostname=self._hostname, timeout=self._timeout, connect_timeout=self._connect_timeout, bind_host=self._bind_host, bandwidth_limiter=self._bandwidth_limiter, sock=sock ) yield from ssl_conn.connect() return ssl_conn
[ "def", "start_tls", "(", "self", ",", "ssl_context", ":", "Union", "[", "bool", ",", "dict", ",", "ssl", ".", "SSLContext", "]", "=", "True", ")", "->", "'SSLConnection'", ":", "sock", "=", "self", ".", "writer", ".", "get_extra_info", "(", "'socket'", ...
Start client TLS on this connection and return SSLConnection. Coroutine
[ "Start", "client", "TLS", "on", "this", "connection", "and", "return", "SSLConnection", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/connection.py#L413-L430
train
201,250
ArchiveTeam/wpull
wpull/network/connection.py
SSLConnection._verify_cert
def _verify_cert(self, sock: ssl.SSLSocket): '''Check if certificate matches hostname.''' # Based on tornado.iostream.SSLIOStream # Needed for older OpenSSL (<0.9.8f) versions verify_mode = self._ssl_context.verify_mode assert verify_mode in (ssl.CERT_NONE, ssl.CERT_REQUIRED, ssl.CERT_OPTIONAL), \ 'Unknown verify mode {}'.format(verify_mode) if verify_mode == ssl.CERT_NONE: return cert = sock.getpeercert() if not cert and verify_mode == ssl.CERT_OPTIONAL: return if not cert: raise SSLVerificationError('No SSL certificate given') try: ssl.match_hostname(cert, self._hostname) except ssl.CertificateError as error: raise SSLVerificationError('Invalid SSL certificate') from error
python
def _verify_cert(self, sock: ssl.SSLSocket): '''Check if certificate matches hostname.''' # Based on tornado.iostream.SSLIOStream # Needed for older OpenSSL (<0.9.8f) versions verify_mode = self._ssl_context.verify_mode assert verify_mode in (ssl.CERT_NONE, ssl.CERT_REQUIRED, ssl.CERT_OPTIONAL), \ 'Unknown verify mode {}'.format(verify_mode) if verify_mode == ssl.CERT_NONE: return cert = sock.getpeercert() if not cert and verify_mode == ssl.CERT_OPTIONAL: return if not cert: raise SSLVerificationError('No SSL certificate given') try: ssl.match_hostname(cert, self._hostname) except ssl.CertificateError as error: raise SSLVerificationError('Invalid SSL certificate') from error
[ "def", "_verify_cert", "(", "self", ",", "sock", ":", "ssl", ".", "SSLSocket", ")", ":", "# Based on tornado.iostream.SSLIOStream", "# Needed for older OpenSSL (<0.9.8f) versions", "verify_mode", "=", "self", ".", "_ssl_context", ".", "verify_mode", "assert", "verify_mode...
Check if certificate matches hostname.
[ "Check", "if", "certificate", "matches", "hostname", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/connection.py#L476-L500
train
201,251
ArchiveTeam/wpull
wpull/cache.py
FIFOCache.trim
def trim(self): '''Remove items that are expired or exceed the max size.''' now_time = time.time() while self._seq and self._seq[0].expire_time < now_time: item = self._seq.popleft() del self._map[item.key] if self._max_items: while self._seq and len(self._seq) > self._max_items: item = self._seq.popleft() del self._map[item.key]
python
def trim(self): '''Remove items that are expired or exceed the max size.''' now_time = time.time() while self._seq and self._seq[0].expire_time < now_time: item = self._seq.popleft() del self._map[item.key] if self._max_items: while self._seq and len(self._seq) > self._max_items: item = self._seq.popleft() del self._map[item.key]
[ "def", "trim", "(", "self", ")", ":", "now_time", "=", "time", ".", "time", "(", ")", "while", "self", ".", "_seq", "and", "self", ".", "_seq", "[", "0", "]", ".", "expire_time", "<", "now_time", ":", "item", "=", "self", ".", "_seq", ".", "pople...
Remove items that are expired or exceed the max size.
[ "Remove", "items", "that", "are", "expired", "or", "exceed", "the", "max", "size", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/cache.py#L71-L82
train
201,252
ArchiveTeam/wpull
wpull/urlrewrite.py
strip_path_session_id
def strip_path_session_id(path): '''Strip session ID from URL path.''' for pattern in SESSION_ID_PATH_PATTERNS: match = pattern.match(path) if match: path = match.group(1) + match.group(3) return path
python
def strip_path_session_id(path): '''Strip session ID from URL path.''' for pattern in SESSION_ID_PATH_PATTERNS: match = pattern.match(path) if match: path = match.group(1) + match.group(3) return path
[ "def", "strip_path_session_id", "(", "path", ")", ":", "for", "pattern", "in", "SESSION_ID_PATH_PATTERNS", ":", "match", "=", "pattern", ".", "match", "(", "path", ")", "if", "match", ":", "path", "=", "match", ".", "group", "(", "1", ")", "+", "match", ...
Strip session ID from URL path.
[ "Strip", "session", "ID", "from", "URL", "path", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/urlrewrite.py#L49-L56
train
201,253
ArchiveTeam/wpull
wpull/urlrewrite.py
URLRewriter.rewrite
def rewrite(self, url_info: URLInfo) -> URLInfo: '''Rewrite the given URL.''' if url_info.scheme not in ('http', 'https'): return url_info if self._session_id_enabled: url = '{scheme}://{authority}{path}?{query}#{fragment}'.format( scheme=url_info.scheme, authority=url_info.authority, path=strip_path_session_id(url_info.path), query=strip_query_session_id(url_info.query), fragment=url_info.fragment, ) url_info = parse_url_or_log(url) or url_info if self._hash_fragment_enabled and url_info.fragment.startswith('!'): if url_info.query: url = '{}&_escaped_fragment_={}'.format(url_info.url, url_info.fragment[1:]) else: url = '{}?_escaped_fragment_={}'.format(url_info.url, url_info.fragment[1:]) url_info = parse_url_or_log(url) or url_info return url_info
python
def rewrite(self, url_info: URLInfo) -> URLInfo: '''Rewrite the given URL.''' if url_info.scheme not in ('http', 'https'): return url_info if self._session_id_enabled: url = '{scheme}://{authority}{path}?{query}#{fragment}'.format( scheme=url_info.scheme, authority=url_info.authority, path=strip_path_session_id(url_info.path), query=strip_query_session_id(url_info.query), fragment=url_info.fragment, ) url_info = parse_url_or_log(url) or url_info if self._hash_fragment_enabled and url_info.fragment.startswith('!'): if url_info.query: url = '{}&_escaped_fragment_={}'.format(url_info.url, url_info.fragment[1:]) else: url = '{}?_escaped_fragment_={}'.format(url_info.url, url_info.fragment[1:]) url_info = parse_url_or_log(url) or url_info return url_info
[ "def", "rewrite", "(", "self", ",", "url_info", ":", "URLInfo", ")", "->", "URLInfo", ":", "if", "url_info", ".", "scheme", "not", "in", "(", "'http'", ",", "'https'", ")", ":", "return", "url_info", "if", "self", ".", "_session_id_enabled", ":", "url", ...
Rewrite the given URL.
[ "Rewrite", "the", "given", "URL", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/urlrewrite.py#L13-L38
train
201,254
ArchiveTeam/wpull
wpull/protocol/ftp/util.py
parse_address
def parse_address(text: str) -> Tuple[str, int]: '''Parse PASV address.''' match = re.search( r'\(' r'(\d{1,3})\s*,' r'\s*(\d{1,3})\s*,' r'\s*(\d{1,3})\s*,' r'\s*(\d{1,3})\s*,' r'\s*(\d{1,3})\s*,' r'\s*(\d{1,3})\s*' r'\)', text) if match: return ( '{0}.{1}.{2}.{3}'.format(int(match.group(1)), int(match.group(2)), int(match.group(3)), int(match.group(4)) ), int(match.group(5)) << 8 | int(match.group(6)) ) else: raise ValueError('No address found')
python
def parse_address(text: str) -> Tuple[str, int]: '''Parse PASV address.''' match = re.search( r'\(' r'(\d{1,3})\s*,' r'\s*(\d{1,3})\s*,' r'\s*(\d{1,3})\s*,' r'\s*(\d{1,3})\s*,' r'\s*(\d{1,3})\s*,' r'\s*(\d{1,3})\s*' r'\)', text) if match: return ( '{0}.{1}.{2}.{3}'.format(int(match.group(1)), int(match.group(2)), int(match.group(3)), int(match.group(4)) ), int(match.group(5)) << 8 | int(match.group(6)) ) else: raise ValueError('No address found')
[ "def", "parse_address", "(", "text", ":", "str", ")", "->", "Tuple", "[", "str", ",", "int", "]", ":", "match", "=", "re", ".", "search", "(", "r'\\('", "r'(\\d{1,3})\\s*,'", "r'\\s*(\\d{1,3})\\s*,'", "r'\\s*(\\d{1,3})\\s*,'", "r'\\s*(\\d{1,3})\\s*,'", "r'\\s*(\\d...
Parse PASV address.
[ "Parse", "PASV", "address", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/util.py#L60-L83
train
201,255
ArchiveTeam/wpull
wpull/protocol/ftp/util.py
reply_code_tuple
def reply_code_tuple(code: int) -> Tuple[int, int, int]: '''Return the reply code as a tuple. Args: code: The reply code. Returns: Each item in the tuple is the digit. ''' return code // 100, code // 10 % 10, code % 10
python
def reply_code_tuple(code: int) -> Tuple[int, int, int]: '''Return the reply code as a tuple. Args: code: The reply code. Returns: Each item in the tuple is the digit. ''' return code // 100, code // 10 % 10, code % 10
[ "def", "reply_code_tuple", "(", "code", ":", "int", ")", "->", "Tuple", "[", "int", ",", "int", ",", "int", "]", ":", "return", "code", "//", "100", ",", "code", "//", "10", "%", "10", ",", "code", "%", "10" ]
Return the reply code as a tuple. Args: code: The reply code. Returns: Each item in the tuple is the digit.
[ "Return", "the", "reply", "code", "as", "a", "tuple", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/util.py#L86-L95
train
201,256
ArchiveTeam/wpull
wpull/protocol/ftp/util.py
parse_machine_listing
def parse_machine_listing(text: str, convert: bool=True, strict: bool=True) -> \ List[dict]: '''Parse machine listing. Args: text: The listing. convert: Convert sizes and dates. strict: Method of handling errors. ``True`` will raise ``ValueError``. ``False`` will ignore rows with errors. Returns: list: A list of dict of the facts defined in RFC 3659. The key names must be lowercase. The filename uses the key ``name``. ''' # TODO: this function should be moved into the 'ls' package listing = [] for line in text.splitlines(False): facts = line.split(';') row = {} filename = None for fact in facts: name, sep, value = fact.partition('=') if sep: name = name.strip().lower() value = value.strip().lower() if convert: try: value = convert_machine_list_value(name, value) except ValueError: if strict: raise row[name] = value else: if name[0:1] == ' ': # Is a filename filename = name[1:] else: name = name.strip().lower() row[name] = '' if filename: row['name'] = filename listing.append(row) elif strict: raise ValueError('Missing filename.') return listing
python
def parse_machine_listing(text: str, convert: bool=True, strict: bool=True) -> \ List[dict]: '''Parse machine listing. Args: text: The listing. convert: Convert sizes and dates. strict: Method of handling errors. ``True`` will raise ``ValueError``. ``False`` will ignore rows with errors. Returns: list: A list of dict of the facts defined in RFC 3659. The key names must be lowercase. The filename uses the key ``name``. ''' # TODO: this function should be moved into the 'ls' package listing = [] for line in text.splitlines(False): facts = line.split(';') row = {} filename = None for fact in facts: name, sep, value = fact.partition('=') if sep: name = name.strip().lower() value = value.strip().lower() if convert: try: value = convert_machine_list_value(name, value) except ValueError: if strict: raise row[name] = value else: if name[0:1] == ' ': # Is a filename filename = name[1:] else: name = name.strip().lower() row[name] = '' if filename: row['name'] = filename listing.append(row) elif strict: raise ValueError('Missing filename.') return listing
[ "def", "parse_machine_listing", "(", "text", ":", "str", ",", "convert", ":", "bool", "=", "True", ",", "strict", ":", "bool", "=", "True", ")", "->", "List", "[", "dict", "]", ":", "# TODO: this function should be moved into the 'ls' package", "listing", "=", ...
Parse machine listing. Args: text: The listing. convert: Convert sizes and dates. strict: Method of handling errors. ``True`` will raise ``ValueError``. ``False`` will ignore rows with errors. Returns: list: A list of dict of the facts defined in RFC 3659. The key names must be lowercase. The filename uses the key ``name``.
[ "Parse", "machine", "listing", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/util.py#L98-L150
train
201,257
ArchiveTeam/wpull
wpull/protocol/ftp/util.py
convert_machine_list_value
def convert_machine_list_value(name: str, value: str) -> \ Union[datetime.datetime, str, int]: '''Convert sizes and time values. Size will be ``int`` while time value will be :class:`datetime.datetime`. ''' if name == 'modify': return convert_machine_list_time_val(value) elif name == 'size': return int(value) else: return value
python
def convert_machine_list_value(name: str, value: str) -> \ Union[datetime.datetime, str, int]: '''Convert sizes and time values. Size will be ``int`` while time value will be :class:`datetime.datetime`. ''' if name == 'modify': return convert_machine_list_time_val(value) elif name == 'size': return int(value) else: return value
[ "def", "convert_machine_list_value", "(", "name", ":", "str", ",", "value", ":", "str", ")", "->", "Union", "[", "datetime", ".", "datetime", ",", "str", ",", "int", "]", ":", "if", "name", "==", "'modify'", ":", "return", "convert_machine_list_time_val", ...
Convert sizes and time values. Size will be ``int`` while time value will be :class:`datetime.datetime`.
[ "Convert", "sizes", "and", "time", "values", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/util.py#L153-L164
train
201,258
ArchiveTeam/wpull
wpull/protocol/ftp/util.py
convert_machine_list_time_val
def convert_machine_list_time_val(text: str) -> datetime.datetime: '''Convert RFC 3659 time-val to datetime objects.''' # TODO: implement fractional seconds text = text[:14] if len(text) != 14: raise ValueError('Time value not 14 chars') year = int(text[0:4]) month = int(text[4:6]) day = int(text[6:8]) hour = int(text[8:10]) minute = int(text[10:12]) second = int(text[12:14]) return datetime.datetime(year, month, day, hour, minute, second, tzinfo=datetime.timezone.utc)
python
def convert_machine_list_time_val(text: str) -> datetime.datetime: '''Convert RFC 3659 time-val to datetime objects.''' # TODO: implement fractional seconds text = text[:14] if len(text) != 14: raise ValueError('Time value not 14 chars') year = int(text[0:4]) month = int(text[4:6]) day = int(text[6:8]) hour = int(text[8:10]) minute = int(text[10:12]) second = int(text[12:14]) return datetime.datetime(year, month, day, hour, minute, second, tzinfo=datetime.timezone.utc)
[ "def", "convert_machine_list_time_val", "(", "text", ":", "str", ")", "->", "datetime", ".", "datetime", ":", "# TODO: implement fractional seconds", "text", "=", "text", "[", ":", "14", "]", "if", "len", "(", "text", ")", "!=", "14", ":", "raise", "ValueErr...
Convert RFC 3659 time-val to datetime objects.
[ "Convert", "RFC", "3659", "time", "-", "val", "to", "datetime", "objects", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/util.py#L167-L183
train
201,259
ArchiveTeam/wpull
wpull/protocol/ftp/util.py
machine_listings_to_file_entries
def machine_listings_to_file_entries(listings: Iterable[dict]) -> \ Iterable[FileEntry]: '''Convert results from parsing machine listings to FileEntry list.''' for listing in listings: yield FileEntry( listing['name'], type=listing.get('type'), size=listing.get('size'), date=listing.get('modify') )
python
def machine_listings_to_file_entries(listings: Iterable[dict]) -> \ Iterable[FileEntry]: '''Convert results from parsing machine listings to FileEntry list.''' for listing in listings: yield FileEntry( listing['name'], type=listing.get('type'), size=listing.get('size'), date=listing.get('modify') )
[ "def", "machine_listings_to_file_entries", "(", "listings", ":", "Iterable", "[", "dict", "]", ")", "->", "Iterable", "[", "FileEntry", "]", ":", "for", "listing", "in", "listings", ":", "yield", "FileEntry", "(", "listing", "[", "'name'", "]", ",", "type", ...
Convert results from parsing machine listings to FileEntry list.
[ "Convert", "results", "from", "parsing", "machine", "listings", "to", "FileEntry", "list", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/util.py#L186-L195
train
201,260
ArchiveTeam/wpull
wpull/protocol/ftp/util.py
FTPServerError.reply_code
def reply_code(self): '''Return reply code.''' if len(self.args) >= 2 and isinstance(self.args[1], int): return self.args[1]
python
def reply_code(self): '''Return reply code.''' if len(self.args) >= 2 and isinstance(self.args[1], int): return self.args[1]
[ "def", "reply_code", "(", "self", ")", ":", "if", "len", "(", "self", ".", "args", ")", ">=", "2", "and", "isinstance", "(", "self", ".", "args", "[", "1", "]", ",", "int", ")", ":", "return", "self", ".", "args", "[", "1", "]" ]
Return reply code.
[ "Return", "reply", "code", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/util.py#L54-L57
train
201,261
ArchiveTeam/wpull
wpull/pipeline/pipeline.py
Pipeline._run_producer_wrapper
def _run_producer_wrapper(self): '''Run the producer, if exception, stop engine.''' try: yield from self._producer.process() except Exception as error: if not isinstance(error, StopIteration): # Stop the workers so the producer exception will be handled # when we finally yield from this coroutine _logger.debug('Producer died.', exc_info=True) self.stop() raise else: self.stop()
python
def _run_producer_wrapper(self): '''Run the producer, if exception, stop engine.''' try: yield from self._producer.process() except Exception as error: if not isinstance(error, StopIteration): # Stop the workers so the producer exception will be handled # when we finally yield from this coroutine _logger.debug('Producer died.', exc_info=True) self.stop() raise else: self.stop()
[ "def", "_run_producer_wrapper", "(", "self", ")", ":", "try", ":", "yield", "from", "self", ".", "_producer", ".", "process", "(", ")", "except", "Exception", "as", "error", ":", "if", "not", "isinstance", "(", "error", ",", "StopIteration", ")", ":", "#...
Run the producer, if exception, stop engine.
[ "Run", "the", "producer", "if", "exception", "stop", "engine", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/pipeline/pipeline.py#L245-L257
train
201,262
ArchiveTeam/wpull
wpull/warc/format.py
read_cdx
def read_cdx(file, encoding='utf8'): '''Iterate CDX file. Args: file (str): A file object. encoding (str): The encoding of the file. Returns: iterator: Each item is a dict that maps from field key to value. ''' with codecs.getreader(encoding)(file) as stream: header_line = stream.readline() separator = header_line[0] field_keys = header_line.strip().split(separator) if field_keys.pop(0) != 'CDX': raise ValueError('CDX header not found.') for line in stream: yield dict(zip(field_keys, line.strip().split(separator)))
python
def read_cdx(file, encoding='utf8'): '''Iterate CDX file. Args: file (str): A file object. encoding (str): The encoding of the file. Returns: iterator: Each item is a dict that maps from field key to value. ''' with codecs.getreader(encoding)(file) as stream: header_line = stream.readline() separator = header_line[0] field_keys = header_line.strip().split(separator) if field_keys.pop(0) != 'CDX': raise ValueError('CDX header not found.') for line in stream: yield dict(zip(field_keys, line.strip().split(separator)))
[ "def", "read_cdx", "(", "file", ",", "encoding", "=", "'utf8'", ")", ":", "with", "codecs", ".", "getreader", "(", "encoding", ")", "(", "file", ")", "as", "stream", ":", "header_line", "=", "stream", ".", "readline", "(", ")", "separator", "=", "heade...
Iterate CDX file. Args: file (str): A file object. encoding (str): The encoding of the file. Returns: iterator: Each item is a dict that maps from field key to value.
[ "Iterate", "CDX", "file", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/warc/format.py#L188-L207
train
201,263
ArchiveTeam/wpull
wpull/warc/format.py
WARCRecord.set_common_fields
def set_common_fields(self, warc_type: str, content_type: str): '''Set the required fields for the record.''' self.fields[self.WARC_TYPE] = warc_type self.fields[self.CONTENT_TYPE] = content_type self.fields[self.WARC_DATE] = wpull.util.datetime_str() self.fields[self.WARC_RECORD_ID] = '<{0}>'.format(uuid.uuid4().urn)
python
def set_common_fields(self, warc_type: str, content_type: str): '''Set the required fields for the record.''' self.fields[self.WARC_TYPE] = warc_type self.fields[self.CONTENT_TYPE] = content_type self.fields[self.WARC_DATE] = wpull.util.datetime_str() self.fields[self.WARC_RECORD_ID] = '<{0}>'.format(uuid.uuid4().urn)
[ "def", "set_common_fields", "(", "self", ",", "warc_type", ":", "str", ",", "content_type", ":", "str", ")", ":", "self", ".", "fields", "[", "self", ".", "WARC_TYPE", "]", "=", "warc_type", "self", ".", "fields", "[", "self", ".", "CONTENT_TYPE", "]", ...
Set the required fields for the record.
[ "Set", "the", "required", "fields", "for", "the", "record", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/warc/format.py#L74-L79
train
201,264
ArchiveTeam/wpull
wpull/warc/format.py
WARCRecord.set_content_length
def set_content_length(self): '''Find and set the content length. .. seealso:: :meth:`compute_checksum`. ''' if not self.block_file: self.fields['Content-Length'] = '0' return with wpull.util.reset_file_offset(self.block_file): wpull.util.seek_file_end(self.block_file) self.fields['Content-Length'] = str(self.block_file.tell())
python
def set_content_length(self): '''Find and set the content length. .. seealso:: :meth:`compute_checksum`. ''' if not self.block_file: self.fields['Content-Length'] = '0' return with wpull.util.reset_file_offset(self.block_file): wpull.util.seek_file_end(self.block_file) self.fields['Content-Length'] = str(self.block_file.tell())
[ "def", "set_content_length", "(", "self", ")", ":", "if", "not", "self", ".", "block_file", ":", "self", ".", "fields", "[", "'Content-Length'", "]", "=", "'0'", "return", "with", "wpull", ".", "util", ".", "reset_file_offset", "(", "self", ".", "block_fil...
Find and set the content length. .. seealso:: :meth:`compute_checksum`.
[ "Find", "and", "set", "the", "content", "length", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/warc/format.py#L81-L92
train
201,265
ArchiveTeam/wpull
wpull/warc/format.py
WARCRecord.compute_checksum
def compute_checksum(self, payload_offset: Optional[int]=None): '''Compute and add the checksum data to the record fields. This function also sets the content length. ''' if not self.block_file: self.fields['Content-Length'] = '0' return block_hasher = hashlib.sha1() payload_hasher = hashlib.sha1() with wpull.util.reset_file_offset(self.block_file): if payload_offset is not None: data = self.block_file.read(payload_offset) block_hasher.update(data) while True: data = self.block_file.read(4096) if data == b'': break block_hasher.update(data) payload_hasher.update(data) content_length = self.block_file.tell() content_hash = block_hasher.digest() self.fields['WARC-Block-Digest'] = 'sha1:{0}'.format( base64.b32encode(content_hash).decode() ) if payload_offset is not None: payload_hash = payload_hasher.digest() self.fields['WARC-Payload-Digest'] = 'sha1:{0}'.format( base64.b32encode(payload_hash).decode() ) self.fields['Content-Length'] = str(content_length)
python
def compute_checksum(self, payload_offset: Optional[int]=None): '''Compute and add the checksum data to the record fields. This function also sets the content length. ''' if not self.block_file: self.fields['Content-Length'] = '0' return block_hasher = hashlib.sha1() payload_hasher = hashlib.sha1() with wpull.util.reset_file_offset(self.block_file): if payload_offset is not None: data = self.block_file.read(payload_offset) block_hasher.update(data) while True: data = self.block_file.read(4096) if data == b'': break block_hasher.update(data) payload_hasher.update(data) content_length = self.block_file.tell() content_hash = block_hasher.digest() self.fields['WARC-Block-Digest'] = 'sha1:{0}'.format( base64.b32encode(content_hash).decode() ) if payload_offset is not None: payload_hash = payload_hasher.digest() self.fields['WARC-Payload-Digest'] = 'sha1:{0}'.format( base64.b32encode(payload_hash).decode() ) self.fields['Content-Length'] = str(content_length)
[ "def", "compute_checksum", "(", "self", ",", "payload_offset", ":", "Optional", "[", "int", "]", "=", "None", ")", ":", "if", "not", "self", ".", "block_file", ":", "self", ".", "fields", "[", "'Content-Length'", "]", "=", "'0'", "return", "block_hasher", ...
Compute and add the checksum data to the record fields. This function also sets the content length.
[ "Compute", "and", "add", "the", "checksum", "data", "to", "the", "record", "fields", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/warc/format.py#L94-L132
train
201,266
ArchiveTeam/wpull
wpull/warc/format.py
WARCRecord.get_http_header
def get_http_header(self) -> Response: '''Return the HTTP header. It only attempts to read the first 4 KiB of the payload. Returns: Response, None: Returns an instance of :class:`.http.request.Response` or None. ''' with wpull.util.reset_file_offset(self.block_file): data = self.block_file.read(4096) match = re.match(br'(.*?\r?\n\r?\n)', data) if not match: return status_line, dummy, field_str = match.group(1).partition(b'\n') try: version, code, reason = Response.parse_status_line(status_line) except ValueError: return response = Response(status_code=code, reason=reason, version=version) try: response.fields.parse(field_str, strict=False) except ValueError: return return response
python
def get_http_header(self) -> Response: '''Return the HTTP header. It only attempts to read the first 4 KiB of the payload. Returns: Response, None: Returns an instance of :class:`.http.request.Response` or None. ''' with wpull.util.reset_file_offset(self.block_file): data = self.block_file.read(4096) match = re.match(br'(.*?\r?\n\r?\n)', data) if not match: return status_line, dummy, field_str = match.group(1).partition(b'\n') try: version, code, reason = Response.parse_status_line(status_line) except ValueError: return response = Response(status_code=code, reason=reason, version=version) try: response.fields.parse(field_str, strict=False) except ValueError: return return response
[ "def", "get_http_header", "(", "self", ")", "->", "Response", ":", "with", "wpull", ".", "util", ".", "reset_file_offset", "(", "self", ".", "block_file", ")", ":", "data", "=", "self", ".", "block_file", ".", "read", "(", "4096", ")", "match", "=", "r...
Return the HTTP header. It only attempts to read the first 4 KiB of the payload. Returns: Response, None: Returns an instance of :class:`.http.request.Response` or None.
[ "Return", "the", "HTTP", "header", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/warc/format.py#L154-L185
train
201,267
ArchiveTeam/wpull
wpull/driver/phantomjs.py
PhantomJSDriver._write_config
def _write_config(self): '''Write the parameters to a file for PhantomJS to read.''' param_dict = { 'url': self._params.url, 'snapshot_paths': self._params.snapshot_paths, 'wait_time': self._params.wait_time, 'num_scrolls': self._params.num_scrolls, 'smart_scroll': self._params.smart_scroll, 'snapshot': self._params.snapshot, 'viewport_width': self._params.viewport_size[0], 'viewport_height': self._params.viewport_size[1], 'paper_width': self._params.paper_size[0], 'paper_height': self._params.paper_size[1], 'custom_headers': self._params.custom_headers, 'page_settings': self._params.page_settings, } if self._params.event_log_filename: param_dict['event_log_filename'] = \ os.path.abspath(self._params.event_log_filename) if self._params.action_log_filename: param_dict['action_log_filename'] = \ os.path.abspath(self._params.action_log_filename) config_text = json.dumps(param_dict) self._config_file.write(config_text.encode('utf-8')) # Close it so the phantomjs process can read it on Windows self._config_file.close()
python
def _write_config(self): '''Write the parameters to a file for PhantomJS to read.''' param_dict = { 'url': self._params.url, 'snapshot_paths': self._params.snapshot_paths, 'wait_time': self._params.wait_time, 'num_scrolls': self._params.num_scrolls, 'smart_scroll': self._params.smart_scroll, 'snapshot': self._params.snapshot, 'viewport_width': self._params.viewport_size[0], 'viewport_height': self._params.viewport_size[1], 'paper_width': self._params.paper_size[0], 'paper_height': self._params.paper_size[1], 'custom_headers': self._params.custom_headers, 'page_settings': self._params.page_settings, } if self._params.event_log_filename: param_dict['event_log_filename'] = \ os.path.abspath(self._params.event_log_filename) if self._params.action_log_filename: param_dict['action_log_filename'] = \ os.path.abspath(self._params.action_log_filename) config_text = json.dumps(param_dict) self._config_file.write(config_text.encode('utf-8')) # Close it so the phantomjs process can read it on Windows self._config_file.close()
[ "def", "_write_config", "(", "self", ")", ":", "param_dict", "=", "{", "'url'", ":", "self", ".", "_params", ".", "url", ",", "'snapshot_paths'", ":", "self", ".", "_params", ".", "snapshot_paths", ",", "'wait_time'", ":", "self", ".", "_params", ".", "w...
Write the parameters to a file for PhantomJS to read.
[ "Write", "the", "parameters", "to", "a", "file", "for", "PhantomJS", "to", "read", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/driver/phantomjs.py#L90-L120
train
201,268
ArchiveTeam/wpull
wpull/network/pool.py
HostPool.clean
def clean(self, force: bool=False): '''Clean closed connections. Args: force: Clean connected and idle connections too. Coroutine. ''' with (yield from self._lock): for connection in tuple(self.ready): if force or connection.closed(): connection.close() self.ready.remove(connection)
python
def clean(self, force: bool=False): '''Clean closed connections. Args: force: Clean connected and idle connections too. Coroutine. ''' with (yield from self._lock): for connection in tuple(self.ready): if force or connection.closed(): connection.close() self.ready.remove(connection)
[ "def", "clean", "(", "self", ",", "force", ":", "bool", "=", "False", ")", ":", "with", "(", "yield", "from", "self", ".", "_lock", ")", ":", "for", "connection", "in", "tuple", "(", "self", ".", "ready", ")", ":", "if", "force", "or", "connection"...
Clean closed connections. Args: force: Clean connected and idle connections too. Coroutine.
[ "Clean", "closed", "connections", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/pool.py#L41-L53
train
201,269
ArchiveTeam/wpull
wpull/network/pool.py
HostPool.close
def close(self): '''Forcibly close all connections. This instance will not be usable after calling this method. ''' for connection in self.ready: connection.close() for connection in self.busy: connection.close() self._closed = True
python
def close(self): '''Forcibly close all connections. This instance will not be usable after calling this method. ''' for connection in self.ready: connection.close() for connection in self.busy: connection.close() self._closed = True
[ "def", "close", "(", "self", ")", ":", "for", "connection", "in", "self", ".", "ready", ":", "connection", ".", "close", "(", ")", "for", "connection", "in", "self", ".", "busy", ":", "connection", ".", "close", "(", ")", "self", ".", "_closed", "=",...
Forcibly close all connections. This instance will not be usable after calling this method.
[ "Forcibly", "close", "all", "connections", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/pool.py#L55-L66
train
201,270
ArchiveTeam/wpull
wpull/network/pool.py
HostPool.acquire
def acquire(self) -> Connection: '''Register and return a connection. Coroutine. ''' assert not self._closed yield from self._condition.acquire() while True: if self.ready: connection = self.ready.pop() break elif len(self.busy) < self.max_connections: connection = self._connection_factory() break else: yield from self._condition.wait() self.busy.add(connection) self._condition.release() return connection
python
def acquire(self) -> Connection: '''Register and return a connection. Coroutine. ''' assert not self._closed yield from self._condition.acquire() while True: if self.ready: connection = self.ready.pop() break elif len(self.busy) < self.max_connections: connection = self._connection_factory() break else: yield from self._condition.wait() self.busy.add(connection) self._condition.release() return connection
[ "def", "acquire", "(", "self", ")", "->", "Connection", ":", "assert", "not", "self", ".", "_closed", "yield", "from", "self", ".", "_condition", ".", "acquire", "(", ")", "while", "True", ":", "if", "self", ".", "ready", ":", "connection", "=", "self"...
Register and return a connection. Coroutine.
[ "Register", "and", "return", "a", "connection", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/pool.py#L73-L95
train
201,271
ArchiveTeam/wpull
wpull/network/pool.py
HostPool.release
def release(self, connection: Connection, reuse: bool=True): '''Unregister a connection. Args: connection: Connection instance returned from :meth:`acquire`. reuse: If True, the connection is made available for reuse. Coroutine. ''' yield from self._condition.acquire() self.busy.remove(connection) if reuse: self.ready.add(connection) self._condition.notify() self._condition.release()
python
def release(self, connection: Connection, reuse: bool=True): '''Unregister a connection. Args: connection: Connection instance returned from :meth:`acquire`. reuse: If True, the connection is made available for reuse. Coroutine. ''' yield from self._condition.acquire() self.busy.remove(connection) if reuse: self.ready.add(connection) self._condition.notify() self._condition.release()
[ "def", "release", "(", "self", ",", "connection", ":", "Connection", ",", "reuse", ":", "bool", "=", "True", ")", ":", "yield", "from", "self", ".", "_condition", ".", "acquire", "(", ")", "self", ".", "busy", ".", "remove", "(", "connection", ")", "...
Unregister a connection. Args: connection: Connection instance returned from :meth:`acquire`. reuse: If True, the connection is made available for reuse. Coroutine.
[ "Unregister", "a", "connection", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/pool.py#L98-L114
train
201,272
ArchiveTeam/wpull
wpull/network/pool.py
ConnectionPool.acquire
def acquire(self, host: str, port: int, use_ssl: bool=False, host_key: Optional[Any]=None) \ -> Union[Connection, SSLConnection]: '''Return an available connection. Args: host: A hostname or IP address. port: Port number. use_ssl: Whether to return a SSL connection. host_key: If provided, it overrides the key used for per-host connection pooling. This is useful for proxies for example. Coroutine. ''' assert isinstance(port, int), 'Expect int. Got {}'.format(type(port)) assert not self._closed yield from self._process_no_wait_releases() if use_ssl: connection_factory = functools.partial( self._ssl_connection_factory, hostname=host) else: connection_factory = functools.partial( self._connection_factory, hostname=host) connection_factory = functools.partial( HappyEyeballsConnection, (host, port), connection_factory, self._resolver, self._happy_eyeballs_table, is_ssl=use_ssl ) key = host_key or (host, port, use_ssl) with (yield from self._host_pools_lock): if key not in self._host_pools: host_pool = self._host_pools[key] = HostPool( connection_factory, max_connections=self._max_host_count ) self._host_pool_waiters[key] = 1 else: host_pool = self._host_pools[key] self._host_pool_waiters[key] += 1 _logger.debug('Check out %s', key) connection = yield from host_pool.acquire() connection.key = key # TODO: Verify this assert is always true # assert host_pool.count() <= host_pool.max_connections # assert key in self._host_pools # assert self._host_pools[key] == host_pool with (yield from self._host_pools_lock): self._host_pool_waiters[key] -= 1 return connection
python
def acquire(self, host: str, port: int, use_ssl: bool=False, host_key: Optional[Any]=None) \ -> Union[Connection, SSLConnection]: '''Return an available connection. Args: host: A hostname or IP address. port: Port number. use_ssl: Whether to return a SSL connection. host_key: If provided, it overrides the key used for per-host connection pooling. This is useful for proxies for example. Coroutine. ''' assert isinstance(port, int), 'Expect int. Got {}'.format(type(port)) assert not self._closed yield from self._process_no_wait_releases() if use_ssl: connection_factory = functools.partial( self._ssl_connection_factory, hostname=host) else: connection_factory = functools.partial( self._connection_factory, hostname=host) connection_factory = functools.partial( HappyEyeballsConnection, (host, port), connection_factory, self._resolver, self._happy_eyeballs_table, is_ssl=use_ssl ) key = host_key or (host, port, use_ssl) with (yield from self._host_pools_lock): if key not in self._host_pools: host_pool = self._host_pools[key] = HostPool( connection_factory, max_connections=self._max_host_count ) self._host_pool_waiters[key] = 1 else: host_pool = self._host_pools[key] self._host_pool_waiters[key] += 1 _logger.debug('Check out %s', key) connection = yield from host_pool.acquire() connection.key = key # TODO: Verify this assert is always true # assert host_pool.count() <= host_pool.max_connections # assert key in self._host_pools # assert self._host_pools[key] == host_pool with (yield from self._host_pools_lock): self._host_pool_waiters[key] -= 1 return connection
[ "def", "acquire", "(", "self", ",", "host", ":", "str", ",", "port", ":", "int", ",", "use_ssl", ":", "bool", "=", "False", ",", "host_key", ":", "Optional", "[", "Any", "]", "=", "None", ")", "->", "Union", "[", "Connection", ",", "SSLConnection", ...
Return an available connection. Args: host: A hostname or IP address. port: Port number. use_ssl: Whether to return a SSL connection. host_key: If provided, it overrides the key used for per-host connection pooling. This is useful for proxies for example. Coroutine.
[ "Return", "an", "available", "connection", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/pool.py#L153-L211
train
201,273
ArchiveTeam/wpull
wpull/network/pool.py
ConnectionPool.release
def release(self, connection: Connection): '''Put a connection back in the pool. Coroutine. ''' assert not self._closed key = connection.key host_pool = self._host_pools[key] _logger.debug('Check in %s', key) yield from host_pool.release(connection) force = self.count() > self._max_count yield from self.clean(force=force)
python
def release(self, connection: Connection): '''Put a connection back in the pool. Coroutine. ''' assert not self._closed key = connection.key host_pool = self._host_pools[key] _logger.debug('Check in %s', key) yield from host_pool.release(connection) force = self.count() > self._max_count yield from self.clean(force=force)
[ "def", "release", "(", "self", ",", "connection", ":", "Connection", ")", ":", "assert", "not", "self", ".", "_closed", "key", "=", "connection", ".", "key", "host_pool", "=", "self", ".", "_host_pools", "[", "key", "]", "_logger", ".", "debug", "(", "...
Put a connection back in the pool. Coroutine.
[ "Put", "a", "connection", "back", "in", "the", "pool", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/pool.py#L214-L229
train
201,274
ArchiveTeam/wpull
wpull/network/pool.py
ConnectionPool.session
def session(self, host: str, port: int, use_ssl: bool=False): '''Return a context manager that returns a connection. Usage:: session = yield from connection_pool.session('example.com', 80) with session as connection: connection.write(b'blah') connection.close() Coroutine. ''' connection = yield from self.acquire(host, port, use_ssl) @contextlib.contextmanager def context_wrapper(): try: yield connection finally: self.no_wait_release(connection) return context_wrapper()
python
def session(self, host: str, port: int, use_ssl: bool=False): '''Return a context manager that returns a connection. Usage:: session = yield from connection_pool.session('example.com', 80) with session as connection: connection.write(b'blah') connection.close() Coroutine. ''' connection = yield from self.acquire(host, port, use_ssl) @contextlib.contextmanager def context_wrapper(): try: yield connection finally: self.no_wait_release(connection) return context_wrapper()
[ "def", "session", "(", "self", ",", "host", ":", "str", ",", "port", ":", "int", ",", "use_ssl", ":", "bool", "=", "False", ")", ":", "connection", "=", "yield", "from", "self", ".", "acquire", "(", "host", ",", "port", ",", "use_ssl", ")", "@", ...
Return a context manager that returns a connection. Usage:: session = yield from connection_pool.session('example.com', 80) with session as connection: connection.write(b'blah') connection.close() Coroutine.
[ "Return", "a", "context", "manager", "that", "returns", "a", "connection", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/pool.py#L251-L272
train
201,275
ArchiveTeam/wpull
wpull/network/pool.py
ConnectionPool.clean
def clean(self, force: bool=False): '''Clean all closed connections. Args: force: Clean connected and idle connections too. Coroutine. ''' assert not self._closed with (yield from self._host_pools_lock): for key, pool in tuple(self._host_pools.items()): yield from pool.clean(force=force) if not self._host_pool_waiters[key] and pool.empty(): del self._host_pools[key] del self._host_pool_waiters[key]
python
def clean(self, force: bool=False): '''Clean all closed connections. Args: force: Clean connected and idle connections too. Coroutine. ''' assert not self._closed with (yield from self._host_pools_lock): for key, pool in tuple(self._host_pools.items()): yield from pool.clean(force=force) if not self._host_pool_waiters[key] and pool.empty(): del self._host_pools[key] del self._host_pool_waiters[key]
[ "def", "clean", "(", "self", ",", "force", ":", "bool", "=", "False", ")", ":", "assert", "not", "self", ".", "_closed", "with", "(", "yield", "from", "self", ".", "_host_pools_lock", ")", ":", "for", "key", ",", "pool", "in", "tuple", "(", "self", ...
Clean all closed connections. Args: force: Clean connected and idle connections too. Coroutine.
[ "Clean", "all", "closed", "connections", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/pool.py#L275-L291
train
201,276
ArchiveTeam/wpull
wpull/network/pool.py
ConnectionPool.close
def close(self): '''Close all the connections and clean up. This instance will not be usable after calling this method. ''' for key, pool in tuple(self._host_pools.items()): pool.close() del self._host_pools[key] del self._host_pool_waiters[key] self._closed = True
python
def close(self): '''Close all the connections and clean up. This instance will not be usable after calling this method. ''' for key, pool in tuple(self._host_pools.items()): pool.close() del self._host_pools[key] del self._host_pool_waiters[key] self._closed = True
[ "def", "close", "(", "self", ")", ":", "for", "key", ",", "pool", "in", "tuple", "(", "self", ".", "_host_pools", ".", "items", "(", ")", ")", ":", "pool", ".", "close", "(", ")", "del", "self", ".", "_host_pools", "[", "key", "]", "del", "self",...
Close all the connections and clean up. This instance will not be usable after calling this method.
[ "Close", "all", "the", "connections", "and", "clean", "up", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/pool.py#L293-L304
train
201,277
ArchiveTeam/wpull
wpull/network/pool.py
ConnectionPool.count
def count(self) -> int: '''Return number of connections.''' counter = 0 for pool in self._host_pools.values(): counter += pool.count() return counter
python
def count(self) -> int: '''Return number of connections.''' counter = 0 for pool in self._host_pools.values(): counter += pool.count() return counter
[ "def", "count", "(", "self", ")", "->", "int", ":", "counter", "=", "0", "for", "pool", "in", "self", ".", "_host_pools", ".", "values", "(", ")", ":", "counter", "+=", "pool", ".", "count", "(", ")", "return", "counter" ]
Return number of connections.
[ "Return", "number", "of", "connections", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/pool.py#L306-L313
train
201,278
ArchiveTeam/wpull
wpull/network/pool.py
HappyEyeballsTable.set_preferred
def set_preferred(self, preferred_addr, addr_1, addr_2): '''Set the preferred address.''' if addr_1 > addr_2: addr_1, addr_2 = addr_2, addr_1 self._cache[(addr_1, addr_2)] = preferred_addr
python
def set_preferred(self, preferred_addr, addr_1, addr_2): '''Set the preferred address.''' if addr_1 > addr_2: addr_1, addr_2 = addr_2, addr_1 self._cache[(addr_1, addr_2)] = preferred_addr
[ "def", "set_preferred", "(", "self", ",", "preferred_addr", ",", "addr_1", ",", "addr_2", ")", ":", "if", "addr_1", ">", "addr_2", ":", "addr_1", ",", "addr_2", "=", "addr_2", ",", "addr_1", "self", ".", "_cache", "[", "(", "addr_1", ",", "addr_2", ")"...
Set the preferred address.
[ "Set", "the", "preferred", "address", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/pool.py#L321-L326
train
201,279
ArchiveTeam/wpull
wpull/network/pool.py
HappyEyeballsTable.get_preferred
def get_preferred(self, addr_1, addr_2): '''Return the preferred address.''' if addr_1 > addr_2: addr_1, addr_2 = addr_2, addr_1 return self._cache.get((addr_1, addr_2))
python
def get_preferred(self, addr_1, addr_2): '''Return the preferred address.''' if addr_1 > addr_2: addr_1, addr_2 = addr_2, addr_1 return self._cache.get((addr_1, addr_2))
[ "def", "get_preferred", "(", "self", ",", "addr_1", ",", "addr_2", ")", ":", "if", "addr_1", ">", "addr_2", ":", "addr_1", ",", "addr_2", "=", "addr_2", ",", "addr_1", "return", "self", ".", "_cache", ".", "get", "(", "(", "addr_1", ",", "addr_2", ")...
Return the preferred address.
[ "Return", "the", "preferred", "address", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/pool.py#L328-L333
train
201,280
ArchiveTeam/wpull
wpull/network/pool.py
HappyEyeballsConnection._connect_dual_stack
def _connect_dual_stack(self, primary_address, secondary_address): '''Connect using happy eyeballs.''' self._primary_connection = self._connection_factory(primary_address) self._secondary_connection = self._connection_factory(secondary_address) @asyncio.coroutine def connect_primary(): yield from self._primary_connection.connect() return self._primary_connection @asyncio.coroutine def connect_secondary(): yield from self._secondary_connection.connect() return self._secondary_connection primary_fut = connect_primary() secondary_fut = connect_secondary() failed = False for fut in asyncio.as_completed((primary_fut, secondary_fut)): if not self._active_connection: try: self._active_connection = yield from fut except NetworkError: if not failed: _logger.debug('Original dual stack exception', exc_info=True) failed = True else: raise else: _logger.debug('Got first of dual stack.') else: @asyncio.coroutine def cleanup(): try: conn = yield from fut except NetworkError: pass else: conn.close() _logger.debug('Closed abandoned connection.') asyncio.get_event_loop().create_task(cleanup()) preferred_host = self._active_connection.host self._happy_eyeballs_table.set_preferred( preferred_host, primary_address[0], secondary_address[0])
python
def _connect_dual_stack(self, primary_address, secondary_address): '''Connect using happy eyeballs.''' self._primary_connection = self._connection_factory(primary_address) self._secondary_connection = self._connection_factory(secondary_address) @asyncio.coroutine def connect_primary(): yield from self._primary_connection.connect() return self._primary_connection @asyncio.coroutine def connect_secondary(): yield from self._secondary_connection.connect() return self._secondary_connection primary_fut = connect_primary() secondary_fut = connect_secondary() failed = False for fut in asyncio.as_completed((primary_fut, secondary_fut)): if not self._active_connection: try: self._active_connection = yield from fut except NetworkError: if not failed: _logger.debug('Original dual stack exception', exc_info=True) failed = True else: raise else: _logger.debug('Got first of dual stack.') else: @asyncio.coroutine def cleanup(): try: conn = yield from fut except NetworkError: pass else: conn.close() _logger.debug('Closed abandoned connection.') asyncio.get_event_loop().create_task(cleanup()) preferred_host = self._active_connection.host self._happy_eyeballs_table.set_preferred( preferred_host, primary_address[0], secondary_address[0])
[ "def", "_connect_dual_stack", "(", "self", ",", "primary_address", ",", "secondary_address", ")", ":", "self", ".", "_primary_connection", "=", "self", ".", "_connection_factory", "(", "primary_address", ")", "self", ".", "_secondary_connection", "=", "self", ".", ...
Connect using happy eyeballs.
[ "Connect", "using", "happy", "eyeballs", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/pool.py#L390-L439
train
201,281
ArchiveTeam/wpull
wpull/network/pool.py
HappyEyeballsConnection._get_preferred_host
def _get_preferred_host(self, result: ResolveResult) -> Tuple[str, str]: '''Get preferred host from DNS results.''' host_1 = result.first_ipv4.ip_address if result.first_ipv4 else None host_2 = result.first_ipv6.ip_address if result.first_ipv6 else None if not host_2: return host_1, None elif not host_1: return host_2, None preferred_host = self._happy_eyeballs_table.get_preferred( host_1, host_2) if preferred_host: return preferred_host, None else: return host_1, host_2
python
def _get_preferred_host(self, result: ResolveResult) -> Tuple[str, str]: '''Get preferred host from DNS results.''' host_1 = result.first_ipv4.ip_address if result.first_ipv4 else None host_2 = result.first_ipv6.ip_address if result.first_ipv6 else None if not host_2: return host_1, None elif not host_1: return host_2, None preferred_host = self._happy_eyeballs_table.get_preferred( host_1, host_2) if preferred_host: return preferred_host, None else: return host_1, host_2
[ "def", "_get_preferred_host", "(", "self", ",", "result", ":", "ResolveResult", ")", "->", "Tuple", "[", "str", ",", "str", "]", ":", "host_1", "=", "result", ".", "first_ipv4", ".", "ip_address", "if", "result", ".", "first_ipv4", "else", "None", "host_2"...
Get preferred host from DNS results.
[ "Get", "preferred", "host", "from", "DNS", "results", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/pool.py#L441-L457
train
201,282
ArchiveTeam/wpull
wpull/warc/recorder.py
WARCRecorder._check_journals_and_maybe_raise
def _check_journals_and_maybe_raise(self): '''Check if any journal files exist and raise an error.''' files = list(glob.glob(self._prefix_filename + '*-wpullinc')) if files: raise OSError('WARC file {} is incomplete.'.format(files[0]))
python
def _check_journals_and_maybe_raise(self): '''Check if any journal files exist and raise an error.''' files = list(glob.glob(self._prefix_filename + '*-wpullinc')) if files: raise OSError('WARC file {} is incomplete.'.format(files[0]))
[ "def", "_check_journals_and_maybe_raise", "(", "self", ")", ":", "files", "=", "list", "(", "glob", ".", "glob", "(", "self", ".", "_prefix_filename", "+", "'*-wpullinc'", ")", ")", "if", "files", ":", "raise", "OSError", "(", "'WARC file {} is incomplete.'", ...
Check if any journal files exist and raise an error.
[ "Check", "if", "any", "journal", "files", "exist", "and", "raise", "an", "error", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/warc/recorder.py#L106-L111
train
201,283
ArchiveTeam/wpull
wpull/warc/recorder.py
WARCRecorder._start_new_warc_file
def _start_new_warc_file(self, meta=False): '''Create and set as current WARC file.''' if self._params.max_size and not meta and self._params.appending: while True: self._warc_filename = self._generate_warc_filename() if os.path.exists(self._warc_filename): _logger.debug('Skip {0}', self._warc_filename) self._sequence_num += 1 else: break else: self._warc_filename = self._generate_warc_filename(meta=meta) _logger.debug('WARC file at {0}', self._warc_filename) if not self._params.appending: wpull.util.truncate_file(self._warc_filename) self._warcinfo_record = WARCRecord() self._populate_warcinfo(self._params.extra_fields) self.write_record(self._warcinfo_record)
python
def _start_new_warc_file(self, meta=False): '''Create and set as current WARC file.''' if self._params.max_size and not meta and self._params.appending: while True: self._warc_filename = self._generate_warc_filename() if os.path.exists(self._warc_filename): _logger.debug('Skip {0}', self._warc_filename) self._sequence_num += 1 else: break else: self._warc_filename = self._generate_warc_filename(meta=meta) _logger.debug('WARC file at {0}', self._warc_filename) if not self._params.appending: wpull.util.truncate_file(self._warc_filename) self._warcinfo_record = WARCRecord() self._populate_warcinfo(self._params.extra_fields) self.write_record(self._warcinfo_record)
[ "def", "_start_new_warc_file", "(", "self", ",", "meta", "=", "False", ")", ":", "if", "self", ".", "_params", ".", "max_size", "and", "not", "meta", "and", "self", ".", "_params", ".", "appending", ":", "while", "True", ":", "self", ".", "_warc_filename...
Create and set as current WARC file.
[ "Create", "and", "set", "as", "current", "WARC", "file", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/warc/recorder.py#L113-L134
train
201,284
ArchiveTeam/wpull
wpull/warc/recorder.py
WARCRecorder._generate_warc_filename
def _generate_warc_filename(self, meta=False): '''Return a suitable WARC filename.''' if self._params.max_size is None: sequence_name = '' elif meta: sequence_name = '-meta' else: sequence_name = '-{0:05d}'.format(self._sequence_num) if self._params.compress: extension = 'warc.gz' else: extension = 'warc' return '{0}{1}.{2}'.format( self._prefix_filename, sequence_name, extension )
python
def _generate_warc_filename(self, meta=False): '''Return a suitable WARC filename.''' if self._params.max_size is None: sequence_name = '' elif meta: sequence_name = '-meta' else: sequence_name = '-{0:05d}'.format(self._sequence_num) if self._params.compress: extension = 'warc.gz' else: extension = 'warc' return '{0}{1}.{2}'.format( self._prefix_filename, sequence_name, extension )
[ "def", "_generate_warc_filename", "(", "self", ",", "meta", "=", "False", ")", ":", "if", "self", ".", "_params", ".", "max_size", "is", "None", ":", "sequence_name", "=", "''", "elif", "meta", ":", "sequence_name", "=", "'-meta'", "else", ":", "sequence_n...
Return a suitable WARC filename.
[ "Return", "a", "suitable", "WARC", "filename", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/warc/recorder.py#L136-L152
train
201,285
ArchiveTeam/wpull
wpull/warc/recorder.py
WARCRecorder._start_new_cdx_file
def _start_new_cdx_file(self): '''Create and set current CDX file.''' self._cdx_filename = '{0}.cdx'.format(self._prefix_filename) if not self._params.appending: wpull.util.truncate_file(self._cdx_filename) self._write_cdx_header() elif not os.path.exists(self._cdx_filename): self._write_cdx_header()
python
def _start_new_cdx_file(self): '''Create and set current CDX file.''' self._cdx_filename = '{0}.cdx'.format(self._prefix_filename) if not self._params.appending: wpull.util.truncate_file(self._cdx_filename) self._write_cdx_header() elif not os.path.exists(self._cdx_filename): self._write_cdx_header()
[ "def", "_start_new_cdx_file", "(", "self", ")", ":", "self", ".", "_cdx_filename", "=", "'{0}.cdx'", ".", "format", "(", "self", ".", "_prefix_filename", ")", "if", "not", "self", ".", "_params", ".", "appending", ":", "wpull", ".", "util", ".", "truncate_...
Create and set current CDX file.
[ "Create", "and", "set", "current", "CDX", "file", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/warc/recorder.py#L154-L162
train
201,286
ArchiveTeam/wpull
wpull/warc/recorder.py
WARCRecorder._populate_warcinfo
def _populate_warcinfo(self, extra_fields=None): '''Add the metadata to the Warcinfo record.''' self._warcinfo_record.set_common_fields( WARCRecord.WARCINFO, WARCRecord.WARC_FIELDS) info_fields = NameValueRecord(wrap_width=1024) info_fields['Software'] = self._params.software_string \ or self.DEFAULT_SOFTWARE_STRING info_fields['format'] = 'WARC File Format 1.0' info_fields['conformsTo'] = \ 'http://bibnum.bnf.fr/WARC/WARC_ISO_28500_version1_latestdraft.pdf' if extra_fields: for name, value in extra_fields: info_fields.add(name, value) self._warcinfo_record.block_file = io.BytesIO( bytes(info_fields) + b'\r\n') self._warcinfo_record.compute_checksum()
python
def _populate_warcinfo(self, extra_fields=None): '''Add the metadata to the Warcinfo record.''' self._warcinfo_record.set_common_fields( WARCRecord.WARCINFO, WARCRecord.WARC_FIELDS) info_fields = NameValueRecord(wrap_width=1024) info_fields['Software'] = self._params.software_string \ or self.DEFAULT_SOFTWARE_STRING info_fields['format'] = 'WARC File Format 1.0' info_fields['conformsTo'] = \ 'http://bibnum.bnf.fr/WARC/WARC_ISO_28500_version1_latestdraft.pdf' if extra_fields: for name, value in extra_fields: info_fields.add(name, value) self._warcinfo_record.block_file = io.BytesIO( bytes(info_fields) + b'\r\n') self._warcinfo_record.compute_checksum()
[ "def", "_populate_warcinfo", "(", "self", ",", "extra_fields", "=", "None", ")", ":", "self", ".", "_warcinfo_record", ".", "set_common_fields", "(", "WARCRecord", ".", "WARCINFO", ",", "WARCRecord", ".", "WARC_FIELDS", ")", "info_fields", "=", "NameValueRecord", ...
Add the metadata to the Warcinfo record.
[ "Add", "the", "metadata", "to", "the", "Warcinfo", "record", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/warc/recorder.py#L164-L182
train
201,287
ArchiveTeam/wpull
wpull/warc/recorder.py
WARCRecorder._setup_log
def _setup_log(self): '''Set up the logging file.''' logger = logging.getLogger() formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') self._log_temp_file = NamedTemporaryFile( prefix='tmp-wpull-warc-', dir=self._params.temp_dir, suffix='.log.gz', delete=False, ) self._log_temp_file.close() # For Windows self._log_handler = handler = logging.StreamHandler( io.TextIOWrapper( gzip.GzipFile( filename=self._log_temp_file.name, mode='wb' ), encoding='utf-8' ) ) logger.setLevel(logging.DEBUG) logger.debug('Wpull needs the root logger level set to DEBUG.') handler.setFormatter(formatter) logger.addHandler(handler) handler.setLevel(logging.INFO)
python
def _setup_log(self): '''Set up the logging file.''' logger = logging.getLogger() formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') self._log_temp_file = NamedTemporaryFile( prefix='tmp-wpull-warc-', dir=self._params.temp_dir, suffix='.log.gz', delete=False, ) self._log_temp_file.close() # For Windows self._log_handler = handler = logging.StreamHandler( io.TextIOWrapper( gzip.GzipFile( filename=self._log_temp_file.name, mode='wb' ), encoding='utf-8' ) ) logger.setLevel(logging.DEBUG) logger.debug('Wpull needs the root logger level set to DEBUG.') handler.setFormatter(formatter) logger.addHandler(handler) handler.setLevel(logging.INFO)
[ "def", "_setup_log", "(", "self", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", ")", "formatter", "=", "logging", ".", "Formatter", "(", "'%(asctime)s - %(name)s - %(levelname)s - %(message)s'", ")", "self", ".", "_log_temp_file", "=", "NamedTemporaryFi...
Set up the logging file.
[ "Set", "up", "the", "logging", "file", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/warc/recorder.py#L184-L211
train
201,288
ArchiveTeam/wpull
wpull/warc/recorder.py
WARCRecorder._move_file_to_dest_dir
def _move_file_to_dest_dir(self, filename): '''Move the file to the ``move_to`` directory.''' assert self._params.move_to if os.path.isdir(self._params.move_to): _logger.debug('Moved {} to {}.', self._warc_filename, self._params.move_to) shutil.move(filename, self._params.move_to) else: _logger.error('{} is not a directory; not moving {}.', self._params.move_to, filename)
python
def _move_file_to_dest_dir(self, filename): '''Move the file to the ``move_to`` directory.''' assert self._params.move_to if os.path.isdir(self._params.move_to): _logger.debug('Moved {} to {}.', self._warc_filename, self._params.move_to) shutil.move(filename, self._params.move_to) else: _logger.error('{} is not a directory; not moving {}.', self._params.move_to, filename)
[ "def", "_move_file_to_dest_dir", "(", "self", ",", "filename", ")", ":", "assert", "self", ".", "_params", ".", "move_to", "if", "os", ".", "path", ".", "isdir", "(", "self", ".", "_params", ".", "move_to", ")", ":", "_logger", ".", "debug", "(", "'Mov...
Move the file to the ``move_to`` directory.
[ "Move", "the", "file", "to", "the", "move_to", "directory", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/warc/recorder.py#L292-L302
train
201,289
ArchiveTeam/wpull
wpull/warc/recorder.py
WARCRecorder.set_length_and_maybe_checksums
def set_length_and_maybe_checksums(self, record, payload_offset=None): '''Set the content length and possibly the checksums.''' if self._params.digests: record.compute_checksum(payload_offset) else: record.set_content_length()
python
def set_length_and_maybe_checksums(self, record, payload_offset=None): '''Set the content length and possibly the checksums.''' if self._params.digests: record.compute_checksum(payload_offset) else: record.set_content_length()
[ "def", "set_length_and_maybe_checksums", "(", "self", ",", "record", ",", "payload_offset", "=", "None", ")", ":", "if", "self", ".", "_params", ".", "digests", ":", "record", ".", "compute_checksum", "(", "payload_offset", ")", "else", ":", "record", ".", "...
Set the content length and possibly the checksums.
[ "Set", "the", "content", "length", "and", "possibly", "the", "checksums", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/warc/recorder.py#L304-L309
train
201,290
ArchiveTeam/wpull
wpull/warc/recorder.py
WARCRecorder.write_record
def write_record(self, record): '''Append the record to the WARC file.''' # FIXME: probably not a good idea to modifiy arguments passed to us # TODO: add extra gzip headers that wget uses record.fields['WARC-Warcinfo-ID'] = self._warcinfo_record.fields[ WARCRecord.WARC_RECORD_ID] _logger.debug('Writing WARC record {0}.', record.fields['WARC-Type']) if self._params.compress: open_func = gzip.GzipFile else: open_func = open # Use getsize to get actual file size. Avoid tell() because it may # not be the raw file position. if os.path.exists(self._warc_filename): before_offset = os.path.getsize(self._warc_filename) else: before_offset = 0 journal_filename = self._warc_filename + '-wpullinc' with open(journal_filename, 'w') as file: file.write('wpull-journal-version:1\n') file.write('offset:{}\n'.format(before_offset)) try: with open_func(self._warc_filename, mode='ab') as out_file: for data in record: out_file.write(data) except (OSError, IOError) as error: _logger.info( _('Rolling back file {filename} to length {length}.'), filename=self._warc_filename, length=before_offset ) with open(self._warc_filename, mode='wb') as out_file: out_file.truncate(before_offset) raise error finally: os.remove(journal_filename) after_offset = os.path.getsize(self._warc_filename) if self._cdx_filename: raw_file_offset = before_offset raw_file_record_size = after_offset - before_offset self._write_cdx_field( record, raw_file_record_size, raw_file_offset )
python
def write_record(self, record): '''Append the record to the WARC file.''' # FIXME: probably not a good idea to modifiy arguments passed to us # TODO: add extra gzip headers that wget uses record.fields['WARC-Warcinfo-ID'] = self._warcinfo_record.fields[ WARCRecord.WARC_RECORD_ID] _logger.debug('Writing WARC record {0}.', record.fields['WARC-Type']) if self._params.compress: open_func = gzip.GzipFile else: open_func = open # Use getsize to get actual file size. Avoid tell() because it may # not be the raw file position. if os.path.exists(self._warc_filename): before_offset = os.path.getsize(self._warc_filename) else: before_offset = 0 journal_filename = self._warc_filename + '-wpullinc' with open(journal_filename, 'w') as file: file.write('wpull-journal-version:1\n') file.write('offset:{}\n'.format(before_offset)) try: with open_func(self._warc_filename, mode='ab') as out_file: for data in record: out_file.write(data) except (OSError, IOError) as error: _logger.info( _('Rolling back file {filename} to length {length}.'), filename=self._warc_filename, length=before_offset ) with open(self._warc_filename, mode='wb') as out_file: out_file.truncate(before_offset) raise error finally: os.remove(journal_filename) after_offset = os.path.getsize(self._warc_filename) if self._cdx_filename: raw_file_offset = before_offset raw_file_record_size = after_offset - before_offset self._write_cdx_field( record, raw_file_record_size, raw_file_offset )
[ "def", "write_record", "(", "self", ",", "record", ")", ":", "# FIXME: probably not a good idea to modifiy arguments passed to us", "# TODO: add extra gzip headers that wget uses", "record", ".", "fields", "[", "'WARC-Warcinfo-ID'", "]", "=", "self", ".", "_warcinfo_record", ...
Append the record to the WARC file.
[ "Append", "the", "record", "to", "the", "WARC", "file", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/warc/recorder.py#L311-L363
train
201,291
ArchiveTeam/wpull
wpull/warc/recorder.py
WARCRecorder.close
def close(self): '''Close the WARC file and clean up any logging handlers.''' if self._log_temp_file: self._log_handler.flush() logger = logging.getLogger() logger.removeHandler(self._log_handler) self._log_handler.stream.close() log_record = WARCRecord() log_record.block_file = gzip.GzipFile( filename=self._log_temp_file.name ) log_record.set_common_fields('resource', 'text/plain') log_record.fields['WARC-Target-URI'] = \ 'urn:X-wpull:log' if self._params.max_size is not None: if self._params.move_to is not None: self._move_file_to_dest_dir(self._warc_filename) self._start_new_warc_file(meta=True) self.set_length_and_maybe_checksums(log_record) self.write_record(log_record) log_record.block_file.close() try: os.remove(self._log_temp_file.name) except OSError: _logger.exception('Could not close log temp file.') self._log_temp_file = None self._log_handler.close() self._log_handler = None if self._params.move_to is not None: self._move_file_to_dest_dir(self._warc_filename) if self._cdx_filename and self._params.move_to is not None: self._move_file_to_dest_dir(self._cdx_filename)
python
def close(self): '''Close the WARC file and clean up any logging handlers.''' if self._log_temp_file: self._log_handler.flush() logger = logging.getLogger() logger.removeHandler(self._log_handler) self._log_handler.stream.close() log_record = WARCRecord() log_record.block_file = gzip.GzipFile( filename=self._log_temp_file.name ) log_record.set_common_fields('resource', 'text/plain') log_record.fields['WARC-Target-URI'] = \ 'urn:X-wpull:log' if self._params.max_size is not None: if self._params.move_to is not None: self._move_file_to_dest_dir(self._warc_filename) self._start_new_warc_file(meta=True) self.set_length_and_maybe_checksums(log_record) self.write_record(log_record) log_record.block_file.close() try: os.remove(self._log_temp_file.name) except OSError: _logger.exception('Could not close log temp file.') self._log_temp_file = None self._log_handler.close() self._log_handler = None if self._params.move_to is not None: self._move_file_to_dest_dir(self._warc_filename) if self._cdx_filename and self._params.move_to is not None: self._move_file_to_dest_dir(self._cdx_filename)
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_log_temp_file", ":", "self", ".", "_log_handler", ".", "flush", "(", ")", "logger", "=", "logging", ".", "getLogger", "(", ")", "logger", ".", "removeHandler", "(", "self", ".", "_log_handler", ...
Close the WARC file and clean up any logging handlers.
[ "Close", "the", "WARC", "file", "and", "clean", "up", "any", "logging", "handlers", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/warc/recorder.py#L365-L408
train
201,292
ArchiveTeam/wpull
wpull/warc/recorder.py
WARCRecorder._write_cdx_header
def _write_cdx_header(self): '''Write the CDX header. It writes the fields: 1. a: original URL 2. b: UNIX timestamp 3. m: MIME Type from the HTTP Content-type 4. s: response code 5. k: new style checksum 6. S: raw file record size 7. V: offset in raw file 8. g: filename of raw file 9. u: record ID ''' with open(self._cdx_filename, mode='a', encoding='utf-8') as out_file: out_file.write(self.CDX_DELIMINATOR) out_file.write(self.CDX_DELIMINATOR.join(( 'CDX', 'a', 'b', 'm', 's', 'k', 'S', 'V', 'g', 'u' ))) out_file.write('\n')
python
def _write_cdx_header(self): '''Write the CDX header. It writes the fields: 1. a: original URL 2. b: UNIX timestamp 3. m: MIME Type from the HTTP Content-type 4. s: response code 5. k: new style checksum 6. S: raw file record size 7. V: offset in raw file 8. g: filename of raw file 9. u: record ID ''' with open(self._cdx_filename, mode='a', encoding='utf-8') as out_file: out_file.write(self.CDX_DELIMINATOR) out_file.write(self.CDX_DELIMINATOR.join(( 'CDX', 'a', 'b', 'm', 's', 'k', 'S', 'V', 'g', 'u' ))) out_file.write('\n')
[ "def", "_write_cdx_header", "(", "self", ")", ":", "with", "open", "(", "self", ".", "_cdx_filename", ",", "mode", "=", "'a'", ",", "encoding", "=", "'utf-8'", ")", "as", "out_file", ":", "out_file", ".", "write", "(", "self", ".", "CDX_DELIMINATOR", ")"...
Write the CDX header. It writes the fields: 1. a: original URL 2. b: UNIX timestamp 3. m: MIME Type from the HTTP Content-type 4. s: response code 5. k: new style checksum 6. S: raw file record size 7. V: offset in raw file 8. g: filename of raw file 9. u: record ID
[ "Write", "the", "CDX", "header", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/warc/recorder.py#L410-L433
train
201,293
ArchiveTeam/wpull
wpull/warc/recorder.py
WARCRecorder._write_cdx_field
def _write_cdx_field(self, record, raw_file_record_size, raw_file_offset): '''Write the CDX field if needed.''' if record.fields[WARCRecord.WARC_TYPE] != WARCRecord.RESPONSE \ or not re.match(r'application/http; *msgtype *= *response', record.fields[WARCRecord.CONTENT_TYPE]): return url = record.fields['WARC-Target-URI'] _logger.debug('Writing CDX record {0}.', url) http_header = record.get_http_header() if http_header: mime_type = self.parse_mimetype( http_header.fields.get('Content-Type', '') ) or '-' response_code = str(http_header.status_code) else: mime_type = '-' response_code = '-' timestamp = str(int( wpull.util.parse_iso8601_str(record.fields[WARCRecord.WARC_DATE]) )) checksum = record.fields.get('WARC-Payload-Digest', '') if checksum.startswith('sha1:'): checksum = checksum.replace('sha1:', '', 1) else: checksum = '-' raw_file_record_size_str = str(raw_file_record_size) raw_file_offset_str = str(raw_file_offset) filename = os.path.basename(self._warc_filename) record_id = record.fields[WARCRecord.WARC_RECORD_ID] fields_strs = ( url, timestamp, mime_type, response_code, checksum, raw_file_record_size_str, raw_file_offset_str, filename, record_id ) with open(self._cdx_filename, mode='a', encoding='utf-8') as out_file: out_file.write(self.CDX_DELIMINATOR.join(fields_strs)) out_file.write('\n')
python
def _write_cdx_field(self, record, raw_file_record_size, raw_file_offset): '''Write the CDX field if needed.''' if record.fields[WARCRecord.WARC_TYPE] != WARCRecord.RESPONSE \ or not re.match(r'application/http; *msgtype *= *response', record.fields[WARCRecord.CONTENT_TYPE]): return url = record.fields['WARC-Target-URI'] _logger.debug('Writing CDX record {0}.', url) http_header = record.get_http_header() if http_header: mime_type = self.parse_mimetype( http_header.fields.get('Content-Type', '') ) or '-' response_code = str(http_header.status_code) else: mime_type = '-' response_code = '-' timestamp = str(int( wpull.util.parse_iso8601_str(record.fields[WARCRecord.WARC_DATE]) )) checksum = record.fields.get('WARC-Payload-Digest', '') if checksum.startswith('sha1:'): checksum = checksum.replace('sha1:', '', 1) else: checksum = '-' raw_file_record_size_str = str(raw_file_record_size) raw_file_offset_str = str(raw_file_offset) filename = os.path.basename(self._warc_filename) record_id = record.fields[WARCRecord.WARC_RECORD_ID] fields_strs = ( url, timestamp, mime_type, response_code, checksum, raw_file_record_size_str, raw_file_offset_str, filename, record_id ) with open(self._cdx_filename, mode='a', encoding='utf-8') as out_file: out_file.write(self.CDX_DELIMINATOR.join(fields_strs)) out_file.write('\n')
[ "def", "_write_cdx_field", "(", "self", ",", "record", ",", "raw_file_record_size", ",", "raw_file_offset", ")", ":", "if", "record", ".", "fields", "[", "WARCRecord", ".", "WARC_TYPE", "]", "!=", "WARCRecord", ".", "RESPONSE", "or", "not", "re", ".", "match...
Write the CDX field if needed.
[ "Write", "the", "CDX", "field", "if", "needed", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/warc/recorder.py#L435-L486
train
201,294
ArchiveTeam/wpull
wpull/warc/recorder.py
WARCRecorder.parse_mimetype
def parse_mimetype(cls, value): '''Return the MIME type from a Content-Type string. Returns: str, None: A string in the form ``type/subtype`` or None. ''' match = re.match(r'([a-zA-Z0-9-]+/[a-zA-Z0-9-]+)', value) if match: return match.group(1)
python
def parse_mimetype(cls, value): '''Return the MIME type from a Content-Type string. Returns: str, None: A string in the form ``type/subtype`` or None. ''' match = re.match(r'([a-zA-Z0-9-]+/[a-zA-Z0-9-]+)', value) if match: return match.group(1)
[ "def", "parse_mimetype", "(", "cls", ",", "value", ")", ":", "match", "=", "re", ".", "match", "(", "r'([a-zA-Z0-9-]+/[a-zA-Z0-9-]+)'", ",", "value", ")", "if", "match", ":", "return", "match", ".", "group", "(", "1", ")" ]
Return the MIME type from a Content-Type string. Returns: str, None: A string in the form ``type/subtype`` or None.
[ "Return", "the", "MIME", "type", "from", "a", "Content", "-", "Type", "string", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/warc/recorder.py#L489-L498
train
201,295
ArchiveTeam/wpull
wpull/warc/recorder.py
BaseWARCRecorderSession._new_temp_file
def _new_temp_file(self, hint='warcrecsess'): '''Return new temp file.''' return wpull.body.new_temp_file( directory=self._temp_dir, hint=hint )
python
def _new_temp_file(self, hint='warcrecsess'): '''Return new temp file.''' return wpull.body.new_temp_file( directory=self._temp_dir, hint=hint )
[ "def", "_new_temp_file", "(", "self", ",", "hint", "=", "'warcrecsess'", ")", ":", "return", "wpull", ".", "body", ".", "new_temp_file", "(", "directory", "=", "self", ".", "_temp_dir", ",", "hint", "=", "hint", ")" ]
Return new temp file.
[ "Return", "new", "temp", "file", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/warc/recorder.py#L508-L512
train
201,296
ArchiveTeam/wpull
wpull/warc/recorder.py
HTTPWARCRecorderSession._record_revisit
def _record_revisit(self, payload_offset: int): '''Record the revisit if possible.''' fields = self._response_record.fields ref_record_id = self._url_table.get_revisit_id( fields['WARC-Target-URI'], fields.get('WARC-Payload-Digest', '').upper().replace('SHA1:', '') ) if ref_record_id: try: self._response_record.block_file.truncate(payload_offset) except TypeError: self._response_record.block_file.seek(0) data = self._response_record.block_file.read(payload_offset) self._response_record.block_file.truncate() self._response_record.block_file.seek(0) self._response_record.block_file.write(data) self._recorder.set_length_and_maybe_checksums( self._response_record ) fields[WARCRecord.WARC_TYPE] = WARCRecord.REVISIT fields['WARC-Refers-To'] = ref_record_id fields['WARC-Profile'] = WARCRecord.SAME_PAYLOAD_DIGEST_URI fields['WARC-Truncated'] = 'length'
python
def _record_revisit(self, payload_offset: int): '''Record the revisit if possible.''' fields = self._response_record.fields ref_record_id = self._url_table.get_revisit_id( fields['WARC-Target-URI'], fields.get('WARC-Payload-Digest', '').upper().replace('SHA1:', '') ) if ref_record_id: try: self._response_record.block_file.truncate(payload_offset) except TypeError: self._response_record.block_file.seek(0) data = self._response_record.block_file.read(payload_offset) self._response_record.block_file.truncate() self._response_record.block_file.seek(0) self._response_record.block_file.write(data) self._recorder.set_length_and_maybe_checksums( self._response_record ) fields[WARCRecord.WARC_TYPE] = WARCRecord.REVISIT fields['WARC-Refers-To'] = ref_record_id fields['WARC-Profile'] = WARCRecord.SAME_PAYLOAD_DIGEST_URI fields['WARC-Truncated'] = 'length'
[ "def", "_record_revisit", "(", "self", ",", "payload_offset", ":", "int", ")", ":", "fields", "=", "self", ".", "_response_record", ".", "fields", "ref_record_id", "=", "self", ".", "_url_table", ".", "get_revisit_id", "(", "fields", "[", "'WARC-Target-URI'", ...
Record the revisit if possible.
[ "Record", "the", "revisit", "if", "possible", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/warc/recorder.py#L595-L623
train
201,297
ArchiveTeam/wpull
wpull/stats.py
Statistics.increment
def increment(self, size: int): '''Increment the number of files downloaded. Args: size: The size of the file ''' assert size >= 0, size self.files += 1 self.size += size self.bandwidth_meter.feed(size)
python
def increment(self, size: int): '''Increment the number of files downloaded. Args: size: The size of the file ''' assert size >= 0, size self.files += 1 self.size += size self.bandwidth_meter.feed(size)
[ "def", "increment", "(", "self", ",", "size", ":", "int", ")", ":", "assert", "size", ">=", "0", ",", "size", "self", ".", "files", "+=", "1", "self", ".", "size", "+=", "size", "self", ".", "bandwidth_meter", ".", "feed", "(", "size", ")" ]
Increment the number of files downloaded. Args: size: The size of the file
[ "Increment", "the", "number", "of", "files", "downloaded", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/stats.py#L56-L66
train
201,298
ArchiveTeam/wpull
wpull/stats.py
Statistics.is_quota_exceeded
def is_quota_exceeded(self) -> bool: '''Return whether the quota is exceeded.''' if self.quota and self._url_table is not None: return self.size >= self.quota and \ self._url_table.get_root_url_todo_count() == 0
python
def is_quota_exceeded(self) -> bool: '''Return whether the quota is exceeded.''' if self.quota and self._url_table is not None: return self.size >= self.quota and \ self._url_table.get_root_url_todo_count() == 0
[ "def", "is_quota_exceeded", "(", "self", ")", "->", "bool", ":", "if", "self", ".", "quota", "and", "self", ".", "_url_table", "is", "not", "None", ":", "return", "self", ".", "size", ">=", "self", ".", "quota", "and", "self", ".", "_url_table", ".", ...
Return whether the quota is exceeded.
[ "Return", "whether", "the", "quota", "is", "exceeded", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/stats.py#L69-L74
train
201,299