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/thirdparty/dammit.py
EncodingDetector.encodings
def encodings(self): """Yield a number of encodings that might work for this markup.""" tried = set() for e in self.override_encodings: if self._usable(e, tried): yield e # Did the document originally start with a byte-order mark # that indicated its encoding? if self._usable(self.sniffed_encoding, tried): yield self.sniffed_encoding # Look within the document for an XML or HTML encoding # declaration. if self.declared_encoding is None: self.declared_encoding = self.find_declared_encoding( self.markup, self.is_html) if self._usable(self.declared_encoding, tried): yield self.declared_encoding # Use third-party character set detection to guess at the # encoding. if self.chardet_encoding is None: self.chardet_encoding = chardet_dammit(self.markup) if self._usable(self.chardet_encoding, tried): yield self.chardet_encoding # As a last-ditch effort, try utf-8 and windows-1252. for e in ('utf-8', 'windows-1252'): if self._usable(e, tried): yield e
python
def encodings(self): """Yield a number of encodings that might work for this markup.""" tried = set() for e in self.override_encodings: if self._usable(e, tried): yield e # Did the document originally start with a byte-order mark # that indicated its encoding? if self._usable(self.sniffed_encoding, tried): yield self.sniffed_encoding # Look within the document for an XML or HTML encoding # declaration. if self.declared_encoding is None: self.declared_encoding = self.find_declared_encoding( self.markup, self.is_html) if self._usable(self.declared_encoding, tried): yield self.declared_encoding # Use third-party character set detection to guess at the # encoding. if self.chardet_encoding is None: self.chardet_encoding = chardet_dammit(self.markup) if self._usable(self.chardet_encoding, tried): yield self.chardet_encoding # As a last-ditch effort, try utf-8 and windows-1252. for e in ('utf-8', 'windows-1252'): if self._usable(e, tried): yield e
[ "def", "encodings", "(", "self", ")", ":", "tried", "=", "set", "(", ")", "for", "e", "in", "self", ".", "override_encodings", ":", "if", "self", ".", "_usable", "(", "e", ",", "tried", ")", ":", "yield", "e", "# Did the document originally start with a by...
Yield a number of encodings that might work for this markup.
[ "Yield", "a", "number", "of", "encodings", "that", "might", "work", "for", "this", "markup", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/thirdparty/dammit.py#L235-L265
train
201,500
ArchiveTeam/wpull
wpull/thirdparty/dammit.py
EncodingDetector.strip_byte_order_mark
def strip_byte_order_mark(cls, data): """If a byte-order mark is present, strip it and return the encoding it implies.""" encoding = None if (len(data) >= 4) and (data[:2] == b'\xfe\xff') \ and (data[2:4] != '\x00\x00'): encoding = 'utf-16be' data = data[2:] elif (len(data) >= 4) and (data[:2] == b'\xff\xfe') \ and (data[2:4] != '\x00\x00'): encoding = 'utf-16le' data = data[2:] elif data[:3] == b'\xef\xbb\xbf': encoding = 'utf-8' data = data[3:] elif data[:4] == b'\x00\x00\xfe\xff': encoding = 'utf-32be' data = data[4:] elif data[:4] == b'\xff\xfe\x00\x00': encoding = 'utf-32le' data = data[4:] return data, encoding
python
def strip_byte_order_mark(cls, data): """If a byte-order mark is present, strip it and return the encoding it implies.""" encoding = None if (len(data) >= 4) and (data[:2] == b'\xfe\xff') \ and (data[2:4] != '\x00\x00'): encoding = 'utf-16be' data = data[2:] elif (len(data) >= 4) and (data[:2] == b'\xff\xfe') \ and (data[2:4] != '\x00\x00'): encoding = 'utf-16le' data = data[2:] elif data[:3] == b'\xef\xbb\xbf': encoding = 'utf-8' data = data[3:] elif data[:4] == b'\x00\x00\xfe\xff': encoding = 'utf-32be' data = data[4:] elif data[:4] == b'\xff\xfe\x00\x00': encoding = 'utf-32le' data = data[4:] return data, encoding
[ "def", "strip_byte_order_mark", "(", "cls", ",", "data", ")", ":", "encoding", "=", "None", "if", "(", "len", "(", "data", ")", ">=", "4", ")", "and", "(", "data", "[", ":", "2", "]", "==", "b'\\xfe\\xff'", ")", "and", "(", "data", "[", "2", ":",...
If a byte-order mark is present, strip it and return the encoding it implies.
[ "If", "a", "byte", "-", "order", "mark", "is", "present", "strip", "it", "and", "return", "the", "encoding", "it", "implies", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/thirdparty/dammit.py#L268-L288
train
201,501
ArchiveTeam/wpull
wpull/thirdparty/dammit.py
EncodingDetector.find_declared_encoding
def find_declared_encoding(cls, markup, is_html=False, search_entire_document=False): """Given a document, tries to find its declared encoding. An XML encoding is declared at the beginning of the document. An HTML encoding is declared in a <meta> tag, hopefully near the beginning of the document. """ if search_entire_document: xml_endpos = html_endpos = len(markup) else: xml_endpos = 1024 html_endpos = max(2048, int(len(markup) * 0.05)) declared_encoding = None declared_encoding_match = xml_encoding_re.search(markup, endpos=xml_endpos) if not declared_encoding_match and is_html: declared_encoding_match = html_meta_re.search(markup, endpos=html_endpos) if declared_encoding_match is not None: declared_encoding = declared_encoding_match.groups()[0].decode( 'ascii', 'replace') if declared_encoding: return declared_encoding.lower() return None
python
def find_declared_encoding(cls, markup, is_html=False, search_entire_document=False): """Given a document, tries to find its declared encoding. An XML encoding is declared at the beginning of the document. An HTML encoding is declared in a <meta> tag, hopefully near the beginning of the document. """ if search_entire_document: xml_endpos = html_endpos = len(markup) else: xml_endpos = 1024 html_endpos = max(2048, int(len(markup) * 0.05)) declared_encoding = None declared_encoding_match = xml_encoding_re.search(markup, endpos=xml_endpos) if not declared_encoding_match and is_html: declared_encoding_match = html_meta_re.search(markup, endpos=html_endpos) if declared_encoding_match is not None: declared_encoding = declared_encoding_match.groups()[0].decode( 'ascii', 'replace') if declared_encoding: return declared_encoding.lower() return None
[ "def", "find_declared_encoding", "(", "cls", ",", "markup", ",", "is_html", "=", "False", ",", "search_entire_document", "=", "False", ")", ":", "if", "search_entire_document", ":", "xml_endpos", "=", "html_endpos", "=", "len", "(", "markup", ")", "else", ":",...
Given a document, tries to find its declared encoding. An XML encoding is declared at the beginning of the document. An HTML encoding is declared in a <meta> tag, hopefully near the beginning of the document.
[ "Given", "a", "document", "tries", "to", "find", "its", "declared", "encoding", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/thirdparty/dammit.py#L291-L314
train
201,502
ArchiveTeam/wpull
wpull/thirdparty/dammit.py
UnicodeDammit._sub_ms_char
def _sub_ms_char(self, match): """Changes a MS smart quote character to an XML or HTML entity, or an ASCII character.""" orig = match.group(1) if self.smart_quotes_to == 'ascii': sub = self.MS_CHARS_TO_ASCII.get(orig).encode() else: sub = self.MS_CHARS.get(orig) if type(sub) == tuple: if self.smart_quotes_to == 'xml': sub = '&#x'.encode() + sub[1].encode() + ';'.encode() else: sub = '&'.encode() + sub[0].encode() + ';'.encode() else: sub = sub.encode() return sub
python
def _sub_ms_char(self, match): """Changes a MS smart quote character to an XML or HTML entity, or an ASCII character.""" orig = match.group(1) if self.smart_quotes_to == 'ascii': sub = self.MS_CHARS_TO_ASCII.get(orig).encode() else: sub = self.MS_CHARS.get(orig) if type(sub) == tuple: if self.smart_quotes_to == 'xml': sub = '&#x'.encode() + sub[1].encode() + ';'.encode() else: sub = '&'.encode() + sub[0].encode() + ';'.encode() else: sub = sub.encode() return sub
[ "def", "_sub_ms_char", "(", "self", ",", "match", ")", ":", "orig", "=", "match", ".", "group", "(", "1", ")", "if", "self", ".", "smart_quotes_to", "==", "'ascii'", ":", "sub", "=", "self", ".", "MS_CHARS_TO_ASCII", ".", "get", "(", "orig", ")", "."...
Changes a MS smart quote character to an XML or HTML entity, or an ASCII character.
[ "Changes", "a", "MS", "smart", "quote", "character", "to", "an", "XML", "or", "HTML", "entity", "or", "an", "ASCII", "character", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/thirdparty/dammit.py#L383-L398
train
201,503
ArchiveTeam/wpull
wpull/thirdparty/dammit.py
UnicodeDammit.detwingle
def detwingle(cls, in_bytes, main_encoding="utf8", embedded_encoding="windows-1252"): """Fix characters from one encoding embedded in some other encoding. Currently the only situation supported is Windows-1252 (or its subset ISO-8859-1), embedded in UTF-8. The input must be a bytestring. If you've already converted the document to Unicode, you're too late. The output is a bytestring in which `embedded_encoding` characters have been converted to their `main_encoding` equivalents. """ if embedded_encoding.replace('_', '-').lower() not in ( 'windows-1252', 'windows_1252'): raise NotImplementedError( "Windows-1252 and ISO-8859-1 are the only currently supported " "embedded encodings.") if main_encoding.lower() not in ('utf8', 'utf-8'): raise NotImplementedError( "UTF-8 is the only currently supported main encoding.") byte_chunks = [] chunk_start = 0 pos = 0 while pos < len(in_bytes): byte = in_bytes[pos] if not isinstance(byte, int): # Python 2.x byte = ord(byte) if (byte >= cls.FIRST_MULTIBYTE_MARKER and byte <= cls.LAST_MULTIBYTE_MARKER): # This is the start of a UTF-8 multibyte character. Skip # to the end. for start, end, size in cls.MULTIBYTE_MARKERS_AND_SIZES: if byte >= start and byte <= end: pos += size break elif byte >= 0x80 and byte in cls.WINDOWS_1252_TO_UTF8: # We found a Windows-1252 character! # Save the string up to this point as a chunk. byte_chunks.append(in_bytes[chunk_start:pos]) # Now translate the Windows-1252 character into UTF-8 # and add it as another, one-byte chunk. byte_chunks.append(cls.WINDOWS_1252_TO_UTF8[byte]) pos += 1 chunk_start = pos else: # Go on to the next character. pos += 1 if chunk_start == 0: # The string is unchanged. return in_bytes else: # Store the final chunk. byte_chunks.append(in_bytes[chunk_start:]) return b''.join(byte_chunks)
python
def detwingle(cls, in_bytes, main_encoding="utf8", embedded_encoding="windows-1252"): """Fix characters from one encoding embedded in some other encoding. Currently the only situation supported is Windows-1252 (or its subset ISO-8859-1), embedded in UTF-8. The input must be a bytestring. If you've already converted the document to Unicode, you're too late. The output is a bytestring in which `embedded_encoding` characters have been converted to their `main_encoding` equivalents. """ if embedded_encoding.replace('_', '-').lower() not in ( 'windows-1252', 'windows_1252'): raise NotImplementedError( "Windows-1252 and ISO-8859-1 are the only currently supported " "embedded encodings.") if main_encoding.lower() not in ('utf8', 'utf-8'): raise NotImplementedError( "UTF-8 is the only currently supported main encoding.") byte_chunks = [] chunk_start = 0 pos = 0 while pos < len(in_bytes): byte = in_bytes[pos] if not isinstance(byte, int): # Python 2.x byte = ord(byte) if (byte >= cls.FIRST_MULTIBYTE_MARKER and byte <= cls.LAST_MULTIBYTE_MARKER): # This is the start of a UTF-8 multibyte character. Skip # to the end. for start, end, size in cls.MULTIBYTE_MARKERS_AND_SIZES: if byte >= start and byte <= end: pos += size break elif byte >= 0x80 and byte in cls.WINDOWS_1252_TO_UTF8: # We found a Windows-1252 character! # Save the string up to this point as a chunk. byte_chunks.append(in_bytes[chunk_start:pos]) # Now translate the Windows-1252 character into UTF-8 # and add it as another, one-byte chunk. byte_chunks.append(cls.WINDOWS_1252_TO_UTF8[byte]) pos += 1 chunk_start = pos else: # Go on to the next character. pos += 1 if chunk_start == 0: # The string is unchanged. return in_bytes else: # Store the final chunk. byte_chunks.append(in_bytes[chunk_start:]) return b''.join(byte_chunks)
[ "def", "detwingle", "(", "cls", ",", "in_bytes", ",", "main_encoding", "=", "\"utf8\"", ",", "embedded_encoding", "=", "\"windows-1252\"", ")", ":", "if", "embedded_encoding", ".", "replace", "(", "'_'", ",", "'-'", ")", ".", "lower", "(", ")", "not", "in"...
Fix characters from one encoding embedded in some other encoding. Currently the only situation supported is Windows-1252 (or its subset ISO-8859-1), embedded in UTF-8. The input must be a bytestring. If you've already converted the document to Unicode, you're too late. The output is a bytestring in which `embedded_encoding` characters have been converted to their `main_encoding` equivalents.
[ "Fix", "characters", "from", "one", "encoding", "embedded", "in", "some", "other", "encoding", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/thirdparty/dammit.py#L770-L830
train
201,504
ArchiveTeam/wpull
wpull/scraper/html.py
HTMLScraper.scrape_file
def scrape_file(self, file, encoding=None, base_url=None): '''Scrape a file for links. See :meth:`scrape` for the return value. ''' elements = self.iter_elements(file, encoding=encoding) link_contexts = set() link_infos = self._element_walker.iter_links(elements) for link_info in link_infos: element_base_url = base_url if link_info.base_link: clean_base_url = clean_link_soup(link_info.base_link) if element_base_url and base_url: element_base_url = urljoin_safe( base_url, clean_base_url ) or base_url if element_base_url: url = urljoin_safe( element_base_url, clean_link_soup(link_info.link), allow_fragments=False ) else: url = clean_link_soup(link_info.link) if url: link_contexts.add(LinkContext( url, inline=link_info.inline, linked=link_info.linked, link_type=link_info.link_type, extra=link_info )) scrape_result = ScrapeResult(link_contexts, encoding) scrape_result['base_url'] = base_url return scrape_result
python
def scrape_file(self, file, encoding=None, base_url=None): '''Scrape a file for links. See :meth:`scrape` for the return value. ''' elements = self.iter_elements(file, encoding=encoding) link_contexts = set() link_infos = self._element_walker.iter_links(elements) for link_info in link_infos: element_base_url = base_url if link_info.base_link: clean_base_url = clean_link_soup(link_info.base_link) if element_base_url and base_url: element_base_url = urljoin_safe( base_url, clean_base_url ) or base_url if element_base_url: url = urljoin_safe( element_base_url, clean_link_soup(link_info.link), allow_fragments=False ) else: url = clean_link_soup(link_info.link) if url: link_contexts.add(LinkContext( url, inline=link_info.inline, linked=link_info.linked, link_type=link_info.link_type, extra=link_info )) scrape_result = ScrapeResult(link_contexts, encoding) scrape_result['base_url'] = base_url return scrape_result
[ "def", "scrape_file", "(", "self", ",", "file", ",", "encoding", "=", "None", ",", "base_url", "=", "None", ")", ":", "elements", "=", "self", ".", "iter_elements", "(", "file", ",", "encoding", "=", "encoding", ")", "link_contexts", "=", "set", "(", "...
Scrape a file for links. See :meth:`scrape` for the return value.
[ "Scrape", "a", "file", "for", "links", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/scraper/html.py#L210-L252
train
201,505
ArchiveTeam/wpull
wpull/scraper/html.py
HTMLScraper._is_accepted
def _is_accepted(self, element_tag): '''Return if the link is accepted by the filters.''' element_tag = element_tag.lower() if self._ignored_tags is not None \ and element_tag in self._ignored_tags: return False if self._followed_tags is not None: return element_tag in self._followed_tags else: return True
python
def _is_accepted(self, element_tag): '''Return if the link is accepted by the filters.''' element_tag = element_tag.lower() if self._ignored_tags is not None \ and element_tag in self._ignored_tags: return False if self._followed_tags is not None: return element_tag in self._followed_tags else: return True
[ "def", "_is_accepted", "(", "self", ",", "element_tag", ")", ":", "element_tag", "=", "element_tag", ".", "lower", "(", ")", "if", "self", ".", "_ignored_tags", "is", "not", "None", "and", "element_tag", "in", "self", ".", "_ignored_tags", ":", "return", "...
Return if the link is accepted by the filters.
[ "Return", "if", "the", "link", "is", "accepted", "by", "the", "filters", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/scraper/html.py#L254-L265
train
201,506
ArchiveTeam/wpull
wpull/scraper/html.py
ElementWalker.iter_links
def iter_links(self, elements): '''Iterate the document root for links. Returns: iterable: A iterator of :class:`LinkedInfo`. ''' for element in elements: if not isinstance(element, Element): continue for link_infos in self.iter_links_element(element): yield link_infos
python
def iter_links(self, elements): '''Iterate the document root for links. Returns: iterable: A iterator of :class:`LinkedInfo`. ''' for element in elements: if not isinstance(element, Element): continue for link_infos in self.iter_links_element(element): yield link_infos
[ "def", "iter_links", "(", "self", ",", "elements", ")", ":", "for", "element", "in", "elements", ":", "if", "not", "isinstance", "(", "element", ",", "Element", ")", ":", "continue", "for", "link_infos", "in", "self", ".", "iter_links_element", "(", "eleme...
Iterate the document root for links. Returns: iterable: A iterator of :class:`LinkedInfo`.
[ "Iterate", "the", "document", "root", "for", "links", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/scraper/html.py#L325-L336
train
201,507
ArchiveTeam/wpull
wpull/scraper/html.py
ElementWalker.iter_links_element
def iter_links_element(self, element): '''Iterate a HTML element.''' # reference: lxml.html.HtmlMixin.iterlinks() attrib = element.attrib tag = element.tag if tag == 'link': iterable = self.iter_links_link_element(element) elif tag == 'meta': iterable = self.iter_links_meta_element(element) elif tag in ('object', 'applet'): iterable = self.iter_links_object_element(element) elif tag == 'param': iterable = self.iter_links_param_element(element) elif tag == 'style': iterable = self.iter_links_style_element(element) elif tag == 'script': iterable = self.iter_links_script_element(element) else: iterable = self.iter_links_plain_element(element) # RSS/Atom if tag in ('link', 'url', 'icon'): iterable = itertools.chain( iterable, self.iter_links_element_text(element) ) for link_info in iterable: yield link_info if 'style' in attrib and self.css_scraper: for link in self.css_scraper.scrape_links(attrib['style']): yield LinkInfo( element=element, tag=element.tag, attrib='style', link=link, inline=True, linked=False, base_link=None, value_type='css', link_type=LinkType.media, )
python
def iter_links_element(self, element): '''Iterate a HTML element.''' # reference: lxml.html.HtmlMixin.iterlinks() attrib = element.attrib tag = element.tag if tag == 'link': iterable = self.iter_links_link_element(element) elif tag == 'meta': iterable = self.iter_links_meta_element(element) elif tag in ('object', 'applet'): iterable = self.iter_links_object_element(element) elif tag == 'param': iterable = self.iter_links_param_element(element) elif tag == 'style': iterable = self.iter_links_style_element(element) elif tag == 'script': iterable = self.iter_links_script_element(element) else: iterable = self.iter_links_plain_element(element) # RSS/Atom if tag in ('link', 'url', 'icon'): iterable = itertools.chain( iterable, self.iter_links_element_text(element) ) for link_info in iterable: yield link_info if 'style' in attrib and self.css_scraper: for link in self.css_scraper.scrape_links(attrib['style']): yield LinkInfo( element=element, tag=element.tag, attrib='style', link=link, inline=True, linked=False, base_link=None, value_type='css', link_type=LinkType.media, )
[ "def", "iter_links_element", "(", "self", ",", "element", ")", ":", "# reference: lxml.html.HtmlMixin.iterlinks()", "attrib", "=", "element", ".", "attrib", "tag", "=", "element", ".", "tag", "if", "tag", "==", "'link'", ":", "iterable", "=", "self", ".", "ite...
Iterate a HTML element.
[ "Iterate", "a", "HTML", "element", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/scraper/html.py#L338-L377
train
201,508
ArchiveTeam/wpull
wpull/scraper/html.py
ElementWalker.iter_links_element_text
def iter_links_element_text(cls, element): '''Get the element text as a link.''' if element.text: link_type = identify_link_type(element.text) yield LinkInfo( element=element, tag=element.tag, attrib=None, link=element.text, inline=False, linked=True, base_link=None, value_type='plain', link_type=link_type )
python
def iter_links_element_text(cls, element): '''Get the element text as a link.''' if element.text: link_type = identify_link_type(element.text) yield LinkInfo( element=element, tag=element.tag, attrib=None, link=element.text, inline=False, linked=True, base_link=None, value_type='plain', link_type=link_type )
[ "def", "iter_links_element_text", "(", "cls", ",", "element", ")", ":", "if", "element", ".", "text", ":", "link_type", "=", "identify_link_type", "(", "element", ".", "text", ")", "yield", "LinkInfo", "(", "element", "=", "element", ",", "tag", "=", "elem...
Get the element text as a link.
[ "Get", "the", "element", "text", "as", "a", "link", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/scraper/html.py#L380-L391
train
201,509
ArchiveTeam/wpull
wpull/scraper/html.py
ElementWalker.iter_links_link_element
def iter_links_link_element(self, element): '''Iterate a ``link`` for URLs. This function handles stylesheets and icons in addition to standard scraping rules. ''' rel = element.attrib.get('rel', '') stylesheet = 'stylesheet' in rel icon = 'icon' in rel inline = stylesheet or icon if stylesheet: link_type = LinkType.css elif icon: link_type = LinkType.media else: link_type = None for attrib_name, link in self.iter_links_by_attrib(element): yield LinkInfo( element=element, tag=element.tag, attrib=attrib_name, link=link, inline=inline, linked=not inline, base_link=None, value_type='plain', link_type=link_type )
python
def iter_links_link_element(self, element): '''Iterate a ``link`` for URLs. This function handles stylesheets and icons in addition to standard scraping rules. ''' rel = element.attrib.get('rel', '') stylesheet = 'stylesheet' in rel icon = 'icon' in rel inline = stylesheet or icon if stylesheet: link_type = LinkType.css elif icon: link_type = LinkType.media else: link_type = None for attrib_name, link in self.iter_links_by_attrib(element): yield LinkInfo( element=element, tag=element.tag, attrib=attrib_name, link=link, inline=inline, linked=not inline, base_link=None, value_type='plain', link_type=link_type )
[ "def", "iter_links_link_element", "(", "self", ",", "element", ")", ":", "rel", "=", "element", ".", "attrib", ".", "get", "(", "'rel'", ",", "''", ")", "stylesheet", "=", "'stylesheet'", "in", "rel", "icon", "=", "'icon'", "in", "rel", "inline", "=", ...
Iterate a ``link`` for URLs. This function handles stylesheets and icons in addition to standard scraping rules.
[ "Iterate", "a", "link", "for", "URLs", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/scraper/html.py#L393-L419
train
201,510
ArchiveTeam/wpull
wpull/scraper/html.py
ElementWalker.iter_links_meta_element
def iter_links_meta_element(cls, element): '''Iterate the ``meta`` element for links. This function handles refresh URLs. ''' if element.attrib.get('http-equiv', '').lower() == 'refresh': content_value = element.attrib.get('content') if content_value: link = parse_refresh(content_value) if link: yield LinkInfo( element=element, tag=element.tag, attrib='http-equiv', link=link, inline=False, linked=True, base_link=None, value_type='refresh', link_type=None # treat it as a redirect ) else: for link_info in cls.iter_links_open_graph_meta(element): yield link_info
python
def iter_links_meta_element(cls, element): '''Iterate the ``meta`` element for links. This function handles refresh URLs. ''' if element.attrib.get('http-equiv', '').lower() == 'refresh': content_value = element.attrib.get('content') if content_value: link = parse_refresh(content_value) if link: yield LinkInfo( element=element, tag=element.tag, attrib='http-equiv', link=link, inline=False, linked=True, base_link=None, value_type='refresh', link_type=None # treat it as a redirect ) else: for link_info in cls.iter_links_open_graph_meta(element): yield link_info
[ "def", "iter_links_meta_element", "(", "cls", ",", "element", ")", ":", "if", "element", ".", "attrib", ".", "get", "(", "'http-equiv'", ",", "''", ")", ".", "lower", "(", ")", "==", "'refresh'", ":", "content_value", "=", "element", ".", "attrib", ".", ...
Iterate the ``meta`` element for links. This function handles refresh URLs.
[ "Iterate", "the", "meta", "element", "for", "links", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/scraper/html.py#L422-L444
train
201,511
ArchiveTeam/wpull
wpull/scraper/html.py
ElementWalker.iter_links_object_element
def iter_links_object_element(cls, element): '''Iterate ``object`` and ``embed`` elements. This function also looks at ``codebase`` and ``archive`` attributes. ''' base_link = element.attrib.get('codebase', None) if base_link: # lxml returns codebase as inline link_type = element.attrib.get(base_link) yield LinkInfo( element=element, tag=element.tag, attrib='codebase', link=base_link, inline=True, linked=False, base_link=None, value_type='plain', link_type=link_type ) for attribute in ('code', 'src', 'classid', 'data'): if attribute in element.attrib: link_type = identify_link_type(element.attrib.get(attribute)) yield LinkInfo( element=element, tag=element.tag, attrib=attribute, link=element.attrib.get(attribute), inline=True, linked=False, base_link=base_link, value_type='plain', link_type=link_type ) if 'archive' in element.attrib: for match in re.finditer(r'[^ ]+', element.attrib.get('archive')): value = match.group(0) link_type = identify_link_type(value) yield LinkInfo( element=element, tag=element.tag, attrib='archive', link=value, inline=True, linked=False, base_link=base_link, value_type='list', link_type=link_type )
python
def iter_links_object_element(cls, element): '''Iterate ``object`` and ``embed`` elements. This function also looks at ``codebase`` and ``archive`` attributes. ''' base_link = element.attrib.get('codebase', None) if base_link: # lxml returns codebase as inline link_type = element.attrib.get(base_link) yield LinkInfo( element=element, tag=element.tag, attrib='codebase', link=base_link, inline=True, linked=False, base_link=None, value_type='plain', link_type=link_type ) for attribute in ('code', 'src', 'classid', 'data'): if attribute in element.attrib: link_type = identify_link_type(element.attrib.get(attribute)) yield LinkInfo( element=element, tag=element.tag, attrib=attribute, link=element.attrib.get(attribute), inline=True, linked=False, base_link=base_link, value_type='plain', link_type=link_type ) if 'archive' in element.attrib: for match in re.finditer(r'[^ ]+', element.attrib.get('archive')): value = match.group(0) link_type = identify_link_type(value) yield LinkInfo( element=element, tag=element.tag, attrib='archive', link=value, inline=True, linked=False, base_link=base_link, value_type='list', link_type=link_type )
[ "def", "iter_links_object_element", "(", "cls", ",", "element", ")", ":", "base_link", "=", "element", ".", "attrib", ".", "get", "(", "'codebase'", ",", "None", ")", "if", "base_link", ":", "# lxml returns codebase as inline", "link_type", "=", "element", ".", ...
Iterate ``object`` and ``embed`` elements. This function also looks at ``codebase`` and ``archive`` attributes.
[ "Iterate", "object", "and", "embed", "elements", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/scraper/html.py#L470-L512
train
201,512
ArchiveTeam/wpull
wpull/scraper/html.py
ElementWalker.iter_links_param_element
def iter_links_param_element(cls, element): '''Iterate a ``param`` element.''' valuetype = element.attrib.get('valuetype', '') if valuetype.lower() == 'ref' and 'value' in element.attrib: link_type = identify_link_type(element.attrib.get('value')) yield LinkInfo( element=element, tag=element.tag, attrib='value', link=element.attrib.get('value'), inline=True, linked=False, base_link=None, value_type='plain', link_type=link_type )
python
def iter_links_param_element(cls, element): '''Iterate a ``param`` element.''' valuetype = element.attrib.get('valuetype', '') if valuetype.lower() == 'ref' and 'value' in element.attrib: link_type = identify_link_type(element.attrib.get('value')) yield LinkInfo( element=element, tag=element.tag, attrib='value', link=element.attrib.get('value'), inline=True, linked=False, base_link=None, value_type='plain', link_type=link_type )
[ "def", "iter_links_param_element", "(", "cls", ",", "element", ")", ":", "valuetype", "=", "element", ".", "attrib", ".", "get", "(", "'valuetype'", ",", "''", ")", "if", "valuetype", ".", "lower", "(", ")", "==", "'ref'", "and", "'value'", "in", "elemen...
Iterate a ``param`` element.
[ "Iterate", "a", "param", "element", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/scraper/html.py#L515-L529
train
201,513
ArchiveTeam/wpull
wpull/scraper/html.py
ElementWalker.iter_links_style_element
def iter_links_style_element(self, element): '''Iterate a ``style`` element.''' if self.css_scraper and element.text: link_iter = self.css_scraper.scrape_links(element.text, context=True) for link, context in link_iter: if context == 'import': link_type = LinkType.css else: link_type = LinkType.media yield LinkInfo( element=element, tag=element.tag, attrib=None, link=link, inline=True, linked=False, base_link=None, value_type='css', link_type=link_type )
python
def iter_links_style_element(self, element): '''Iterate a ``style`` element.''' if self.css_scraper and element.text: link_iter = self.css_scraper.scrape_links(element.text, context=True) for link, context in link_iter: if context == 'import': link_type = LinkType.css else: link_type = LinkType.media yield LinkInfo( element=element, tag=element.tag, attrib=None, link=link, inline=True, linked=False, base_link=None, value_type='css', link_type=link_type )
[ "def", "iter_links_style_element", "(", "self", ",", "element", ")", ":", "if", "self", ".", "css_scraper", "and", "element", ".", "text", ":", "link_iter", "=", "self", ".", "css_scraper", ".", "scrape_links", "(", "element", ".", "text", ",", "context", ...
Iterate a ``style`` element.
[ "Iterate", "a", "style", "element", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/scraper/html.py#L531-L549
train
201,514
ArchiveTeam/wpull
wpull/scraper/html.py
ElementWalker.iter_links_script_element
def iter_links_script_element(self, element): '''Iterate a ``script`` element.''' if self.javascript_scraper and element.text: link_iter = self.javascript_scraper.scrape_links(element.text, context=True) for link, context in link_iter: inline = is_likely_inline(link) if context is True: link_type = None else: link_type = context yield LinkInfo( element=element, tag=element.tag, attrib=None, link=link, inline=inline, linked=not inline, base_link=None, value_type='script', link_type=link_type ) for link in self.iter_links_plain_element(element): yield link
python
def iter_links_script_element(self, element): '''Iterate a ``script`` element.''' if self.javascript_scraper and element.text: link_iter = self.javascript_scraper.scrape_links(element.text, context=True) for link, context in link_iter: inline = is_likely_inline(link) if context is True: link_type = None else: link_type = context yield LinkInfo( element=element, tag=element.tag, attrib=None, link=link, inline=inline, linked=not inline, base_link=None, value_type='script', link_type=link_type ) for link in self.iter_links_plain_element(element): yield link
[ "def", "iter_links_script_element", "(", "self", ",", "element", ")", ":", "if", "self", ".", "javascript_scraper", "and", "element", ".", "text", ":", "link_iter", "=", "self", ".", "javascript_scraper", ".", "scrape_links", "(", "element", ".", "text", ",", ...
Iterate a ``script`` element.
[ "Iterate", "a", "script", "element", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/scraper/html.py#L551-L575
train
201,515
ArchiveTeam/wpull
wpull/scraper/html.py
ElementWalker.iter_links_plain_element
def iter_links_plain_element(self, element): '''Iterate any element for links using generic rules.''' for attrib_name, link in self.iter_links_by_attrib(element): if attrib_name in self.LINK_ATTRIBUTES: inline = self.is_link_inline(element.tag, attrib_name) linked = self.is_html_link(element.tag, attrib_name) else: inline = is_likely_inline(link) linked = not inline link_type = identify_link_type(link) yield LinkInfo( element=element, tag=element.tag, attrib=attrib_name, link=link, inline=inline, linked=linked, base_link=None, value_type='plain', link_type=link_type )
python
def iter_links_plain_element(self, element): '''Iterate any element for links using generic rules.''' for attrib_name, link in self.iter_links_by_attrib(element): if attrib_name in self.LINK_ATTRIBUTES: inline = self.is_link_inline(element.tag, attrib_name) linked = self.is_html_link(element.tag, attrib_name) else: inline = is_likely_inline(link) linked = not inline link_type = identify_link_type(link) yield LinkInfo( element=element, tag=element.tag, attrib=attrib_name, link=link, inline=inline, linked=linked, base_link=None, value_type='plain', link_type=link_type )
[ "def", "iter_links_plain_element", "(", "self", ",", "element", ")", ":", "for", "attrib_name", ",", "link", "in", "self", ".", "iter_links_by_attrib", "(", "element", ")", ":", "if", "attrib_name", "in", "self", ".", "LINK_ATTRIBUTES", ":", "inline", "=", "...
Iterate any element for links using generic rules.
[ "Iterate", "any", "element", "for", "links", "using", "generic", "rules", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/scraper/html.py#L577-L596
train
201,516
ArchiveTeam/wpull
wpull/scraper/html.py
ElementWalker.iter_links_by_attrib
def iter_links_by_attrib(self, element): '''Iterate an element by looking at its attributes for links.''' for attrib_name in element.attrib.keys(): attrib_value = element.attrib.get(attrib_name) if attrib_name in self.LINK_ATTRIBUTES: if self.javascript_scraper and \ attrib_value.lstrip().startswith('javascript:'): for link in self.iter_links_by_js_attrib( attrib_name, percent_decode(attrib_value)): yield link else: yield attrib_name, attrib_value elif self.javascript_scraper and \ attrib_name[:5] in self.DYNAMIC_ATTRIBUTES: for link in self.iter_links_by_js_attrib(attrib_name, attrib_value): yield link elif attrib_name.startswith('data-'): if is_likely_link(attrib_value) \ and not is_unlikely_link(attrib_value): yield attrib_name, attrib_value elif attrib_name == 'srcset': items = self.iter_links_by_srcset_attrib( attrib_name, attrib_value) for item in items: yield item
python
def iter_links_by_attrib(self, element): '''Iterate an element by looking at its attributes for links.''' for attrib_name in element.attrib.keys(): attrib_value = element.attrib.get(attrib_name) if attrib_name in self.LINK_ATTRIBUTES: if self.javascript_scraper and \ attrib_value.lstrip().startswith('javascript:'): for link in self.iter_links_by_js_attrib( attrib_name, percent_decode(attrib_value)): yield link else: yield attrib_name, attrib_value elif self.javascript_scraper and \ attrib_name[:5] in self.DYNAMIC_ATTRIBUTES: for link in self.iter_links_by_js_attrib(attrib_name, attrib_value): yield link elif attrib_name.startswith('data-'): if is_likely_link(attrib_value) \ and not is_unlikely_link(attrib_value): yield attrib_name, attrib_value elif attrib_name == 'srcset': items = self.iter_links_by_srcset_attrib( attrib_name, attrib_value) for item in items: yield item
[ "def", "iter_links_by_attrib", "(", "self", ",", "element", ")", ":", "for", "attrib_name", "in", "element", ".", "attrib", ".", "keys", "(", ")", ":", "attrib_value", "=", "element", ".", "attrib", ".", "get", "(", "attrib_name", ")", "if", "attrib_name",...
Iterate an element by looking at its attributes for links.
[ "Iterate", "an", "element", "by", "looking", "at", "its", "attributes", "for", "links", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/scraper/html.py#L598-L628
train
201,517
ArchiveTeam/wpull
wpull/scraper/html.py
ElementWalker.iter_links_by_js_attrib
def iter_links_by_js_attrib(self, attrib_name, attrib_value): '''Iterate links of a JavaScript pseudo-link attribute.''' links = self.javascript_scraper.scrape_links(attrib_value) for link in links: yield attrib_name, link
python
def iter_links_by_js_attrib(self, attrib_name, attrib_value): '''Iterate links of a JavaScript pseudo-link attribute.''' links = self.javascript_scraper.scrape_links(attrib_value) for link in links: yield attrib_name, link
[ "def", "iter_links_by_js_attrib", "(", "self", ",", "attrib_name", ",", "attrib_value", ")", ":", "links", "=", "self", ".", "javascript_scraper", ".", "scrape_links", "(", "attrib_value", ")", "for", "link", "in", "links", ":", "yield", "attrib_name", ",", "l...
Iterate links of a JavaScript pseudo-link attribute.
[ "Iterate", "links", "of", "a", "JavaScript", "pseudo", "-", "link", "attribute", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/scraper/html.py#L630-L635
train
201,518
ArchiveTeam/wpull
wpull/scraper/html.py
ElementWalker.is_link_inline
def is_link_inline(cls, tag, attribute): '''Return whether the link is likely to be inline object.''' if tag in cls.TAG_ATTRIBUTES \ and attribute in cls.TAG_ATTRIBUTES[tag]: attr_flags = cls.TAG_ATTRIBUTES[tag][attribute] return attr_flags & cls.ATTR_INLINE return attribute != 'href'
python
def is_link_inline(cls, tag, attribute): '''Return whether the link is likely to be inline object.''' if tag in cls.TAG_ATTRIBUTES \ and attribute in cls.TAG_ATTRIBUTES[tag]: attr_flags = cls.TAG_ATTRIBUTES[tag][attribute] return attr_flags & cls.ATTR_INLINE return attribute != 'href'
[ "def", "is_link_inline", "(", "cls", ",", "tag", ",", "attribute", ")", ":", "if", "tag", "in", "cls", ".", "TAG_ATTRIBUTES", "and", "attribute", "in", "cls", ".", "TAG_ATTRIBUTES", "[", "tag", "]", ":", "attr_flags", "=", "cls", ".", "TAG_ATTRIBUTES", "...
Return whether the link is likely to be inline object.
[ "Return", "whether", "the", "link", "is", "likely", "to", "be", "inline", "object", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/scraper/html.py#L646-L653
train
201,519
ArchiveTeam/wpull
wpull/scraper/html.py
ElementWalker.is_html_link
def is_html_link(cls, tag, attribute): '''Return whether the link is likely to be external object.''' if tag in cls.TAG_ATTRIBUTES \ and attribute in cls.TAG_ATTRIBUTES[tag]: attr_flags = cls.TAG_ATTRIBUTES[tag][attribute] return attr_flags & cls.ATTR_HTML return attribute == 'href'
python
def is_html_link(cls, tag, attribute): '''Return whether the link is likely to be external object.''' if tag in cls.TAG_ATTRIBUTES \ and attribute in cls.TAG_ATTRIBUTES[tag]: attr_flags = cls.TAG_ATTRIBUTES[tag][attribute] return attr_flags & cls.ATTR_HTML return attribute == 'href'
[ "def", "is_html_link", "(", "cls", ",", "tag", ",", "attribute", ")", ":", "if", "tag", "in", "cls", ".", "TAG_ATTRIBUTES", "and", "attribute", "in", "cls", ".", "TAG_ATTRIBUTES", "[", "tag", "]", ":", "attr_flags", "=", "cls", ".", "TAG_ATTRIBUTES", "["...
Return whether the link is likely to be external object.
[ "Return", "whether", "the", "link", "is", "likely", "to", "be", "external", "object", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/scraper/html.py#L656-L663
train
201,520
ArchiveTeam/wpull
wpull/scraper/html.py
ElementWalker.robots_cannot_follow
def robots_cannot_follow(cls, element): '''Return whether we cannot follow links due to robots.txt directives. ''' return ( element.tag == 'meta' and element.attrib.get('name', '').lower() == 'robots' and 'nofollow' in element.attrib.get('value', '').lower() )
python
def robots_cannot_follow(cls, element): '''Return whether we cannot follow links due to robots.txt directives. ''' return ( element.tag == 'meta' and element.attrib.get('name', '').lower() == 'robots' and 'nofollow' in element.attrib.get('value', '').lower() )
[ "def", "robots_cannot_follow", "(", "cls", ",", "element", ")", ":", "return", "(", "element", ".", "tag", "==", "'meta'", "and", "element", ".", "attrib", ".", "get", "(", "'name'", ",", "''", ")", ".", "lower", "(", ")", "==", "'robots'", "and", "'...
Return whether we cannot follow links due to robots.txt directives.
[ "Return", "whether", "we", "cannot", "follow", "links", "due", "to", "robots", ".", "txt", "directives", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/scraper/html.py#L666-L673
train
201,521
ArchiveTeam/wpull
wpull/scraper/base.py
BaseTextStreamScraper.iter_processed_text
def iter_processed_text(self, file, encoding=None, base_url=None): '''Return the file text and processed absolute links. Args: file: A file object containing the document. encoding (str): The encoding of the document. base_url (str): The URL at which the document is located. Returns: iterator: Each item is a tuple: 1. str: The text 2. bool: Whether the text a link ''' for text, is_link in self.iter_text(file, encoding): if is_link and base_url: new_link = urljoin_safe(base_url, text, allow_fragments=False) if new_link: yield (new_link, is_link) else: yield (new_link, False) else: yield (text, is_link)
python
def iter_processed_text(self, file, encoding=None, base_url=None): '''Return the file text and processed absolute links. Args: file: A file object containing the document. encoding (str): The encoding of the document. base_url (str): The URL at which the document is located. Returns: iterator: Each item is a tuple: 1. str: The text 2. bool: Whether the text a link ''' for text, is_link in self.iter_text(file, encoding): if is_link and base_url: new_link = urljoin_safe(base_url, text, allow_fragments=False) if new_link: yield (new_link, is_link) else: yield (new_link, False) else: yield (text, is_link)
[ "def", "iter_processed_text", "(", "self", ",", "file", ",", "encoding", "=", "None", ",", "base_url", "=", "None", ")", ":", "for", "text", ",", "is_link", "in", "self", ".", "iter_text", "(", "file", ",", "encoding", ")", ":", "if", "is_link", "and",...
Return the file text and processed absolute links. Args: file: A file object containing the document. encoding (str): The encoding of the document. base_url (str): The URL at which the document is located. Returns: iterator: Each item is a tuple: 1. str: The text 2. bool: Whether the text a link
[ "Return", "the", "file", "text", "and", "processed", "absolute", "links", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/scraper/base.py#L102-L125
train
201,522
ArchiveTeam/wpull
wpull/scraper/base.py
BaseTextStreamScraper.scrape_links
def scrape_links(self, text, context=False): '''Convenience function for scraping from a text string.''' return self.iter_processed_links(io.StringIO(text), context=context)
python
def scrape_links(self, text, context=False): '''Convenience function for scraping from a text string.''' return self.iter_processed_links(io.StringIO(text), context=context)
[ "def", "scrape_links", "(", "self", ",", "text", ",", "context", "=", "False", ")", ":", "return", "self", ".", "iter_processed_links", "(", "io", ".", "StringIO", "(", "text", ")", ",", "context", "=", "context", ")" ]
Convenience function for scraping from a text string.
[ "Convenience", "function", "for", "scraping", "from", "a", "text", "string", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/scraper/base.py#L138-L140
train
201,523
ArchiveTeam/wpull
wpull/scraper/base.py
DemuxDocumentScraper.scrape
def scrape(self, request, response, link_type=None): '''Iterate the scrapers, returning the first of the results.''' for scraper in self._document_scrapers: scrape_result = scraper.scrape(request, response, link_type) if scrape_result is None: continue if scrape_result.link_contexts: return scrape_result
python
def scrape(self, request, response, link_type=None): '''Iterate the scrapers, returning the first of the results.''' for scraper in self._document_scrapers: scrape_result = scraper.scrape(request, response, link_type) if scrape_result is None: continue if scrape_result.link_contexts: return scrape_result
[ "def", "scrape", "(", "self", ",", "request", ",", "response", ",", "link_type", "=", "None", ")", ":", "for", "scraper", "in", "self", ".", "_document_scrapers", ":", "scrape_result", "=", "scraper", ".", "scrape", "(", "request", ",", "response", ",", ...
Iterate the scrapers, returning the first of the results.
[ "Iterate", "the", "scrapers", "returning", "the", "first", "of", "the", "results", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/scraper/base.py#L165-L174
train
201,524
ArchiveTeam/wpull
wpull/scraper/base.py
DemuxDocumentScraper.scrape_info
def scrape_info(self, request, response, link_type=None): '''Iterate the scrapers and return a dict of results. Returns: dict: A dict where the keys are the scrapers instances and the values are the results. That is, a mapping from :class:`BaseDocumentScraper` to :class:`ScrapeResult`. ''' info = {} for scraper in self._document_scrapers: scrape_result = scraper.scrape(request, response, link_type) info[scraper] = scrape_result return info
python
def scrape_info(self, request, response, link_type=None): '''Iterate the scrapers and return a dict of results. Returns: dict: A dict where the keys are the scrapers instances and the values are the results. That is, a mapping from :class:`BaseDocumentScraper` to :class:`ScrapeResult`. ''' info = {} for scraper in self._document_scrapers: scrape_result = scraper.scrape(request, response, link_type) info[scraper] = scrape_result return info
[ "def", "scrape_info", "(", "self", ",", "request", ",", "response", ",", "link_type", "=", "None", ")", ":", "info", "=", "{", "}", "for", "scraper", "in", "self", ".", "_document_scrapers", ":", "scrape_result", "=", "scraper", ".", "scrape", "(", "requ...
Iterate the scrapers and return a dict of results. Returns: dict: A dict where the keys are the scrapers instances and the values are the results. That is, a mapping from :class:`BaseDocumentScraper` to :class:`ScrapeResult`.
[ "Iterate", "the", "scrapers", "and", "return", "a", "dict", "of", "results", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/scraper/base.py#L176-L189
train
201,525
ArchiveTeam/wpull
wpull/network/bandwidth.py
BandwidthMeter.feed
def feed(self, data_len, feed_time=None): '''Update the bandwidth meter. Args: data_len (int): The number of bytes transfered since the last call to :func:`feed`. feed_time (float): Current time. ''' self._bytes_transferred += data_len self._collected_bytes_transferred += data_len time_now = feed_time or time.time() time_diff = time_now - self._last_feed_time if time_diff < self._sample_min_time: return self._last_feed_time = time.time() if data_len == 0 and time_diff >= self._stall_time: self._stalled = True return self._samples.append((time_diff, self._collected_bytes_transferred)) self._collected_bytes_transferred = 0
python
def feed(self, data_len, feed_time=None): '''Update the bandwidth meter. Args: data_len (int): The number of bytes transfered since the last call to :func:`feed`. feed_time (float): Current time. ''' self._bytes_transferred += data_len self._collected_bytes_transferred += data_len time_now = feed_time or time.time() time_diff = time_now - self._last_feed_time if time_diff < self._sample_min_time: return self._last_feed_time = time.time() if data_len == 0 and time_diff >= self._stall_time: self._stalled = True return self._samples.append((time_diff, self._collected_bytes_transferred)) self._collected_bytes_transferred = 0
[ "def", "feed", "(", "self", ",", "data_len", ",", "feed_time", "=", "None", ")", ":", "self", ".", "_bytes_transferred", "+=", "data_len", "self", ".", "_collected_bytes_transferred", "+=", "data_len", "time_now", "=", "feed_time", "or", "time", ".", "time", ...
Update the bandwidth meter. Args: data_len (int): The number of bytes transfered since the last call to :func:`feed`. feed_time (float): Current time.
[ "Update", "the", "bandwidth", "meter", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/bandwidth.py#L49-L73
train
201,526
ArchiveTeam/wpull
wpull/network/bandwidth.py
BandwidthMeter.speed
def speed(self): '''Return the current transfer speed. Returns: int: The speed in bytes per second. ''' if self._stalled: return 0 time_sum = 0 data_len_sum = 0 for time_diff, data_len in self._samples: time_sum += time_diff data_len_sum += data_len if time_sum: return data_len_sum / time_sum else: return 0
python
def speed(self): '''Return the current transfer speed. Returns: int: The speed in bytes per second. ''' if self._stalled: return 0 time_sum = 0 data_len_sum = 0 for time_diff, data_len in self._samples: time_sum += time_diff data_len_sum += data_len if time_sum: return data_len_sum / time_sum else: return 0
[ "def", "speed", "(", "self", ")", ":", "if", "self", ".", "_stalled", ":", "return", "0", "time_sum", "=", "0", "data_len_sum", "=", "0", "for", "time_diff", ",", "data_len", "in", "self", ".", "_samples", ":", "time_sum", "+=", "time_diff", "data_len_su...
Return the current transfer speed. Returns: int: The speed in bytes per second.
[ "Return", "the", "current", "transfer", "speed", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/bandwidth.py#L75-L94
train
201,527
ArchiveTeam/wpull
wpull/resmon.py
ResourceMonitor.get_info
def get_info(self): '''Return ResourceInfo instances.''' if self._min_disk: for path in self._resource_paths: usage = psutil.disk_usage(path) yield ResourceInfo(path, usage.free, self._min_disk) if self._min_memory: usage = psutil.virtual_memory() yield ResourceInfo(None, usage.available, self._min_memory)
python
def get_info(self): '''Return ResourceInfo instances.''' if self._min_disk: for path in self._resource_paths: usage = psutil.disk_usage(path) yield ResourceInfo(path, usage.free, self._min_disk) if self._min_memory: usage = psutil.virtual_memory() yield ResourceInfo(None, usage.available, self._min_memory)
[ "def", "get_info", "(", "self", ")", ":", "if", "self", ".", "_min_disk", ":", "for", "path", "in", "self", ".", "_resource_paths", ":", "usage", "=", "psutil", ".", "disk_usage", "(", "path", ")", "yield", "ResourceInfo", "(", "path", ",", "usage", "....
Return ResourceInfo instances.
[ "Return", "ResourceInfo", "instances", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/resmon.py#L57-L68
train
201,528
ArchiveTeam/wpull
wpull/resmon.py
ResourceMonitor.check
def check(self): '''Check resource levels. Returns: None, ResourceInfo: If None is provided, no levels are exceeded. Otherwise, the first ResourceInfo exceeding limits is returned. ''' for info in self.get_info(): if info.free < info.limit: return info
python
def check(self): '''Check resource levels. Returns: None, ResourceInfo: If None is provided, no levels are exceeded. Otherwise, the first ResourceInfo exceeding limits is returned. ''' for info in self.get_info(): if info.free < info.limit: return info
[ "def", "check", "(", "self", ")", ":", "for", "info", "in", "self", ".", "get_info", "(", ")", ":", "if", "info", ".", "free", "<", "info", ".", "limit", ":", "return", "info" ]
Check resource levels. Returns: None, ResourceInfo: If None is provided, no levels are exceeded. Otherwise, the first ResourceInfo exceeding limits is returned.
[ "Check", "resource", "levels", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/resmon.py#L70-L80
train
201,529
ArchiveTeam/wpull
wpull/protocol/http/redirect.py
RedirectTracker.load
def load(self, response): '''Load the response and increment the counter. Args: response (:class:`.http.request.Response`): The response from a previous request. ''' self._response = response if self.next_location(raw=True): self._num_redirects += 1
python
def load(self, response): '''Load the response and increment the counter. Args: response (:class:`.http.request.Response`): The response from a previous request. ''' self._response = response if self.next_location(raw=True): self._num_redirects += 1
[ "def", "load", "(", "self", ",", "response", ")", ":", "self", ".", "_response", "=", "response", "if", "self", ".", "next_location", "(", "raw", "=", "True", ")", ":", "self", ".", "_num_redirects", "+=", "1" ]
Load the response and increment the counter. Args: response (:class:`.http.request.Response`): The response from a previous request.
[ "Load", "the", "response", "and", "increment", "the", "counter", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/redirect.py#L27-L37
train
201,530
ArchiveTeam/wpull
wpull/protocol/http/redirect.py
RedirectTracker.next_location
def next_location(self, raw=False): '''Returns the next location. Args: raw (bool): If True, the original string contained in the Location field will be returned. Otherwise, the URL will be normalized to a complete URL. Returns: str, None: If str, the location. Otherwise, no next location. ''' if self._response: location = self._response.fields.get('location') if not location or raw: return location return wpull.url.urljoin(self._response.request.url_info.url, location)
python
def next_location(self, raw=False): '''Returns the next location. Args: raw (bool): If True, the original string contained in the Location field will be returned. Otherwise, the URL will be normalized to a complete URL. Returns: str, None: If str, the location. Otherwise, no next location. ''' if self._response: location = self._response.fields.get('location') if not location or raw: return location return wpull.url.urljoin(self._response.request.url_info.url, location)
[ "def", "next_location", "(", "self", ",", "raw", "=", "False", ")", ":", "if", "self", ".", "_response", ":", "location", "=", "self", ".", "_response", ".", "fields", ".", "get", "(", "'location'", ")", "if", "not", "location", "or", "raw", ":", "re...
Returns the next location. Args: raw (bool): If True, the original string contained in the Location field will be returned. Otherwise, the URL will be normalized to a complete URL. Returns: str, None: If str, the location. Otherwise, no next location.
[ "Returns", "the", "next", "location", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/redirect.py#L39-L57
train
201,531
ArchiveTeam/wpull
wpull/protocol/http/redirect.py
RedirectTracker.is_redirect
def is_redirect(self): '''Return whether the response contains a redirect code.''' if self._response: status_code = self._response.status_code return status_code in self._codes \ or status_code in self._repeat_codes
python
def is_redirect(self): '''Return whether the response contains a redirect code.''' if self._response: status_code = self._response.status_code return status_code in self._codes \ or status_code in self._repeat_codes
[ "def", "is_redirect", "(", "self", ")", ":", "if", "self", ".", "_response", ":", "status_code", "=", "self", ".", "_response", ".", "status_code", "return", "status_code", "in", "self", ".", "_codes", "or", "status_code", "in", "self", ".", "_repeat_codes" ...
Return whether the response contains a redirect code.
[ "Return", "whether", "the", "response", "contains", "a", "redirect", "code", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/redirect.py#L59-L64
train
201,532
ArchiveTeam/wpull
wpull/application/tasks/network.py
NetworkSetupTask._build_resolver
def _build_resolver(cls, session: AppSession): '''Build resolver.''' args = session.args dns_timeout = args.dns_timeout if args.timeout: dns_timeout = args.timeout if args.inet_family == 'IPv4': family = IPFamilyPreference.ipv4_only elif args.inet_family == 'IPv6': family = IPFamilyPreference.ipv6_only elif args.prefer_family == 'IPv6': family = IPFamilyPreference.prefer_ipv6 elif args.prefer_family == 'IPv4': family = IPFamilyPreference.prefer_ipv4 else: family = IPFamilyPreference.any return session.factory.new( 'Resolver', family=family, timeout=dns_timeout, rotate=args.rotate_dns, cache=session.factory.class_map['Resolver'].new_cache() if args.dns_cache else None, )
python
def _build_resolver(cls, session: AppSession): '''Build resolver.''' args = session.args dns_timeout = args.dns_timeout if args.timeout: dns_timeout = args.timeout if args.inet_family == 'IPv4': family = IPFamilyPreference.ipv4_only elif args.inet_family == 'IPv6': family = IPFamilyPreference.ipv6_only elif args.prefer_family == 'IPv6': family = IPFamilyPreference.prefer_ipv6 elif args.prefer_family == 'IPv4': family = IPFamilyPreference.prefer_ipv4 else: family = IPFamilyPreference.any return session.factory.new( 'Resolver', family=family, timeout=dns_timeout, rotate=args.rotate_dns, cache=session.factory.class_map['Resolver'].new_cache() if args.dns_cache else None, )
[ "def", "_build_resolver", "(", "cls", ",", "session", ":", "AppSession", ")", ":", "args", "=", "session", ".", "args", "dns_timeout", "=", "args", ".", "dns_timeout", "if", "args", ".", "timeout", ":", "dns_timeout", "=", "args", ".", "timeout", "if", "...
Build resolver.
[ "Build", "resolver", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/network.py#L24-L49
train
201,533
ArchiveTeam/wpull
wpull/application/tasks/network.py
NetworkSetupTask._build_connection_pool
def _build_connection_pool(cls, session: AppSession): '''Create connection pool.''' args = session.args connect_timeout = args.connect_timeout read_timeout = args.read_timeout if args.timeout: connect_timeout = read_timeout = args.timeout if args.limit_rate: bandwidth_limiter = session.factory.new('BandwidthLimiter', args.limit_rate) else: bandwidth_limiter = None connection_factory = functools.partial( Connection, timeout=read_timeout, connect_timeout=connect_timeout, bind_host=session.args.bind_address, bandwidth_limiter=bandwidth_limiter, ) ssl_connection_factory = functools.partial( SSLConnection, timeout=read_timeout, connect_timeout=connect_timeout, bind_host=session.args.bind_address, ssl_context=session.ssl_context, ) if not session.args.no_proxy: if session.args.https_proxy: http_proxy = session.args.http_proxy.split(':', 1) proxy_ssl = True elif session.args.http_proxy: http_proxy = session.args.http_proxy.split(':', 1) proxy_ssl = False else: http_proxy = None proxy_ssl = None if http_proxy: http_proxy[1] = int(http_proxy[1]) if session.args.proxy_user: authentication = (session.args.proxy_user, session.args.proxy_password) else: authentication = None session.factory.class_map['ConnectionPool'] = \ HTTPProxyConnectionPool host_filter = session.factory.new( 'ProxyHostFilter', accept_domains=session.args.proxy_domains, reject_domains=session.args.proxy_exclude_domains, accept_hostnames=session.args.proxy_hostnames, reject_hostnames=session.args.proxy_exclude_hostnames ) return session.factory.new( 'ConnectionPool', http_proxy, proxy_ssl=proxy_ssl, authentication=authentication, resolver=session.factory['Resolver'], connection_factory=connection_factory, ssl_connection_factory=ssl_connection_factory, host_filter=host_filter, ) return session.factory.new( 'ConnectionPool', resolver=session.factory['Resolver'], connection_factory=connection_factory, ssl_connection_factory=ssl_connection_factory )
python
def _build_connection_pool(cls, session: AppSession): '''Create connection pool.''' args = session.args connect_timeout = args.connect_timeout read_timeout = args.read_timeout if args.timeout: connect_timeout = read_timeout = args.timeout if args.limit_rate: bandwidth_limiter = session.factory.new('BandwidthLimiter', args.limit_rate) else: bandwidth_limiter = None connection_factory = functools.partial( Connection, timeout=read_timeout, connect_timeout=connect_timeout, bind_host=session.args.bind_address, bandwidth_limiter=bandwidth_limiter, ) ssl_connection_factory = functools.partial( SSLConnection, timeout=read_timeout, connect_timeout=connect_timeout, bind_host=session.args.bind_address, ssl_context=session.ssl_context, ) if not session.args.no_proxy: if session.args.https_proxy: http_proxy = session.args.http_proxy.split(':', 1) proxy_ssl = True elif session.args.http_proxy: http_proxy = session.args.http_proxy.split(':', 1) proxy_ssl = False else: http_proxy = None proxy_ssl = None if http_proxy: http_proxy[1] = int(http_proxy[1]) if session.args.proxy_user: authentication = (session.args.proxy_user, session.args.proxy_password) else: authentication = None session.factory.class_map['ConnectionPool'] = \ HTTPProxyConnectionPool host_filter = session.factory.new( 'ProxyHostFilter', accept_domains=session.args.proxy_domains, reject_domains=session.args.proxy_exclude_domains, accept_hostnames=session.args.proxy_hostnames, reject_hostnames=session.args.proxy_exclude_hostnames ) return session.factory.new( 'ConnectionPool', http_proxy, proxy_ssl=proxy_ssl, authentication=authentication, resolver=session.factory['Resolver'], connection_factory=connection_factory, ssl_connection_factory=ssl_connection_factory, host_filter=host_filter, ) return session.factory.new( 'ConnectionPool', resolver=session.factory['Resolver'], connection_factory=connection_factory, ssl_connection_factory=ssl_connection_factory )
[ "def", "_build_connection_pool", "(", "cls", ",", "session", ":", "AppSession", ")", ":", "args", "=", "session", ".", "args", "connect_timeout", "=", "args", ".", "connect_timeout", "read_timeout", "=", "args", ".", "read_timeout", "if", "args", ".", "timeout...
Create connection pool.
[ "Create", "connection", "pool", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/network.py#L52-L130
train
201,534
ArchiveTeam/wpull
wpull/converter.py
BatchDocumentConverter.convert_all
def convert_all(self): '''Convert all links in URL table.''' for url_record in self._url_table.get_all(): if url_record.status != Status.done: continue self.convert_by_record(url_record)
python
def convert_all(self): '''Convert all links in URL table.''' for url_record in self._url_table.get_all(): if url_record.status != Status.done: continue self.convert_by_record(url_record)
[ "def", "convert_all", "(", "self", ")", ":", "for", "url_record", "in", "self", ".", "_url_table", ".", "get_all", "(", ")", ":", "if", "url_record", ".", "status", "!=", "Status", ".", "done", ":", "continue", "self", ".", "convert_by_record", "(", "url...
Convert all links in URL table.
[ "Convert", "all", "links", "in", "URL", "table", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/converter.py#L51-L57
train
201,535
ArchiveTeam/wpull
wpull/protocol/http/chunked.py
ChunkedTransferReader.read_chunk_header
def read_chunk_header(self): '''Read a single chunk's header. Returns: tuple: 2-item tuple with the size of the content in the chunk and the raw header byte string. Coroutine. ''' # _logger.debug('Reading chunk.') try: chunk_size_hex = yield from self._connection.readline() except ValueError as error: raise ProtocolError( 'Invalid chunk size: {0}'.format(error)) from error if not chunk_size_hex.endswith(b'\n'): raise NetworkError('Connection closed.') try: chunk_size = int(chunk_size_hex.split(b';', 1)[0].strip(), 16) except ValueError as error: raise ProtocolError( 'Invalid chunk size: {0}'.format(error)) from error if chunk_size < 0: raise ProtocolError('Chunk size cannot be negative.') self._chunk_size = self._bytes_left = chunk_size return chunk_size, chunk_size_hex
python
def read_chunk_header(self): '''Read a single chunk's header. Returns: tuple: 2-item tuple with the size of the content in the chunk and the raw header byte string. Coroutine. ''' # _logger.debug('Reading chunk.') try: chunk_size_hex = yield from self._connection.readline() except ValueError as error: raise ProtocolError( 'Invalid chunk size: {0}'.format(error)) from error if not chunk_size_hex.endswith(b'\n'): raise NetworkError('Connection closed.') try: chunk_size = int(chunk_size_hex.split(b';', 1)[0].strip(), 16) except ValueError as error: raise ProtocolError( 'Invalid chunk size: {0}'.format(error)) from error if chunk_size < 0: raise ProtocolError('Chunk size cannot be negative.') self._chunk_size = self._bytes_left = chunk_size return chunk_size, chunk_size_hex
[ "def", "read_chunk_header", "(", "self", ")", ":", "# _logger.debug('Reading chunk.')", "try", ":", "chunk_size_hex", "=", "yield", "from", "self", ".", "_connection", ".", "readline", "(", ")", "except", "ValueError", "as", "error", ":", "raise", "ProtocolError",...
Read a single chunk's header. Returns: tuple: 2-item tuple with the size of the content in the chunk and the raw header byte string. Coroutine.
[ "Read", "a", "single", "chunk", "s", "header", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/chunked.py#L30-L61
train
201,536
ArchiveTeam/wpull
wpull/protocol/http/chunked.py
ChunkedTransferReader.read_chunk_body
def read_chunk_body(self): '''Read a fragment of a single chunk. Call :meth:`read_chunk_header` first. Returns: tuple: 2-item tuple with the content data and raw data. First item is empty bytes string when chunk is fully read. Coroutine. ''' # chunk_size = self._chunk_size bytes_left = self._bytes_left # _logger.debug(__('Getting chunk size={0}, remain={1}.', # chunk_size, bytes_left)) if bytes_left > 0: size = min(bytes_left, self._read_size) data = yield from self._connection.read(size) self._bytes_left -= len(data) return (data, data) elif bytes_left < 0: raise ProtocolError('Chunked-transfer overrun.') elif bytes_left: raise NetworkError('Connection closed.') newline_data = yield from self._connection.readline() if len(newline_data) > 2: # Should be either CRLF or LF # This could our problem or the server's problem raise ProtocolError('Error reading newline after chunk.') self._chunk_size = self._bytes_left = None return (b'', newline_data)
python
def read_chunk_body(self): '''Read a fragment of a single chunk. Call :meth:`read_chunk_header` first. Returns: tuple: 2-item tuple with the content data and raw data. First item is empty bytes string when chunk is fully read. Coroutine. ''' # chunk_size = self._chunk_size bytes_left = self._bytes_left # _logger.debug(__('Getting chunk size={0}, remain={1}.', # chunk_size, bytes_left)) if bytes_left > 0: size = min(bytes_left, self._read_size) data = yield from self._connection.read(size) self._bytes_left -= len(data) return (data, data) elif bytes_left < 0: raise ProtocolError('Chunked-transfer overrun.') elif bytes_left: raise NetworkError('Connection closed.') newline_data = yield from self._connection.readline() if len(newline_data) > 2: # Should be either CRLF or LF # This could our problem or the server's problem raise ProtocolError('Error reading newline after chunk.') self._chunk_size = self._bytes_left = None return (b'', newline_data)
[ "def", "read_chunk_body", "(", "self", ")", ":", "# chunk_size = self._chunk_size", "bytes_left", "=", "self", ".", "_bytes_left", "# _logger.debug(__('Getting chunk size={0}, remain={1}.',", "# chunk_size, bytes_left))", "if", "bytes_left", ">", "0", ":", "size...
Read a fragment of a single chunk. Call :meth:`read_chunk_header` first. Returns: tuple: 2-item tuple with the content data and raw data. First item is empty bytes string when chunk is fully read. Coroutine.
[ "Read", "a", "fragment", "of", "a", "single", "chunk", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/chunked.py#L64-L102
train
201,537
ArchiveTeam/wpull
wpull/protocol/http/chunked.py
ChunkedTransferReader.read_trailer
def read_trailer(self): '''Read the HTTP trailer fields. Returns: bytes: The trailer data. Coroutine. ''' _logger.debug('Reading chunked trailer.') trailer_data_list = [] while True: trailer_data = yield from self._connection.readline() trailer_data_list.append(trailer_data) if not trailer_data.strip(): break return b''.join(trailer_data_list)
python
def read_trailer(self): '''Read the HTTP trailer fields. Returns: bytes: The trailer data. Coroutine. ''' _logger.debug('Reading chunked trailer.') trailer_data_list = [] while True: trailer_data = yield from self._connection.readline() trailer_data_list.append(trailer_data) if not trailer_data.strip(): break return b''.join(trailer_data_list)
[ "def", "read_trailer", "(", "self", ")", ":", "_logger", ".", "debug", "(", "'Reading chunked trailer.'", ")", "trailer_data_list", "=", "[", "]", "while", "True", ":", "trailer_data", "=", "yield", "from", "self", ".", "_connection", ".", "readline", "(", "...
Read the HTTP trailer fields. Returns: bytes: The trailer data. Coroutine.
[ "Read", "the", "HTTP", "trailer", "fields", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/chunked.py#L105-L125
train
201,538
ArchiveTeam/wpull
wpull/version.py
get_version_tuple
def get_version_tuple(string): '''Return a version tuple from a string.''' match = re.match(r'(\d+)\.(\d+)\.?(\d*)([abc]?)(\d*)', string) major = int(match.group(1)) minor = int(match.group(2)) patch = int(match.group(3) or 0) level = RELEASE_LEVEL_MAP.get(match.group(4), 'final') serial = int(match.group(5) or 0) return major, minor, patch, level, serial
python
def get_version_tuple(string): '''Return a version tuple from a string.''' match = re.match(r'(\d+)\.(\d+)\.?(\d*)([abc]?)(\d*)', string) major = int(match.group(1)) minor = int(match.group(2)) patch = int(match.group(3) or 0) level = RELEASE_LEVEL_MAP.get(match.group(4), 'final') serial = int(match.group(5) or 0) return major, minor, patch, level, serial
[ "def", "get_version_tuple", "(", "string", ")", ":", "match", "=", "re", ".", "match", "(", "r'(\\d+)\\.(\\d+)\\.?(\\d*)([abc]?)(\\d*)'", ",", "string", ")", "major", "=", "int", "(", "match", ".", "group", "(", "1", ")", ")", "minor", "=", "int", "(", "...
Return a version tuple from a string.
[ "Return", "a", "version", "tuple", "from", "a", "string", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/version.py#L23-L32
train
201,539
ArchiveTeam/wpull
wpull/application/tasks/database.py
InputURLTask._read_input_urls
def _read_input_urls(cls, session: AppSession, default_scheme='http'): '''Read the URLs provided by the user.''' url_string_iter = session.args.urls or () # FIXME: url rewriter isn't created yet url_rewriter = session.factory.get('URLRewriter') if session.args.input_file: if session.args.force_html: lines = cls._input_file_as_html_links(session) else: lines = cls._input_file_as_lines(session) url_string_iter = itertools.chain(url_string_iter, lines) base_url = session.args.base for url_string in url_string_iter: _logger.debug(__('Parsing URL {0}', url_string)) if base_url: url_string = wpull.url.urljoin(base_url, url_string) try: url_info = wpull.url.URLInfo.parse( url_string, default_scheme=default_scheme) _logger.debug(__('Parsed URL {0}', url_info)) if url_rewriter: # TODO: this logic should be a hook url_info = url_rewriter.rewrite(url_info) _logger.debug(__('Rewritten URL {0}', url_info)) yield url_info except ValueError as e: _logger.info(__('Invalid URL {0}: {1}', url_string, e))
python
def _read_input_urls(cls, session: AppSession, default_scheme='http'): '''Read the URLs provided by the user.''' url_string_iter = session.args.urls or () # FIXME: url rewriter isn't created yet url_rewriter = session.factory.get('URLRewriter') if session.args.input_file: if session.args.force_html: lines = cls._input_file_as_html_links(session) else: lines = cls._input_file_as_lines(session) url_string_iter = itertools.chain(url_string_iter, lines) base_url = session.args.base for url_string in url_string_iter: _logger.debug(__('Parsing URL {0}', url_string)) if base_url: url_string = wpull.url.urljoin(base_url, url_string) try: url_info = wpull.url.URLInfo.parse( url_string, default_scheme=default_scheme) _logger.debug(__('Parsed URL {0}', url_info)) if url_rewriter: # TODO: this logic should be a hook url_info = url_rewriter.rewrite(url_info) _logger.debug(__('Rewritten URL {0}', url_info)) yield url_info except ValueError as e: _logger.info(__('Invalid URL {0}: {1}', url_string, e))
[ "def", "_read_input_urls", "(", "cls", ",", "session", ":", "AppSession", ",", "default_scheme", "=", "'http'", ")", ":", "url_string_iter", "=", "session", ".", "args", ".", "urls", "or", "(", ")", "# FIXME: url rewriter isn't created yet", "url_rewriter", "=", ...
Read the URLs provided by the user.
[ "Read", "the", "URLs", "provided", "by", "the", "user", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/database.py#L56-L93
train
201,540
ArchiveTeam/wpull
wpull/application/tasks/database.py
InputURLTask._input_file_as_lines
def _input_file_as_lines(cls, session: AppSession): '''Read lines from input file and return them.''' if session.args.input_file == sys.stdin: input_file = session.args.input_file else: reader = codecs.getreader(session.args.local_encoding or 'utf-8') input_file = reader(session.args.input_file) return input_file
python
def _input_file_as_lines(cls, session: AppSession): '''Read lines from input file and return them.''' if session.args.input_file == sys.stdin: input_file = session.args.input_file else: reader = codecs.getreader(session.args.local_encoding or 'utf-8') input_file = reader(session.args.input_file) return input_file
[ "def", "_input_file_as_lines", "(", "cls", ",", "session", ":", "AppSession", ")", ":", "if", "session", ".", "args", ".", "input_file", "==", "sys", ".", "stdin", ":", "input_file", "=", "session", ".", "args", ".", "input_file", "else", ":", "reader", ...
Read lines from input file and return them.
[ "Read", "lines", "from", "input", "file", "and", "return", "them", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/database.py#L96-L104
train
201,541
ArchiveTeam/wpull
wpull/application/tasks/database.py
InputURLTask._input_file_as_html_links
def _input_file_as_html_links(cls, session: AppSession): '''Read input file as HTML and return the links.''' scrape_result = session.factory['HTMLScraper'].scrape_file( session.args.input_file, encoding=session.args.local_encoding or 'utf-8' ) for context in scrape_result.link_contexts: yield context.link
python
def _input_file_as_html_links(cls, session: AppSession): '''Read input file as HTML and return the links.''' scrape_result = session.factory['HTMLScraper'].scrape_file( session.args.input_file, encoding=session.args.local_encoding or 'utf-8' ) for context in scrape_result.link_contexts: yield context.link
[ "def", "_input_file_as_html_links", "(", "cls", ",", "session", ":", "AppSession", ")", ":", "scrape_result", "=", "session", ".", "factory", "[", "'HTMLScraper'", "]", ".", "scrape_file", "(", "session", ".", "args", ".", "input_file", ",", "encoding", "=", ...
Read input file as HTML and return the links.
[ "Read", "input", "file", "as", "HTML", "and", "return", "the", "links", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/database.py#L107-L115
train
201,542
ArchiveTeam/wpull
wpull/processor/web.py
WebProcessorSession._new_initial_request
def _new_initial_request(self, with_body: bool=True): '''Return a new Request to be passed to the Web Client.''' url_record = self._item_session.url_record url_info = url_record.url_info request = self._item_session.app_session.factory['WebClient'].request_factory(url_info.url) self._populate_common_request(request) if with_body: if url_record.post_data or self._processor.fetch_params.post_data: self._add_post_data(request) if self._file_writer_session: request = self._file_writer_session.process_request(request) return request
python
def _new_initial_request(self, with_body: bool=True): '''Return a new Request to be passed to the Web Client.''' url_record = self._item_session.url_record url_info = url_record.url_info request = self._item_session.app_session.factory['WebClient'].request_factory(url_info.url) self._populate_common_request(request) if with_body: if url_record.post_data or self._processor.fetch_params.post_data: self._add_post_data(request) if self._file_writer_session: request = self._file_writer_session.process_request(request) return request
[ "def", "_new_initial_request", "(", "self", ",", "with_body", ":", "bool", "=", "True", ")", ":", "url_record", "=", "self", ".", "_item_session", ".", "url_record", "url_info", "=", "url_record", ".", "url_info", "request", "=", "self", ".", "_item_session", ...
Return a new Request to be passed to the Web Client.
[ "Return", "a", "new", "Request", "to", "be", "passed", "to", "the", "Web", "Client", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/web.py#L132-L148
train
201,543
ArchiveTeam/wpull
wpull/processor/web.py
WebProcessorSession._populate_common_request
def _populate_common_request(self, request): '''Populate the Request with common fields.''' url_record = self._item_session.url_record # Note that referrer may have already been set by the --referer option if url_record.parent_url and not request.fields.get('Referer'): self._add_referrer(request, url_record) if self._fetch_rule.http_login: request.username, request.password = self._fetch_rule.http_login
python
def _populate_common_request(self, request): '''Populate the Request with common fields.''' url_record = self._item_session.url_record # Note that referrer may have already been set by the --referer option if url_record.parent_url and not request.fields.get('Referer'): self._add_referrer(request, url_record) if self._fetch_rule.http_login: request.username, request.password = self._fetch_rule.http_login
[ "def", "_populate_common_request", "(", "self", ",", "request", ")", ":", "url_record", "=", "self", ".", "_item_session", ".", "url_record", "# Note that referrer may have already been set by the --referer option", "if", "url_record", ".", "parent_url", "and", "not", "re...
Populate the Request with common fields.
[ "Populate", "the", "Request", "with", "common", "fields", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/web.py#L150-L159
train
201,544
ArchiveTeam/wpull
wpull/processor/web.py
WebProcessorSession._add_referrer
def _add_referrer(cls, request: Request, url_record: URLRecord): '''Add referrer URL to request.''' # Prohibit leak of referrer from HTTPS to HTTP # rfc7231 section 5.5.2. if url_record.parent_url.startswith('https://') and \ url_record.url_info.scheme == 'http': return request.fields['Referer'] = url_record.parent_url
python
def _add_referrer(cls, request: Request, url_record: URLRecord): '''Add referrer URL to request.''' # Prohibit leak of referrer from HTTPS to HTTP # rfc7231 section 5.5.2. if url_record.parent_url.startswith('https://') and \ url_record.url_info.scheme == 'http': return request.fields['Referer'] = url_record.parent_url
[ "def", "_add_referrer", "(", "cls", ",", "request", ":", "Request", ",", "url_record", ":", "URLRecord", ")", ":", "# Prohibit leak of referrer from HTTPS to HTTP", "# rfc7231 section 5.5.2.", "if", "url_record", ".", "parent_url", ".", "startswith", "(", "'https://'", ...
Add referrer URL to request.
[ "Add", "referrer", "URL", "to", "request", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/web.py#L162-L170
train
201,545
ArchiveTeam/wpull
wpull/processor/web.py
WebProcessorSession._process_robots
def _process_robots(self): '''Process robots.txt. Coroutine. ''' try: self._item_session.request = request = self._new_initial_request(with_body=False) verdict, reason = (yield from self._should_fetch_reason_with_robots( request)) except REMOTE_ERRORS as error: _logger.error( _('Fetching robots.txt for ‘{url}’ ' 'encountered an error: {error}'), url=self._next_url_info.url, error=error ) self._result_rule.handle_error(self._item_session, error) wait_time = self._result_rule.get_wait_time( self._item_session, error=error ) if wait_time: _logger.debug('Sleeping {0}.', wait_time) yield from asyncio.sleep(wait_time) return False else: _logger.debug('Robots filter verdict {} reason {}', verdict, reason) if not verdict: self._item_session.skip() return False return True
python
def _process_robots(self): '''Process robots.txt. Coroutine. ''' try: self._item_session.request = request = self._new_initial_request(with_body=False) verdict, reason = (yield from self._should_fetch_reason_with_robots( request)) except REMOTE_ERRORS as error: _logger.error( _('Fetching robots.txt for ‘{url}’ ' 'encountered an error: {error}'), url=self._next_url_info.url, error=error ) self._result_rule.handle_error(self._item_session, error) wait_time = self._result_rule.get_wait_time( self._item_session, error=error ) if wait_time: _logger.debug('Sleeping {0}.', wait_time) yield from asyncio.sleep(wait_time) return False else: _logger.debug('Robots filter verdict {} reason {}', verdict, reason) if not verdict: self._item_session.skip() return False return True
[ "def", "_process_robots", "(", "self", ")", ":", "try", ":", "self", ".", "_item_session", ".", "request", "=", "request", "=", "self", ".", "_new_initial_request", "(", "with_body", "=", "False", ")", "verdict", ",", "reason", "=", "(", "yield", "from", ...
Process robots.txt. Coroutine.
[ "Process", "robots", ".", "txt", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/web.py#L193-L226
train
201,546
ArchiveTeam/wpull
wpull/processor/web.py
WebProcessorSession._process_loop
def _process_loop(self): '''Fetch URL including redirects. Coroutine. ''' while not self._web_client_session.done(): self._item_session.request = self._web_client_session.next_request() verdict, reason = self._should_fetch_reason() _logger.debug('Filter verdict {} reason {}', verdict, reason) if not verdict: self._item_session.skip() break exit_early, wait_time = yield from self._fetch_one(cast(Request, self._item_session.request)) if wait_time: _logger.debug('Sleeping {}', wait_time) yield from asyncio.sleep(wait_time) if exit_early: break
python
def _process_loop(self): '''Fetch URL including redirects. Coroutine. ''' while not self._web_client_session.done(): self._item_session.request = self._web_client_session.next_request() verdict, reason = self._should_fetch_reason() _logger.debug('Filter verdict {} reason {}', verdict, reason) if not verdict: self._item_session.skip() break exit_early, wait_time = yield from self._fetch_one(cast(Request, self._item_session.request)) if wait_time: _logger.debug('Sleeping {}', wait_time) yield from asyncio.sleep(wait_time) if exit_early: break
[ "def", "_process_loop", "(", "self", ")", ":", "while", "not", "self", ".", "_web_client_session", ".", "done", "(", ")", ":", "self", ".", "_item_session", ".", "request", "=", "self", ".", "_web_client_session", ".", "next_request", "(", ")", "verdict", ...
Fetch URL including redirects. Coroutine.
[ "Fetch", "URL", "including", "redirects", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/web.py#L229-L252
train
201,547
ArchiveTeam/wpull
wpull/processor/web.py
WebProcessorSession._next_url_info
def _next_url_info(self) -> URLInfo: '''Return the next URLInfo to be processed. This returns either the original URLInfo or the next URLinfo containing the redirect link. ''' if not self._web_client_session: return self._item_session.url_record.url_info return self._web_client_session.next_request().url_info
python
def _next_url_info(self) -> URLInfo: '''Return the next URLInfo to be processed. This returns either the original URLInfo or the next URLinfo containing the redirect link. ''' if not self._web_client_session: return self._item_session.url_record.url_info return self._web_client_session.next_request().url_info
[ "def", "_next_url_info", "(", "self", ")", "->", "URLInfo", ":", "if", "not", "self", ".", "_web_client_session", ":", "return", "self", ".", "_item_session", ".", "url_record", ".", "url_info", "return", "self", ".", "_web_client_session", ".", "next_request", ...
Return the next URLInfo to be processed. This returns either the original URLInfo or the next URLinfo containing the redirect link.
[ "Return", "the", "next", "URLInfo", "to", "be", "processed", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/web.py#L327-L336
train
201,548
ArchiveTeam/wpull
wpull/processor/web.py
WebProcessorSession._should_fetch_reason
def _should_fetch_reason(self) -> Tuple[bool, str]: '''Return info about whether the URL should be fetched. Returns: tuple: A two item tuple: 1. bool: If True, the URL should be fetched. 2. str: A short reason string explaining the verdict. ''' is_redirect = False if self._strong_redirects: try: is_redirect = self._web_client_session.redirect_tracker\ .is_redirect() except AttributeError: pass return self._fetch_rule.check_subsequent_web_request( self._item_session, is_redirect=is_redirect)
python
def _should_fetch_reason(self) -> Tuple[bool, str]: '''Return info about whether the URL should be fetched. Returns: tuple: A two item tuple: 1. bool: If True, the URL should be fetched. 2. str: A short reason string explaining the verdict. ''' is_redirect = False if self._strong_redirects: try: is_redirect = self._web_client_session.redirect_tracker\ .is_redirect() except AttributeError: pass return self._fetch_rule.check_subsequent_web_request( self._item_session, is_redirect=is_redirect)
[ "def", "_should_fetch_reason", "(", "self", ")", "->", "Tuple", "[", "bool", ",", "str", "]", ":", "is_redirect", "=", "False", "if", "self", ".", "_strong_redirects", ":", "try", ":", "is_redirect", "=", "self", ".", "_web_client_session", ".", "redirect_tr...
Return info about whether the URL should be fetched. Returns: tuple: A two item tuple: 1. bool: If True, the URL should be fetched. 2. str: A short reason string explaining the verdict.
[ "Return", "info", "about", "whether", "the", "URL", "should", "be", "fetched", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/web.py#L338-L357
train
201,549
ArchiveTeam/wpull
wpull/processor/web.py
WebProcessorSession._should_fetch_reason_with_robots
def _should_fetch_reason_with_robots(self, request: Request) -> Tuple[bool, str]: '''Return info whether the URL should be fetched including checking robots.txt. Coroutine. ''' result = yield from \ self._fetch_rule.check_initial_web_request(self._item_session, request) return result
python
def _should_fetch_reason_with_robots(self, request: Request) -> Tuple[bool, str]: '''Return info whether the URL should be fetched including checking robots.txt. Coroutine. ''' result = yield from \ self._fetch_rule.check_initial_web_request(self._item_session, request) return result
[ "def", "_should_fetch_reason_with_robots", "(", "self", ",", "request", ":", "Request", ")", "->", "Tuple", "[", "bool", ",", "str", "]", ":", "result", "=", "yield", "from", "self", ".", "_fetch_rule", ".", "check_initial_web_request", "(", "self", ".", "_i...
Return info whether the URL should be fetched including checking robots.txt. Coroutine.
[ "Return", "info", "whether", "the", "URL", "should", "be", "fetched", "including", "checking", "robots", ".", "txt", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/web.py#L360-L368
train
201,550
ArchiveTeam/wpull
wpull/processor/web.py
WebProcessorSession._add_post_data
def _add_post_data(self, request: Request): '''Add data to the payload.''' if self._item_session.url_record.post_data: data = wpull.string.to_bytes(self._item_session.url_record.post_data) else: data = wpull.string.to_bytes( self._processor.fetch_params.post_data ) request.method = 'POST' request.fields['Content-Type'] = 'application/x-www-form-urlencoded' request.fields['Content-Length'] = str(len(data)) _logger.debug('Posting with data {0}.', data) if not request.body: request.body = Body(io.BytesIO()) with wpull.util.reset_file_offset(request.body): request.body.write(data)
python
def _add_post_data(self, request: Request): '''Add data to the payload.''' if self._item_session.url_record.post_data: data = wpull.string.to_bytes(self._item_session.url_record.post_data) else: data = wpull.string.to_bytes( self._processor.fetch_params.post_data ) request.method = 'POST' request.fields['Content-Type'] = 'application/x-www-form-urlencoded' request.fields['Content-Length'] = str(len(data)) _logger.debug('Posting with data {0}.', data) if not request.body: request.body = Body(io.BytesIO()) with wpull.util.reset_file_offset(request.body): request.body.write(data)
[ "def", "_add_post_data", "(", "self", ",", "request", ":", "Request", ")", ":", "if", "self", ".", "_item_session", ".", "url_record", ".", "post_data", ":", "data", "=", "wpull", ".", "string", ".", "to_bytes", "(", "self", ".", "_item_session", ".", "u...
Add data to the payload.
[ "Add", "data", "to", "the", "payload", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/web.py#L370-L389
train
201,551
ArchiveTeam/wpull
wpull/application/options.py
AppArgumentParser.int_0_inf
def int_0_inf(cls, string): '''Convert string to int. If ``inf`` is supplied, it returns ``0``. ''' if string == 'inf': return 0 try: value = int(string) except ValueError as error: raise argparse.ArgumentTypeError(error) if value < 0: raise argparse.ArgumentTypeError(_('Value must not be negative.')) else: return value
python
def int_0_inf(cls, string): '''Convert string to int. If ``inf`` is supplied, it returns ``0``. ''' if string == 'inf': return 0 try: value = int(string) except ValueError as error: raise argparse.ArgumentTypeError(error) if value < 0: raise argparse.ArgumentTypeError(_('Value must not be negative.')) else: return value
[ "def", "int_0_inf", "(", "cls", ",", "string", ")", ":", "if", "string", "==", "'inf'", ":", "return", "0", "try", ":", "value", "=", "int", "(", "string", ")", "except", "ValueError", "as", "error", ":", "raise", "argparse", ".", "ArgumentTypeError", ...
Convert string to int. If ``inf`` is supplied, it returns ``0``.
[ "Convert", "string", "to", "int", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/options.py#L104-L120
train
201,552
ArchiveTeam/wpull
wpull/application/options.py
AppArgumentParser.int_bytes
def int_bytes(cls, string): '''Convert string describing size to int.''' if string[-1] in ('k', 'm'): value = cls.int_0_inf(string[:-1]) unit = string[-1] if unit == 'k': value *= 2 ** 10 else: value *= 2 ** 20 return value else: return cls.int_0_inf(string)
python
def int_bytes(cls, string): '''Convert string describing size to int.''' if string[-1] in ('k', 'm'): value = cls.int_0_inf(string[:-1]) unit = string[-1] if unit == 'k': value *= 2 ** 10 else: value *= 2 ** 20 return value else: return cls.int_0_inf(string)
[ "def", "int_bytes", "(", "cls", ",", "string", ")", ":", "if", "string", "[", "-", "1", "]", "in", "(", "'k'", ",", "'m'", ")", ":", "value", "=", "cls", ".", "int_0_inf", "(", "string", "[", ":", "-", "1", "]", ")", "unit", "=", "string", "[...
Convert string describing size to int.
[ "Convert", "string", "describing", "size", "to", "int", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/options.py#L123-L134
train
201,553
ArchiveTeam/wpull
wpull/application/options.py
AppArgumentParser.comma_list
def comma_list(cls, string): '''Convert a comma separated string to list.''' items = string.split(',') items = list([item.strip() for item in items]) return items
python
def comma_list(cls, string): '''Convert a comma separated string to list.''' items = string.split(',') items = list([item.strip() for item in items]) return items
[ "def", "comma_list", "(", "cls", ",", "string", ")", ":", "items", "=", "string", ".", "split", "(", "','", ")", "items", "=", "list", "(", "[", "item", ".", "strip", "(", ")", "for", "item", "in", "items", "]", ")", "return", "items" ]
Convert a comma separated string to list.
[ "Convert", "a", "comma", "separated", "string", "to", "list", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/options.py#L137-L141
train
201,554
ArchiveTeam/wpull
wpull/application/options.py
AppArgumentParser.comma_choice_list
def comma_choice_list(cls, string): '''Convert a comma separated string to `CommaChoiceListArgs`.''' items = string.split(',') items = CommaChoiceListArgs([item.strip() for item in items]) return items
python
def comma_choice_list(cls, string): '''Convert a comma separated string to `CommaChoiceListArgs`.''' items = string.split(',') items = CommaChoiceListArgs([item.strip() for item in items]) return items
[ "def", "comma_choice_list", "(", "cls", ",", "string", ")", ":", "items", "=", "string", ".", "split", "(", "','", ")", "items", "=", "CommaChoiceListArgs", "(", "[", "item", ".", "strip", "(", ")", "for", "item", "in", "items", "]", ")", "return", "...
Convert a comma separated string to `CommaChoiceListArgs`.
[ "Convert", "a", "comma", "separated", "string", "to", "CommaChoiceListArgs", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/options.py#L144-L148
train
201,555
ArchiveTeam/wpull
wpull/document/javascript.py
JavaScriptReader.read_links
def read_links(self, file, encoding=None): '''Return an iterator of links found in the document. Args: file: A file object containing the document. encoding (str): The encoding of the document. Returns: iterable: str ''' return [item[0] for item in self.iter_text(file, encoding) if item[1]]
python
def read_links(self, file, encoding=None): '''Return an iterator of links found in the document. Args: file: A file object containing the document. encoding (str): The encoding of the document. Returns: iterable: str ''' return [item[0] for item in self.iter_text(file, encoding) if item[1]]
[ "def", "read_links", "(", "self", ",", "file", ",", "encoding", "=", "None", ")", ":", "return", "[", "item", "[", "0", "]", "for", "item", "in", "self", ".", "iter_text", "(", "file", ",", "encoding", ")", "if", "item", "[", "1", "]", "]" ]
Return an iterator of links found in the document. Args: file: A file object containing the document. encoding (str): The encoding of the document. Returns: iterable: str
[ "Return", "an", "iterator", "of", "links", "found", "in", "the", "document", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/document/javascript.py#L68-L78
train
201,556
ArchiveTeam/wpull
wpull/application/tasks/writer.py
FileWriterSetupTask._build_file_writer
def _build_file_writer(cls, session: AppSession): '''Create the File Writer. Returns: FileWriter: An instance of :class:`.writer.BaseFileWriter`. ''' args = session.args if args.delete_after: return session.factory.new('FileWriter') # is a NullWriter elif args.output_document: session.factory.class_map['FileWriter'] = SingleDocumentWriter return session.factory.new('FileWriter', args.output_document, headers_included=args.save_headers) use_dir = (len(args.urls) != 1 or args.page_requisites or args.recursive) if args.use_directories == 'force': use_dir = True elif args.use_directories == 'no': use_dir = False os_type = 'windows' if 'windows' in args.restrict_file_names \ else 'unix' ascii_only = 'ascii' in args.restrict_file_names no_control = 'nocontrol' not in args.restrict_file_names if 'lower' in args.restrict_file_names: case = 'lower' elif 'upper' in args.restrict_file_names: case = 'upper' else: case = None path_namer = session.factory.new( 'PathNamer', args.directory_prefix, index=args.default_page, use_dir=use_dir, cut=args.cut_dirs, protocol=args.protocol_directories, hostname=args.host_directories, os_type=os_type, ascii_only=ascii_only, no_control=no_control, case=case, max_filename_length=args.max_filename_length, ) if args.recursive or args.page_requisites or args.continue_download: if args.clobber_method == 'disable': file_class = OverwriteFileWriter else: file_class = IgnoreFileWriter elif args.timestamping: file_class = TimestampingFileWriter else: file_class = AntiClobberFileWriter session.factory.class_map['FileWriter'] = file_class return session.factory.new( 'FileWriter', path_namer, file_continuing=args.continue_download, headers_included=args.save_headers, local_timestamping=args.use_server_timestamps, adjust_extension=args.adjust_extension, content_disposition=args.content_disposition, trust_server_names=args.trust_server_names, )
python
def _build_file_writer(cls, session: AppSession): '''Create the File Writer. Returns: FileWriter: An instance of :class:`.writer.BaseFileWriter`. ''' args = session.args if args.delete_after: return session.factory.new('FileWriter') # is a NullWriter elif args.output_document: session.factory.class_map['FileWriter'] = SingleDocumentWriter return session.factory.new('FileWriter', args.output_document, headers_included=args.save_headers) use_dir = (len(args.urls) != 1 or args.page_requisites or args.recursive) if args.use_directories == 'force': use_dir = True elif args.use_directories == 'no': use_dir = False os_type = 'windows' if 'windows' in args.restrict_file_names \ else 'unix' ascii_only = 'ascii' in args.restrict_file_names no_control = 'nocontrol' not in args.restrict_file_names if 'lower' in args.restrict_file_names: case = 'lower' elif 'upper' in args.restrict_file_names: case = 'upper' else: case = None path_namer = session.factory.new( 'PathNamer', args.directory_prefix, index=args.default_page, use_dir=use_dir, cut=args.cut_dirs, protocol=args.protocol_directories, hostname=args.host_directories, os_type=os_type, ascii_only=ascii_only, no_control=no_control, case=case, max_filename_length=args.max_filename_length, ) if args.recursive or args.page_requisites or args.continue_download: if args.clobber_method == 'disable': file_class = OverwriteFileWriter else: file_class = IgnoreFileWriter elif args.timestamping: file_class = TimestampingFileWriter else: file_class = AntiClobberFileWriter session.factory.class_map['FileWriter'] = file_class return session.factory.new( 'FileWriter', path_namer, file_continuing=args.continue_download, headers_included=args.save_headers, local_timestamping=args.use_server_timestamps, adjust_extension=args.adjust_extension, content_disposition=args.content_disposition, trust_server_names=args.trust_server_names, )
[ "def", "_build_file_writer", "(", "cls", ",", "session", ":", "AppSession", ")", ":", "args", "=", "session", ".", "args", "if", "args", ".", "delete_after", ":", "return", "session", ".", "factory", ".", "new", "(", "'FileWriter'", ")", "# is a NullWriter",...
Create the File Writer. Returns: FileWriter: An instance of :class:`.writer.BaseFileWriter`.
[ "Create", "the", "File", "Writer", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/writer.py#L21-L93
train
201,557
ArchiveTeam/wpull
wpull/application/app.py
Application.setup_signal_handlers
def setup_signal_handlers(self): '''Setup Ctrl+C and SIGTERM handlers.''' if platform.system() == 'Windows': _logger.warning(_( 'Graceful stopping with Unix signals is not supported ' 'on this OS.' )) return event_loop = asyncio.get_event_loop() graceful_called = False def graceful_stop_callback(): nonlocal graceful_called if graceful_called: forceful_stop_callback() return graceful_called = True _logger.info(_('Stopping once all requests complete...')) _logger.info(_('Interrupt again to force stopping immediately.')) self.stop() def forceful_stop_callback(): _logger.info(_('Forcing immediate stop...')) logging.raiseExceptions = False event_loop.stop() event_loop.add_signal_handler(signal.SIGINT, graceful_stop_callback) event_loop.add_signal_handler(signal.SIGTERM, forceful_stop_callback)
python
def setup_signal_handlers(self): '''Setup Ctrl+C and SIGTERM handlers.''' if platform.system() == 'Windows': _logger.warning(_( 'Graceful stopping with Unix signals is not supported ' 'on this OS.' )) return event_loop = asyncio.get_event_loop() graceful_called = False def graceful_stop_callback(): nonlocal graceful_called if graceful_called: forceful_stop_callback() return graceful_called = True _logger.info(_('Stopping once all requests complete...')) _logger.info(_('Interrupt again to force stopping immediately.')) self.stop() def forceful_stop_callback(): _logger.info(_('Forcing immediate stop...')) logging.raiseExceptions = False event_loop.stop() event_loop.add_signal_handler(signal.SIGINT, graceful_stop_callback) event_loop.add_signal_handler(signal.SIGTERM, forceful_stop_callback)
[ "def", "setup_signal_handlers", "(", "self", ")", ":", "if", "platform", ".", "system", "(", ")", "==", "'Windows'", ":", "_logger", ".", "warning", "(", "_", "(", "'Graceful stopping with Unix signals is not supported '", "'on this OS.'", ")", ")", "return", "eve...
Setup Ctrl+C and SIGTERM handlers.
[ "Setup", "Ctrl", "+", "C", "and", "SIGTERM", "handlers", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/app.py#L82-L113
train
201,558
ArchiveTeam/wpull
wpull/application/app.py
Application._update_exit_code_from_error
def _update_exit_code_from_error(self, error): '''Set the exit code based on the error type. Args: error (:class:`Exception`): An exception instance. ''' for error_type, exit_code in self.ERROR_CODE_MAP.items(): if isinstance(error, error_type): self.update_exit_code(exit_code) break else: self.update_exit_code(ExitStatus.generic_error)
python
def _update_exit_code_from_error(self, error): '''Set the exit code based on the error type. Args: error (:class:`Exception`): An exception instance. ''' for error_type, exit_code in self.ERROR_CODE_MAP.items(): if isinstance(error, error_type): self.update_exit_code(exit_code) break else: self.update_exit_code(ExitStatus.generic_error)
[ "def", "_update_exit_code_from_error", "(", "self", ",", "error", ")", ":", "for", "error_type", ",", "exit_code", "in", "self", ".", "ERROR_CODE_MAP", ".", "items", "(", ")", ":", "if", "isinstance", "(", "error", ",", "error_type", ")", ":", "self", ".",...
Set the exit code based on the error type. Args: error (:class:`Exception`): An exception instance.
[ "Set", "the", "exit", "code", "based", "on", "the", "error", "type", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/app.py#L196-L207
train
201,559
ArchiveTeam/wpull
wpull/application/app.py
Application.update_exit_code
def update_exit_code(self, code: int): '''Set the exit code if it is serious than before. Args: code: The exit code. ''' if code: if self._exit_code: self._exit_code = min(self._exit_code, code) else: self._exit_code = code
python
def update_exit_code(self, code: int): '''Set the exit code if it is serious than before. Args: code: The exit code. ''' if code: if self._exit_code: self._exit_code = min(self._exit_code, code) else: self._exit_code = code
[ "def", "update_exit_code", "(", "self", ",", "code", ":", "int", ")", ":", "if", "code", ":", "if", "self", ".", "_exit_code", ":", "self", ".", "_exit_code", "=", "min", "(", "self", ".", "_exit_code", ",", "code", ")", "else", ":", "self", ".", "...
Set the exit code if it is serious than before. Args: code: The exit code.
[ "Set", "the", "exit", "code", "if", "it", "is", "serious", "than", "before", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/app.py#L209-L219
train
201,560
ArchiveTeam/wpull
wpull/processor/rule.py
FetchRule.consult_robots_txt
def consult_robots_txt(self, request: HTTPRequest) -> bool: '''Consult by fetching robots.txt as needed. Args: request: The request to be made to get the file. Returns: True if can fetch Coroutine ''' if not self._robots_txt_checker: return True result = yield from self._robots_txt_checker.can_fetch(request) return result
python
def consult_robots_txt(self, request: HTTPRequest) -> bool: '''Consult by fetching robots.txt as needed. Args: request: The request to be made to get the file. Returns: True if can fetch Coroutine ''' if not self._robots_txt_checker: return True result = yield from self._robots_txt_checker.can_fetch(request) return result
[ "def", "consult_robots_txt", "(", "self", ",", "request", ":", "HTTPRequest", ")", "->", "bool", ":", "if", "not", "self", ".", "_robots_txt_checker", ":", "return", "True", "result", "=", "yield", "from", "self", ".", "_robots_txt_checker", ".", "can_fetch", ...
Consult by fetching robots.txt as needed. Args: request: The request to be made to get the file. Returns: True if can fetch Coroutine
[ "Consult", "by", "fetching", "robots", ".", "txt", "as", "needed", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/rule.py#L47-L63
train
201,561
ArchiveTeam/wpull
wpull/processor/rule.py
FetchRule.consult_filters
def consult_filters(self, url_info: URLInfo, url_record: URLRecord, is_redirect: bool=False) \ -> Tuple[bool, str, dict]: '''Consult the URL filter. Args: url_record: The URL record. is_redirect: Whether the request is a redirect and it is desired that it spans hosts. Returns tuple: 1. bool: The verdict 2. str: A short reason string: nofilters, filters, redirect 3. dict: The result from :func:`DemuxURLFilter.test_info` ''' if not self._url_filter: return True, 'nofilters', None test_info = self._url_filter.test_info(url_info, url_record) verdict = test_info['verdict'] if verdict: reason = 'filters' elif is_redirect and self.is_only_span_hosts_failed(test_info): verdict = True reason = 'redirect' else: reason = 'filters' return verdict, reason, test_info
python
def consult_filters(self, url_info: URLInfo, url_record: URLRecord, is_redirect: bool=False) \ -> Tuple[bool, str, dict]: '''Consult the URL filter. Args: url_record: The URL record. is_redirect: Whether the request is a redirect and it is desired that it spans hosts. Returns tuple: 1. bool: The verdict 2. str: A short reason string: nofilters, filters, redirect 3. dict: The result from :func:`DemuxURLFilter.test_info` ''' if not self._url_filter: return True, 'nofilters', None test_info = self._url_filter.test_info(url_info, url_record) verdict = test_info['verdict'] if verdict: reason = 'filters' elif is_redirect and self.is_only_span_hosts_failed(test_info): verdict = True reason = 'redirect' else: reason = 'filters' return verdict, reason, test_info
[ "def", "consult_filters", "(", "self", ",", "url_info", ":", "URLInfo", ",", "url_record", ":", "URLRecord", ",", "is_redirect", ":", "bool", "=", "False", ")", "->", "Tuple", "[", "bool", ",", "str", ",", "dict", "]", ":", "if", "not", "self", ".", ...
Consult the URL filter. Args: url_record: The URL record. is_redirect: Whether the request is a redirect and it is desired that it spans hosts. Returns tuple: 1. bool: The verdict 2. str: A short reason string: nofilters, filters, redirect 3. dict: The result from :func:`DemuxURLFilter.test_info`
[ "Consult", "the", "URL", "filter", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/rule.py#L74-L105
train
201,562
ArchiveTeam/wpull
wpull/processor/rule.py
FetchRule.consult_hook
def consult_hook(self, item_session: ItemSession, verdict: bool, reason: str, test_info: dict): '''Consult the scripting hook. Returns: tuple: (bool, str) ''' try: reasons = { 'filters': test_info['map'], 'reason': reason, } verdict = self.hook_dispatcher.call( PluginFunctions.accept_url, item_session, verdict, reasons, ) reason = 'callback_hook' except HookDisconnected: pass return verdict, reason
python
def consult_hook(self, item_session: ItemSession, verdict: bool, reason: str, test_info: dict): '''Consult the scripting hook. Returns: tuple: (bool, str) ''' try: reasons = { 'filters': test_info['map'], 'reason': reason, } verdict = self.hook_dispatcher.call( PluginFunctions.accept_url, item_session, verdict, reasons, ) reason = 'callback_hook' except HookDisconnected: pass return verdict, reason
[ "def", "consult_hook", "(", "self", ",", "item_session", ":", "ItemSession", ",", "verdict", ":", "bool", ",", "reason", ":", "str", ",", "test_info", ":", "dict", ")", ":", "try", ":", "reasons", "=", "{", "'filters'", ":", "test_info", "[", "'map'", ...
Consult the scripting hook. Returns: tuple: (bool, str)
[ "Consult", "the", "scripting", "hook", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/rule.py#L116-L136
train
201,563
ArchiveTeam/wpull
wpull/processor/rule.py
FetchRule.check_initial_web_request
def check_initial_web_request(self, item_session: ItemSession, request: HTTPRequest) -> Tuple[bool, str]: '''Check robots.txt, URL filters, and scripting hook. Returns: tuple: (bool, str) Coroutine. ''' verdict, reason, test_info = self.consult_filters(item_session.request.url_info, item_session.url_record) if verdict and self._robots_txt_checker: can_fetch = yield from self.consult_robots_txt(request) if not can_fetch: verdict = False reason = 'robotstxt' verdict, reason = self.consult_hook( item_session, verdict, reason, test_info ) return verdict, reason
python
def check_initial_web_request(self, item_session: ItemSession, request: HTTPRequest) -> Tuple[bool, str]: '''Check robots.txt, URL filters, and scripting hook. Returns: tuple: (bool, str) Coroutine. ''' verdict, reason, test_info = self.consult_filters(item_session.request.url_info, item_session.url_record) if verdict and self._robots_txt_checker: can_fetch = yield from self.consult_robots_txt(request) if not can_fetch: verdict = False reason = 'robotstxt' verdict, reason = self.consult_hook( item_session, verdict, reason, test_info ) return verdict, reason
[ "def", "check_initial_web_request", "(", "self", ",", "item_session", ":", "ItemSession", ",", "request", ":", "HTTPRequest", ")", "->", "Tuple", "[", "bool", ",", "str", "]", ":", "verdict", ",", "reason", ",", "test_info", "=", "self", ".", "consult_filter...
Check robots.txt, URL filters, and scripting hook. Returns: tuple: (bool, str) Coroutine.
[ "Check", "robots", ".", "txt", "URL", "filters", "and", "scripting", "hook", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/rule.py#L161-L182
train
201,564
ArchiveTeam/wpull
wpull/processor/rule.py
ResultRule.handle_pre_response
def handle_pre_response(self, item_session: ItemSession) -> Actions: '''Process a response that is starting.''' action = self.consult_pre_response_hook(item_session) if action == Actions.RETRY: item_session.set_status(Status.skipped) elif action == Actions.FINISH: item_session.set_status(Status.done) elif action == Actions.STOP: raise HookStop('Script requested immediate stop.') return action
python
def handle_pre_response(self, item_session: ItemSession) -> Actions: '''Process a response that is starting.''' action = self.consult_pre_response_hook(item_session) if action == Actions.RETRY: item_session.set_status(Status.skipped) elif action == Actions.FINISH: item_session.set_status(Status.done) elif action == Actions.STOP: raise HookStop('Script requested immediate stop.') return action
[ "def", "handle_pre_response", "(", "self", ",", "item_session", ":", "ItemSession", ")", "->", "Actions", ":", "action", "=", "self", ".", "consult_pre_response_hook", "(", "item_session", ")", "if", "action", "==", "Actions", ".", "RETRY", ":", "item_session", ...
Process a response that is starting.
[ "Process", "a", "response", "that", "is", "starting", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/rule.py#L251-L262
train
201,565
ArchiveTeam/wpull
wpull/processor/rule.py
ResultRule.handle_document
def handle_document(self, item_session: ItemSession, filename: str) -> Actions: '''Process a successful document response. Returns: A value from :class:`.hook.Actions`. ''' self._waiter.reset() action = self.handle_response(item_session) if action == Actions.NORMAL: self._statistics.increment(item_session.response.body.size()) item_session.set_status(Status.done, filename=filename) return action
python
def handle_document(self, item_session: ItemSession, filename: str) -> Actions: '''Process a successful document response. Returns: A value from :class:`.hook.Actions`. ''' self._waiter.reset() action = self.handle_response(item_session) if action == Actions.NORMAL: self._statistics.increment(item_session.response.body.size()) item_session.set_status(Status.done, filename=filename) return action
[ "def", "handle_document", "(", "self", ",", "item_session", ":", "ItemSession", ",", "filename", ":", "str", ")", "->", "Actions", ":", "self", ".", "_waiter", ".", "reset", "(", ")", "action", "=", "self", ".", "handle_response", "(", "item_session", ")",...
Process a successful document response. Returns: A value from :class:`.hook.Actions`.
[ "Process", "a", "successful", "document", "response", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/rule.py#L264-L278
train
201,566
ArchiveTeam/wpull
wpull/processor/rule.py
ResultRule.handle_no_document
def handle_no_document(self, item_session: ItemSession) -> Actions: '''Callback for successful responses containing no useful document. Returns: A value from :class:`.hook.Actions`. ''' self._waiter.reset() action = self.handle_response(item_session) if action == Actions.NORMAL: item_session.set_status(Status.skipped) return action
python
def handle_no_document(self, item_session: ItemSession) -> Actions: '''Callback for successful responses containing no useful document. Returns: A value from :class:`.hook.Actions`. ''' self._waiter.reset() action = self.handle_response(item_session) if action == Actions.NORMAL: item_session.set_status(Status.skipped) return action
[ "def", "handle_no_document", "(", "self", ",", "item_session", ":", "ItemSession", ")", "->", "Actions", ":", "self", ".", "_waiter", ".", "reset", "(", ")", "action", "=", "self", ".", "handle_response", "(", "item_session", ")", "if", "action", "==", "Ac...
Callback for successful responses containing no useful document. Returns: A value from :class:`.hook.Actions`.
[ "Callback", "for", "successful", "responses", "containing", "no", "useful", "document", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/rule.py#L280-L293
train
201,567
ArchiveTeam/wpull
wpull/processor/rule.py
ResultRule.handle_intermediate_response
def handle_intermediate_response(self, item_session: ItemSession) -> Actions: '''Callback for successful intermediate responses. Returns: A value from :class:`.hook.Actions`. ''' self._waiter.reset() action = self.handle_response(item_session) return action
python
def handle_intermediate_response(self, item_session: ItemSession) -> Actions: '''Callback for successful intermediate responses. Returns: A value from :class:`.hook.Actions`. ''' self._waiter.reset() action = self.handle_response(item_session) return action
[ "def", "handle_intermediate_response", "(", "self", ",", "item_session", ":", "ItemSession", ")", "->", "Actions", ":", "self", ".", "_waiter", ".", "reset", "(", ")", "action", "=", "self", ".", "handle_response", "(", "item_session", ")", "return", "action" ...
Callback for successful intermediate responses. Returns: A value from :class:`.hook.Actions`.
[ "Callback", "for", "successful", "intermediate", "responses", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/rule.py#L295-L305
train
201,568
ArchiveTeam/wpull
wpull/processor/rule.py
ResultRule.handle_document_error
def handle_document_error(self, item_session: ItemSession) -> Actions: '''Callback for when the document only describes an server error. Returns: A value from :class:`.hook.Actions`. ''' self._waiter.increment() self._statistics.errors[ServerError] += 1 action = self.handle_response(item_session) if action == Actions.NORMAL: item_session.set_status(Status.error) return action
python
def handle_document_error(self, item_session: ItemSession) -> Actions: '''Callback for when the document only describes an server error. Returns: A value from :class:`.hook.Actions`. ''' self._waiter.increment() self._statistics.errors[ServerError] += 1 action = self.handle_response(item_session) if action == Actions.NORMAL: item_session.set_status(Status.error) return action
[ "def", "handle_document_error", "(", "self", ",", "item_session", ":", "ItemSession", ")", "->", "Actions", ":", "self", ".", "_waiter", ".", "increment", "(", ")", "self", ".", "_statistics", ".", "errors", "[", "ServerError", "]", "+=", "1", "action", "=...
Callback for when the document only describes an server error. Returns: A value from :class:`.hook.Actions`.
[ "Callback", "for", "when", "the", "document", "only", "describes", "an", "server", "error", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/rule.py#L307-L322
train
201,569
ArchiveTeam/wpull
wpull/processor/rule.py
ResultRule.handle_response
def handle_response(self, item_session: ItemSession) -> Actions: '''Generic handler for a response. Returns: A value from :class:`.hook.Actions`. ''' action = self.consult_response_hook(item_session) if action == Actions.RETRY: item_session.set_status(Status.error) elif action == Actions.FINISH: item_session.set_status(Status.done) elif action == Actions.STOP: raise HookStop('Script requested immediate stop.') return action
python
def handle_response(self, item_session: ItemSession) -> Actions: '''Generic handler for a response. Returns: A value from :class:`.hook.Actions`. ''' action = self.consult_response_hook(item_session) if action == Actions.RETRY: item_session.set_status(Status.error) elif action == Actions.FINISH: item_session.set_status(Status.done) elif action == Actions.STOP: raise HookStop('Script requested immediate stop.') return action
[ "def", "handle_response", "(", "self", ",", "item_session", ":", "ItemSession", ")", "->", "Actions", ":", "action", "=", "self", ".", "consult_response_hook", "(", "item_session", ")", "if", "action", "==", "Actions", ".", "RETRY", ":", "item_session", ".", ...
Generic handler for a response. Returns: A value from :class:`.hook.Actions`.
[ "Generic", "handler", "for", "a", "response", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/rule.py#L324-L339
train
201,570
ArchiveTeam/wpull
wpull/processor/rule.py
ResultRule.handle_error
def handle_error(self, item_session: ItemSession, error: BaseException) -> Actions: '''Process an error. Returns: A value from :class:`.hook.Actions`. ''' if not self._ssl_verification and \ isinstance(error, SSLVerificationError): # Change it into a different error since the user doesn't care # about verifying certificates self._statistics.increment_error(ProtocolError()) else: self._statistics.increment_error(error) self._waiter.increment() action = self.consult_error_hook(item_session, error) if action == Actions.RETRY: item_session.set_status(Status.error) elif action == Actions.FINISH: item_session.set_status(Status.done) elif action == Actions.STOP: raise HookStop('Script requested immediate stop.') elif self._ssl_verification and isinstance(error, SSLVerificationError): raise elif isinstance(error, ConnectionRefused) and \ not self.retry_connrefused: item_session.set_status(Status.skipped) elif isinstance(error, DNSNotFound) and \ not self.retry_dns_error: item_session.set_status(Status.skipped) else: item_session.set_status(Status.error) return action
python
def handle_error(self, item_session: ItemSession, error: BaseException) -> Actions: '''Process an error. Returns: A value from :class:`.hook.Actions`. ''' if not self._ssl_verification and \ isinstance(error, SSLVerificationError): # Change it into a different error since the user doesn't care # about verifying certificates self._statistics.increment_error(ProtocolError()) else: self._statistics.increment_error(error) self._waiter.increment() action = self.consult_error_hook(item_session, error) if action == Actions.RETRY: item_session.set_status(Status.error) elif action == Actions.FINISH: item_session.set_status(Status.done) elif action == Actions.STOP: raise HookStop('Script requested immediate stop.') elif self._ssl_verification and isinstance(error, SSLVerificationError): raise elif isinstance(error, ConnectionRefused) and \ not self.retry_connrefused: item_session.set_status(Status.skipped) elif isinstance(error, DNSNotFound) and \ not self.retry_dns_error: item_session.set_status(Status.skipped) else: item_session.set_status(Status.error) return action
[ "def", "handle_error", "(", "self", ",", "item_session", ":", "ItemSession", ",", "error", ":", "BaseException", ")", "->", "Actions", ":", "if", "not", "self", ".", "_ssl_verification", "and", "isinstance", "(", "error", ",", "SSLVerificationError", ")", ":",...
Process an error. Returns: A value from :class:`.hook.Actions`.
[ "Process", "an", "error", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/rule.py#L341-L376
train
201,571
ArchiveTeam/wpull
wpull/processor/rule.py
ResultRule.get_wait_time
def get_wait_time(self, item_session: ItemSession, error=None): '''Return the wait time in seconds between requests.''' seconds = self._waiter.get() try: return self.hook_dispatcher.call(PluginFunctions.wait_time, seconds, item_session, error) except HookDisconnected: return seconds
python
def get_wait_time(self, item_session: ItemSession, error=None): '''Return the wait time in seconds between requests.''' seconds = self._waiter.get() try: return self.hook_dispatcher.call(PluginFunctions.wait_time, seconds, item_session, error) except HookDisconnected: return seconds
[ "def", "get_wait_time", "(", "self", ",", "item_session", ":", "ItemSession", ",", "error", "=", "None", ")", ":", "seconds", "=", "self", ".", "_waiter", ".", "get", "(", ")", "try", ":", "return", "self", ".", "hook_dispatcher", ".", "call", "(", "Pl...
Return the wait time in seconds between requests.
[ "Return", "the", "wait", "time", "in", "seconds", "between", "requests", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/rule.py#L378-L385
train
201,572
ArchiveTeam/wpull
wpull/processor/rule.py
ResultRule.plugin_wait_time
def plugin_wait_time(seconds: float, item_session: ItemSession, error: Optional[Exception]=None) -> float: '''Return the wait time between requests. Args: seconds: The original time in seconds. item_session: error: Returns: The time in seconds. ''' return seconds
python
def plugin_wait_time(seconds: float, item_session: ItemSession, error: Optional[Exception]=None) -> float: '''Return the wait time between requests. Args: seconds: The original time in seconds. item_session: error: Returns: The time in seconds. ''' return seconds
[ "def", "plugin_wait_time", "(", "seconds", ":", "float", ",", "item_session", ":", "ItemSession", ",", "error", ":", "Optional", "[", "Exception", "]", "=", "None", ")", "->", "float", ":", "return", "seconds" ]
Return the wait time between requests. Args: seconds: The original time in seconds. item_session: error: Returns: The time in seconds.
[ "Return", "the", "wait", "time", "between", "requests", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/rule.py#L389-L400
train
201,573
ArchiveTeam/wpull
wpull/processor/rule.py
ResultRule.consult_pre_response_hook
def consult_pre_response_hook(self, item_session: ItemSession) -> Actions: '''Return scripting action when a response begins.''' try: return self.hook_dispatcher.call( PluginFunctions.handle_pre_response, item_session ) except HookDisconnected: return Actions.NORMAL
python
def consult_pre_response_hook(self, item_session: ItemSession) -> Actions: '''Return scripting action when a response begins.''' try: return self.hook_dispatcher.call( PluginFunctions.handle_pre_response, item_session ) except HookDisconnected: return Actions.NORMAL
[ "def", "consult_pre_response_hook", "(", "self", ",", "item_session", ":", "ItemSession", ")", "->", "Actions", ":", "try", ":", "return", "self", ".", "hook_dispatcher", ".", "call", "(", "PluginFunctions", ".", "handle_pre_response", ",", "item_session", ")", ...
Return scripting action when a response begins.
[ "Return", "scripting", "action", "when", "a", "response", "begins", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/rule.py#L402-L410
train
201,574
ArchiveTeam/wpull
wpull/processor/rule.py
ResultRule.consult_response_hook
def consult_response_hook(self, item_session: ItemSession) -> Actions: '''Return scripting action when a response ends.''' try: return self.hook_dispatcher.call( PluginFunctions.handle_response, item_session ) except HookDisconnected: return Actions.NORMAL
python
def consult_response_hook(self, item_session: ItemSession) -> Actions: '''Return scripting action when a response ends.''' try: return self.hook_dispatcher.call( PluginFunctions.handle_response, item_session ) except HookDisconnected: return Actions.NORMAL
[ "def", "consult_response_hook", "(", "self", ",", "item_session", ":", "ItemSession", ")", "->", "Actions", ":", "try", ":", "return", "self", ".", "hook_dispatcher", ".", "call", "(", "PluginFunctions", ".", "handle_response", ",", "item_session", ")", "except"...
Return scripting action when a response ends.
[ "Return", "scripting", "action", "when", "a", "response", "ends", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/rule.py#L426-L433
train
201,575
ArchiveTeam/wpull
wpull/processor/rule.py
ResultRule.consult_error_hook
def consult_error_hook(self, item_session: ItemSession, error: BaseException): '''Return scripting action when an error occured.''' try: return self.hook_dispatcher.call( PluginFunctions.handle_error, item_session, error) except HookDisconnected: return Actions.NORMAL
python
def consult_error_hook(self, item_session: ItemSession, error: BaseException): '''Return scripting action when an error occured.''' try: return self.hook_dispatcher.call( PluginFunctions.handle_error, item_session, error) except HookDisconnected: return Actions.NORMAL
[ "def", "consult_error_hook", "(", "self", ",", "item_session", ":", "ItemSession", ",", "error", ":", "BaseException", ")", ":", "try", ":", "return", "self", ".", "hook_dispatcher", ".", "call", "(", "PluginFunctions", ".", "handle_error", ",", "item_session", ...
Return scripting action when an error occured.
[ "Return", "scripting", "action", "when", "an", "error", "occured", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/rule.py#L449-L455
train
201,576
ArchiveTeam/wpull
wpull/processor/rule.py
ProcessingRule.add_extra_urls
def add_extra_urls(self, item_session: ItemSession): '''Add additional URLs such as robots.txt, favicon.ico.''' if item_session.url_record.level == 0 and self._sitemaps: extra_url_infos = ( self.parse_url( '{0}://{1}/robots.txt'.format( item_session.url_record.url_info.scheme, item_session.url_record.url_info.hostname_with_port) ), self.parse_url( '{0}://{1}/sitemap.xml'.format( item_session.url_record.url_info.scheme, item_session.url_record.url_info.hostname_with_port) ) ) for url_info in extra_url_infos: item_session.add_child_url(url_info.url)
python
def add_extra_urls(self, item_session: ItemSession): '''Add additional URLs such as robots.txt, favicon.ico.''' if item_session.url_record.level == 0 and self._sitemaps: extra_url_infos = ( self.parse_url( '{0}://{1}/robots.txt'.format( item_session.url_record.url_info.scheme, item_session.url_record.url_info.hostname_with_port) ), self.parse_url( '{0}://{1}/sitemap.xml'.format( item_session.url_record.url_info.scheme, item_session.url_record.url_info.hostname_with_port) ) ) for url_info in extra_url_infos: item_session.add_child_url(url_info.url)
[ "def", "add_extra_urls", "(", "self", ",", "item_session", ":", "ItemSession", ")", ":", "if", "item_session", ".", "url_record", ".", "level", "==", "0", "and", "self", ".", "_sitemaps", ":", "extra_url_infos", "=", "(", "self", ".", "parse_url", "(", "'{...
Add additional URLs such as robots.txt, favicon.ico.
[ "Add", "additional", "URLs", "such", "as", "robots", ".", "txt", "favicon", ".", "ico", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/rule.py#L496-L514
train
201,577
ArchiveTeam/wpull
wpull/processor/rule.py
ProcessingRule.scrape_document
def scrape_document(self, item_session: ItemSession): '''Process document for links.''' self.event_dispatcher.notify( PluginFunctions.get_urls, item_session ) if not self._document_scraper: return demux_info = self._document_scraper.scrape_info( item_session.request, item_session.response, item_session.url_record.link_type ) num_inline_urls = 0 num_linked_urls = 0 for scraper, scrape_result in demux_info.items(): new_inline, new_linked = self._process_scrape_info( scraper, scrape_result, item_session ) num_inline_urls += new_inline num_linked_urls += new_linked _logger.debug('Candidate URLs: inline={0} linked={1}', num_inline_urls, num_linked_urls )
python
def scrape_document(self, item_session: ItemSession): '''Process document for links.''' self.event_dispatcher.notify( PluginFunctions.get_urls, item_session ) if not self._document_scraper: return demux_info = self._document_scraper.scrape_info( item_session.request, item_session.response, item_session.url_record.link_type ) num_inline_urls = 0 num_linked_urls = 0 for scraper, scrape_result in demux_info.items(): new_inline, new_linked = self._process_scrape_info( scraper, scrape_result, item_session ) num_inline_urls += new_inline num_linked_urls += new_linked _logger.debug('Candidate URLs: inline={0} linked={1}', num_inline_urls, num_linked_urls )
[ "def", "scrape_document", "(", "self", ",", "item_session", ":", "ItemSession", ")", ":", "self", ".", "event_dispatcher", ".", "notify", "(", "PluginFunctions", ".", "get_urls", ",", "item_session", ")", "if", "not", "self", ".", "_document_scraper", ":", "re...
Process document for links.
[ "Process", "document", "for", "links", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/rule.py#L516-L542
train
201,578
ArchiveTeam/wpull
wpull/processor/rule.py
ProcessingRule._process_scrape_info
def _process_scrape_info(self, scraper: BaseScraper, scrape_result: ScrapeResult, item_session: ItemSession): '''Collect the URLs from the scrape info dict.''' if not scrape_result: return 0, 0 num_inline = 0 num_linked = 0 for link_context in scrape_result.link_contexts: url_info = self.parse_url(link_context.link) if not url_info: continue url_info = self.rewrite_url(url_info) child_url_record = item_session.child_url_record( url_info.url, inline=link_context.inline ) if not self._fetch_rule.consult_filters(item_session.request.url_info, child_url_record)[0]: continue if link_context.inline: num_inline += 1 else: num_linked += 1 item_session.add_child_url(url_info.url, inline=link_context.inline, link_type=link_context.link_type) return num_inline, num_linked
python
def _process_scrape_info(self, scraper: BaseScraper, scrape_result: ScrapeResult, item_session: ItemSession): '''Collect the URLs from the scrape info dict.''' if not scrape_result: return 0, 0 num_inline = 0 num_linked = 0 for link_context in scrape_result.link_contexts: url_info = self.parse_url(link_context.link) if not url_info: continue url_info = self.rewrite_url(url_info) child_url_record = item_session.child_url_record( url_info.url, inline=link_context.inline ) if not self._fetch_rule.consult_filters(item_session.request.url_info, child_url_record)[0]: continue if link_context.inline: num_inline += 1 else: num_linked += 1 item_session.add_child_url(url_info.url, inline=link_context.inline, link_type=link_context.link_type) return num_inline, num_linked
[ "def", "_process_scrape_info", "(", "self", ",", "scraper", ":", "BaseScraper", ",", "scrape_result", ":", "ScrapeResult", ",", "item_session", ":", "ItemSession", ")", ":", "if", "not", "scrape_result", ":", "return", "0", ",", "0", "num_inline", "=", "0", ...
Collect the URLs from the scrape info dict.
[ "Collect", "the", "URLs", "from", "the", "scrape", "info", "dict", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/rule.py#L553-L585
train
201,579
ArchiveTeam/wpull
wpull/processor/rule.py
ProcessingRule.rewrite_url
def rewrite_url(self, url_info: URLInfo) -> URLInfo: '''Return a rewritten URL such as escaped fragment.''' if self._url_rewriter: return self._url_rewriter.rewrite(url_info) else: return url_info
python
def rewrite_url(self, url_info: URLInfo) -> URLInfo: '''Return a rewritten URL such as escaped fragment.''' if self._url_rewriter: return self._url_rewriter.rewrite(url_info) else: return url_info
[ "def", "rewrite_url", "(", "self", ",", "url_info", ":", "URLInfo", ")", "->", "URLInfo", ":", "if", "self", ".", "_url_rewriter", ":", "return", "self", ".", "_url_rewriter", ".", "rewrite", "(", "url_info", ")", "else", ":", "return", "url_info" ]
Return a rewritten URL such as escaped fragment.
[ "Return", "a", "rewritten", "URL", "such", "as", "escaped", "fragment", "." ]
ddf051aa3322479325ba20aa778cb2cb97606bf5
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/rule.py#L587-L592
train
201,580
jayfk/statuspage
statuspage/statuspage.py
run_add_system
def run_add_system(name, token, org, system, prompt): """ Adds a new system to the repo. """ repo = get_repo(token=token, org=org, name=name) try: repo.create_label(name=system.strip(), color=SYSTEM_LABEL_COLOR) click.secho("Successfully added new system {}".format(system), fg="green") if prompt and click.confirm("Run update to re-generate the page?"): run_update(name=name, token=token, org=org) except GithubException as e: if e.status == 422: click.secho( "Unable to add new system {}, it already exists.".format(system), fg="yellow") return raise
python
def run_add_system(name, token, org, system, prompt): """ Adds a new system to the repo. """ repo = get_repo(token=token, org=org, name=name) try: repo.create_label(name=system.strip(), color=SYSTEM_LABEL_COLOR) click.secho("Successfully added new system {}".format(system), fg="green") if prompt and click.confirm("Run update to re-generate the page?"): run_update(name=name, token=token, org=org) except GithubException as e: if e.status == 422: click.secho( "Unable to add new system {}, it already exists.".format(system), fg="yellow") return raise
[ "def", "run_add_system", "(", "name", ",", "token", ",", "org", ",", "system", ",", "prompt", ")", ":", "repo", "=", "get_repo", "(", "token", "=", "token", ",", "org", "=", "org", ",", "name", "=", "name", ")", "try", ":", "repo", ".", "create_lab...
Adds a new system to the repo.
[ "Adds", "a", "new", "system", "to", "the", "repo", "." ]
c1e6cd6ce98159a073929c6b7301beec5914e32b
https://github.com/jayfk/statuspage/blob/c1e6cd6ce98159a073929c6b7301beec5914e32b/statuspage/statuspage.py#L104-L119
train
201,581
jayfk/statuspage
statuspage/statuspage.py
run_remove_system
def run_remove_system(name, token, org, system, prompt): """ Removes a system from the repo. """ repo = get_repo(token=token, org=org, name=name) try: label = repo.get_label(name=system.strip()) label.delete() click.secho("Successfully deleted {}".format(system), fg="green") if prompt and click.confirm("Run update to re-generate the page?"): run_update(name=name, token=token, org=org) except UnknownObjectException: click.secho("Unable to remove system {}, it does not exist.".format(system), fg="yellow")
python
def run_remove_system(name, token, org, system, prompt): """ Removes a system from the repo. """ repo = get_repo(token=token, org=org, name=name) try: label = repo.get_label(name=system.strip()) label.delete() click.secho("Successfully deleted {}".format(system), fg="green") if prompt and click.confirm("Run update to re-generate the page?"): run_update(name=name, token=token, org=org) except UnknownObjectException: click.secho("Unable to remove system {}, it does not exist.".format(system), fg="yellow")
[ "def", "run_remove_system", "(", "name", ",", "token", ",", "org", ",", "system", ",", "prompt", ")", ":", "repo", "=", "get_repo", "(", "token", "=", "token", ",", "org", "=", "org", ",", "name", "=", "name", ")", "try", ":", "label", "=", "repo",...
Removes a system from the repo.
[ "Removes", "a", "system", "from", "the", "repo", "." ]
c1e6cd6ce98159a073929c6b7301beec5914e32b
https://github.com/jayfk/statuspage/blob/c1e6cd6ce98159a073929c6b7301beec5914e32b/statuspage/statuspage.py#L122-L134
train
201,582
jayfk/statuspage
statuspage/statuspage.py
get_config
def get_config(repo): """ Get the config for the repo, merged with the default config. Returns the default config if no config file is found. """ files = get_files(repo) config = DEFAULT_CONFIG if "config.json" in files: # get the config file, parse JSON and merge it with the default config config_file = repo.get_file_contents('/config.json', ref="gh-pages") try: repo_config = json.loads(config_file.decoded_content.decode("utf-8")) config.update(repo_config) except ValueError: click.secho("WARNING: Unable to parse config file. Using defaults.", fg="yellow") return config
python
def get_config(repo): """ Get the config for the repo, merged with the default config. Returns the default config if no config file is found. """ files = get_files(repo) config = DEFAULT_CONFIG if "config.json" in files: # get the config file, parse JSON and merge it with the default config config_file = repo.get_file_contents('/config.json', ref="gh-pages") try: repo_config = json.loads(config_file.decoded_content.decode("utf-8")) config.update(repo_config) except ValueError: click.secho("WARNING: Unable to parse config file. Using defaults.", fg="yellow") return config
[ "def", "get_config", "(", "repo", ")", ":", "files", "=", "get_files", "(", "repo", ")", "config", "=", "DEFAULT_CONFIG", "if", "\"config.json\"", "in", "files", ":", "# get the config file, parse JSON and merge it with the default config", "config_file", "=", "repo", ...
Get the config for the repo, merged with the default config. Returns the default config if no config file is found.
[ "Get", "the", "config", "for", "the", "repo", "merged", "with", "the", "default", "config", ".", "Returns", "the", "default", "config", "if", "no", "config", "file", "is", "found", "." ]
c1e6cd6ce98159a073929c6b7301beec5914e32b
https://github.com/jayfk/statuspage/blob/c1e6cd6ce98159a073929c6b7301beec5914e32b/statuspage/statuspage.py#L314-L329
train
201,583
ubernostrum/django-registration
src/django_registration/views.py
RegistrationView.dispatch
def dispatch(self, *args, **kwargs): """ Check that user signup is allowed before even bothering to dispatch or do other processing. """ if not self.registration_allowed(): return HttpResponseRedirect(force_text(self.disallowed_url)) return super(RegistrationView, self).dispatch(*args, **kwargs)
python
def dispatch(self, *args, **kwargs): """ Check that user signup is allowed before even bothering to dispatch or do other processing. """ if not self.registration_allowed(): return HttpResponseRedirect(force_text(self.disallowed_url)) return super(RegistrationView, self).dispatch(*args, **kwargs)
[ "def", "dispatch", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "registration_allowed", "(", ")", ":", "return", "HttpResponseRedirect", "(", "force_text", "(", "self", ".", "disallowed_url", ")", ")", "retu...
Check that user signup is allowed before even bothering to dispatch or do other processing.
[ "Check", "that", "user", "signup", "is", "allowed", "before", "even", "bothering", "to", "dispatch", "or", "do", "other", "processing", "." ]
cf10b13423669346a1f4cfaa31aae0b42856b416
https://github.com/ubernostrum/django-registration/blob/cf10b13423669346a1f4cfaa31aae0b42856b416/src/django_registration/views.py#L28-L36
train
201,584
ubernostrum/django-registration
src/django_registration/backends/activation/views.py
RegistrationView.get_email_context
def get_email_context(self, activation_key): """ Build the template context used for the activation email. """ scheme = 'https' if self.request.is_secure() else 'http' return { 'scheme': scheme, 'activation_key': activation_key, 'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS, 'site': get_current_site(self.request) }
python
def get_email_context(self, activation_key): """ Build the template context used for the activation email. """ scheme = 'https' if self.request.is_secure() else 'http' return { 'scheme': scheme, 'activation_key': activation_key, 'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS, 'site': get_current_site(self.request) }
[ "def", "get_email_context", "(", "self", ",", "activation_key", ")", ":", "scheme", "=", "'https'", "if", "self", ".", "request", ".", "is_secure", "(", ")", "else", "'http'", "return", "{", "'scheme'", ":", "scheme", ",", "'activation_key'", ":", "activatio...
Build the template context used for the activation email.
[ "Build", "the", "template", "context", "used", "for", "the", "activation", "email", "." ]
cf10b13423669346a1f4cfaa31aae0b42856b416
https://github.com/ubernostrum/django-registration/blob/cf10b13423669346a1f4cfaa31aae0b42856b416/src/django_registration/backends/activation/views.py#L72-L83
train
201,585
ubernostrum/django-registration
src/django_registration/backends/activation/views.py
ActivationView.validate_key
def validate_key(self, activation_key): """ Verify that the activation key is valid and within the permitted activation time window, returning the username if valid or raising ``ActivationError`` if not. """ try: username = signing.loads( activation_key, salt=REGISTRATION_SALT, max_age=settings.ACCOUNT_ACTIVATION_DAYS * 86400 ) return username except signing.SignatureExpired: raise ActivationError( self.EXPIRED_MESSAGE, code='expired' ) except signing.BadSignature: raise ActivationError( self.INVALID_KEY_MESSAGE, code='invalid_key', params={'activation_key': activation_key} )
python
def validate_key(self, activation_key): """ Verify that the activation key is valid and within the permitted activation time window, returning the username if valid or raising ``ActivationError`` if not. """ try: username = signing.loads( activation_key, salt=REGISTRATION_SALT, max_age=settings.ACCOUNT_ACTIVATION_DAYS * 86400 ) return username except signing.SignatureExpired: raise ActivationError( self.EXPIRED_MESSAGE, code='expired' ) except signing.BadSignature: raise ActivationError( self.INVALID_KEY_MESSAGE, code='invalid_key', params={'activation_key': activation_key} )
[ "def", "validate_key", "(", "self", ",", "activation_key", ")", ":", "try", ":", "username", "=", "signing", ".", "loads", "(", "activation_key", ",", "salt", "=", "REGISTRATION_SALT", ",", "max_age", "=", "settings", ".", "ACCOUNT_ACTIVATION_DAYS", "*", "8640...
Verify that the activation key is valid and within the permitted activation time window, returning the username if valid or raising ``ActivationError`` if not.
[ "Verify", "that", "the", "activation", "key", "is", "valid", "and", "within", "the", "permitted", "activation", "time", "window", "returning", "the", "username", "if", "valid", "or", "raising", "ActivationError", "if", "not", "." ]
cf10b13423669346a1f4cfaa31aae0b42856b416
https://github.com/ubernostrum/django-registration/blob/cf10b13423669346a1f4cfaa31aae0b42856b416/src/django_registration/backends/activation/views.py#L136-L160
train
201,586
ubernostrum/django-registration
src/django_registration/backends/activation/views.py
ActivationView.get_user
def get_user(self, username): """ Given the verified username, look up and return the corresponding user account if it exists, or raising ``ActivationError`` if it doesn't. """ User = get_user_model() try: user = User.objects.get(**{ User.USERNAME_FIELD: username, }) if user.is_active: raise ActivationError( self.ALREADY_ACTIVATED_MESSAGE, code='already_activated' ) return user except User.DoesNotExist: raise ActivationError( self.BAD_USERNAME_MESSAGE, code='bad_username' )
python
def get_user(self, username): """ Given the verified username, look up and return the corresponding user account if it exists, or raising ``ActivationError`` if it doesn't. """ User = get_user_model() try: user = User.objects.get(**{ User.USERNAME_FIELD: username, }) if user.is_active: raise ActivationError( self.ALREADY_ACTIVATED_MESSAGE, code='already_activated' ) return user except User.DoesNotExist: raise ActivationError( self.BAD_USERNAME_MESSAGE, code='bad_username' )
[ "def", "get_user", "(", "self", ",", "username", ")", ":", "User", "=", "get_user_model", "(", ")", "try", ":", "user", "=", "User", ".", "objects", ".", "get", "(", "*", "*", "{", "User", ".", "USERNAME_FIELD", ":", "username", ",", "}", ")", "if"...
Given the verified username, look up and return the corresponding user account if it exists, or raising ``ActivationError`` if it doesn't.
[ "Given", "the", "verified", "username", "look", "up", "and", "return", "the", "corresponding", "user", "account", "if", "it", "exists", "or", "raising", "ActivationError", "if", "it", "doesn", "t", "." ]
cf10b13423669346a1f4cfaa31aae0b42856b416
https://github.com/ubernostrum/django-registration/blob/cf10b13423669346a1f4cfaa31aae0b42856b416/src/django_registration/backends/activation/views.py#L162-L184
train
201,587
ubernostrum/django-registration
src/django_registration/validators.py
validate_confusables
def validate_confusables(value): """ Validator which disallows 'dangerous' usernames likely to represent homograph attacks. A username is 'dangerous' if it is mixed-script (as defined by Unicode 'Script' property) and contains one or more characters appearing in the Unicode Visually Confusable Characters file. """ if not isinstance(value, six.text_type): return if confusables.is_dangerous(value): raise ValidationError(CONFUSABLE, code='invalid')
python
def validate_confusables(value): """ Validator which disallows 'dangerous' usernames likely to represent homograph attacks. A username is 'dangerous' if it is mixed-script (as defined by Unicode 'Script' property) and contains one or more characters appearing in the Unicode Visually Confusable Characters file. """ if not isinstance(value, six.text_type): return if confusables.is_dangerous(value): raise ValidationError(CONFUSABLE, code='invalid')
[ "def", "validate_confusables", "(", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "six", ".", "text_type", ")", ":", "return", "if", "confusables", ".", "is_dangerous", "(", "value", ")", ":", "raise", "ValidationError", "(", "CONFUSABLE",...
Validator which disallows 'dangerous' usernames likely to represent homograph attacks. A username is 'dangerous' if it is mixed-script (as defined by Unicode 'Script' property) and contains one or more characters appearing in the Unicode Visually Confusable Characters file.
[ "Validator", "which", "disallows", "dangerous", "usernames", "likely", "to", "represent", "homograph", "attacks", "." ]
cf10b13423669346a1f4cfaa31aae0b42856b416
https://github.com/ubernostrum/django-registration/blob/cf10b13423669346a1f4cfaa31aae0b42856b416/src/django_registration/validators.py#L237-L250
train
201,588
ubernostrum/django-registration
src/django_registration/validators.py
validate_confusables_email
def validate_confusables_email(value): """ Validator which disallows 'dangerous' email addresses likely to represent homograph attacks. An email address is 'dangerous' if either the local-part or the domain, considered on their own, are mixed-script and contain one or more characters appearing in the Unicode Visually Confusable Characters file. """ if '@' not in value: return local_part, domain = value.split('@') if confusables.is_dangerous(local_part) or \ confusables.is_dangerous(domain): raise ValidationError(CONFUSABLE_EMAIL, code='invalid')
python
def validate_confusables_email(value): """ Validator which disallows 'dangerous' email addresses likely to represent homograph attacks. An email address is 'dangerous' if either the local-part or the domain, considered on their own, are mixed-script and contain one or more characters appearing in the Unicode Visually Confusable Characters file. """ if '@' not in value: return local_part, domain = value.split('@') if confusables.is_dangerous(local_part) or \ confusables.is_dangerous(domain): raise ValidationError(CONFUSABLE_EMAIL, code='invalid')
[ "def", "validate_confusables_email", "(", "value", ")", ":", "if", "'@'", "not", "in", "value", ":", "return", "local_part", ",", "domain", "=", "value", ".", "split", "(", "'@'", ")", "if", "confusables", ".", "is_dangerous", "(", "local_part", ")", "or",...
Validator which disallows 'dangerous' email addresses likely to represent homograph attacks. An email address is 'dangerous' if either the local-part or the domain, considered on their own, are mixed-script and contain one or more characters appearing in the Unicode Visually Confusable Characters file.
[ "Validator", "which", "disallows", "dangerous", "email", "addresses", "likely", "to", "represent", "homograph", "attacks", "." ]
cf10b13423669346a1f4cfaa31aae0b42856b416
https://github.com/ubernostrum/django-registration/blob/cf10b13423669346a1f4cfaa31aae0b42856b416/src/django_registration/validators.py#L253-L269
train
201,589
erdem/django-map-widgets
fabfile.py
minify_js_files
def minify_js_files(): """ This command minified js files with UglifyJS """ for k, v in JS_FILE_MAPPING.items(): input_files = " ".join(v["input_files"]) output_file = v["output_file"] uglifyjs_command = "uglifyjs {input_files} -o {output_file}".format( input_files=input_files, output_file=output_file ) local(uglifyjs_command)
python
def minify_js_files(): """ This command minified js files with UglifyJS """ for k, v in JS_FILE_MAPPING.items(): input_files = " ".join(v["input_files"]) output_file = v["output_file"] uglifyjs_command = "uglifyjs {input_files} -o {output_file}".format( input_files=input_files, output_file=output_file ) local(uglifyjs_command)
[ "def", "minify_js_files", "(", ")", ":", "for", "k", ",", "v", "in", "JS_FILE_MAPPING", ".", "items", "(", ")", ":", "input_files", "=", "\" \"", ".", "join", "(", "v", "[", "\"input_files\"", "]", ")", "output_file", "=", "v", "[", "\"output_file\"", ...
This command minified js files with UglifyJS
[ "This", "command", "minified", "js", "files", "with", "UglifyJS" ]
fa61c0196209a48245312d5475a59243b88aae4e
https://github.com/erdem/django-map-widgets/blob/fa61c0196209a48245312d5475a59243b88aae4e/fabfile.py#L47-L59
train
201,590
erdem/django-map-widgets
fabfile.py
minify_css_files
def minify_css_files(): """ This command minified js files with UglifyCSS """ for k, v in CSS_FILE_MAPPING.items(): input_files = " ".join(v["input_files"]) output_file = v["output_file"] uglifyjs_command = "uglifycss {input_files} > {output_file}".format( input_files=input_files, output_file=output_file ) local(uglifyjs_command)
python
def minify_css_files(): """ This command minified js files with UglifyCSS """ for k, v in CSS_FILE_MAPPING.items(): input_files = " ".join(v["input_files"]) output_file = v["output_file"] uglifyjs_command = "uglifycss {input_files} > {output_file}".format( input_files=input_files, output_file=output_file ) local(uglifyjs_command)
[ "def", "minify_css_files", "(", ")", ":", "for", "k", ",", "v", "in", "CSS_FILE_MAPPING", ".", "items", "(", ")", ":", "input_files", "=", "\" \"", ".", "join", "(", "v", "[", "\"input_files\"", "]", ")", "output_file", "=", "v", "[", "\"output_file\"", ...
This command minified js files with UglifyCSS
[ "This", "command", "minified", "js", "files", "with", "UglifyCSS" ]
fa61c0196209a48245312d5475a59243b88aae4e
https://github.com/erdem/django-map-widgets/blob/fa61c0196209a48245312d5475a59243b88aae4e/fabfile.py#L62-L74
train
201,591
mbi/django-rosetta
rosetta/poutil.py
timestamp_with_timezone
def timestamp_with_timezone(dt=None): """ Return a timestamp with a timezone for the configured locale. If all else fails, consider localtime to be UTC. """ dt = dt or datetime.now() if timezone is None: return dt.strftime('%Y-%m-%d %H:%M%z') if not dt.tzinfo: tz = timezone.get_current_timezone() if not tz: tz = timezone.utc dt = dt.replace(tzinfo=timezone.get_current_timezone()) return dt.strftime("%Y-%m-%d %H:%M%z")
python
def timestamp_with_timezone(dt=None): """ Return a timestamp with a timezone for the configured locale. If all else fails, consider localtime to be UTC. """ dt = dt or datetime.now() if timezone is None: return dt.strftime('%Y-%m-%d %H:%M%z') if not dt.tzinfo: tz = timezone.get_current_timezone() if not tz: tz = timezone.utc dt = dt.replace(tzinfo=timezone.get_current_timezone()) return dt.strftime("%Y-%m-%d %H:%M%z")
[ "def", "timestamp_with_timezone", "(", "dt", "=", "None", ")", ":", "dt", "=", "dt", "or", "datetime", ".", "now", "(", ")", "if", "timezone", "is", "None", ":", "return", "dt", ".", "strftime", "(", "'%Y-%m-%d %H:%M%z'", ")", "if", "not", "dt", ".", ...
Return a timestamp with a timezone for the configured locale. If all else fails, consider localtime to be UTC.
[ "Return", "a", "timestamp", "with", "a", "timezone", "for", "the", "configured", "locale", ".", "If", "all", "else", "fails", "consider", "localtime", "to", "be", "UTC", "." ]
3c249d344eaf667b58a61a0433d65fb2a8c72355
https://github.com/mbi/django-rosetta/blob/3c249d344eaf667b58a61a0433d65fb2a8c72355/rosetta/poutil.py#L17-L30
train
201,592
mbi/django-rosetta
rosetta/access.py
get_access_control_function
def get_access_control_function(): """ Return a predicate for determining if a user can access the Rosetta views """ fn_path = getattr(settings, 'ROSETTA_ACCESS_CONTROL_FUNCTION', None) if fn_path is None: return is_superuser_staff_or_in_translators_group # Dynamically load a permissions function perm_module, perm_func = fn_path.rsplit('.', 1) perm_module = importlib.import_module(perm_module) return getattr(perm_module, perm_func)
python
def get_access_control_function(): """ Return a predicate for determining if a user can access the Rosetta views """ fn_path = getattr(settings, 'ROSETTA_ACCESS_CONTROL_FUNCTION', None) if fn_path is None: return is_superuser_staff_or_in_translators_group # Dynamically load a permissions function perm_module, perm_func = fn_path.rsplit('.', 1) perm_module = importlib.import_module(perm_module) return getattr(perm_module, perm_func)
[ "def", "get_access_control_function", "(", ")", ":", "fn_path", "=", "getattr", "(", "settings", ",", "'ROSETTA_ACCESS_CONTROL_FUNCTION'", ",", "None", ")", "if", "fn_path", "is", "None", ":", "return", "is_superuser_staff_or_in_translators_group", "# Dynamically load a p...
Return a predicate for determining if a user can access the Rosetta views
[ "Return", "a", "predicate", "for", "determining", "if", "a", "user", "can", "access", "the", "Rosetta", "views" ]
3c249d344eaf667b58a61a0433d65fb2a8c72355
https://github.com/mbi/django-rosetta/blob/3c249d344eaf667b58a61a0433d65fb2a8c72355/rosetta/access.py#L13-L24
train
201,593
mbi/django-rosetta
rosetta/views.py
TranslationFormView.fix_nls
def fix_nls(self, in_, out_): """Fixes submitted translations by filtering carriage returns and pairing newlines at the begging and end of the translated string with the original """ if 0 == len(in_) or 0 == len(out_): return out_ if "\r" in out_ and "\r" not in in_: out_ = out_.replace("\r", '') if "\n" == in_[0] and "\n" != out_[0]: out_ = "\n" + out_ elif "\n" != in_[0] and "\n" == out_[0]: out_ = out_.lstrip() if 0 == len(out_): pass elif "\n" == in_[-1] and "\n" != out_[-1]: out_ = out_ + "\n" elif "\n" != in_[-1] and "\n" == out_[-1]: out_ = out_.rstrip() return out_
python
def fix_nls(self, in_, out_): """Fixes submitted translations by filtering carriage returns and pairing newlines at the begging and end of the translated string with the original """ if 0 == len(in_) or 0 == len(out_): return out_ if "\r" in out_ and "\r" not in in_: out_ = out_.replace("\r", '') if "\n" == in_[0] and "\n" != out_[0]: out_ = "\n" + out_ elif "\n" != in_[0] and "\n" == out_[0]: out_ = out_.lstrip() if 0 == len(out_): pass elif "\n" == in_[-1] and "\n" != out_[-1]: out_ = out_ + "\n" elif "\n" != in_[-1] and "\n" == out_[-1]: out_ = out_.rstrip() return out_
[ "def", "fix_nls", "(", "self", ",", "in_", ",", "out_", ")", ":", "if", "0", "==", "len", "(", "in_", ")", "or", "0", "==", "len", "(", "out_", ")", ":", "return", "out_", "if", "\"\\r\"", "in", "out_", "and", "\"\\r\"", "not", "in", "in_", ":"...
Fixes submitted translations by filtering carriage returns and pairing newlines at the begging and end of the translated string with the original
[ "Fixes", "submitted", "translations", "by", "filtering", "carriage", "returns", "and", "pairing", "newlines", "at", "the", "begging", "and", "end", "of", "the", "translated", "string", "with", "the", "original" ]
3c249d344eaf667b58a61a0433d65fb2a8c72355
https://github.com/mbi/django-rosetta/blob/3c249d344eaf667b58a61a0433d65fb2a8c72355/rosetta/views.py#L263-L283
train
201,594
mbi/django-rosetta
rosetta/views.py
TranslationFormView.ref_lang_po_file
def ref_lang_po_file(self): """Return a parsed .po file object for the "reference language", if one exists, otherwise None. """ ref_pofile = None if rosetta_settings.ENABLE_REFLANG and self.ref_lang != 'msgid': replacement = '{separator}locale{separator}{ref_lang}'.format( separator=os.sep, ref_lang=self.ref_lang ) pattern = '\{separator}locale\{separator}[a-z]{{2}}'.format(separator=os.sep) ref_fn = re.sub(pattern, replacement, self.po_file_path,) try: ref_pofile = pofile(ref_fn) except IOError: # there's a syntax error in the PO file and polib can't # open it. Let's just do nothing and thus display msgids. # XXX: :-/ pass return ref_pofile
python
def ref_lang_po_file(self): """Return a parsed .po file object for the "reference language", if one exists, otherwise None. """ ref_pofile = None if rosetta_settings.ENABLE_REFLANG and self.ref_lang != 'msgid': replacement = '{separator}locale{separator}{ref_lang}'.format( separator=os.sep, ref_lang=self.ref_lang ) pattern = '\{separator}locale\{separator}[a-z]{{2}}'.format(separator=os.sep) ref_fn = re.sub(pattern, replacement, self.po_file_path,) try: ref_pofile = pofile(ref_fn) except IOError: # there's a syntax error in the PO file and polib can't # open it. Let's just do nothing and thus display msgids. # XXX: :-/ pass return ref_pofile
[ "def", "ref_lang_po_file", "(", "self", ")", ":", "ref_pofile", "=", "None", "if", "rosetta_settings", ".", "ENABLE_REFLANG", "and", "self", ".", "ref_lang", "!=", "'msgid'", ":", "replacement", "=", "'{separator}locale{separator}{ref_lang}'", ".", "format", "(", ...
Return a parsed .po file object for the "reference language", if one exists, otherwise None.
[ "Return", "a", "parsed", ".", "po", "file", "object", "for", "the", "reference", "language", "if", "one", "exists", "otherwise", "None", "." ]
3c249d344eaf667b58a61a0433d65fb2a8c72355
https://github.com/mbi/django-rosetta/blob/3c249d344eaf667b58a61a0433d65fb2a8c72355/rosetta/views.py#L565-L584
train
201,595
mapillary/mapillary_tools
mapillary_tools/process_csv.py
convert_from_gps_time
def convert_from_gps_time(gps_time, gps_week=None): """ Convert gps time in ticks to standard time. """ converted_gps_time = None gps_timestamp = float(gps_time) if gps_week != None: # image date converted_gps_time = GPS_START + datetime.timedelta(seconds=int(gps_week) * SECS_IN_WEEK + gps_timestamp) else: # TAI scale with 1970-01-01 00:00:10 (TAI) epoch os.environ['TZ'] = 'right/UTC' # by definition gps_time_as_gps = GPS_START + \ datetime.timedelta(seconds=gps_timestamp) # constant offset gps_time_as_tai = gps_time_as_gps + \ datetime.timedelta(seconds=19) tai_epoch_as_tai = datetime.datetime(1970, 1, 1, 0, 0, 10) # by definition tai_timestamp = (gps_time_as_tai - tai_epoch_as_tai).total_seconds() converted_gps_time = ( datetime.datetime.utcfromtimestamp(tai_timestamp)) # "right" timezone is in effect return converted_gps_time
python
def convert_from_gps_time(gps_time, gps_week=None): """ Convert gps time in ticks to standard time. """ converted_gps_time = None gps_timestamp = float(gps_time) if gps_week != None: # image date converted_gps_time = GPS_START + datetime.timedelta(seconds=int(gps_week) * SECS_IN_WEEK + gps_timestamp) else: # TAI scale with 1970-01-01 00:00:10 (TAI) epoch os.environ['TZ'] = 'right/UTC' # by definition gps_time_as_gps = GPS_START + \ datetime.timedelta(seconds=gps_timestamp) # constant offset gps_time_as_tai = gps_time_as_gps + \ datetime.timedelta(seconds=19) tai_epoch_as_tai = datetime.datetime(1970, 1, 1, 0, 0, 10) # by definition tai_timestamp = (gps_time_as_tai - tai_epoch_as_tai).total_seconds() converted_gps_time = ( datetime.datetime.utcfromtimestamp(tai_timestamp)) # "right" timezone is in effect return converted_gps_time
[ "def", "convert_from_gps_time", "(", "gps_time", ",", "gps_week", "=", "None", ")", ":", "converted_gps_time", "=", "None", "gps_timestamp", "=", "float", "(", "gps_time", ")", "if", "gps_week", "!=", "None", ":", "# image date", "converted_gps_time", "=", "GPS_...
Convert gps time in ticks to standard time.
[ "Convert", "gps", "time", "in", "ticks", "to", "standard", "time", "." ]
816785e90c589cae6e8e34a5530ce8417d29591c
https://github.com/mapillary/mapillary_tools/blob/816785e90c589cae6e8e34a5530ce8417d29591c/mapillary_tools/process_csv.py#L68-L100
train
201,596
mapillary/mapillary_tools
mapillary_tools/process_video.py
get_video_duration
def get_video_duration(video_file): """Get video duration in seconds""" try: return float(FFProbe(video_file).video[0].duration) except Exception as e: print("could not extract duration from video {} due to {}".format(video_file, e)) return None
python
def get_video_duration(video_file): """Get video duration in seconds""" try: return float(FFProbe(video_file).video[0].duration) except Exception as e: print("could not extract duration from video {} due to {}".format(video_file, e)) return None
[ "def", "get_video_duration", "(", "video_file", ")", ":", "try", ":", "return", "float", "(", "FFProbe", "(", "video_file", ")", ".", "video", "[", "0", "]", ".", "duration", ")", "except", "Exception", "as", "e", ":", "print", "(", "\"could not extract du...
Get video duration in seconds
[ "Get", "video", "duration", "in", "seconds" ]
816785e90c589cae6e8e34a5530ce8417d29591c
https://github.com/mapillary/mapillary_tools/blob/816785e90c589cae6e8e34a5530ce8417d29591c/mapillary_tools/process_video.py#L156-L162
train
201,597
mapillary/mapillary_tools
mapillary_tools/process_video.py
get_video_end_time
def get_video_end_time(video_file): """Get video end time in seconds""" if not os.path.isfile(video_file): print("Error, video file {} does not exist".format(video_file)) return None try: time_string = FFProbe(video_file).video[0].creation_time try: creation_time = datetime.datetime.strptime( time_string, TIME_FORMAT) except: creation_time = datetime.datetime.strptime( time_string, TIME_FORMAT_2) except: return None return creation_time
python
def get_video_end_time(video_file): """Get video end time in seconds""" if not os.path.isfile(video_file): print("Error, video file {} does not exist".format(video_file)) return None try: time_string = FFProbe(video_file).video[0].creation_time try: creation_time = datetime.datetime.strptime( time_string, TIME_FORMAT) except: creation_time = datetime.datetime.strptime( time_string, TIME_FORMAT_2) except: return None return creation_time
[ "def", "get_video_end_time", "(", "video_file", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "video_file", ")", ":", "print", "(", "\"Error, video file {} does not exist\"", ".", "format", "(", "video_file", ")", ")", "return", "None", "try", ...
Get video end time in seconds
[ "Get", "video", "end", "time", "in", "seconds" ]
816785e90c589cae6e8e34a5530ce8417d29591c
https://github.com/mapillary/mapillary_tools/blob/816785e90c589cae6e8e34a5530ce8417d29591c/mapillary_tools/process_video.py#L194-L209
train
201,598
mapillary/mapillary_tools
mapillary_tools/process_video.py
get_video_start_time
def get_video_start_time(video_file): """Get start time in seconds""" if not os.path.isfile(video_file): print("Error, video file {} does not exist".format(video_file)) return None video_end_time = get_video_end_time(video_file) duration = get_video_duration(video_file) if video_end_time == None or duration == None: return None else: video_start_time = ( video_end_time - datetime.timedelta(seconds=duration)) return video_start_time
python
def get_video_start_time(video_file): """Get start time in seconds""" if not os.path.isfile(video_file): print("Error, video file {} does not exist".format(video_file)) return None video_end_time = get_video_end_time(video_file) duration = get_video_duration(video_file) if video_end_time == None or duration == None: return None else: video_start_time = ( video_end_time - datetime.timedelta(seconds=duration)) return video_start_time
[ "def", "get_video_start_time", "(", "video_file", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "video_file", ")", ":", "print", "(", "\"Error, video file {} does not exist\"", ".", "format", "(", "video_file", ")", ")", "return", "None", "vide...
Get start time in seconds
[ "Get", "start", "time", "in", "seconds" ]
816785e90c589cae6e8e34a5530ce8417d29591c
https://github.com/mapillary/mapillary_tools/blob/816785e90c589cae6e8e34a5530ce8417d29591c/mapillary_tools/process_video.py#L212-L224
train
201,599