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
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
inspirehep/refextract
refextract/references/text.py
strip_footer
def strip_footer(ref_lines, section_title): """Remove footer title from references lines""" pattern = ur'\(?\[?\d{0,4}\]?\)?\.?\s*%s\s*$' % re.escape(section_title) re_footer = re.compile(pattern, re.UNICODE) return [l for l in ref_lines if not re_footer.match(l)]
python
def strip_footer(ref_lines, section_title): """Remove footer title from references lines""" pattern = ur'\(?\[?\d{0,4}\]?\)?\.?\s*%s\s*$' % re.escape(section_title) re_footer = re.compile(pattern, re.UNICODE) return [l for l in ref_lines if not re_footer.match(l)]
[ "def", "strip_footer", "(", "ref_lines", ",", "section_title", ")", ":", "pattern", "=", "ur'\\(?\\[?\\d{0,4}\\]?\\)?\\.?\\s*%s\\s*$'", "%", "re", ".", "escape", "(", "section_title", ")", "re_footer", "=", "re", ".", "compile", "(", "pattern", ",", "re", ".", ...
Remove footer title from references lines
[ "Remove", "footer", "title", "from", "references", "lines" ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/text.py#L155-L159
train
inspirehep/refextract
refextract/references/api.py
extract_references_from_url
def extract_references_from_url(url, headers=None, chunk_size=1024, **kwargs): """Extract references from the pdf specified in the url. The first parameter is the URL of the file. It returns a list of parsed references. It raises FullTextNotAvailableError if the URL gives a 404, UnknownDocumentTyp...
python
def extract_references_from_url(url, headers=None, chunk_size=1024, **kwargs): """Extract references from the pdf specified in the url. The first parameter is the URL of the file. It returns a list of parsed references. It raises FullTextNotAvailableError if the URL gives a 404, UnknownDocumentTyp...
[ "def", "extract_references_from_url", "(", "url", ",", "headers", "=", "None", ",", "chunk_size", "=", "1024", ",", "**", "kwargs", ")", ":", "filename", ",", "filepath", "=", "mkstemp", "(", "suffix", "=", "u\"_{0}\"", ".", "format", "(", "os", ".", "pa...
Extract references from the pdf specified in the url. The first parameter is the URL of the file. It returns a list of parsed references. It raises FullTextNotAvailableError if the URL gives a 404, UnknownDocumentTypeError if it is not a PDF or plain text. The standard reference format is: {title...
[ "Extract", "references", "from", "the", "pdf", "specified", "in", "the", "url", "." ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/api.py#L54-L99
train
inspirehep/refextract
refextract/references/api.py
extract_references_from_file
def extract_references_from_file(path, recid=None, reference_format=u"{title} {volume} ({year}) {page}", linker_callback=None, override_kbs_files=None): """Extract references from a lo...
python
def extract_references_from_file(path, recid=None, reference_format=u"{title} {volume} ({year}) {page}", linker_callback=None, override_kbs_files=None): """Extract references from a lo...
[ "def", "extract_references_from_file", "(", "path", ",", "recid", "=", "None", ",", "reference_format", "=", "u\"{title} {volume} ({year}) {page}\"", ",", "linker_callback", "=", "None", ",", "override_kbs_files", "=", "None", ")", ":", "if", "not", "os", ".", "pa...
Extract references from a local pdf file. The first parameter is the path to the file. It returns a list of parsed references. It raises FullTextNotAvailableError if the file does not exist, UnknownDocumentTypeError if it is not a PDF or plain text. The standard reference format is: {title} {volum...
[ "Extract", "references", "from", "a", "local", "pdf", "file", "." ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/api.py#L102-L151
train
inspirehep/refextract
refextract/references/api.py
extract_references_from_string
def extract_references_from_string(source, is_only_references=True, recid=None, reference_format="{title} {volume} ({year}) {page}", linker_callback=None, ...
python
def extract_references_from_string(source, is_only_references=True, recid=None, reference_format="{title} {volume} ({year}) {page}", linker_callback=None, ...
[ "def", "extract_references_from_string", "(", "source", ",", "is_only_references", "=", "True", ",", "recid", "=", "None", ",", "reference_format", "=", "\"{title} {volume} ({year}) {page}\"", ",", "linker_callback", "=", "None", ",", "override_kbs_files", "=", "None", ...
Extract references from a raw string. The first parameter is the path to the file. It returns a tuple (references, stats). If the string does not only contain references, improve accuracy by specifing ``is_only_references=False``. The standard reference format is: {title} {volume} ({year}) {page}...
[ "Extract", "references", "from", "a", "raw", "string", "." ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/api.py#L154-L201
train
inspirehep/refextract
refextract/references/api.py
extract_journal_reference
def extract_journal_reference(line, override_kbs_files=None): """Extract the journal reference from string. Extracts the journal reference from string and parses for specific journal information. """ kbs = get_kbs(custom_kbs_files=override_kbs_files) references, dummy_m, dummy_c, dummy_co = par...
python
def extract_journal_reference(line, override_kbs_files=None): """Extract the journal reference from string. Extracts the journal reference from string and parses for specific journal information. """ kbs = get_kbs(custom_kbs_files=override_kbs_files) references, dummy_m, dummy_c, dummy_co = par...
[ "def", "extract_journal_reference", "(", "line", ",", "override_kbs_files", "=", "None", ")", ":", "kbs", "=", "get_kbs", "(", "custom_kbs_files", "=", "override_kbs_files", ")", "references", ",", "dummy_m", ",", "dummy_c", ",", "dummy_co", "=", "parse_reference_...
Extract the journal reference from string. Extracts the journal reference from string and parses for specific journal information.
[ "Extract", "the", "journal", "reference", "from", "string", "." ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/api.py#L204-L216
train
inspirehep/refextract
refextract/references/record.py
build_references
def build_references(citations, reference_format=False): """Build list of reference dictionaries from a references list """ # Now, run the method which will take as input: # 1. A list of lists of dictionaries, where each dictionary is a piece # of citation information corresponding to a tag in the c...
python
def build_references(citations, reference_format=False): """Build list of reference dictionaries from a references list """ # Now, run the method which will take as input: # 1. A list of lists of dictionaries, where each dictionary is a piece # of citation information corresponding to a tag in the c...
[ "def", "build_references", "(", "citations", ",", "reference_format", "=", "False", ")", ":", "return", "[", "c", "for", "citation_elements", "in", "citations", "for", "elements", "in", "citation_elements", "[", "'elements'", "]", "for", "c", "in", "build_refere...
Build list of reference dictionaries from a references list
[ "Build", "list", "of", "reference", "dictionaries", "from", "a", "references", "list" ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/record.py#L31-L47
train
inspirehep/refextract
refextract/references/record.py
build_reference_fields
def build_reference_fields(citation_elements, line_marker, raw_ref, reference_format): """Create the final representation of the reference information. @param citation_elements: (list) an ordered list of dictionary elements, with each element correspondi...
python
def build_reference_fields(citation_elements, line_marker, raw_ref, reference_format): """Create the final representation of the reference information. @param citation_elements: (list) an ordered list of dictionary elements, with each element correspondi...
[ "def", "build_reference_fields", "(", "citation_elements", ",", "line_marker", ",", "raw_ref", ",", "reference_format", ")", ":", "current_field", "=", "create_reference_field", "(", "line_marker", ")", "current_field", "[", "'raw_ref'", "]", "=", "[", "raw_ref", "]...
Create the final representation of the reference information. @param citation_elements: (list) an ordered list of dictionary elements, with each element corresponding to a found piece of information from a reference line. @param line_marker: (string) ...
[ "Create", "the", "final", "representation", "of", "the", "reference", "information", "." ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/record.py#L71-L161
train
inspirehep/refextract
refextract/references/pdf.py
extract_texkeys_from_pdf
def extract_texkeys_from_pdf(pdf_file): """ Extract the texkeys from the given PDF file This is done by looking up the named destinations in the PDF @param pdf_file: path to a PDF @return: list of all texkeys found in the PDF """ with open(pdf_file, 'rb') as pdf_stream: try: ...
python
def extract_texkeys_from_pdf(pdf_file): """ Extract the texkeys from the given PDF file This is done by looking up the named destinations in the PDF @param pdf_file: path to a PDF @return: list of all texkeys found in the PDF """ with open(pdf_file, 'rb') as pdf_stream: try: ...
[ "def", "extract_texkeys_from_pdf", "(", "pdf_file", ")", ":", "with", "open", "(", "pdf_file", ",", "'rb'", ")", "as", "pdf_stream", ":", "try", ":", "pdf", "=", "PdfFileReader", "(", "pdf_stream", ",", "strict", "=", "False", ")", "destinations", "=", "pd...
Extract the texkeys from the given PDF file This is done by looking up the named destinations in the PDF @param pdf_file: path to a PDF @return: list of all texkeys found in the PDF
[ "Extract", "the", "texkeys", "from", "the", "given", "PDF", "file" ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/pdf.py#L43-L84
train
inspirehep/refextract
refextract/references/regexs.py
get_reference_line_numeration_marker_patterns
def get_reference_line_numeration_marker_patterns(prefix=u''): """Return a list of compiled regex patterns used to search for the marker of a reference line in a full-text document. @param prefix: (string) the possible prefix to a reference line @return: (list) of compiled regex patterns. "...
python
def get_reference_line_numeration_marker_patterns(prefix=u''): """Return a list of compiled regex patterns used to search for the marker of a reference line in a full-text document. @param prefix: (string) the possible prefix to a reference line @return: (list) of compiled regex patterns. "...
[ "def", "get_reference_line_numeration_marker_patterns", "(", "prefix", "=", "u''", ")", ":", "title", "=", "u\"\"", "if", "type", "(", "prefix", ")", "in", "(", "str", ",", "unicode", ")", ":", "title", "=", "prefix", "g_name", "=", "u'(?P<mark>'", "g_close"...
Return a list of compiled regex patterns used to search for the marker of a reference line in a full-text document. @param prefix: (string) the possible prefix to a reference line @return: (list) of compiled regex patterns.
[ "Return", "a", "list", "of", "compiled", "regex", "patterns", "used", "to", "search", "for", "the", "marker", "of", "a", "reference", "line", "in", "a", "full", "-", "text", "document", "." ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/regexs.py#L733-L772
train
inspirehep/refextract
refextract/references/regexs.py
get_post_reference_section_title_patterns
def get_post_reference_section_title_patterns(): """Return a list of compiled regex patterns used to search for the title of the section after the reference section in a full-text document. @return: (list) of compiled regex patterns. """ compiled_patterns = [] thead = ur'^\s*([\{\(\<\[]?\s...
python
def get_post_reference_section_title_patterns(): """Return a list of compiled regex patterns used to search for the title of the section after the reference section in a full-text document. @return: (list) of compiled regex patterns. """ compiled_patterns = [] thead = ur'^\s*([\{\(\<\[]?\s...
[ "def", "get_post_reference_section_title_patterns", "(", ")", ":", "compiled_patterns", "=", "[", "]", "thead", "=", "ur'^\\s*([\\{\\(\\<\\[]?\\s*(\\w|\\d)\\s*[\\)\\}\\>\\.\\-\\]]?\\s*)?'", "ttail", "=", "ur'(\\s*\\:\\s*)?'", "numatn", "=", "ur'(\\d+|\\w\\b|i{1,3}v?|vi{0,3})[\\.\\,...
Return a list of compiled regex patterns used to search for the title of the section after the reference section in a full-text document. @return: (list) of compiled regex patterns.
[ "Return", "a", "list", "of", "compiled", "regex", "patterns", "used", "to", "search", "for", "the", "title", "of", "the", "section", "after", "the", "reference", "section", "in", "a", "full", "-", "text", "document", "." ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/regexs.py#L800-L871
train
inspirehep/refextract
refextract/references/regexs.py
get_post_reference_section_keyword_patterns
def get_post_reference_section_keyword_patterns(): """Return a list of compiled regex patterns used to search for various keywords that can often be found after, and therefore suggest the end of, a reference section in a full-text document. @return: (list) of compiled regex patterns. """ ...
python
def get_post_reference_section_keyword_patterns(): """Return a list of compiled regex patterns used to search for various keywords that can often be found after, and therefore suggest the end of, a reference section in a full-text document. @return: (list) of compiled regex patterns. """ ...
[ "def", "get_post_reference_section_keyword_patterns", "(", ")", ":", "compiled_patterns", "=", "[", "]", "patterns", "=", "[", "u'('", "+", "_create_regex_pattern_add_optional_spaces_to_word_characters", "(", "u'prepared'", ")", "+", "ur'|'", "+", "_create_regex_pattern_add...
Return a list of compiled regex patterns used to search for various keywords that can often be found after, and therefore suggest the end of, a reference section in a full-text document. @return: (list) of compiled regex patterns.
[ "Return", "a", "list", "of", "compiled", "regex", "patterns", "used", "to", "search", "for", "various", "keywords", "that", "can", "often", "be", "found", "after", "and", "therefore", "suggest", "the", "end", "of", "a", "reference", "section", "in", "a", "...
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/regexs.py#L874-L894
train
inspirehep/refextract
refextract/references/regexs.py
regex_match_list
def regex_match_list(line, patterns): """Given a list of COMPILED regex patters, perform the "re.match" operation on the line for every pattern. Break from searching at the first match, returning the match object. In the case that no patterns match, the None type will be returned. @param...
python
def regex_match_list(line, patterns): """Given a list of COMPILED regex patters, perform the "re.match" operation on the line for every pattern. Break from searching at the first match, returning the match object. In the case that no patterns match, the None type will be returned. @param...
[ "def", "regex_match_list", "(", "line", ",", "patterns", ")", ":", "m", "=", "None", "for", "ptn", "in", "patterns", ":", "m", "=", "ptn", ".", "match", "(", "line", ")", "if", "m", "is", "not", "None", ":", "break", "return", "m" ]
Given a list of COMPILED regex patters, perform the "re.match" operation on the line for every pattern. Break from searching at the first match, returning the match object. In the case that no patterns match, the None type will be returned. @param line: (unicode string) to be searched in. ...
[ "Given", "a", "list", "of", "COMPILED", "regex", "patters", "perform", "the", "re", ".", "match", "operation", "on", "the", "line", "for", "every", "pattern", ".", "Break", "from", "searching", "at", "the", "first", "match", "returning", "the", "match", "o...
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/regexs.py#L897-L913
train
inspirehep/refextract
refextract/documents/text.py
get_url_repair_patterns
def get_url_repair_patterns(): """Initialise and return a list of precompiled regexp patterns that are used to try to re-assemble URLs that have been broken during a document's conversion to plain-text. @return: (list) of compiled re regexp patterns used for finding various broken URLs....
python
def get_url_repair_patterns(): """Initialise and return a list of precompiled regexp patterns that are used to try to re-assemble URLs that have been broken during a document's conversion to plain-text. @return: (list) of compiled re regexp patterns used for finding various broken URLs....
[ "def", "get_url_repair_patterns", "(", ")", ":", "file_types_list", "=", "[", "ur'h\\s*t\\s*m'", ",", "ur'h\\s*t\\s*m\\s*l'", ",", "ur't\\s*x\\s*t'", "ur'p\\s*h\\s*p'", "ur'a\\s*s\\s*p\\s*'", "ur'j\\s*s\\s*p'", ",", "ur'p\\s*y'", ",", "ur'p\\s*l'", ",", "ur'x\\s*m\\s*l'", ...
Initialise and return a list of precompiled regexp patterns that are used to try to re-assemble URLs that have been broken during a document's conversion to plain-text. @return: (list) of compiled re regexp patterns used for finding various broken URLs.
[ "Initialise", "and", "return", "a", "list", "of", "precompiled", "regexp", "patterns", "that", "are", "used", "to", "try", "to", "re", "-", "assemble", "URLs", "that", "have", "been", "broken", "during", "a", "document", "s", "conversion", "to", "plain", "...
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/documents/text.py#L45-L95
train
inspirehep/refextract
refextract/documents/text.py
join_lines
def join_lines(line1, line2): """Join 2 lines of text >>> join_lines('abc', 'de') 'abcde' >>> join_lines('a-', 'b') 'ab' """ if line1 == u"": pass elif line1[-1] == u'-': # hyphenated word at the end of the # line - don't add in a space and remove hyphen ...
python
def join_lines(line1, line2): """Join 2 lines of text >>> join_lines('abc', 'de') 'abcde' >>> join_lines('a-', 'b') 'ab' """ if line1 == u"": pass elif line1[-1] == u'-': # hyphenated word at the end of the # line - don't add in a space and remove hyphen ...
[ "def", "join_lines", "(", "line1", ",", "line2", ")", ":", "if", "line1", "==", "u\"\"", ":", "pass", "elif", "line1", "[", "-", "1", "]", "==", "u'-'", ":", "line1", "=", "line1", "[", ":", "-", "1", "]", "elif", "line1", "[", "-", "1", "]", ...
Join 2 lines of text >>> join_lines('abc', 'de') 'abcde' >>> join_lines('a-', 'b') 'ab'
[ "Join", "2", "lines", "of", "text" ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/documents/text.py#L102-L120
train
inspirehep/refextract
refextract/documents/text.py
repair_broken_urls
def repair_broken_urls(line): """Attempt to repair broken URLs in a line of text. E.g.: remove spaces from the middle of a URL; something like that. @param line: (string) the line in which to check for broken URLs. @return: (string) the line after any broken URLs have been repaired. """ def _c...
python
def repair_broken_urls(line): """Attempt to repair broken URLs in a line of text. E.g.: remove spaces from the middle of a URL; something like that. @param line: (string) the line in which to check for broken URLs. @return: (string) the line after any broken URLs have been repaired. """ def _c...
[ "def", "repair_broken_urls", "(", "line", ")", ":", "def", "_chop_spaces_in_url_match", "(", "m", ")", ":", "return", "m", ".", "group", "(", "1", ")", ".", "replace", "(", "\" \"", ",", "\"\"", ")", "for", "ptn", "in", "re_list_url_repair_patterns", ":", ...
Attempt to repair broken URLs in a line of text. E.g.: remove spaces from the middle of a URL; something like that. @param line: (string) the line in which to check for broken URLs. @return: (string) the line after any broken URLs have been repaired.
[ "Attempt", "to", "repair", "broken", "URLs", "in", "a", "line", "of", "text", "." ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/documents/text.py#L123-L136
train
inspirehep/refextract
refextract/documents/text.py
remove_and_record_multiple_spaces_in_line
def remove_and_record_multiple_spaces_in_line(line): """For a given string, locate all ocurrences of multiple spaces together in the line, record the number of spaces found at each position, and replace them with a single space. @param line: (string) the text line to be processed for multiple ...
python
def remove_and_record_multiple_spaces_in_line(line): """For a given string, locate all ocurrences of multiple spaces together in the line, record the number of spaces found at each position, and replace them with a single space. @param line: (string) the text line to be processed for multiple ...
[ "def", "remove_and_record_multiple_spaces_in_line", "(", "line", ")", ":", "removed_spaces", "=", "{", "}", "multispace_matches", "=", "re_group_captured_multiple_space", ".", "finditer", "(", "line", ")", "for", "multispace", "in", "multispace_matches", ":", "removed_s...
For a given string, locate all ocurrences of multiple spaces together in the line, record the number of spaces found at each position, and replace them with a single space. @param line: (string) the text line to be processed for multiple spaces. @return: (tuple) countaining a diction...
[ "For", "a", "given", "string", "locate", "all", "ocurrences", "of", "multiple", "spaces", "together", "in", "the", "line", "record", "the", "number", "of", "spaces", "found", "at", "each", "position", "and", "replace", "them", "with", "a", "single", "space",...
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/documents/text.py#L139-L164
train
inspirehep/refextract
refextract/documents/text.py
remove_page_boundary_lines
def remove_page_boundary_lines(docbody): """Try to locate page breaks, headers and footers within a document body, and remove the array cells at which they are found. @param docbody: (list) of strings, each string being a line in the document's body. @return: (list) of strings. The docu...
python
def remove_page_boundary_lines(docbody): """Try to locate page breaks, headers and footers within a document body, and remove the array cells at which they are found. @param docbody: (list) of strings, each string being a line in the document's body. @return: (list) of strings. The docu...
[ "def", "remove_page_boundary_lines", "(", "docbody", ")", ":", "number_head_lines", "=", "number_foot_lines", "=", "0", "if", "not", "document_contains_text", "(", "docbody", ")", ":", "return", "docbody", "page_break_posns", "=", "get_page_break_positions", "(", "doc...
Try to locate page breaks, headers and footers within a document body, and remove the array cells at which they are found. @param docbody: (list) of strings, each string being a line in the document's body. @return: (list) of strings. The document body, hopefully with page- breaks, ...
[ "Try", "to", "locate", "page", "breaks", "headers", "and", "footers", "within", "a", "document", "body", "and", "remove", "the", "array", "cells", "at", "which", "they", "are", "found", "." ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/documents/text.py#L186-L217
train
inspirehep/refextract
refextract/documents/text.py
get_page_break_positions
def get_page_break_positions(docbody): """Locate page breaks in the list of document lines and create a list positions in the document body list. @param docbody: (list) of strings - each string is a line in the document. @return: (list) of integer positions, whereby each integer represe...
python
def get_page_break_positions(docbody): """Locate page breaks in the list of document lines and create a list positions in the document body list. @param docbody: (list) of strings - each string is a line in the document. @return: (list) of integer positions, whereby each integer represe...
[ "def", "get_page_break_positions", "(", "docbody", ")", ":", "page_break_posns", "=", "[", "]", "p_break", "=", "re", ".", "compile", "(", "ur'^\\s*\\f\\s*$'", ",", "re", ".", "UNICODE", ")", "num_document_lines", "=", "len", "(", "docbody", ")", "for", "i",...
Locate page breaks in the list of document lines and create a list positions in the document body list. @param docbody: (list) of strings - each string is a line in the document. @return: (list) of integer positions, whereby each integer represents the position (in the document body...
[ "Locate", "page", "breaks", "in", "the", "list", "of", "document", "lines", "and", "create", "a", "list", "positions", "in", "the", "document", "body", "list", "." ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/documents/text.py#L237-L251
train
inspirehep/refextract
refextract/documents/text.py
get_number_header_lines
def get_number_header_lines(docbody, page_break_posns): """Try to guess the number of header lines each page of a document has. The positions of the page breaks in the document are used to try to guess the number of header lines. @param docbody: (list) of strings - each string being a line in t...
python
def get_number_header_lines(docbody, page_break_posns): """Try to guess the number of header lines each page of a document has. The positions of the page breaks in the document are used to try to guess the number of header lines. @param docbody: (list) of strings - each string being a line in t...
[ "def", "get_number_header_lines", "(", "docbody", ",", "page_break_posns", ")", ":", "remaining_breaks", "=", "len", "(", "page_break_posns", ")", "-", "1", "num_header_lines", "=", "empty_line", "=", "0", "p_wordSearch", "=", "re", ".", "compile", "(", "ur'([A-...
Try to guess the number of header lines each page of a document has. The positions of the page breaks in the document are used to try to guess the number of header lines. @param docbody: (list) of strings - each string being a line in the document @param page_break_posns: (list) of i...
[ "Try", "to", "guess", "the", "number", "of", "header", "lines", "each", "page", "of", "a", "document", "has", ".", "The", "positions", "of", "the", "page", "breaks", "in", "the", "document", "are", "used", "to", "try", "to", "guess", "the", "number", "...
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/documents/text.py#L254-L320
train
inspirehep/refextract
refextract/documents/text.py
get_number_footer_lines
def get_number_footer_lines(docbody, page_break_posns): """Try to guess the number of footer lines each page of a document has. The positions of the page breaks in the document are used to try to guess the number of footer lines. @param docbody: (list) of strings - each string being a line in t...
python
def get_number_footer_lines(docbody, page_break_posns): """Try to guess the number of footer lines each page of a document has. The positions of the page breaks in the document are used to try to guess the number of footer lines. @param docbody: (list) of strings - each string being a line in t...
[ "def", "get_number_footer_lines", "(", "docbody", ",", "page_break_posns", ")", ":", "num_breaks", "=", "len", "(", "page_break_posns", ")", "num_footer_lines", "=", "0", "empty_line", "=", "0", "keep_checking", "=", "1", "p_wordSearch", "=", "re", ".", "compile...
Try to guess the number of footer lines each page of a document has. The positions of the page breaks in the document are used to try to guess the number of footer lines. @param docbody: (list) of strings - each string being a line in the document @param page_break_posns: (list) of i...
[ "Try", "to", "guess", "the", "number", "of", "footer", "lines", "each", "page", "of", "a", "document", "has", ".", "The", "positions", "of", "the", "page", "breaks", "in", "the", "document", "are", "used", "to", "try", "to", "guess", "the", "number", "...
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/documents/text.py#L323-L377
train
inspirehep/refextract
refextract/documents/text.py
strip_headers_footers_pagebreaks
def strip_headers_footers_pagebreaks(docbody, page_break_posns, num_head_lines, num_foot_lines): """Remove page-break lines, header lines, and footer lines from the document. @param docbody: ...
python
def strip_headers_footers_pagebreaks(docbody, page_break_posns, num_head_lines, num_foot_lines): """Remove page-break lines, header lines, and footer lines from the document. @param docbody: ...
[ "def", "strip_headers_footers_pagebreaks", "(", "docbody", ",", "page_break_posns", ",", "num_head_lines", ",", "num_foot_lines", ")", ":", "num_breaks", "=", "len", "(", "page_break_posns", ")", "page_lens", "=", "[", "]", "for", "x", "in", "xrange", "(", "0", ...
Remove page-break lines, header lines, and footer lines from the document. @param docbody: (list) of strings, whereby each string in the list is a line in the document. @param page_break_posns: (list) of integers, whereby each integer represents the index in docbody at which a page-...
[ "Remove", "page", "-", "break", "lines", "header", "lines", "and", "footer", "lines", "from", "the", "document", "." ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/documents/text.py#L380-L424
train
inspirehep/refextract
refextract/documents/text.py
check_boundary_lines_similar
def check_boundary_lines_similar(l_1, l_2): """Compare two lists to see if their elements are roughly the same. @param l_1: (list) of strings. @param l_2: (list) of strings. @return: (int) 1/0. """ num_matches = 0 if (type(l_1) != list) or (type(l_2) != list) or (len(l_1) != len(l_2)): ...
python
def check_boundary_lines_similar(l_1, l_2): """Compare two lists to see if their elements are roughly the same. @param l_1: (list) of strings. @param l_2: (list) of strings. @return: (int) 1/0. """ num_matches = 0 if (type(l_1) != list) or (type(l_2) != list) or (len(l_1) != len(l_2)): ...
[ "def", "check_boundary_lines_similar", "(", "l_1", ",", "l_2", ")", ":", "num_matches", "=", "0", "if", "(", "type", "(", "l_1", ")", "!=", "list", ")", "or", "(", "type", "(", "l_2", ")", "!=", "list", ")", "or", "(", "len", "(", "l_1", ")", "!=...
Compare two lists to see if their elements are roughly the same. @param l_1: (list) of strings. @param l_2: (list) of strings. @return: (int) 1/0.
[ "Compare", "two", "lists", "to", "see", "if", "their", "elements", "are", "roughly", "the", "same", "." ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/documents/text.py#L427-L452
train
inspirehep/refextract
refextract/references/kbs.py
make_cache_key
def make_cache_key(custom_kbs_files=None): """Create cache key for kbs caches instances This function generates a unique key for a given set of arguments. The files dictionary is transformed like this: {'journal': '/var/journal.kb', 'books': '/var/books.kb'} to "journal=/var/journal.kb;books=/...
python
def make_cache_key(custom_kbs_files=None): """Create cache key for kbs caches instances This function generates a unique key for a given set of arguments. The files dictionary is transformed like this: {'journal': '/var/journal.kb', 'books': '/var/books.kb'} to "journal=/var/journal.kb;books=/...
[ "def", "make_cache_key", "(", "custom_kbs_files", "=", "None", ")", ":", "if", "custom_kbs_files", ":", "serialized_args", "=", "(", "'%s=%s'", "%", "v", "for", "v", "in", "iteritems", "(", "custom_kbs_files", ")", ")", "serialized_args", "=", "';'", ".", "j...
Create cache key for kbs caches instances This function generates a unique key for a given set of arguments. The files dictionary is transformed like this: {'journal': '/var/journal.kb', 'books': '/var/books.kb'} to "journal=/var/journal.kb;books=/var/books.kb" Then _inspire is appended if we...
[ "Create", "cache", "key", "for", "kbs", "caches", "instances" ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/kbs.py#L112-L130
train
inspirehep/refextract
refextract/references/kbs.py
create_institute_numeration_group_regexp_pattern
def create_institute_numeration_group_regexp_pattern(patterns): """Using a list of regexp patterns for recognising numeration patterns for institute preprint references, ordered by length - longest to shortest - create a grouped 'OR' or of these patterns, ready to be used in a bigger regexp. ...
python
def create_institute_numeration_group_regexp_pattern(patterns): """Using a list of regexp patterns for recognising numeration patterns for institute preprint references, ordered by length - longest to shortest - create a grouped 'OR' or of these patterns, ready to be used in a bigger regexp. ...
[ "def", "create_institute_numeration_group_regexp_pattern", "(", "patterns", ")", ":", "patterns_list", "=", "[", "institute_num_pattern_to_regex", "(", "p", "[", "1", "]", ")", "for", "p", "in", "patterns", "]", "grouped_numeration_pattern", "=", "u\"(?P<numn>%s)\"", ...
Using a list of regexp patterns for recognising numeration patterns for institute preprint references, ordered by length - longest to shortest - create a grouped 'OR' or of these patterns, ready to be used in a bigger regexp. @param patterns: (list) of strings. All of the numeration regexp ...
[ "Using", "a", "list", "of", "regexp", "patterns", "for", "recognising", "numeration", "patterns", "for", "institute", "preprint", "references", "ordered", "by", "length", "-", "longest", "to", "shortest", "-", "create", "a", "grouped", "OR", "or", "of", "these...
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/kbs.py#L161-L174
train
inspirehep/refextract
refextract/references/kbs.py
build_reportnum_kb
def build_reportnum_kb(fpath): """Given the path to a knowledge base file containing the details of institutes and the patterns that their preprint report numbering schemes take, create a dictionary of regexp search patterns to recognise these preprint references in reference lines, and ...
python
def build_reportnum_kb(fpath): """Given the path to a knowledge base file containing the details of institutes and the patterns that their preprint report numbering schemes take, create a dictionary of regexp search patterns to recognise these preprint references in reference lines, and ...
[ "def", "build_reportnum_kb", "(", "fpath", ")", ":", "def", "_add_institute_preprint_patterns", "(", "preprint_classifications", ",", "preprint_numeration_ptns", ",", "preprint_reference_search_regexp_patterns", ",", "standardised_preprint_reference_categories", ",", "kb_line_num",...
Given the path to a knowledge base file containing the details of institutes and the patterns that their preprint report numbering schemes take, create a dictionary of regexp search patterns to recognise these preprint references in reference lines, and a dictionary of replacements for non-s...
[ "Given", "the", "path", "to", "a", "knowledge", "base", "file", "containing", "the", "details", "of", "institutes", "and", "the", "patterns", "that", "their", "preprint", "report", "numbering", "schemes", "take", "create", "a", "dictionary", "of", "regexp", "s...
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/kbs.py#L222-L415
train
inspirehep/refextract
refextract/references/kbs.py
_cmp_bystrlen_reverse
def _cmp_bystrlen_reverse(a, b): """A private "cmp" function to be used by the "sort" function of a list when ordering the titles found in a knowledge base by string- length - LONGEST -> SHORTEST. @param a: (string) @param b: (string) @return: (integer) - 0 if len(a) == len(b); 1 ...
python
def _cmp_bystrlen_reverse(a, b): """A private "cmp" function to be used by the "sort" function of a list when ordering the titles found in a knowledge base by string- length - LONGEST -> SHORTEST. @param a: (string) @param b: (string) @return: (integer) - 0 if len(a) == len(b); 1 ...
[ "def", "_cmp_bystrlen_reverse", "(", "a", ",", "b", ")", ":", "if", "len", "(", "a", ")", ">", "len", "(", "b", ")", ":", "return", "-", "1", "elif", "len", "(", "a", ")", "<", "len", "(", "b", ")", ":", "return", "1", "else", ":", "return", ...
A private "cmp" function to be used by the "sort" function of a list when ordering the titles found in a knowledge base by string- length - LONGEST -> SHORTEST. @param a: (string) @param b: (string) @return: (integer) - 0 if len(a) == len(b); 1 if len(a) < len(b); -1 if len(a)...
[ "A", "private", "cmp", "function", "to", "be", "used", "by", "the", "sort", "function", "of", "a", "list", "when", "ordering", "the", "titles", "found", "in", "a", "knowledge", "base", "by", "string", "-", "length", "-", "LONGEST", "-", ">", "SHORTEST", ...
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/kbs.py#L418-L432
train
inspirehep/refextract
refextract/references/kbs.py
build_special_journals_kb
def build_special_journals_kb(fpath): """Load special journals database from file Special journals are journals that have a volume which is not unique among different years. To keep the volume unique we are adding the year before the volume. """ journals = set() with file_resolving(fpath) a...
python
def build_special_journals_kb(fpath): """Load special journals database from file Special journals are journals that have a volume which is not unique among different years. To keep the volume unique we are adding the year before the volume. """ journals = set() with file_resolving(fpath) a...
[ "def", "build_special_journals_kb", "(", "fpath", ")", ":", "journals", "=", "set", "(", ")", "with", "file_resolving", "(", "fpath", ")", "as", "fh", ":", "for", "line", "in", "fh", ":", "if", "line", ".", "startswith", "(", "'#'", ")", ":", "continue...
Load special journals database from file Special journals are journals that have a volume which is not unique among different years. To keep the volume unique we are adding the year before the volume.
[ "Load", "special", "journals", "database", "from", "file" ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/kbs.py#L435-L453
train
inspirehep/refextract
refextract/references/kbs.py
build_journals_re_kb
def build_journals_re_kb(fpath): """Load journals regexps knowledge base @see build_journals_kb """ def make_tuple(match): regexp = match.group('seek') repl = match.group('repl') return regexp, repl kb = [] with file_resolving(fpath) as fh: for rawline in fh: ...
python
def build_journals_re_kb(fpath): """Load journals regexps knowledge base @see build_journals_kb """ def make_tuple(match): regexp = match.group('seek') repl = match.group('repl') return regexp, repl kb = [] with file_resolving(fpath) as fh: for rawline in fh: ...
[ "def", "build_journals_re_kb", "(", "fpath", ")", ":", "def", "make_tuple", "(", "match", ")", ":", "regexp", "=", "match", ".", "group", "(", "'seek'", ")", "repl", "=", "match", ".", "group", "(", "'repl'", ")", "return", "regexp", ",", "repl", "kb",...
Load journals regexps knowledge base @see build_journals_kb
[ "Load", "journals", "regexps", "knowledge", "base" ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/kbs.py#L492-L512
train
brettcannon/gidgethub
gidgethub/sansio.py
_parse_content_type
def _parse_content_type(content_type: Optional[str]) -> Tuple[Optional[str], str]: """Tease out the content-type and character encoding. A default character encoding of UTF-8 is used, so the content-type must be used to determine if any decoding is necessary to begin with. """ if not content_ty...
python
def _parse_content_type(content_type: Optional[str]) -> Tuple[Optional[str], str]: """Tease out the content-type and character encoding. A default character encoding of UTF-8 is used, so the content-type must be used to determine if any decoding is necessary to begin with. """ if not content_ty...
[ "def", "_parse_content_type", "(", "content_type", ":", "Optional", "[", "str", "]", ")", "->", "Tuple", "[", "Optional", "[", "str", "]", ",", "str", "]", ":", "if", "not", "content_type", ":", "return", "None", ",", "\"utf-8\"", "else", ":", "type_", ...
Tease out the content-type and character encoding. A default character encoding of UTF-8 is used, so the content-type must be used to determine if any decoding is necessary to begin with.
[ "Tease", "out", "the", "content", "-", "type", "and", "character", "encoding", "." ]
24feb6c35bba3966c6cc9ec2896729578f6d7ccc
https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L24-L36
train
brettcannon/gidgethub
gidgethub/sansio.py
_decode_body
def _decode_body(content_type: Optional[str], body: bytes, *, strict: bool = False) -> Any: """Decode an HTTP body based on the specified content type. If 'strict' is true, then raise ValueError if the content type is not recognized. Otherwise simply returned the body as a decoded stri...
python
def _decode_body(content_type: Optional[str], body: bytes, *, strict: bool = False) -> Any: """Decode an HTTP body based on the specified content type. If 'strict' is true, then raise ValueError if the content type is not recognized. Otherwise simply returned the body as a decoded stri...
[ "def", "_decode_body", "(", "content_type", ":", "Optional", "[", "str", "]", ",", "body", ":", "bytes", ",", "*", ",", "strict", ":", "bool", "=", "False", ")", "->", "Any", ":", "type_", ",", "encoding", "=", "_parse_content_type", "(", "content_type",...
Decode an HTTP body based on the specified content type. If 'strict' is true, then raise ValueError if the content type is not recognized. Otherwise simply returned the body as a decoded string.
[ "Decode", "an", "HTTP", "body", "based", "on", "the", "specified", "content", "type", "." ]
24feb6c35bba3966c6cc9ec2896729578f6d7ccc
https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L39-L57
train
brettcannon/gidgethub
gidgethub/sansio.py
validate_event
def validate_event(payload: bytes, *, signature: str, secret: str) -> None: """Validate the signature of a webhook event.""" # https://developer.github.com/webhooks/securing/#validating-payloads-from-github signature_prefix = "sha1=" if not signature.startswith(signature_prefix): raise Validatio...
python
def validate_event(payload: bytes, *, signature: str, secret: str) -> None: """Validate the signature of a webhook event.""" # https://developer.github.com/webhooks/securing/#validating-payloads-from-github signature_prefix = "sha1=" if not signature.startswith(signature_prefix): raise Validatio...
[ "def", "validate_event", "(", "payload", ":", "bytes", ",", "*", ",", "signature", ":", "str", ",", "secret", ":", "str", ")", "->", "None", ":", "signature_prefix", "=", "\"sha1=\"", "if", "not", "signature", ".", "startswith", "(", "signature_prefix", ")...
Validate the signature of a webhook event.
[ "Validate", "the", "signature", "of", "a", "webhook", "event", "." ]
24feb6c35bba3966c6cc9ec2896729578f6d7ccc
https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L60-L71
train
brettcannon/gidgethub
gidgethub/sansio.py
accept_format
def accept_format(*, version: str = "v3", media: Optional[str] = None, json: bool = True) -> str: """Construct the specification of the format that a request should return. The version argument defaults to v3 of the GitHub API and is applicable to all requests. The media argument along wi...
python
def accept_format(*, version: str = "v3", media: Optional[str] = None, json: bool = True) -> str: """Construct the specification of the format that a request should return. The version argument defaults to v3 of the GitHub API and is applicable to all requests. The media argument along wi...
[ "def", "accept_format", "(", "*", ",", "version", ":", "str", "=", "\"v3\"", ",", "media", ":", "Optional", "[", "str", "]", "=", "None", ",", "json", ":", "bool", "=", "True", ")", "->", "str", ":", "accept", "=", "f\"application/vnd.github.{version}\""...
Construct the specification of the format that a request should return. The version argument defaults to v3 of the GitHub API and is applicable to all requests. The media argument along with 'json' specifies what format the request should return, e.g. requesting the rendered HTML of a comment. Do note ...
[ "Construct", "the", "specification", "of", "the", "format", "that", "a", "request", "should", "return", "." ]
24feb6c35bba3966c6cc9ec2896729578f6d7ccc
https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L125-L145
train
brettcannon/gidgethub
gidgethub/sansio.py
create_headers
def create_headers(requester: str, *, accept: str = accept_format(), oauth_token: Optional[str] = None, jwt: Optional[str] = None) -> Dict[str, str]: """Create a dict representing GitHub-specific header fields. The user agent is set according to who the requester is. GitHu...
python
def create_headers(requester: str, *, accept: str = accept_format(), oauth_token: Optional[str] = None, jwt: Optional[str] = None) -> Dict[str, str]: """Create a dict representing GitHub-specific header fields. The user agent is set according to who the requester is. GitHu...
[ "def", "create_headers", "(", "requester", ":", "str", ",", "*", ",", "accept", ":", "str", "=", "accept_format", "(", ")", ",", "oauth_token", ":", "Optional", "[", "str", "]", "=", "None", ",", "jwt", ":", "Optional", "[", "str", "]", "=", "None", ...
Create a dict representing GitHub-specific header fields. The user agent is set according to who the requester is. GitHub asks it be either a username or project name. The 'accept' argument corresponds to the 'accept' field and defaults to the default result of accept_format(). You should only need to...
[ "Create", "a", "dict", "representing", "GitHub", "-", "specific", "header", "fields", "." ]
24feb6c35bba3966c6cc9ec2896729578f6d7ccc
https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L148-L186
train
brettcannon/gidgethub
gidgethub/sansio.py
decipher_response
def decipher_response(status_code: int, headers: Mapping[str, str], body: bytes) -> Tuple[Any, Optional[RateLimit], Optional[str]]: """Decipher an HTTP response for a GitHub API request. The mapping providing the headers is expected to support lowercase keys. The parameters of this f...
python
def decipher_response(status_code: int, headers: Mapping[str, str], body: bytes) -> Tuple[Any, Optional[RateLimit], Optional[str]]: """Decipher an HTTP response for a GitHub API request. The mapping providing the headers is expected to support lowercase keys. The parameters of this f...
[ "def", "decipher_response", "(", "status_code", ":", "int", ",", "headers", ":", "Mapping", "[", "str", ",", "str", "]", ",", "body", ":", "bytes", ")", "->", "Tuple", "[", "Any", ",", "Optional", "[", "RateLimit", "]", ",", "Optional", "[", "str", "...
Decipher an HTTP response for a GitHub API request. The mapping providing the headers is expected to support lowercase keys. The parameters of this function correspond to the three main parts of an HTTP response: the status code, headers, and body. Assuming no errors which lead to an exception being r...
[ "Decipher", "an", "HTTP", "response", "for", "a", "GitHub", "API", "request", "." ]
24feb6c35bba3966c6cc9ec2896729578f6d7ccc
https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L269-L326
train
brettcannon/gidgethub
gidgethub/sansio.py
format_url
def format_url(url: str, url_vars: Mapping[str, Any]) -> str: """Construct a URL for the GitHub API. The URL may be absolute or relative. In the latter case the appropriate domain will be added. This is to help when copying the relative URL directly from the GitHub developer documentation. The dic...
python
def format_url(url: str, url_vars: Mapping[str, Any]) -> str: """Construct a URL for the GitHub API. The URL may be absolute or relative. In the latter case the appropriate domain will be added. This is to help when copying the relative URL directly from the GitHub developer documentation. The dic...
[ "def", "format_url", "(", "url", ":", "str", ",", "url_vars", ":", "Mapping", "[", "str", ",", "Any", "]", ")", "->", "str", ":", "url", "=", "urllib", ".", "parse", ".", "urljoin", "(", "DOMAIN", ",", "url", ")", "expanded_url", ":", "str", "=", ...
Construct a URL for the GitHub API. The URL may be absolute or relative. In the latter case the appropriate domain will be added. This is to help when copying the relative URL directly from the GitHub developer documentation. The dict provided in url_vars is used in URI template formatting.
[ "Construct", "a", "URL", "for", "the", "GitHub", "API", "." ]
24feb6c35bba3966c6cc9ec2896729578f6d7ccc
https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L331-L342
train
brettcannon/gidgethub
gidgethub/sansio.py
Event.from_http
def from_http(cls, headers: Mapping[str, str], body: bytes, *, secret: Optional[str] = None) -> "Event": """Construct an event from HTTP headers and JSON body data. The mapping providing the headers is expected to support lowercase keys. Since this method assumes the body of ...
python
def from_http(cls, headers: Mapping[str, str], body: bytes, *, secret: Optional[str] = None) -> "Event": """Construct an event from HTTP headers and JSON body data. The mapping providing the headers is expected to support lowercase keys. Since this method assumes the body of ...
[ "def", "from_http", "(", "cls", ",", "headers", ":", "Mapping", "[", "str", ",", "str", "]", ",", "body", ":", "bytes", ",", "*", ",", "secret", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "\"Event\"", ":", "if", "\"x-hub-signature\"", ...
Construct an event from HTTP headers and JSON body data. The mapping providing the headers is expected to support lowercase keys. Since this method assumes the body of the HTTP request is JSON, a check is performed for a content-type of "application/json" (GitHub does support other con...
[ "Construct", "an", "event", "from", "HTTP", "headers", "and", "JSON", "body", "data", "." ]
24feb6c35bba3966c6cc9ec2896729578f6d7ccc
https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L90-L122
train
brettcannon/gidgethub
gidgethub/sansio.py
RateLimit.from_http
def from_http(cls, headers: Mapping[str, str]) -> Optional["RateLimit"]: """Gather rate limit information from HTTP headers. The mapping providing the headers is expected to support lowercase keys. Returns ``None`` if ratelimit info is not found in the headers. """ try: ...
python
def from_http(cls, headers: Mapping[str, str]) -> Optional["RateLimit"]: """Gather rate limit information from HTTP headers. The mapping providing the headers is expected to support lowercase keys. Returns ``None`` if ratelimit info is not found in the headers. """ try: ...
[ "def", "from_http", "(", "cls", ",", "headers", ":", "Mapping", "[", "str", ",", "str", "]", ")", "->", "Optional", "[", "\"RateLimit\"", "]", ":", "try", ":", "limit", "=", "int", "(", "headers", "[", "\"x-ratelimit-limit\"", "]", ")", "remaining", "=...
Gather rate limit information from HTTP headers. The mapping providing the headers is expected to support lowercase keys. Returns ``None`` if ratelimit info is not found in the headers.
[ "Gather", "rate", "limit", "information", "from", "HTTP", "headers", "." ]
24feb6c35bba3966c6cc9ec2896729578f6d7ccc
https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L237-L250
train
brettcannon/gidgethub
gidgethub/routing.py
Router.add
def add(self, func: AsyncCallback, event_type: str, **data_detail: Any) -> None: """Add a new route. After registering 'func' for the specified event_type, an optional data_detail may be provided. By providing an extra keyword argument, dispatching can occur based on a top-level ...
python
def add(self, func: AsyncCallback, event_type: str, **data_detail: Any) -> None: """Add a new route. After registering 'func' for the specified event_type, an optional data_detail may be provided. By providing an extra keyword argument, dispatching can occur based on a top-level ...
[ "def", "add", "(", "self", ",", "func", ":", "AsyncCallback", ",", "event_type", ":", "str", ",", "**", "data_detail", ":", "Any", ")", "->", "None", ":", "if", "len", "(", "data_detail", ")", ">", "1", ":", "msg", "=", "(", ")", "raise", "TypeErro...
Add a new route. After registering 'func' for the specified event_type, an optional data_detail may be provided. By providing an extra keyword argument, dispatching can occur based on a top-level key of the data in the event being dispatched.
[ "Add", "a", "new", "route", "." ]
24feb6c35bba3966c6cc9ec2896729578f6d7ccc
https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/routing.py#L29-L50
train
brettcannon/gidgethub
gidgethub/abc.py
GitHubAPI._make_request
async def _make_request(self, method: str, url: str, url_vars: Dict[str, str], data: Any, accept: str, jwt: Opt[str] = None, oauth_token: Opt[str] = None, ) -> Tuple[bytes, Opt[str]]: """Construct and...
python
async def _make_request(self, method: str, url: str, url_vars: Dict[str, str], data: Any, accept: str, jwt: Opt[str] = None, oauth_token: Opt[str] = None, ) -> Tuple[bytes, Opt[str]]: """Construct and...
[ "async", "def", "_make_request", "(", "self", ",", "method", ":", "str", ",", "url", ":", "str", ",", "url_vars", ":", "Dict", "[", "str", ",", "str", "]", ",", "data", ":", "Any", ",", "accept", ":", "str", ",", "jwt", ":", "Opt", "[", "str", ...
Construct and make an HTTP request.
[ "Construct", "and", "make", "an", "HTTP", "request", "." ]
24feb6c35bba3966c6cc9ec2896729578f6d7ccc
https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/abc.py#L34-L89
train
brettcannon/gidgethub
gidgethub/abc.py
GitHubAPI.getitem
async def getitem(self, url: str, url_vars: Dict[str, str] = {}, *, accept: str = sansio.accept_format(), jwt: Opt[str] = None, oauth_token: Opt[str] = None ) -> Any: """Send a GET request for a single item to the specified ...
python
async def getitem(self, url: str, url_vars: Dict[str, str] = {}, *, accept: str = sansio.accept_format(), jwt: Opt[str] = None, oauth_token: Opt[str] = None ) -> Any: """Send a GET request for a single item to the specified ...
[ "async", "def", "getitem", "(", "self", ",", "url", ":", "str", ",", "url_vars", ":", "Dict", "[", "str", ",", "str", "]", "=", "{", "}", ",", "*", ",", "accept", ":", "str", "=", "sansio", ".", "accept_format", "(", ")", ",", "jwt", ":", "Opt"...
Send a GET request for a single item to the specified endpoint.
[ "Send", "a", "GET", "request", "for", "a", "single", "item", "to", "the", "specified", "endpoint", "." ]
24feb6c35bba3966c6cc9ec2896729578f6d7ccc
https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/abc.py#L91-L100
train
brettcannon/gidgethub
gidgethub/abc.py
GitHubAPI.getiter
async def getiter(self, url: str, url_vars: Dict[str, str] = {}, *, accept: str = sansio.accept_format(), jwt: Opt[str] = None, oauth_token: Opt[str] = None ) -> AsyncGenerator[Any, None]: """Return an async iterable for all...
python
async def getiter(self, url: str, url_vars: Dict[str, str] = {}, *, accept: str = sansio.accept_format(), jwt: Opt[str] = None, oauth_token: Opt[str] = None ) -> AsyncGenerator[Any, None]: """Return an async iterable for all...
[ "async", "def", "getiter", "(", "self", ",", "url", ":", "str", ",", "url_vars", ":", "Dict", "[", "str", ",", "str", "]", "=", "{", "}", ",", "*", ",", "accept", ":", "str", "=", "sansio", ".", "accept_format", "(", ")", ",", "jwt", ":", "Opt"...
Return an async iterable for all the items at a specified endpoint.
[ "Return", "an", "async", "iterable", "for", "all", "the", "items", "at", "a", "specified", "endpoint", "." ]
24feb6c35bba3966c6cc9ec2896729578f6d7ccc
https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/abc.py#L102-L120
train
rkargon/pixelsorter
pixelsorter/images2gif.py
NeuQuant.quantize
def quantize(self, image): """ Use a kdtree to quickly find the closest palette colors for the pixels """ if get_cKDTree(): return self.quantize_with_scipy(image) else: print('Scipy not available, falling back to slower version.') return self.quantize_without_...
python
def quantize(self, image): """ Use a kdtree to quickly find the closest palette colors for the pixels """ if get_cKDTree(): return self.quantize_with_scipy(image) else: print('Scipy not available, falling back to slower version.') return self.quantize_without_...
[ "def", "quantize", "(", "self", ",", "image", ")", ":", "if", "get_cKDTree", "(", ")", ":", "return", "self", ".", "quantize_with_scipy", "(", "image", ")", "else", ":", "print", "(", "'Scipy not available, falling back to slower version.'", ")", "return", "self...
Use a kdtree to quickly find the closest palette colors for the pixels
[ "Use", "a", "kdtree", "to", "quickly", "find", "the", "closest", "palette", "colors", "for", "the", "pixels" ]
0775d1e487fbcb023e411e1818ba3290b0e8665e
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/images2gif.py#L1017-L1023
train
rkargon/pixelsorter
pixelsorter/images2gif.py
NeuQuant.inxsearch
def inxsearch(self, r, g, b): """Search for BGR values 0..255 and return colour index""" dists = (self.colormap[:, :3] - np.array([r, g, b])) a = np.argmin((dists * dists).sum(1)) return a
python
def inxsearch(self, r, g, b): """Search for BGR values 0..255 and return colour index""" dists = (self.colormap[:, :3] - np.array([r, g, b])) a = np.argmin((dists * dists).sum(1)) return a
[ "def", "inxsearch", "(", "self", ",", "r", ",", "g", ",", "b", ")", ":", "dists", "=", "(", "self", ".", "colormap", "[", ":", ",", ":", "3", "]", "-", "np", ".", "array", "(", "[", "r", ",", "g", ",", "b", "]", ")", ")", "a", "=", "np"...
Search for BGR values 0..255 and return colour index
[ "Search", "for", "BGR", "values", "0", "..", "255", "and", "return", "colour", "index" ]
0775d1e487fbcb023e411e1818ba3290b0e8665e
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/images2gif.py#L1061-L1065
train
European-XFEL/karabo-bridge-py
karabo_bridge/cli/glimpse.py
gen_filename
def gen_filename(endpoint): """Generate a filename from endpoint with timestamp. return: str hostname_port_YearMonthDay_HourMinSecFrac.h5 """ now = datetime.now().strftime('%Y%m%d_%H%M%S%f')[:-4] base = endpoint.split('://', 1)[1] if base.startswith('localhost:'): base = gethost...
python
def gen_filename(endpoint): """Generate a filename from endpoint with timestamp. return: str hostname_port_YearMonthDay_HourMinSecFrac.h5 """ now = datetime.now().strftime('%Y%m%d_%H%M%S%f')[:-4] base = endpoint.split('://', 1)[1] if base.startswith('localhost:'): base = gethost...
[ "def", "gen_filename", "(", "endpoint", ")", ":", "now", "=", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "'%Y%m%d_%H%M%S%f'", ")", "[", ":", "-", "4", "]", "base", "=", "endpoint", ".", "split", "(", "'://'", ",", "1", ")", "[", "1", ...
Generate a filename from endpoint with timestamp. return: str hostname_port_YearMonthDay_HourMinSecFrac.h5
[ "Generate", "a", "filename", "from", "endpoint", "with", "timestamp", "." ]
ca20d72b8beb0039649d10cb01d027db42efd91c
https://github.com/European-XFEL/karabo-bridge-py/blob/ca20d72b8beb0039649d10cb01d027db42efd91c/karabo_bridge/cli/glimpse.py#L15-L26
train
European-XFEL/karabo-bridge-py
karabo_bridge/cli/glimpse.py
dict_to_hdf5
def dict_to_hdf5(dic, endpoint): """Dump a dict to an HDF5 file. """ filename = gen_filename(endpoint) with h5py.File(filename, 'w') as handler: walk_dict_to_hdf5(dic, handler) print('dumped to', filename)
python
def dict_to_hdf5(dic, endpoint): """Dump a dict to an HDF5 file. """ filename = gen_filename(endpoint) with h5py.File(filename, 'w') as handler: walk_dict_to_hdf5(dic, handler) print('dumped to', filename)
[ "def", "dict_to_hdf5", "(", "dic", ",", "endpoint", ")", ":", "filename", "=", "gen_filename", "(", "endpoint", ")", "with", "h5py", ".", "File", "(", "filename", ",", "'w'", ")", "as", "handler", ":", "walk_dict_to_hdf5", "(", "dic", ",", "handler", ")"...
Dump a dict to an HDF5 file.
[ "Dump", "a", "dict", "to", "an", "HDF5", "file", "." ]
ca20d72b8beb0039649d10cb01d027db42efd91c
https://github.com/European-XFEL/karabo-bridge-py/blob/ca20d72b8beb0039649d10cb01d027db42efd91c/karabo_bridge/cli/glimpse.py#L29-L35
train
European-XFEL/karabo-bridge-py
karabo_bridge/cli/glimpse.py
hdf5_to_dict
def hdf5_to_dict(filepath, group='/'): """load the content of an hdf5 file to a dict. # TODO: how to split domain_type_dev : parameter : value ? """ if not h5py.is_hdf5(filepath): raise RuntimeError(filepath, 'is not a valid HDF5 file.') with h5py.File(filepath, 'r') as handler: di...
python
def hdf5_to_dict(filepath, group='/'): """load the content of an hdf5 file to a dict. # TODO: how to split domain_type_dev : parameter : value ? """ if not h5py.is_hdf5(filepath): raise RuntimeError(filepath, 'is not a valid HDF5 file.') with h5py.File(filepath, 'r') as handler: di...
[ "def", "hdf5_to_dict", "(", "filepath", ",", "group", "=", "'/'", ")", ":", "if", "not", "h5py", ".", "is_hdf5", "(", "filepath", ")", ":", "raise", "RuntimeError", "(", "filepath", ",", "'is not a valid HDF5 file.'", ")", "with", "h5py", ".", "File", "(",...
load the content of an hdf5 file to a dict. # TODO: how to split domain_type_dev : parameter : value ?
[ "load", "the", "content", "of", "an", "hdf5", "file", "to", "a", "dict", "." ]
ca20d72b8beb0039649d10cb01d027db42efd91c
https://github.com/European-XFEL/karabo-bridge-py/blob/ca20d72b8beb0039649d10cb01d027db42efd91c/karabo_bridge/cli/glimpse.py#L38-L48
train
European-XFEL/karabo-bridge-py
karabo_bridge/cli/glimpse.py
print_one_train
def print_one_train(client, verbosity=0): """Retrieve data for one train and print it. Returns the (data, metadata) dicts from the client. This is used by the -glimpse and -monitor command line tools. """ ts_before = time() data, meta = client.next() ts_after = time() if not data: ...
python
def print_one_train(client, verbosity=0): """Retrieve data for one train and print it. Returns the (data, metadata) dicts from the client. This is used by the -glimpse and -monitor command line tools. """ ts_before = time() data, meta = client.next() ts_after = time() if not data: ...
[ "def", "print_one_train", "(", "client", ",", "verbosity", "=", "0", ")", ":", "ts_before", "=", "time", "(", ")", "data", ",", "meta", "=", "client", ".", "next", "(", ")", "ts_after", "=", "time", "(", ")", "if", "not", "data", ":", "print", "(",...
Retrieve data for one train and print it. Returns the (data, metadata) dicts from the client. This is used by the -glimpse and -monitor command line tools.
[ "Retrieve", "data", "for", "one", "train", "and", "print", "it", "." ]
ca20d72b8beb0039649d10cb01d027db42efd91c
https://github.com/European-XFEL/karabo-bridge-py/blob/ca20d72b8beb0039649d10cb01d027db42efd91c/karabo_bridge/cli/glimpse.py#L92-L140
train
European-XFEL/karabo-bridge-py
karabo_bridge/cli/glimpse.py
pretty_print
def pretty_print(d, ind='', verbosity=0): """Pretty print a data dictionary from the bridge client """ assert isinstance(d, dict) for k, v in sorted(d.items()): str_base = '{} - [{}] {}'.format(ind, type(v).__name__, k) if isinstance(v, dict): print(str_base.replace('-', '+'...
python
def pretty_print(d, ind='', verbosity=0): """Pretty print a data dictionary from the bridge client """ assert isinstance(d, dict) for k, v in sorted(d.items()): str_base = '{} - [{}] {}'.format(ind, type(v).__name__, k) if isinstance(v, dict): print(str_base.replace('-', '+'...
[ "def", "pretty_print", "(", "d", ",", "ind", "=", "''", ",", "verbosity", "=", "0", ")", ":", "assert", "isinstance", "(", "d", ",", "dict", ")", "for", "k", ",", "v", "in", "sorted", "(", "d", ".", "items", "(", ")", ")", ":", "str_base", "=",...
Pretty print a data dictionary from the bridge client
[ "Pretty", "print", "a", "data", "dictionary", "from", "the", "bridge", "client" ]
ca20d72b8beb0039649d10cb01d027db42efd91c
https://github.com/European-XFEL/karabo-bridge-py/blob/ca20d72b8beb0039649d10cb01d027db42efd91c/karabo_bridge/cli/glimpse.py#L143-L168
train
European-XFEL/karabo-bridge-py
karabo_bridge/simulation.py
start_gen
def start_gen(port, ser='msgpack', version='2.2', detector='AGIPD', raw=False, nsources=1, datagen='random', *, debug=True): """"Karabo bridge server simulation. Simulate a Karabo Bridge server and send random data from a detector, either AGIPD or LPD. Parameters ------...
python
def start_gen(port, ser='msgpack', version='2.2', detector='AGIPD', raw=False, nsources=1, datagen='random', *, debug=True): """"Karabo bridge server simulation. Simulate a Karabo Bridge server and send random data from a detector, either AGIPD or LPD. Parameters ------...
[ "def", "start_gen", "(", "port", ",", "ser", "=", "'msgpack'", ",", "version", "=", "'2.2'", ",", "detector", "=", "'AGIPD'", ",", "raw", "=", "False", ",", "nsources", "=", "1", ",", "datagen", "=", "'random'", ",", "*", ",", "debug", "=", "True", ...
Karabo bridge server simulation. Simulate a Karabo Bridge server and send random data from a detector, either AGIPD or LPD. Parameters ---------- port: str The port to on which the server is bound. ser: str, optional The serialization algorithm, default is msgpack. version:...
[ "Karabo", "bridge", "server", "simulation", "." ]
ca20d72b8beb0039649d10cb01d027db42efd91c
https://github.com/European-XFEL/karabo-bridge-py/blob/ca20d72b8beb0039649d10cb01d027db42efd91c/karabo_bridge/simulation.py#L262-L328
train
European-XFEL/karabo-bridge-py
karabo_bridge/client.py
Client.next
def next(self): """Request next data container. This function call is blocking. Returns ------- data : dict The data for this train, keyed by source name. meta : dict The metadata for this train, keyed by source name. This dictionary...
python
def next(self): """Request next data container. This function call is blocking. Returns ------- data : dict The data for this train, keyed by source name. meta : dict The metadata for this train, keyed by source name. This dictionary...
[ "def", "next", "(", "self", ")", ":", "if", "self", ".", "_pattern", "==", "zmq", ".", "REQ", "and", "not", "self", ".", "_recv_ready", ":", "self", ".", "_socket", ".", "send", "(", "b'next'", ")", "self", ".", "_recv_ready", "=", "True", "try", "...
Request next data container. This function call is blocking. Returns ------- data : dict The data for this train, keyed by source name. meta : dict The metadata for this train, keyed by source name. This dictionary is populated for protocol ...
[ "Request", "next", "data", "container", "." ]
ca20d72b8beb0039649d10cb01d027db42efd91c
https://github.com/European-XFEL/karabo-bridge-py/blob/ca20d72b8beb0039649d10cb01d027db42efd91c/karabo_bridge/client.py#L90-L122
train
materialsvirtuallab/monty
monty/io.py
zopen
def zopen(filename, *args, **kwargs): """ This function wraps around the bz2, gzip and standard python's open function to deal intelligently with bzipped, gzipped or standard text files. Args: filename (str/Path): filename or pathlib.Path. \*args: Standard args for python open(..). ...
python
def zopen(filename, *args, **kwargs): """ This function wraps around the bz2, gzip and standard python's open function to deal intelligently with bzipped, gzipped or standard text files. Args: filename (str/Path): filename or pathlib.Path. \*args: Standard args for python open(..). ...
[ "def", "zopen", "(", "filename", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "Path", "is", "not", "None", "and", "isinstance", "(", "filename", ",", "Path", ")", ":", "filename", "=", "str", "(", "filename", ")", "name", ",", "ext", "=",...
This function wraps around the bz2, gzip and standard python's open function to deal intelligently with bzipped, gzipped or standard text files. Args: filename (str/Path): filename or pathlib.Path. \*args: Standard args for python open(..). E.g., 'r' for read, 'w' for write. ...
[ "This", "function", "wraps", "around", "the", "bz2", "gzip", "and", "standard", "python", "s", "open", "function", "to", "deal", "intelligently", "with", "bzipped", "gzipped", "or", "standard", "text", "files", "." ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/io.py#L38-L72
train
materialsvirtuallab/monty
monty/io.py
reverse_readline
def reverse_readline(m_file, blk_size=4096, max_mem=4000000): """ Generator method to read a file line-by-line, but backwards. This allows one to efficiently get data at the end of a file. Based on code by Peter Astrand <astrand@cendio.se>, using modifications by Raymond Hettinger and Kevin German....
python
def reverse_readline(m_file, blk_size=4096, max_mem=4000000): """ Generator method to read a file line-by-line, but backwards. This allows one to efficiently get data at the end of a file. Based on code by Peter Astrand <astrand@cendio.se>, using modifications by Raymond Hettinger and Kevin German....
[ "def", "reverse_readline", "(", "m_file", ",", "blk_size", "=", "4096", ",", "max_mem", "=", "4000000", ")", ":", "is_text", "=", "isinstance", "(", "m_file", ",", "io", ".", "TextIOWrapper", ")", "try", ":", "file_size", "=", "os", ".", "path", ".", "...
Generator method to read a file line-by-line, but backwards. This allows one to efficiently get data at the end of a file. Based on code by Peter Astrand <astrand@cendio.se>, using modifications by Raymond Hettinger and Kevin German. http://code.activestate.com/recipes/439045-read-a-text-file-backwards...
[ "Generator", "method", "to", "read", "a", "file", "line", "-", "by", "-", "line", "but", "backwards", ".", "This", "allows", "one", "to", "efficiently", "get", "data", "at", "the", "end", "of", "a", "file", "." ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/io.py#L105-L187
train
materialsvirtuallab/monty
monty/io.py
get_open_fds
def get_open_fds(): """ Return the number of open file descriptors for current process .. warning: will only work on UNIX-like OS-es. """ pid = os.getpid() procs = subprocess.check_output(["lsof", '-w', '-Ff', "-p", str(pid)]) procs = procs.decode("utf-8") return len([s for s in procs....
python
def get_open_fds(): """ Return the number of open file descriptors for current process .. warning: will only work on UNIX-like OS-es. """ pid = os.getpid() procs = subprocess.check_output(["lsof", '-w', '-Ff', "-p", str(pid)]) procs = procs.decode("utf-8") return len([s for s in procs....
[ "def", "get_open_fds", "(", ")", ":", "pid", "=", "os", ".", "getpid", "(", ")", "procs", "=", "subprocess", ".", "check_output", "(", "[", "\"lsof\"", ",", "'-w'", ",", "'-Ff'", ",", "\"-p\"", ",", "str", "(", "pid", ")", "]", ")", "procs", "=", ...
Return the number of open file descriptors for current process .. warning: will only work on UNIX-like OS-es.
[ "Return", "the", "number", "of", "open", "file", "descriptors", "for", "current", "process" ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/io.py#L287-L298
train
materialsvirtuallab/monty
monty/io.py
FileLock.acquire
def acquire(self): """ Acquire the lock, if possible. If the lock is in use, it check again every `delay` seconds. It does this until it either gets the lock or exceeds `timeout` number of seconds, in which case it throws an exception. """ start_time = time.time()...
python
def acquire(self): """ Acquire the lock, if possible. If the lock is in use, it check again every `delay` seconds. It does this until it either gets the lock or exceeds `timeout` number of seconds, in which case it throws an exception. """ start_time = time.time()...
[ "def", "acquire", "(", "self", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "while", "True", ":", "try", ":", "self", ".", "fd", "=", "os", ".", "open", "(", "self", ".", "lockfile", ",", "os", ".", "O_CREAT", "|", "os", ".", "O_...
Acquire the lock, if possible. If the lock is in use, it check again every `delay` seconds. It does this until it either gets the lock or exceeds `timeout` number of seconds, in which case it throws an exception.
[ "Acquire", "the", "lock", "if", "possible", ".", "If", "the", "lock", "is", "in", "use", "it", "check", "again", "every", "delay", "seconds", ".", "It", "does", "this", "until", "it", "either", "gets", "the", "lock", "or", "exceeds", "timeout", "number",...
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/io.py#L229-L250
train
materialsvirtuallab/monty
monty/io.py
FileLock.release
def release(self): """ Get rid of the lock by deleting the lockfile. When working in a `with` statement, this gets automatically called at the end. """ if self.is_locked: os.close(self.fd) os.unlink(self.lockfile) self.is_locked = False
python
def release(self): """ Get rid of the lock by deleting the lockfile. When working in a `with` statement, this gets automatically called at the end. """ if self.is_locked: os.close(self.fd) os.unlink(self.lockfile) self.is_locked = False
[ "def", "release", "(", "self", ")", ":", "if", "self", ".", "is_locked", ":", "os", ".", "close", "(", "self", ".", "fd", ")", "os", ".", "unlink", "(", "self", ".", "lockfile", ")", "self", ".", "is_locked", "=", "False" ]
Get rid of the lock by deleting the lockfile. When working in a `with` statement, this gets automatically called at the end.
[ "Get", "rid", "of", "the", "lock", "by", "deleting", "the", "lockfile", ".", "When", "working", "in", "a", "with", "statement", "this", "gets", "automatically", "called", "at", "the", "end", "." ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/io.py#L252-L260
train
materialsvirtuallab/monty
monty/fnmatch.py
WildCard.filter
def filter(self, names): """ Returns a list with the names matching the pattern. """ names = list_strings(names) fnames = [] for f in names: for pat in self.pats: if fnmatch.fnmatch(f, pat): fnames.append(f) return...
python
def filter(self, names): """ Returns a list with the names matching the pattern. """ names = list_strings(names) fnames = [] for f in names: for pat in self.pats: if fnmatch.fnmatch(f, pat): fnames.append(f) return...
[ "def", "filter", "(", "self", ",", "names", ")", ":", "names", "=", "list_strings", "(", "names", ")", "fnames", "=", "[", "]", "for", "f", "in", "names", ":", "for", "pat", "in", "self", ".", "pats", ":", "if", "fnmatch", ".", "fnmatch", "(", "f...
Returns a list with the names matching the pattern.
[ "Returns", "a", "list", "with", "the", "names", "matching", "the", "pattern", "." ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/fnmatch.py#L41-L53
train
materialsvirtuallab/monty
monty/fnmatch.py
WildCard.match
def match(self, name): """ Returns True if name matches one of the patterns. """ for pat in self.pats: if fnmatch.fnmatch(name, pat): return True return False
python
def match(self, name): """ Returns True if name matches one of the patterns. """ for pat in self.pats: if fnmatch.fnmatch(name, pat): return True return False
[ "def", "match", "(", "self", ",", "name", ")", ":", "for", "pat", "in", "self", ".", "pats", ":", "if", "fnmatch", ".", "fnmatch", "(", "name", ",", "pat", ")", ":", "return", "True", "return", "False" ]
Returns True if name matches one of the patterns.
[ "Returns", "True", "if", "name", "matches", "one", "of", "the", "patterns", "." ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/fnmatch.py#L55-L63
train
materialsvirtuallab/monty
monty/dev.py
deprecated
def deprecated(replacement=None, message=None): """ Decorator to mark classes or functions as deprecated, with a possible replacement. Args: replacement (callable): A replacement class or method. message (str): A warning message to be displayed. Returns: Original function, ...
python
def deprecated(replacement=None, message=None): """ Decorator to mark classes or functions as deprecated, with a possible replacement. Args: replacement (callable): A replacement class or method. message (str): A warning message to be displayed. Returns: Original function, ...
[ "def", "deprecated", "(", "replacement", "=", "None", ",", "message", "=", "None", ")", ":", "def", "wrap", "(", "old", ")", ":", "def", "wrapped", "(", "*", "args", ",", "**", "kwargs", ")", ":", "msg", "=", "\"%s is deprecated\"", "%", "old", ".", ...
Decorator to mark classes or functions as deprecated, with a possible replacement. Args: replacement (callable): A replacement class or method. message (str): A warning message to be displayed. Returns: Original function, but with a warning to use the updated class.
[ "Decorator", "to", "mark", "classes", "or", "functions", "as", "deprecated", "with", "a", "possible", "replacement", "." ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/dev.py#L26-L58
train
materialsvirtuallab/monty
monty/dev.py
install_excepthook
def install_excepthook(hook_type="color", **kwargs): """ This function replaces the original python traceback with an improved version from Ipython. Use `color` for colourful traceback formatting, `verbose` for Ka-Ping Yee's "cgitb.py" version kwargs are the keyword arguments passed to the construct...
python
def install_excepthook(hook_type="color", **kwargs): """ This function replaces the original python traceback with an improved version from Ipython. Use `color` for colourful traceback formatting, `verbose` for Ka-Ping Yee's "cgitb.py" version kwargs are the keyword arguments passed to the construct...
[ "def", "install_excepthook", "(", "hook_type", "=", "\"color\"", ",", "**", "kwargs", ")", ":", "try", ":", "from", "IPython", ".", "core", "import", "ultratb", "except", "ImportError", ":", "import", "warnings", "warnings", ".", "warn", "(", "\"Cannot install...
This function replaces the original python traceback with an improved version from Ipython. Use `color` for colourful traceback formatting, `verbose` for Ka-Ping Yee's "cgitb.py" version kwargs are the keyword arguments passed to the constructor. See IPython.core.ultratb.py for more info. Return: ...
[ "This", "function", "replaces", "the", "original", "python", "traceback", "with", "an", "improved", "version", "from", "Ipython", ".", "Use", "color", "for", "colourful", "traceback", "formatting", "verbose", "for", "Ka", "-", "Ping", "Yee", "s", "cgitb", ".",...
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/dev.py#L198-L228
train
materialsvirtuallab/monty
monty/re.py
regrep
def regrep(filename, patterns, reverse=False, terminate_on_match=False, postprocess=str): """ A powerful regular expression version of grep. Args: filename (str): Filename to grep. patterns (dict): A dict of patterns, e.g., {"energy": "energy\(sigma->0\)\s+=\s+([\d\-\...
python
def regrep(filename, patterns, reverse=False, terminate_on_match=False, postprocess=str): """ A powerful regular expression version of grep. Args: filename (str): Filename to grep. patterns (dict): A dict of patterns, e.g., {"energy": "energy\(sigma->0\)\s+=\s+([\d\-\...
[ "def", "regrep", "(", "filename", ",", "patterns", ",", "reverse", "=", "False", ",", "terminate_on_match", "=", "False", ",", "postprocess", "=", "str", ")", ":", "compiled", "=", "{", "k", ":", "re", ".", "compile", "(", "v", ")", "for", "k", ",", ...
A powerful regular expression version of grep. Args: filename (str): Filename to grep. patterns (dict): A dict of patterns, e.g., {"energy": "energy\(sigma->0\)\s+=\s+([\d\-\.]+)"}. reverse (bool): Read files in reverse. Defaults to false. Useful for large files, esp...
[ "A", "powerful", "regular", "expression", "version", "of", "grep", "." ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/re.py#L21-L62
train
materialsvirtuallab/monty
monty/design_patterns.py
cached_class
def cached_class(klass): """ Decorator to cache class instances by constructor arguments. This results in a class that behaves like a singleton for each set of constructor arguments, ensuring efficiency. Note that this should be used for *immutable classes only*. Having a cached mutable class ...
python
def cached_class(klass): """ Decorator to cache class instances by constructor arguments. This results in a class that behaves like a singleton for each set of constructor arguments, ensuring efficiency. Note that this should be used for *immutable classes only*. Having a cached mutable class ...
[ "def", "cached_class", "(", "klass", ")", ":", "cache", "=", "{", "}", "@", "wraps", "(", "klass", ",", "assigned", "=", "(", "\"__name__\"", ",", "\"__module__\"", ")", ",", "updated", "=", "(", ")", ")", "class", "_decorated", "(", "klass", ")", ":...
Decorator to cache class instances by constructor arguments. This results in a class that behaves like a singleton for each set of constructor arguments, ensuring efficiency. Note that this should be used for *immutable classes only*. Having a cached mutable class makes very little sense. For efficie...
[ "Decorator", "to", "cache", "class", "instances", "by", "constructor", "arguments", ".", "This", "results", "in", "a", "class", "that", "behaves", "like", "a", "singleton", "for", "each", "set", "of", "constructor", "arguments", "ensuring", "efficiency", "." ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/design_patterns.py#L37-L94
train
materialsvirtuallab/monty
monty/operator.py
operator_from_str
def operator_from_str(op): """ Return the operator associated to the given string `op`. raises: `KeyError` if invalid string. >>> assert operator_from_str("==")(1, 1) and operator_from_str("+")(1,1) == 2 """ d = {"==": operator.eq, "!=": operator.ne, ">": operator.gt,...
python
def operator_from_str(op): """ Return the operator associated to the given string `op`. raises: `KeyError` if invalid string. >>> assert operator_from_str("==")(1, 1) and operator_from_str("+")(1,1) == 2 """ d = {"==": operator.eq, "!=": operator.ne, ">": operator.gt,...
[ "def", "operator_from_str", "(", "op", ")", ":", "d", "=", "{", "\"==\"", ":", "operator", ".", "eq", ",", "\"!=\"", ":", "operator", ".", "ne", ",", "\">\"", ":", "operator", ".", "gt", ",", "\">=\"", ":", "operator", ".", "ge", ",", "\"<\"", ":",...
Return the operator associated to the given string `op`. raises: `KeyError` if invalid string. >>> assert operator_from_str("==")(1, 1) and operator_from_str("+")(1,1) == 2
[ "Return", "the", "operator", "associated", "to", "the", "given", "string", "op", "." ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/operator.py#L9-L36
train
materialsvirtuallab/monty
monty/subprocess.py
Command.run
def run(self, timeout=None, **kwargs): """ Run a command in a separated thread and wait timeout seconds. kwargs are keyword arguments passed to Popen. Return: self """ from subprocess import Popen, PIPE def target(**kw): try: # print(...
python
def run(self, timeout=None, **kwargs): """ Run a command in a separated thread and wait timeout seconds. kwargs are keyword arguments passed to Popen. Return: self """ from subprocess import Popen, PIPE def target(**kw): try: # print(...
[ "def", "run", "(", "self", ",", "timeout", "=", "None", ",", "**", "kwargs", ")", ":", "from", "subprocess", "import", "Popen", ",", "PIPE", "def", "target", "(", "**", "kw", ")", ":", "try", ":", "self", ".", "process", "=", "Popen", "(", "self", ...
Run a command in a separated thread and wait timeout seconds. kwargs are keyword arguments passed to Popen. Return: self
[ "Run", "a", "command", "in", "a", "separated", "thread", "and", "wait", "timeout", "seconds", ".", "kwargs", "are", "keyword", "arguments", "passed", "to", "Popen", "." ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/subprocess.py#L59-L99
train
materialsvirtuallab/monty
monty/string.py
marquee
def marquee(text="", width=78, mark='*'): """ Return the input string centered in a 'marquee'. Args: text (str): Input string width (int): Width of final output string. mark (str): Character used to fill string. :Examples: >>> marquee('A test', width=40) '*************...
python
def marquee(text="", width=78, mark='*'): """ Return the input string centered in a 'marquee'. Args: text (str): Input string width (int): Width of final output string. mark (str): Character used to fill string. :Examples: >>> marquee('A test', width=40) '*************...
[ "def", "marquee", "(", "text", "=", "\"\"", ",", "width", "=", "78", ",", "mark", "=", "'*'", ")", ":", "if", "not", "text", ":", "return", "(", "mark", "*", "width", ")", "[", ":", "width", "]", "nmark", "=", "(", "width", "-", "len", "(", "...
Return the input string centered in a 'marquee'. Args: text (str): Input string width (int): Width of final output string. mark (str): Character used to fill string. :Examples: >>> marquee('A test', width=40) '**************** A test ****************' >>> marquee('A test'...
[ "Return", "the", "input", "string", "centered", "in", "a", "marquee", "." ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/string.py#L90-L118
train
materialsvirtuallab/monty
monty/string.py
boxed
def boxed(msg, ch="=", pad=5): """ Returns a string in a box Args: msg: Input string. ch: Character used to form the box. pad: Number of characters ch added before and after msg. >>> print(boxed("hello", ch="*", pad=2)) *********** ** hello ** *********** """ ...
python
def boxed(msg, ch="=", pad=5): """ Returns a string in a box Args: msg: Input string. ch: Character used to form the box. pad: Number of characters ch added before and after msg. >>> print(boxed("hello", ch="*", pad=2)) *********** ** hello ** *********** """ ...
[ "def", "boxed", "(", "msg", ",", "ch", "=", "\"=\"", ",", "pad", "=", "5", ")", ":", "if", "pad", ">", "0", ":", "msg", "=", "pad", "*", "ch", "+", "\" \"", "+", "msg", ".", "strip", "(", ")", "+", "\" \"", "+", "pad", "*", "ch", "return", ...
Returns a string in a box Args: msg: Input string. ch: Character used to form the box. pad: Number of characters ch added before and after msg. >>> print(boxed("hello", ch="*", pad=2)) *********** ** hello ** ***********
[ "Returns", "a", "string", "in", "a", "box" ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/string.py#L121-L141
train
materialsvirtuallab/monty
monty/string.py
indent
def indent(lines, amount, ch=' '): """Indent the lines in a string by padding each one with proper number of pad characters""" padding = amount * ch return padding + ('\n' + padding).join(lines.split('\n'))
python
def indent(lines, amount, ch=' '): """Indent the lines in a string by padding each one with proper number of pad characters""" padding = amount * ch return padding + ('\n' + padding).join(lines.split('\n'))
[ "def", "indent", "(", "lines", ",", "amount", ",", "ch", "=", "' '", ")", ":", "padding", "=", "amount", "*", "ch", "return", "padding", "+", "(", "'\\n'", "+", "padding", ")", ".", "join", "(", "lines", ".", "split", "(", "'\\n'", ")", ")" ]
Indent the lines in a string by padding each one with proper number of pad characters
[ "Indent", "the", "lines", "in", "a", "string", "by", "padding", "each", "one", "with", "proper", "number", "of", "pad", "characters" ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/string.py#L149-L152
train
materialsvirtuallab/monty
monty/functools.py
prof_main
def prof_main(main): """ Decorator for profiling main programs. Profiling is activated by prepending the command line options supported by the original main program with the keyword `prof`. Example: $ script.py arg --foo=1 becomes $ script.py prof arg --foo=1 The decorat...
python
def prof_main(main): """ Decorator for profiling main programs. Profiling is activated by prepending the command line options supported by the original main program with the keyword `prof`. Example: $ script.py arg --foo=1 becomes $ script.py prof arg --foo=1 The decorat...
[ "def", "prof_main", "(", "main", ")", ":", "@", "wraps", "(", "main", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "import", "sys", "try", ":", "do_prof", "=", "sys", ".", "argv", "[", "1", "]", "==", "\"prof\"", "if", ...
Decorator for profiling main programs. Profiling is activated by prepending the command line options supported by the original main program with the keyword `prof`. Example: $ script.py arg --foo=1 becomes $ script.py prof arg --foo=1 The decorated main accepts two new arguments...
[ "Decorator", "for", "profiling", "main", "programs", "." ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/functools.py#L380-L429
train
materialsvirtuallab/monty
monty/functools.py
lazy_property.invalidate
def invalidate(cls, inst, name): """Invalidate a lazy attribute. This obviously violates the lazy contract. A subclass of lazy may however have a contract where invalidation is appropriate. """ inst_cls = inst.__class__ if not hasattr(inst, '__dict__'): rais...
python
def invalidate(cls, inst, name): """Invalidate a lazy attribute. This obviously violates the lazy contract. A subclass of lazy may however have a contract where invalidation is appropriate. """ inst_cls = inst.__class__ if not hasattr(inst, '__dict__'): rais...
[ "def", "invalidate", "(", "cls", ",", "inst", ",", "name", ")", ":", "inst_cls", "=", "inst", ".", "__class__", "if", "not", "hasattr", "(", "inst", ",", "'__dict__'", ")", ":", "raise", "AttributeError", "(", "\"'%s' object has no attribute '__dict__'\"", "%"...
Invalidate a lazy attribute. This obviously violates the lazy contract. A subclass of lazy may however have a contract where invalidation is appropriate.
[ "Invalidate", "a", "lazy", "attribute", "." ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/functools.py#L257-L277
train
materialsvirtuallab/monty
monty/collections.py
as_set
def as_set(obj): """ Convert obj into a set, returns None if obj is None. >>> assert as_set(None) is None and as_set(1) == set([1]) and as_set(range(1,3)) == set([1, 2]) """ if obj is None or isinstance(obj, collections.Set): return obj if not isinstance(obj, collections.Iterable): ...
python
def as_set(obj): """ Convert obj into a set, returns None if obj is None. >>> assert as_set(None) is None and as_set(1) == set([1]) and as_set(range(1,3)) == set([1, 2]) """ if obj is None or isinstance(obj, collections.Set): return obj if not isinstance(obj, collections.Iterable): ...
[ "def", "as_set", "(", "obj", ")", ":", "if", "obj", "is", "None", "or", "isinstance", "(", "obj", ",", "collections", ".", "Set", ")", ":", "return", "obj", "if", "not", "isinstance", "(", "obj", ",", "collections", ".", "Iterable", ")", ":", "return...
Convert obj into a set, returns None if obj is None. >>> assert as_set(None) is None and as_set(1) == set([1]) and as_set(range(1,3)) == set([1, 2])
[ "Convert", "obj", "into", "a", "set", "returns", "None", "if", "obj", "is", "None", "." ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/collections.py#L30-L42
train
materialsvirtuallab/monty
monty/logging.py
logged
def logged(level=logging.DEBUG): """ Useful logging decorator. If a method is logged, the beginning and end of the method call will be logged at a pre-specified level. Args: level: Level to log method at. Defaults to DEBUG. """ def wrap(f): _logger = logging.getLogger("{}.{}".fo...
python
def logged(level=logging.DEBUG): """ Useful logging decorator. If a method is logged, the beginning and end of the method call will be logged at a pre-specified level. Args: level: Level to log method at. Defaults to DEBUG. """ def wrap(f): _logger = logging.getLogger("{}.{}".fo...
[ "def", "logged", "(", "level", "=", "logging", ".", "DEBUG", ")", ":", "def", "wrap", "(", "f", ")", ":", "_logger", "=", "logging", ".", "getLogger", "(", "\"{}.{}\"", ".", "format", "(", "f", ".", "__module__", ",", "f", ".", "__name__", ")", ")"...
Useful logging decorator. If a method is logged, the beginning and end of the method call will be logged at a pre-specified level. Args: level: Level to log method at. Defaults to DEBUG.
[ "Useful", "logging", "decorator", ".", "If", "a", "method", "is", "logged", "the", "beginning", "and", "end", "of", "the", "method", "call", "will", "be", "logged", "at", "a", "pre", "-", "specified", "level", "." ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/logging.py#L24-L44
train
materialsvirtuallab/monty
monty/logging.py
enable_logging
def enable_logging(main): """ This decorator is used to decorate main functions. It adds the initialization of the logger and an argument parser that allows one to select the loglevel. Useful if we are writing simple main functions that call libraries where the logging module is used Args: ...
python
def enable_logging(main): """ This decorator is used to decorate main functions. It adds the initialization of the logger and an argument parser that allows one to select the loglevel. Useful if we are writing simple main functions that call libraries where the logging module is used Args: ...
[ "def", "enable_logging", "(", "main", ")", ":", "@", "functools", ".", "wraps", "(", "main", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "import", "argparse", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "pars...
This decorator is used to decorate main functions. It adds the initialization of the logger and an argument parser that allows one to select the loglevel. Useful if we are writing simple main functions that call libraries where the logging module is used Args: main: main functio...
[ "This", "decorator", "is", "used", "to", "decorate", "main", "functions", ".", "It", "adds", "the", "initialization", "of", "the", "logger", "and", "an", "argument", "parser", "that", "allows", "one", "to", "select", "the", "loglevel", ".", "Useful", "if", ...
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/logging.py#L47-L83
train
materialsvirtuallab/monty
monty/os/path.py
which
def which(cmd): """ Returns full path to a executable. Args: cmd (str): Executable command to search for. Returns: (str) Full path to command. None if it is not found. Example:: full_path_to_python = which("python") """ def is_exe(fp): return os.path.isfil...
python
def which(cmd): """ Returns full path to a executable. Args: cmd (str): Executable command to search for. Returns: (str) Full path to command. None if it is not found. Example:: full_path_to_python = which("python") """ def is_exe(fp): return os.path.isfil...
[ "def", "which", "(", "cmd", ")", ":", "def", "is_exe", "(", "fp", ")", ":", "return", "os", ".", "path", ".", "isfile", "(", "fp", ")", "and", "os", ".", "access", "(", "fp", ",", "os", ".", "X_OK", ")", "fpath", ",", "fname", "=", "os", ".",...
Returns full path to a executable. Args: cmd (str): Executable command to search for. Returns: (str) Full path to command. None if it is not found. Example:: full_path_to_python = which("python")
[ "Returns", "full", "path", "to", "a", "executable", "." ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/os/path.py#L15-L41
train
materialsvirtuallab/monty
monty/inspect.py
all_subclasses
def all_subclasses(cls): """ Given a class `cls`, this recursive function returns a list with all subclasses, subclasses of subclasses, and so on. """ subclasses = cls.__subclasses__() return subclasses + [g for s in subclasses for g in all_subclasses(s)]
python
def all_subclasses(cls): """ Given a class `cls`, this recursive function returns a list with all subclasses, subclasses of subclasses, and so on. """ subclasses = cls.__subclasses__() return subclasses + [g for s in subclasses for g in all_subclasses(s)]
[ "def", "all_subclasses", "(", "cls", ")", ":", "subclasses", "=", "cls", ".", "__subclasses__", "(", ")", "return", "subclasses", "+", "[", "g", "for", "s", "in", "subclasses", "for", "g", "in", "all_subclasses", "(", "s", ")", "]" ]
Given a class `cls`, this recursive function returns a list with all subclasses, subclasses of subclasses, and so on.
[ "Given", "a", "class", "cls", "this", "recursive", "function", "returns", "a", "list", "with", "all", "subclasses", "subclasses", "of", "subclasses", "and", "so", "on", "." ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/inspect.py#L11-L17
train
materialsvirtuallab/monty
monty/inspect.py
find_top_pyfile
def find_top_pyfile(): """ This function inspects the Cpython frame to find the path of the script. """ import os frame = currentframe() while True: if frame.f_back is None: finfo = getframeinfo(frame) #print(getframeinfo(frame)) return os.path.abspath...
python
def find_top_pyfile(): """ This function inspects the Cpython frame to find the path of the script. """ import os frame = currentframe() while True: if frame.f_back is None: finfo = getframeinfo(frame) #print(getframeinfo(frame)) return os.path.abspath...
[ "def", "find_top_pyfile", "(", ")", ":", "import", "os", "frame", "=", "currentframe", "(", ")", "while", "True", ":", "if", "frame", ".", "f_back", "is", "None", ":", "finfo", "=", "getframeinfo", "(", "frame", ")", "return", "os", ".", "path", ".", ...
This function inspects the Cpython frame to find the path of the script.
[ "This", "function", "inspects", "the", "Cpython", "frame", "to", "find", "the", "path", "of", "the", "script", "." ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/inspect.py#L20-L32
train
materialsvirtuallab/monty
monty/pprint.py
pprint_table
def pprint_table(table, out=sys.stdout, rstrip=False): """ Prints out a table of data, padded for alignment Each row must have the same number of columns. Args: table: The table to print. A list of lists. out: Output stream (file-like object) rstrip: if True, trailing withespace...
python
def pprint_table(table, out=sys.stdout, rstrip=False): """ Prints out a table of data, padded for alignment Each row must have the same number of columns. Args: table: The table to print. A list of lists. out: Output stream (file-like object) rstrip: if True, trailing withespace...
[ "def", "pprint_table", "(", "table", ",", "out", "=", "sys", ".", "stdout", ",", "rstrip", "=", "False", ")", ":", "def", "max_width_col", "(", "table", ",", "col_idx", ")", ":", "return", "max", "(", "[", "len", "(", "row", "[", "col_idx", "]", ")...
Prints out a table of data, padded for alignment Each row must have the same number of columns. Args: table: The table to print. A list of lists. out: Output stream (file-like object) rstrip: if True, trailing withespaces are removed from the entries.
[ "Prints", "out", "a", "table", "of", "data", "padded", "for", "alignment", "Each", "row", "must", "have", "the", "same", "number", "of", "columns", "." ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/pprint.py#L10-L42
train
materialsvirtuallab/monty
monty/fractions.py
gcd
def gcd(*numbers): """ Returns the greatest common divisor for a sequence of numbers. Args: \*numbers: Sequence of numbers. Returns: (int) Greatest common divisor of numbers. """ n = numbers[0] for i in numbers: n = pygcd(n, i) return n
python
def gcd(*numbers): """ Returns the greatest common divisor for a sequence of numbers. Args: \*numbers: Sequence of numbers. Returns: (int) Greatest common divisor of numbers. """ n = numbers[0] for i in numbers: n = pygcd(n, i) return n
[ "def", "gcd", "(", "*", "numbers", ")", ":", "n", "=", "numbers", "[", "0", "]", "for", "i", "in", "numbers", ":", "n", "=", "pygcd", "(", "n", ",", "i", ")", "return", "n" ]
Returns the greatest common divisor for a sequence of numbers. Args: \*numbers: Sequence of numbers. Returns: (int) Greatest common divisor of numbers.
[ "Returns", "the", "greatest", "common", "divisor", "for", "a", "sequence", "of", "numbers", "." ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/fractions.py#L22-L35
train
materialsvirtuallab/monty
monty/fractions.py
lcm
def lcm(*numbers): """ Return lowest common multiple of a sequence of numbers. Args: \*numbers: Sequence of numbers. Returns: (int) Lowest common multiple of numbers. """ n = 1 for i in numbers: n = (i * n) // gcd(i, n) return n
python
def lcm(*numbers): """ Return lowest common multiple of a sequence of numbers. Args: \*numbers: Sequence of numbers. Returns: (int) Lowest common multiple of numbers. """ n = 1 for i in numbers: n = (i * n) // gcd(i, n) return n
[ "def", "lcm", "(", "*", "numbers", ")", ":", "n", "=", "1", "for", "i", "in", "numbers", ":", "n", "=", "(", "i", "*", "n", ")", "//", "gcd", "(", "i", ",", "n", ")", "return", "n" ]
Return lowest common multiple of a sequence of numbers. Args: \*numbers: Sequence of numbers. Returns: (int) Lowest common multiple of numbers.
[ "Return", "lowest", "common", "multiple", "of", "a", "sequence", "of", "numbers", "." ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/fractions.py#L38-L51
train
materialsvirtuallab/monty
monty/fractions.py
gcd_float
def gcd_float(numbers, tol=1e-8): """ Returns the greatest common divisor for a sequence of numbers. Uses a numerical tolerance, so can be used on floats Args: numbers: Sequence of numbers. tol: Numerical tolerance Returns: (int) Greatest common divisor of numbers. """ ...
python
def gcd_float(numbers, tol=1e-8): """ Returns the greatest common divisor for a sequence of numbers. Uses a numerical tolerance, so can be used on floats Args: numbers: Sequence of numbers. tol: Numerical tolerance Returns: (int) Greatest common divisor of numbers. """ ...
[ "def", "gcd_float", "(", "numbers", ",", "tol", "=", "1e-8", ")", ":", "def", "pair_gcd_tol", "(", "a", ",", "b", ")", ":", "while", "b", ">", "tol", ":", "a", ",", "b", "=", "b", ",", "a", "%", "b", "return", "a", "n", "=", "numbers", "[", ...
Returns the greatest common divisor for a sequence of numbers. Uses a numerical tolerance, so can be used on floats Args: numbers: Sequence of numbers. tol: Numerical tolerance Returns: (int) Greatest common divisor of numbers.
[ "Returns", "the", "greatest", "common", "divisor", "for", "a", "sequence", "of", "numbers", ".", "Uses", "a", "numerical", "tolerance", "so", "can", "be", "used", "on", "floats" ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/fractions.py#L54-L80
train
materialsvirtuallab/monty
monty/itertools.py
chunks
def chunks(items, n): """ Yield successive n-sized chunks from a list-like object. >>> import pprint >>> pprint.pprint(list(chunks(range(1, 25), 10))) [(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), (11, 12, 13, 14, 15, 16, 17, 18, 19, 20), (21, 22, 23, 24)] """ it = iter(items) chunk = tup...
python
def chunks(items, n): """ Yield successive n-sized chunks from a list-like object. >>> import pprint >>> pprint.pprint(list(chunks(range(1, 25), 10))) [(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), (11, 12, 13, 14, 15, 16, 17, 18, 19, 20), (21, 22, 23, 24)] """ it = iter(items) chunk = tup...
[ "def", "chunks", "(", "items", ",", "n", ")", ":", "it", "=", "iter", "(", "items", ")", "chunk", "=", "tuple", "(", "itertools", ".", "islice", "(", "it", ",", "n", ")", ")", "while", "chunk", ":", "yield", "chunk", "chunk", "=", "tuple", "(", ...
Yield successive n-sized chunks from a list-like object. >>> import pprint >>> pprint.pprint(list(chunks(range(1, 25), 10))) [(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), (11, 12, 13, 14, 15, 16, 17, 18, 19, 20), (21, 22, 23, 24)]
[ "Yield", "successive", "n", "-", "sized", "chunks", "from", "a", "list", "-", "like", "object", "." ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/itertools.py#L7-L21
train
materialsvirtuallab/monty
monty/itertools.py
iterator_from_slice
def iterator_from_slice(s): """ Constructs an iterator given a slice object s. .. note:: The function returns an infinite iterator if s.stop is None """ import numpy as np start = s.start if s.start is not None else 0 step = s.step if s.step is not None else 1 if s.stop is Non...
python
def iterator_from_slice(s): """ Constructs an iterator given a slice object s. .. note:: The function returns an infinite iterator if s.stop is None """ import numpy as np start = s.start if s.start is not None else 0 step = s.step if s.step is not None else 1 if s.stop is Non...
[ "def", "iterator_from_slice", "(", "s", ")", ":", "import", "numpy", "as", "np", "start", "=", "s", ".", "start", "if", "s", ".", "start", "is", "not", "None", "else", "0", "step", "=", "s", ".", "step", "if", "s", ".", "step", "is", "not", "None...
Constructs an iterator given a slice object s. .. note:: The function returns an infinite iterator if s.stop is None
[ "Constructs", "an", "iterator", "given", "a", "slice", "object", "s", "." ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/itertools.py#L24-L41
train
materialsvirtuallab/monty
monty/termcolor.py
colored_map
def colored_map(text, cmap): """ Return colorized text. cmap is a dict mapping tokens to color options. .. Example: colored_key("foo bar", {bar: "green"}) colored_key("foo bar", {bar: {"color": "green", "on_color": "on_red"}}) """ if not __ISON: return text for key, v in cmap.i...
python
def colored_map(text, cmap): """ Return colorized text. cmap is a dict mapping tokens to color options. .. Example: colored_key("foo bar", {bar: "green"}) colored_key("foo bar", {bar: {"color": "green", "on_color": "on_red"}}) """ if not __ISON: return text for key, v in cmap.i...
[ "def", "colored_map", "(", "text", ",", "cmap", ")", ":", "if", "not", "__ISON", ":", "return", "text", "for", "key", ",", "v", "in", "cmap", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "dict", ")", ":", "text", "=", "text", ...
Return colorized text. cmap is a dict mapping tokens to color options. .. Example: colored_key("foo bar", {bar: "green"}) colored_key("foo bar", {bar: {"color": "green", "on_color": "on_red"}})
[ "Return", "colorized", "text", ".", "cmap", "is", "a", "dict", "mapping", "tokens", "to", "color", "options", "." ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/termcolor.py#L161-L176
train
materialsvirtuallab/monty
monty/termcolor.py
cprint_map
def cprint_map(text, cmap, **kwargs): """ Print colorize text. cmap is a dict mapping keys to color options. kwargs are passed to print function Example: cprint_map("Hello world", {"Hello": "red"}) """ try: print(colored_map(text, cmap), **kwargs) except TypeError: ...
python
def cprint_map(text, cmap, **kwargs): """ Print colorize text. cmap is a dict mapping keys to color options. kwargs are passed to print function Example: cprint_map("Hello world", {"Hello": "red"}) """ try: print(colored_map(text, cmap), **kwargs) except TypeError: ...
[ "def", "cprint_map", "(", "text", ",", "cmap", ",", "**", "kwargs", ")", ":", "try", ":", "print", "(", "colored_map", "(", "text", ",", "cmap", ")", ",", "**", "kwargs", ")", "except", "TypeError", ":", "kwargs", ".", "pop", "(", "\"flush\"", ",", ...
Print colorize text. cmap is a dict mapping keys to color options. kwargs are passed to print function Example: cprint_map("Hello world", {"Hello": "red"})
[ "Print", "colorize", "text", ".", "cmap", "is", "a", "dict", "mapping", "keys", "to", "color", "options", ".", "kwargs", "are", "passed", "to", "print", "function" ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/termcolor.py#L179-L193
train
materialsvirtuallab/monty
monty/json.py
MSONable.as_dict
def as_dict(self): """ A JSON serializable dict representation of an object. """ d = {"@module": self.__class__.__module__, "@class": self.__class__.__name__} try: parent_module = self.__class__.__module__.split('.')[0] module_version = impor...
python
def as_dict(self): """ A JSON serializable dict representation of an object. """ d = {"@module": self.__class__.__module__, "@class": self.__class__.__name__} try: parent_module = self.__class__.__module__.split('.')[0] module_version = impor...
[ "def", "as_dict", "(", "self", ")", ":", "d", "=", "{", "\"@module\"", ":", "self", ".", "__class__", ".", "__module__", ",", "\"@class\"", ":", "self", ".", "__class__", ".", "__name__", "}", "try", ":", "parent_module", "=", "self", ".", "__class__", ...
A JSON serializable dict representation of an object.
[ "A", "JSON", "serializable", "dict", "representation", "of", "an", "object", "." ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/json.py#L74-L120
train
materialsvirtuallab/monty
monty/json.py
MontyDecoder.process_decoded
def process_decoded(self, d): """ Recursive method to support decoding dicts and lists containing pymatgen objects. """ if isinstance(d, dict): if "@module" in d and "@class" in d: modname = d["@module"] classname = d["@class"] ...
python
def process_decoded(self, d): """ Recursive method to support decoding dicts and lists containing pymatgen objects. """ if isinstance(d, dict): if "@module" in d and "@class" in d: modname = d["@module"] classname = d["@class"] ...
[ "def", "process_decoded", "(", "self", ",", "d", ")", ":", "if", "isinstance", "(", "d", ",", "dict", ")", ":", "if", "\"@module\"", "in", "d", "and", "\"@class\"", "in", "d", ":", "modname", "=", "d", "[", "\"@module\"", "]", "classname", "=", "d", ...
Recursive method to support decoding dicts and lists containing pymatgen objects.
[ "Recursive", "method", "to", "support", "decoding", "dicts", "and", "lists", "containing", "pymatgen", "objects", "." ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/json.py#L210-L252
train
materialsvirtuallab/monty
monty/math.py
nCr
def nCr(n, r): """ Calculates nCr. Args: n (int): total number of items. r (int): items to choose Returns: nCr. """ f = math.factorial return int(f(n) / f(r) / f(n-r))
python
def nCr(n, r): """ Calculates nCr. Args: n (int): total number of items. r (int): items to choose Returns: nCr. """ f = math.factorial return int(f(n) / f(r) / f(n-r))
[ "def", "nCr", "(", "n", ",", "r", ")", ":", "f", "=", "math", ".", "factorial", "return", "int", "(", "f", "(", "n", ")", "/", "f", "(", "r", ")", "/", "f", "(", "n", "-", "r", ")", ")" ]
Calculates nCr. Args: n (int): total number of items. r (int): items to choose Returns: nCr.
[ "Calculates", "nCr", "." ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/math.py#L20-L32
train
materialsvirtuallab/monty
monty/math.py
nPr
def nPr(n, r): """ Calculates nPr. Args: n (int): total number of items. r (int): items to permute Returns: nPr. """ f = math.factorial return int(f(n) / f(n-r))
python
def nPr(n, r): """ Calculates nPr. Args: n (int): total number of items. r (int): items to permute Returns: nPr. """ f = math.factorial return int(f(n) / f(n-r))
[ "def", "nPr", "(", "n", ",", "r", ")", ":", "f", "=", "math", ".", "factorial", "return", "int", "(", "f", "(", "n", ")", "/", "f", "(", "n", "-", "r", ")", ")" ]
Calculates nPr. Args: n (int): total number of items. r (int): items to permute Returns: nPr.
[ "Calculates", "nPr", "." ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/math.py#L35-L47
train
materialsvirtuallab/monty
monty/shutil.py
copy_r
def copy_r(src, dst): """ Implements a recursive copy function similar to Unix's "cp -r" command. Surprisingly, python does not have a real equivalent. shutil.copytree only works if the destination directory is not present. Args: src (str): Source folder to copy. dst (str): Destinat...
python
def copy_r(src, dst): """ Implements a recursive copy function similar to Unix's "cp -r" command. Surprisingly, python does not have a real equivalent. shutil.copytree only works if the destination directory is not present. Args: src (str): Source folder to copy. dst (str): Destinat...
[ "def", "copy_r", "(", "src", ",", "dst", ")", ":", "abssrc", "=", "os", ".", "path", ".", "abspath", "(", "src", ")", "absdst", "=", "os", ".", "path", ".", "abspath", "(", "dst", ")", "try", ":", "os", ".", "makedirs", "(", "absdst", ")", "exc...
Implements a recursive copy function similar to Unix's "cp -r" command. Surprisingly, python does not have a real equivalent. shutil.copytree only works if the destination directory is not present. Args: src (str): Source folder to copy. dst (str): Destination folder.
[ "Implements", "a", "recursive", "copy", "function", "similar", "to", "Unix", "s", "cp", "-", "r", "command", ".", "Surprisingly", "python", "does", "not", "have", "a", "real", "equivalent", ".", "shutil", ".", "copytree", "only", "works", "if", "the", "des...
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/shutil.py#L15-L40
train
materialsvirtuallab/monty
monty/shutil.py
gzip_dir
def gzip_dir(path, compresslevel=6): """ Gzips all files in a directory. Note that this is different from shutil.make_archive, which creates a tar archive. The aim of this method is to create gzipped files that can still be read using common Unix-style commands like zless or zcat. Args: ...
python
def gzip_dir(path, compresslevel=6): """ Gzips all files in a directory. Note that this is different from shutil.make_archive, which creates a tar archive. The aim of this method is to create gzipped files that can still be read using common Unix-style commands like zless or zcat. Args: ...
[ "def", "gzip_dir", "(", "path", ",", "compresslevel", "=", "6", ")", ":", "for", "f", "in", "os", ".", "listdir", "(", "path", ")", ":", "full_f", "=", "os", ".", "path", ".", "join", "(", "path", ",", "f", ")", "if", "not", "f", ".", "lower", ...
Gzips all files in a directory. Note that this is different from shutil.make_archive, which creates a tar archive. The aim of this method is to create gzipped files that can still be read using common Unix-style commands like zless or zcat. Args: path (str): Path to directory. compressl...
[ "Gzips", "all", "files", "in", "a", "directory", ".", "Note", "that", "this", "is", "different", "from", "shutil", ".", "make_archive", "which", "creates", "a", "tar", "archive", ".", "The", "aim", "of", "this", "method", "is", "to", "create", "gzipped", ...
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/shutil.py#L43-L63
train
materialsvirtuallab/monty
monty/shutil.py
compress_file
def compress_file(filepath, compression="gz"): """ Compresses a file with the correct extension. Functions like standard Unix command line gzip and bzip2 in the sense that the original uncompressed files are not retained. Args: filepath (str): Path to file. compression (str): A comp...
python
def compress_file(filepath, compression="gz"): """ Compresses a file with the correct extension. Functions like standard Unix command line gzip and bzip2 in the sense that the original uncompressed files are not retained. Args: filepath (str): Path to file. compression (str): A comp...
[ "def", "compress_file", "(", "filepath", ",", "compression", "=", "\"gz\"", ")", ":", "if", "compression", "not", "in", "[", "\"gz\"", ",", "\"bz2\"", "]", ":", "raise", "ValueError", "(", "\"Supported compression formats are 'gz' and 'bz2'.\"", ")", "from", "mont...
Compresses a file with the correct extension. Functions like standard Unix command line gzip and bzip2 in the sense that the original uncompressed files are not retained. Args: filepath (str): Path to file. compression (str): A compression mode. Valid options are "gz" or "bz2". ...
[ "Compresses", "a", "file", "with", "the", "correct", "extension", ".", "Functions", "like", "standard", "Unix", "command", "line", "gzip", "and", "bzip2", "in", "the", "sense", "that", "the", "original", "uncompressed", "files", "are", "not", "retained", "." ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/shutil.py#L66-L84
train
materialsvirtuallab/monty
monty/shutil.py
compress_dir
def compress_dir(path, compression="gz"): """ Recursively compresses all files in a directory. Note that this compresses all files singly, i.e., it does not create a tar archive. For that, just use Python tarfile class. Args: path (str): Path to parent directory. compression (str): ...
python
def compress_dir(path, compression="gz"): """ Recursively compresses all files in a directory. Note that this compresses all files singly, i.e., it does not create a tar archive. For that, just use Python tarfile class. Args: path (str): Path to parent directory. compression (str): ...
[ "def", "compress_dir", "(", "path", ",", "compression", "=", "\"gz\"", ")", ":", "for", "parent", ",", "subdirs", ",", "files", "in", "os", ".", "walk", "(", "path", ")", ":", "for", "f", "in", "files", ":", "compress_file", "(", "os", ".", "path", ...
Recursively compresses all files in a directory. Note that this compresses all files singly, i.e., it does not create a tar archive. For that, just use Python tarfile class. Args: path (str): Path to parent directory. compression (str): A compression mode. Valid options are "gz" or ...
[ "Recursively", "compresses", "all", "files", "in", "a", "directory", ".", "Note", "that", "this", "compresses", "all", "files", "singly", "i", ".", "e", ".", "it", "does", "not", "create", "a", "tar", "archive", ".", "For", "that", "just", "use", "Python...
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/shutil.py#L87-L100
train
materialsvirtuallab/monty
monty/shutil.py
decompress_file
def decompress_file(filepath): """ Decompresses a file with the correct extension. Automatically detects gz, bz2 or z extension. Args: filepath (str): Path to file. compression (str): A compression mode. Valid options are "gz" or "bz2". Defaults to "gz". """ toks = f...
python
def decompress_file(filepath): """ Decompresses a file with the correct extension. Automatically detects gz, bz2 or z extension. Args: filepath (str): Path to file. compression (str): A compression mode. Valid options are "gz" or "bz2". Defaults to "gz". """ toks = f...
[ "def", "decompress_file", "(", "filepath", ")", ":", "toks", "=", "filepath", ".", "split", "(", "\".\"", ")", "file_ext", "=", "toks", "[", "-", "1", "]", ".", "upper", "(", ")", "from", "monty", ".", "io", "import", "zopen", "if", "file_ext", "in",...
Decompresses a file with the correct extension. Automatically detects gz, bz2 or z extension. Args: filepath (str): Path to file. compression (str): A compression mode. Valid options are "gz" or "bz2". Defaults to "gz".
[ "Decompresses", "a", "file", "with", "the", "correct", "extension", ".", "Automatically", "detects", "gz", "bz2", "or", "z", "extension", "." ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/shutil.py#L103-L120
train
materialsvirtuallab/monty
monty/shutil.py
decompress_dir
def decompress_dir(path): """ Recursively decompresses all files in a directory. Args: path (str): Path to parent directory. """ for parent, subdirs, files in os.walk(path): for f in files: decompress_file(os.path.join(parent, f))
python
def decompress_dir(path): """ Recursively decompresses all files in a directory. Args: path (str): Path to parent directory. """ for parent, subdirs, files in os.walk(path): for f in files: decompress_file(os.path.join(parent, f))
[ "def", "decompress_dir", "(", "path", ")", ":", "for", "parent", ",", "subdirs", ",", "files", "in", "os", ".", "walk", "(", "path", ")", ":", "for", "f", "in", "files", ":", "decompress_file", "(", "os", ".", "path", ".", "join", "(", "parent", ",...
Recursively decompresses all files in a directory. Args: path (str): Path to parent directory.
[ "Recursively", "decompresses", "all", "files", "in", "a", "directory", "." ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/shutil.py#L123-L132
train
materialsvirtuallab/monty
monty/shutil.py
remove
def remove(path, follow_symlink=False): """ Implements an remove function that will delete files, folder trees and symlink trees 1.) Remove a file 2.) Remove a symlink and follow into with a recursive rm if follow_symlink 3.) Remove directory with rmtree Args: path (str): path to remov...
python
def remove(path, follow_symlink=False): """ Implements an remove function that will delete files, folder trees and symlink trees 1.) Remove a file 2.) Remove a symlink and follow into with a recursive rm if follow_symlink 3.) Remove directory with rmtree Args: path (str): path to remov...
[ "def", "remove", "(", "path", ",", "follow_symlink", "=", "False", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "os", ".", "remove", "(", "path", ")", "elif", "os", ".", "path", ".", "islink", "(", "path", ")", ":", ...
Implements an remove function that will delete files, folder trees and symlink trees 1.) Remove a file 2.) Remove a symlink and follow into with a recursive rm if follow_symlink 3.) Remove directory with rmtree Args: path (str): path to remove follow_symlink(bool): follow symlinks and ...
[ "Implements", "an", "remove", "function", "that", "will", "delete", "files", "folder", "trees", "and", "symlink", "trees" ]
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/shutil.py#L135-L154
train
fair-research/bdbag
bdbag/bdbag_utils.py
compute_hashes
def compute_hashes(obj, hashes=frozenset(['md5'])): """ Digests input data read from file-like object fd or passed directly as bytes-like object. Compute hashes for multiple algorithms. Default is MD5. Returns a tuple of a hex-encoded digest string and a base64-encoded value suitable for an HTT...
python
def compute_hashes(obj, hashes=frozenset(['md5'])): """ Digests input data read from file-like object fd or passed directly as bytes-like object. Compute hashes for multiple algorithms. Default is MD5. Returns a tuple of a hex-encoded digest string and a base64-encoded value suitable for an HTT...
[ "def", "compute_hashes", "(", "obj", ",", "hashes", "=", "frozenset", "(", "[", "'md5'", "]", ")", ")", ":", "if", "not", "(", "hasattr", "(", "obj", ",", "'read'", ")", "or", "isinstance", "(", "obj", ",", "bytes", ")", ")", ":", "raise", "ValueEr...
Digests input data read from file-like object fd or passed directly as bytes-like object. Compute hashes for multiple algorithms. Default is MD5. Returns a tuple of a hex-encoded digest string and a base64-encoded value suitable for an HTTP header.
[ "Digests", "input", "data", "read", "from", "file", "-", "like", "object", "fd", "or", "passed", "directly", "as", "bytes", "-", "like", "object", ".", "Compute", "hashes", "for", "multiple", "algorithms", ".", "Default", "is", "MD5", ".", "Returns", "a", ...
795229d1fb77721d0a2d024b34645319d15502cf
https://github.com/fair-research/bdbag/blob/795229d1fb77721d0a2d024b34645319d15502cf/bdbag/bdbag_utils.py#L221-L258
train
fair-research/bdbag
bdbag/bdbag_utils.py
compute_file_hashes
def compute_file_hashes(file_path, hashes=frozenset(['md5'])): """ Digests data read from file denoted by file_path. """ if not os.path.exists(file_path): logging.warning("%s does not exist" % file_path) return else: logging.debug("Computing [%s] hashes for file [%s]" % ('...
python
def compute_file_hashes(file_path, hashes=frozenset(['md5'])): """ Digests data read from file denoted by file_path. """ if not os.path.exists(file_path): logging.warning("%s does not exist" % file_path) return else: logging.debug("Computing [%s] hashes for file [%s]" % ('...
[ "def", "compute_file_hashes", "(", "file_path", ",", "hashes", "=", "frozenset", "(", "[", "'md5'", "]", ")", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "file_path", ")", ":", "logging", ".", "warning", "(", "\"%s does not exist\"", "%...
Digests data read from file denoted by file_path.
[ "Digests", "data", "read", "from", "file", "denoted", "by", "file_path", "." ]
795229d1fb77721d0a2d024b34645319d15502cf
https://github.com/fair-research/bdbag/blob/795229d1fb77721d0a2d024b34645319d15502cf/bdbag/bdbag_utils.py#L261-L276
train
fair-research/bdbag
bdbag/bdbagit.py
BDBag.validate
def validate(self, processes=1, fast=False, completeness_only=False, callback=None): """Checks the structure and contents are valid. If you supply the parameter fast=True the Payload-Oxum (if present) will be used to check that the payload files are present and accounted for, instead of...
python
def validate(self, processes=1, fast=False, completeness_only=False, callback=None): """Checks the structure and contents are valid. If you supply the parameter fast=True the Payload-Oxum (if present) will be used to check that the payload files are present and accounted for, instead of...
[ "def", "validate", "(", "self", ",", "processes", "=", "1", ",", "fast", "=", "False", ",", "completeness_only", "=", "False", ",", "callback", "=", "None", ")", ":", "self", ".", "_validate_structure", "(", ")", "self", ".", "_validate_bagittxt", "(", "...
Checks the structure and contents are valid. If you supply the parameter fast=True the Payload-Oxum (if present) will be used to check that the payload files are present and accounted for, instead of re-calculating fixities and comparing them against the manifest. By default validate() ...
[ "Checks", "the", "structure", "and", "contents", "are", "valid", "." ]
795229d1fb77721d0a2d024b34645319d15502cf
https://github.com/fair-research/bdbag/blob/795229d1fb77721d0a2d024b34645319d15502cf/bdbag/bdbagit.py#L473-L489
train
fair-research/bdbag
bdbag/bdbagit.py
BDBag._validate_fetch
def _validate_fetch(self): """Validate the fetch.txt file Raises `BagError` for errors and otherwise returns no value """ for url, file_size, filename in self.fetch_entries(): # fetch_entries will raise a BagError for unsafe filenames # so at this point we will c...
python
def _validate_fetch(self): """Validate the fetch.txt file Raises `BagError` for errors and otherwise returns no value """ for url, file_size, filename in self.fetch_entries(): # fetch_entries will raise a BagError for unsafe filenames # so at this point we will c...
[ "def", "_validate_fetch", "(", "self", ")", ":", "for", "url", ",", "file_size", ",", "filename", "in", "self", ".", "fetch_entries", "(", ")", ":", "parsed_url", "=", "urlparse", "(", "url", ")", "if", "not", "all", "(", "parsed_url", ".", "scheme", "...
Validate the fetch.txt file Raises `BagError` for errors and otherwise returns no value
[ "Validate", "the", "fetch", ".", "txt", "file" ]
795229d1fb77721d0a2d024b34645319d15502cf
https://github.com/fair-research/bdbag/blob/795229d1fb77721d0a2d024b34645319d15502cf/bdbag/bdbagit.py#L491-L505
train
fair-research/bdbag
bdbag/bdbagit.py
BDBag._validate_completeness
def _validate_completeness(self): """ Verify that the actual file manifests match the files in the data directory """ errors = list() # First we'll make sure there's no mismatch between the filesystem # and the list of files in the manifest(s) only_in_manifests, ...
python
def _validate_completeness(self): """ Verify that the actual file manifests match the files in the data directory """ errors = list() # First we'll make sure there's no mismatch between the filesystem # and the list of files in the manifest(s) only_in_manifests, ...
[ "def", "_validate_completeness", "(", "self", ")", ":", "errors", "=", "list", "(", ")", "only_in_manifests", ",", "only_on_fs", ",", "only_in_fetch", "=", "self", ".", "compare_manifests_with_fs_and_fetch", "(", ")", "for", "path", "in", "only_in_manifests", ":",...
Verify that the actual file manifests match the files in the data directory
[ "Verify", "that", "the", "actual", "file", "manifests", "match", "the", "files", "in", "the", "data", "directory" ]
795229d1fb77721d0a2d024b34645319d15502cf
https://github.com/fair-research/bdbag/blob/795229d1fb77721d0a2d024b34645319d15502cf/bdbag/bdbagit.py#L523-L546
train
alertot/detectem
detectem/cli.py
get_detection_results
def get_detection_results(url, timeout, metadata=False, save_har=False): """ Return results from detector. This function prepares the environment loading the plugins, getting the response and passing it to the detector. In case of errors, it raises exceptions to be handled externally. """ plu...
python
def get_detection_results(url, timeout, metadata=False, save_har=False): """ Return results from detector. This function prepares the environment loading the plugins, getting the response and passing it to the detector. In case of errors, it raises exceptions to be handled externally. """ plu...
[ "def", "get_detection_results", "(", "url", ",", "timeout", ",", "metadata", "=", "False", ",", "save_har", "=", "False", ")", ":", "plugins", "=", "load_plugins", "(", ")", "if", "not", "plugins", ":", "raise", "NoPluginsError", "(", "'No plugins found'", "...
Return results from detector. This function prepares the environment loading the plugins, getting the response and passing it to the detector. In case of errors, it raises exceptions to be handled externally.
[ "Return", "results", "from", "detector", "." ]
b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1
https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/cli.py#L73-L106
train
alertot/detectem
detectem/cli.py
get_plugins
def get_plugins(metadata): """ Return the registered plugins. Load and return all registered plugins. """ plugins = load_plugins() if not plugins: raise NoPluginsError('No plugins found') results = [] for p in sorted(plugins.get_all(), key=attrgetter('name')): if metadata: ...
python
def get_plugins(metadata): """ Return the registered plugins. Load and return all registered plugins. """ plugins = load_plugins() if not plugins: raise NoPluginsError('No plugins found') results = [] for p in sorted(plugins.get_all(), key=attrgetter('name')): if metadata: ...
[ "def", "get_plugins", "(", "metadata", ")", ":", "plugins", "=", "load_plugins", "(", ")", "if", "not", "plugins", ":", "raise", "NoPluginsError", "(", "'No plugins found'", ")", "results", "=", "[", "]", "for", "p", "in", "sorted", "(", "plugins", ".", ...
Return the registered plugins. Load and return all registered plugins.
[ "Return", "the", "registered", "plugins", "." ]
b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1
https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/cli.py#L109-L128
train