INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
r""" Return an iterator over the lines of a file or URI response.
>>> len(list(iter_lines('cats_and_dogs.txt')))
263
>>> len(list(iter_lines(list('abcdefgh'))))
8
>>> len(list(iter_lines('abc\n def\n gh\n')))
3
>>> len(list(iter_lines('abc\n def\n gh')))
3
>>> 20000 > len(list(iter_... | def iter_lines(url_or_text, ext=None, mode='rt'):
r""" Return an iterator over the lines of a file or URI response.
>>> len(list(iter_lines('cats_and_dogs.txt')))
263
>>> len(list(iter_lines(list('abcdefgh'))))
8
>>> len(list(iter_lines('abc\n def\n gh\n')))
3
>>> len(list(iter_lines('a... |
r""" Parse the HTTP documentation HTML page in filename
Return:
code_dict: {200: "OK", ...}
>>> fn = 'HTTP_1.1 Status Code Definitions.html'
>>> code_dict = read_http_status_codes(fn)
>>> code_dict
{'100': 'Continue',
100: 'Continue',
'101': 'Switching Protocols',
101: 'Sw... | def read_http_status_codes(filename='HTTP_1.1 Status Code Definitions.html'):
r""" Parse the HTTP documentation HTML page in filename
Return:
code_dict: {200: "OK", ...}
>>> fn = 'HTTP_1.1 Status Code Definitions.html'
>>> code_dict = read_http_status_codes(fn)
>>> code_dict
{'10... |
Parse HTML table UTF8 char descriptions returning DataFrame with `ascii` and `mutliascii` | def parse_utf_html(url=os.path.join(DATA_PATH, 'utf8_table.html')):
""" Parse HTML table UTF8 char descriptions returning DataFrame with `ascii` and `mutliascii` """
utf = pd.read_html(url)
utf = [df for df in utf if len(df) > 1023 and len(df.columns) > 2][0]
utf = utf.iloc[:1024] if len(utf) == 1025 el... |
Translate non-ASCII characters to spaces or equivalent ASCII characters | def clean_csvs(dialogpath=None):
""" Translate non-ASCII characters to spaces or equivalent ASCII characters """
dialogdir = os.dirname(dialogpath) if os.path.isfile(dialogpath) else dialogpath
filenames = [dialogpath.split(os.path.sep)[-1]] if os.path.isfile(dialogpath) else os.listdir(dialogpath)
for ... |
r""" Translate UTF8 characters to ASCII
>> unicode2ascii("żółw")
zozw
utf8_letters = 'ą ę ć ź ż ó ł ń ś “ ” ’'.split()
ascii_letters = 'a e c z z o l n s " " \'' | def unicode2ascii(text, expand=True):
r""" Translate UTF8 characters to ASCII
>> unicode2ascii("żółw")
zozw
utf8_letters = 'ą ę ć ź ż ó ł ń ś “ ” ’'.split()
ascii_letters = 'a e c z z o l n s " " \''
"""
translate = UTF8_TO_ASCII if not expand else UTF8_TO_MULTIASCII
output = ''
f... |
Convert UTF8 characters in a CSV file or dataframe into ASCII
Args:
df (DataFrame or str): DataFrame or path or url to CSV | def clean_df(df, header=None, **read_csv_kwargs):
""" Convert UTF8 characters in a CSV file or dataframe into ASCII
Args:
df (DataFrame or str): DataFrame or path or url to CSV
"""
df = read_csv(df, header=header, **read_csv_kwargs)
df = df.fillna(' ')
for col in df.columns:
df[co... |
r""" Retrieve text lines from the manuscript Chapter*.asc and Appendix*.asc files
Args:
file_path (str): Path to directory containing manuscript asciidoc files
i.e.: /Users/cole-home/repos/nlpinaction/manuscript/ or nlpia.constants.BOOK_PATH
Returns:
list of lists of str, one list for ... | def get_lines(file_path=BOOK_PATH):
r""" Retrieve text lines from the manuscript Chapter*.asc and Appendix*.asc files
Args:
file_path (str): Path to directory containing manuscript asciidoc files
i.e.: /Users/cole-home/repos/nlpinaction/manuscript/ or nlpia.constants.BOOK_PATH
Returns:
... |
Find all the 2 and 3-letter acronyms in the manuscript and return as a sorted list of tuples | def get_acronyms(manuscript=os.path.expanduser('~/code/nlpia/lane/manuscript')):
""" Find all the 2 and 3-letter acronyms in the manuscript and return as a sorted list of tuples """
acronyms = []
for f, lines in get_lines(manuscript):
for line in lines:
matches = CRE_ACRONYM.finditer(lin... |
Compose an asciidoc string with acronyms culled from the manuscript | def write_glossary(manuscript=os.path.expanduser('~/code/nlpia/lane/manuscript'), linesep=None):
""" Compose an asciidoc string with acronyms culled from the manuscript """
linesep = linesep or os.linesep
lines = ['[acronyms]', '== Acronyms', '', '[acronyms,template="glossary",id="terms"]']
acronyms = g... |
r""" Naively tags lines from manuscript with: code, natural, heading, etc.
Returns:
list of tuples [(tag, line), ...]
>>> ' '.join(sorted(VALID_TAGS))
'anchor attribute blank_line block_header caption code code_end code_header code_start
comment comment_end comment_start image_link latexmath... | def tag_lines(lines, include_tags=None):
r""" Naively tags lines from manuscript with: code, natural, heading, etc.
Returns:
list of tuples [(tag, line), ...]
>>> ' '.join(sorted(VALID_TAGS))
'anchor attribute blank_line block_header caption code code_end code_header code_start
comment c... |
Get list of (adoc_file_path, (adoc_syntax_tag, raw_line_str))
>>> get_tagged_sections()
[('...src/nlpia/data/book/Appendix F -- Glossary.asc', <generator object filter_tagged_lines at ...>)] | def get_tagged_sections(book_dir=BOOK_PATH, include_tags=None):
""" Get list of (adoc_file_path, (adoc_syntax_tag, raw_line_str))
>>> get_tagged_sections()
[('...src/nlpia/data/book/Appendix F -- Glossary.asc', <generator object filter_tagged_lines at ...>)]
"""
return [(filepath, tag_lines(lines, ... |
Find lines in the list of 2-tuples of adoc-tagged lines that contain bad footnotes (only urls)
>>> sections = get_tagged_sections(BOOK_PATH)
>>> tagged_lines = list(sections[0][1])
>>> find_bad_footnote_urls(tagged_lines)
[[30, 'https://spacy.io/usage/linguistic-features#rule-based-morphology']] | def find_bad_footnote_urls(tagged_lines, include_tags=None):
""" Find lines in the list of 2-tuples of adoc-tagged lines that contain bad footnotes (only urls)
>>> sections = get_tagged_sections(BOOK_PATH)
>>> tagged_lines = list(sections[0][1])
>>> find_bad_footnote_urls(tagged_lines)
[[30, 'http... |
Guess what the page title is going to be from the path and FQDN in the URL
>>> infer_url_title('https://ai.googleblog.com/2018/09/the-what-if-tool-code-free-probing-of.html')
'the what if tool code free probing of' | def infer_url_title(url):
""" Guess what the page title is going to be from the path and FQDN in the URL
>>> infer_url_title('https://ai.googleblog.com/2018/09/the-what-if-tool-code-free-probing-of.html')
'the what if tool code free probing of'
"""
meta = get_url_filemeta(url)
title = ''
if... |
Return [original_line, url_footnote1, url_footnote2, ... url_footnoteN] for N bad footnotes in the line | def get_line_bad_footnotes(line, tag=None, include_tags=None):
""" Return [original_line, url_footnote1, url_footnote2, ... url_footnoteN] for N bad footnotes in the line """
if tag is None or include_tags is None or tag in include_tags or any((tag.startswith(t) for t in include_tags)):
found_baddies =... |
r""" Find all bare-url footnotes, like "footnote:[moz.org]" and add a title like "footnote:[Moz (moz.org)]"
>>> translate_line_footnotes('*Morphemes*:: Parts of tokens or words that contain meaning in and of themselves.'\
... 'footnote:[https://spacy.io/usage/linguistic-features#rule-based-morphology]')
... | def translate_line_footnotes(line, tag=None, default_title='<NOT_FOUND>'):
r""" Find all bare-url footnotes, like "footnote:[moz.org]" and add a title like "footnote:[Moz (moz.org)]"
>>> translate_line_footnotes('*Morphemes*:: Parts of tokens or words that contain meaning in and of themselves.'\
... '... |
Fix any style corrections listed in `translate` list of translation functions
>>> len(translate_book(book_dir=BOOK_PATH, dest='cleaned_hyperlinks'))
3
>>> rm_rf(os.path.join(BOOK_PATH, 'cleaned_hyperlinks')) | def translate_book(translators=(HyperlinkStyleCorrector().translate, translate_line_footnotes),
book_dir=BOOK_PATH, dest=None, include_tags=None,
ext='.nlpiabak', skip_untitled=True):
""" Fix any style corrections listed in `translate` list of translation functions
>>> len... |
DEPRECATED (see translate_line_footnotes)
Find bad footnotes (only urls), visit the page, add the title to the footnote
>>> len(correct_hyperlinks(book_dir=BOOK_PATH, dest='cleaned_hyperlinks'))
2
>>> rm_rf(os.path.join(BOOK_PATH, 'cleaned_hyperlinks')) | def correct_hyperlinks(book_dir=BOOK_PATH, dest=None, include_tags=None,
ext='.nlpiabak', skip_untitled=True):
""" DEPRECATED (see translate_line_footnotes)
Find bad footnotes (only urls), visit the page, add the title to the footnote
>>> len(correct_hyperlinks(book_dir=BOOK_PATH, ... |
DEPRECATED (see translate_line_footnotes)
Find bad footnotes (only urls), visit the page, add the title to the footnote
>>> len(correct_bad_footnote_urls(book_dir=BOOK_PATH, dest='cleaned_footnotes'))
1
>>> rm_r(os.path.join(BOOK_PATH, 'cleaned_footnotes')) | def correct_bad_footnote_urls(book_dir=BOOK_PATH, dest=None, include_tags=None,
ext='.nlpiabak', skip_untitled=True):
""" DEPRECATED (see translate_line_footnotes)
Find bad footnotes (only urls), visit the page, add the title to the footnote
>>> len(correct_bad_footnote_urls... |
Translate all the lines of a single file | def filter_lines(input_file, output_file, translate=lambda line: line):
""" Translate all the lines of a single file """
filepath, lines = get_lines([input_file])[0]
return filepath, [(tag, translate(line=line, tag=tag)) for (tag, line) in lines] |
r""" Return iterable of tagged lines where the tags all start with one of the include_tags prefixes
>>> filter_tagged_lines([('natural', "Hello."), ('code', '[source,python]'), ('code', '>>> hello()')])
<generator object filter_tagged_lines at ...>
>>> list(filter_tagged_lines([('natural', "Hello."), ('cod... | def filter_tagged_lines(tagged_lines, include_tags=None, exclude_tags=None):
r""" Return iterable of tagged lines where the tags all start with one of the include_tags prefixes
>>> filter_tagged_lines([('natural', "Hello."), ('code', '[source,python]'), ('code', '>>> hello()')])
<generator object filter_ta... |
r""" Parse all the asciidoc files in book_dir, returning a list of 2-tuples of lists of 2-tuples (tagged lines)
>>> main(BOOK_PATH, verbosity=0)
[('.../src/nlpia/data/book/Appendix F -- Glossary.asc', <generator object filter_tagged_lines at ...>)]
>>> main(BOOK_PATH, include_tags='natural', verbosity=1)
... | def main(book_dir=BOOK_PATH, include_tags=None, verbosity=1):
r""" Parse all the asciidoc files in book_dir, returning a list of 2-tuples of lists of 2-tuples (tagged lines)
>>> main(BOOK_PATH, verbosity=0)
[('.../src/nlpia/data/book/Appendix F -- Glossary.asc', <generator object filter_tagged_lines at ..... |
Retrieve as many anki paired-statement corpora as you can for the requested language
If `ankis` (requested languages) is more than one, then get the english texts associated with those languages.
TODO: improve modularity: def function that takes a single language and call it recursively if necessary
>>> g... | def get_anki_phrases(lang='english', limit=None):
""" Retrieve as many anki paired-statement corpora as you can for the requested language
If `ankis` (requested languages) is more than one, then get the english texts associated with those languages.
TODO: improve modularity: def function that takes a sing... |
Reconstruct the term-document matrix and measure error as SVD terms are truncated | def accuracy_study(tdm=None, u=None, s=None, vt=None, verbosity=0, **kwargs):
""" Reconstruct the term-document matrix and measure error as SVD terms are truncated
"""
smat = np.zeros((len(u), len(vt)))
np.fill_diagonal(smat, s)
smat = pd.DataFrame(smat, columns=vt.index, index=u.index)
if verbo... |
Return all the English phrases in the Anki translation flashcards
>>> len(get_anki_phrases_english(limit=100)) > 700
True | def get_anki_phrases_english(limit=None):
""" Return all the English phrases in the Anki translation flashcards
>>> len(get_anki_phrases_english(limit=100)) > 700
True
"""
texts = set()
for lang in ANKI_LANGUAGES:
df = get_data(lang)
phrases = df.eng.str.strip().values
... |
Build a DataFrame containing all the words in the docs provided along with their POS tags etc
>>> doc = nlp("Hey Mr. Tangerine Man!")
<BLANKLINE>
...
>>> get_vocab([doc])
word pos tag dep ent_type ent_iob sentiment
0 ! PUNCT . punct O 0.... | def get_vocab(docs):
""" Build a DataFrame containing all the words in the docs provided along with their POS tags etc
>>> doc = nlp("Hey Mr. Tangerine Man!")
<BLANKLINE>
...
>>> get_vocab([doc])
word pos tag dep ent_type ent_iob sentiment
0 ! PUNCT . pun... |
Create a word2vec embedding matrix for all the words in the vocab | def get_word_vectors(vocab):
""" Create a word2vec embedding matrix for all the words in the vocab """
wv = get_data('word2vec')
vectors = np.array(len(vocab), len(wv['the']))
for i, tok in enumerate(vocab):
word = tok[0]
variations = (word, word.lower(), word.lower()[:-1])
for w... |
Get all the vocab words+tags+wordvectors for the tokens in the Anki translation corpus
Returns a DataFrame of with columns = word, pos, tag, dep, ent, ent_iob, sentiment, vectors | def get_anki_vocab(lang=['eng'], limit=None, filename='anki_en_vocabulary.csv'):
""" Get all the vocab words+tags+wordvectors for the tokens in the Anki translation corpus
Returns a DataFrame of with columns = word, pos, tag, dep, ent, ent_iob, sentiment, vectors
"""
texts = get_anki_phrases(lang=lang,... |
Latent Sentiment Analyis on random sampling of twitter search results for words listed in cased_tokens | def lsa_twitter(cased_tokens):
""" Latent Sentiment Analyis on random sampling of twitter search results for words listed in cased_tokens """
# Only 5 of these tokens are saved for a no_below=2 filter:
# PyCons NLPS #PyCon2016 #NaturalLanguageProcessing #naturallanguageprocessing
if cased_tokens is N... |
r""" Count lines in a text file
References:
https://stackoverflow.com/q/845058/623735
>>> with open(os.path.join(DATA_PATH, 'dictionary_fda_drug_names.txt')) as fin:
... print(wc(fin) == wc(fin) == 7037 == wc(fin.name))
True
>>> wc(fin.name)
7037 | def wc(f, verbose=False, nrows=None):
r""" Count lines in a text file
References:
https://stackoverflow.com/q/845058/623735
>>> with open(os.path.join(DATA_PATH, 'dictionary_fda_drug_names.txt')) as fin:
... print(wc(fin) == wc(fin) == 7037 == wc(fin.name))
True
>>> wc(fin.name)
... |
r""" Ensure that s is a str and not a bytes (.decode() if necessary)
>>> ensure_str(b"I'm 2. When I grow up I want to be a str!")
"I'm 2. When I grow up I want to be a str!"
>>> ensure_str(42)
'42' | def ensure_str(s):
r""" Ensure that s is a str and not a bytes (.decode() if necessary)
>>> ensure_str(b"I'm 2. When I grow up I want to be a str!")
"I'm 2. When I grow up I want to be a str!"
>>> ensure_str(42)
'42'
"""
try:
return s.decode()
except AttributeError:
if i... |
bash `ls -a`: List both file paths or directory contents (files and directories)
>>> ls('.')
[...]
>>> ls('~/')
[...]
>>> __file__.endswith(os.path.join('nlpia', 'futil.py'))
True
>>> ls(__file__).endswith(os.path.join('nlpia', 'futil.py'))
True | def ls(path, force=False):
""" bash `ls -a`: List both file paths or directory contents (files and directories)
>>> ls('.')
[...]
>>> ls('~/')
[...]
>>> __file__.endswith(os.path.join('nlpia', 'futil.py'))
True
>>> ls(__file__).endswith(os.path.join('nlpia', 'futil.py'))
True
"... |
bash `rm -r`: Recursively remove dirpath. If `force==True`, don't raise exception if path doesn't exist.
>>> rm_r('/tmp/nlpia_dir_that_doesnt_exist_3.141591234/', force=True)
>>> rm_r('/tmp/nlpia_dir_that_doesnt_exist_3.141591234/')
Traceback (most recent call last):
...
FileNotFoundError: [Err... | def rm_r(path, force=False):
""" bash `rm -r`: Recursively remove dirpath. If `force==True`, don't raise exception if path doesn't exist.
>>> rm_r('/tmp/nlpia_dir_that_doesnt_exist_3.141591234/', force=True)
>>> rm_r('/tmp/nlpia_dir_that_doesnt_exist_3.141591234/')
Traceback (most recent call last):
... |
Expand any '~', '.', '*' variables in filepath.
See also: pugnlp.futil.expand_path
>>> len(expand_filepath('~')) > 3
True | def expand_filepath(filepath):
""" Expand any '~', '.', '*' variables in filepath.
See also: pugnlp.futil.expand_path
>>> len(expand_filepath('~')) > 3
True
"""
return os.path.abspath(os.path.expandvars(os.path.expanduser(filepath))) |
r""" Return a file pointer using gzip.open if filename ends with .gz otherwise open()
TODO: try to read a gzip rather than relying on gz extension, likewise for zip and other formats
TODO: monkey patch the file so that .write_bytes=.write and .write writes both str and bytes
>>> fn = os.path.join(DATA_PAT... | def ensure_open(f, mode='r'):
r""" Return a file pointer using gzip.open if filename ends with .gz otherwise open()
TODO: try to read a gzip rather than relying on gz extension, likewise for zip and other formats
TODO: monkey patch the file so that .write_bytes=.write and .write writes both str and bytes
... |
Convert file extension(s) to normalized form, e.g. '.tgz' -> '.tar.gz'
Normalized extensions are ordered in reverse order of how they should be processed.
Also extensions are ordered in order of decreasing specificity/detail.
e.g. zip last, then txt/bin, then model type, then model dimensionality
.TGZ... | def normalize_ext(filepath):
""" Convert file extension(s) to normalized form, e.g. '.tgz' -> '.tar.gz'
Normalized extensions are ordered in reverse order of how they should be processed.
Also extensions are ordered in order of decreasing specificity/detail.
e.g. zip last, then txt/bin, then model type... |
r""" Lowercase the filename and ext, expanding extensions like .tgz to .tar.gz.
>>> normalize_filepath('/Hello_World.txt\n')
'hello_world.txt'
>>> normalize_filepath('NLPIA/src/nlpia/bigdata/Goog New 300Dneg\f.bIn\n.GZ')
'NLPIA/src/nlpia/bigdata/goog new 300dneg.bin.gz' | def normalize_filepath(filepath):
r""" Lowercase the filename and ext, expanding extensions like .tgz to .tar.gz.
>>> normalize_filepath('/Hello_World.txt\n')
'hello_world.txt'
>>> normalize_filepath('NLPIA/src/nlpia/bigdata/Goog New 300Dneg\f.bIn\n.GZ')
'NLPIA/src/nlpia/bigdata/goog new 300dneg.bi... |
Given a filename or path see if it exists in any of the common places datafiles might be
>>> p = find_filepath('iq_test.csv')
>>> p == expand_filepath(os.path.join(DATA_PATH, 'iq_test.csv'))
True
>>> p[-len('iq_test.csv'):]
'iq_test.csv'
>>> find_filepath('exponentially-crazy-filename-2.7182818... | def find_filepath(
filename,
basepaths=(os.path.curdir, DATA_PATH, BIGDATA_PATH, BASE_DIR, '~', '~/Downloads', os.path.join('/', 'tmp'), '..')):
""" Given a filename or path see if it exists in any of the common places datafiles might be
>>> p = find_filepath('iq_test.csv')
>>> p == expand_... |
read text from filepath (`open(find_filepath(expand_filepath(fp)))`) then json.loads()
>>> read_json('HTTP_1.1 Status Code Definitions.html.json')
{'100': 'Continue',
'101': 'Switching Protocols',... | def read_json(filepath, intkeys=True, intvalues=True):
""" read text from filepath (`open(find_filepath(expand_filepath(fp)))`) then json.loads()
>>> read_json('HTTP_1.1 Status Code Definitions.html.json')
{'100': 'Continue',
'101': 'Switching Protocols',...
"""
d = json.load(ensure_open(... |
Tries to infer if the Series (usually leftmost column) should be the index_col
>>> looks_like_index(pd.Series(np.arange(100)))
True | def looks_like_index(series, index_names=('Unnamed: 0', 'pk', 'index', '')):
""" Tries to infer if the Series (usually leftmost column) should be the index_col
>>> looks_like_index(pd.Series(np.arange(100)))
True
"""
if series.name in index_names:
return True
if (series == series.index.... |
Like pandas.read_csv, only little smarter: check left column to see if it should be the index_col
>>> read_csv(os.path.join(DATA_PATH, 'mavis-batey-greetings.csv')).head()
sentence is_greeting
0 It was a strange little outfit in the cottage. 0... | def read_csv(*args, **kwargs):
"""Like pandas.read_csv, only little smarter: check left column to see if it should be the index_col
>>> read_csv(os.path.join(DATA_PATH, 'mavis-batey-greetings.csv')).head()
sentence is_greeting
0 It was a strange litt... |
r""" Read all the lines (up to nrows) from a text file or txt.gz file
>>> fn = os.path.join(DATA_PATH, 'mavis-batey-greetings.txt')
>>> len(read_text(fn, nrows=3))
3 | def read_text(forfn, nrows=None, verbose=True):
r""" Read all the lines (up to nrows) from a text file or txt.gz file
>>> fn = os.path.join(DATA_PATH, 'mavis-batey-greetings.txt')
>>> len(read_text(fn, nrows=3))
3
"""
tqdm_prog = tqdm if verbose else no_tqdm
nrows = wc(forfn, nrows=nrows) ... |
Generate a basic auth token for a given user and password.
:param user: user name
:param password: current password
:param realm: specifies the authentication provider
:return: auth token for use with :meth:`GraphDatabase.driver` | def basic_auth(user, password, realm=None):
""" Generate a basic auth token for a given user and password.
:param user: user name
:param password: current password
:param realm: specifies the authentication provider
:return: auth token for use with :meth:`GraphDatabase.driver`
"""
from neob... |
Generate a basic auth token for a given user and password.
:param principal: specifies who is being authenticated
:param credentials: authenticates the principal
:param realm: specifies the authentication provider
:param scheme: specifies the type of authentication
:param parameters: parameters pas... | def custom_auth(principal, credentials, realm, scheme, **parameters):
""" Generate a basic auth token for a given user and password.
:param principal: specifies who is being authenticated
:param credentials: authenticates the principal
:param realm: specifies the authentication provider
:param sche... |
Check whether a URI is compatible with a :class:`.Driver`
subclass. When called from a subclass, execution simply passes
through if the URI scheme is valid for that class. If invalid,
a `ValueError` is raised.
:param uri: URI to check for compatibility
:raise: `ValueError` if UR... | def _check_uri(cls, uri):
""" Check whether a URI is compatible with a :class:`.Driver`
subclass. When called from a subclass, execution simply passes
through if the URI scheme is valid for that class. If invalid,
a `ValueError` is raised.
:param uri: URI to check for compatibil... |
Shut down, closing any open connections in the pool. | def close(self):
""" Shut down, closing any open connections in the pool.
"""
if not self._closed:
self._closed = True
if self._pool is not None:
self._pool.close()
self._pool = None |
Create a new instance of a Point subclass from a raw
set of fields. The subclass chosen is determined by the
given SRID; a ValueError will be raised if no such
subclass can be found. | def hydrate_point(srid, *coordinates):
""" Create a new instance of a Point subclass from a raw
set of fields. The subclass chosen is determined by the
given SRID; a ValueError will be raised if no such
subclass can be found.
"""
try:
point_class, dim = __srid_table[srid]
except KeyE... |
Dehydrator for Point data.
:param value:
:type value: Point
:return: | def dehydrate_point(value):
""" Dehydrator for Point data.
:param value:
:type value: Point
:return:
"""
dim = len(value)
if dim == 2:
return Structure(b"X", value.srid, *value)
elif dim == 3:
return Structure(b"Y", value.srid, *value)
else:
raise ValueError(... |
Iterate through all items (key-value pairs) within an iterable
dictionary-like object. If the object has a `keys` method, this is
used along with `__getitem__` to yield each pair in turn. If no
`keys` method exists, each iterable element is assumed to be a
2-tuple of key and value. | def iter_items(iterable):
""" Iterate through all items (key-value pairs) within an iterable
dictionary-like object. If the object has a `keys` method, this is
used along with `__getitem__` to yield each pair in turn. If no
`keys` method exists, each iterable element is assumed to be a
2-tuple of ke... |
Convert native values into PackStream values. | def dehydrate(self, values):
""" Convert native values into PackStream values.
"""
def dehydrate_(obj):
try:
f = self.dehydration_functions[type(obj)]
except KeyError:
pass
else:
return f(obj)
if obj... |
Obtain a value from the record by key, returning a default
value if the key does not exist.
:param key:
:param default:
:return: | def get(self, key, default=None):
""" Obtain a value from the record by key, returning a default
value if the key does not exist.
:param key:
:param default:
:return:
"""
try:
index = self.__keys.index(str(key))
except ValueError:
... |
Return the index of the given item.
:param key:
:return: | def index(self, key):
""" Return the index of the given item.
:param key:
:return:
"""
if isinstance(key, int):
if 0 <= key < len(self.__keys):
return key
raise IndexError(key)
elif isinstance(key, str):
try:
... |
Obtain a single value from the record by index or key. If no
index or key is specified, the first value is returned. If the
specified item does not exist, the default value is returned.
:param key:
:param default:
:return: | def value(self, key=0, default=None):
""" Obtain a single value from the record by index or key. If no
index or key is specified, the first value is returned. If the
specified item does not exist, the default value is returned.
:param key:
:param default:
:return:
... |
Return the values of the record, optionally filtering to
include only certain values by index or key.
:param keys: indexes or keys of the items to include; if none
are provided, all values will be included
:return: list of values | def values(self, *keys):
""" Return the values of the record, optionally filtering to
include only certain values by index or key.
:param keys: indexes or keys of the items to include; if none
are provided, all values will be included
:return: list of values
... |
Return the fields of the record as a list of key and value tuples
:return: | def items(self, *keys):
""" Return the fields of the record as a list of key and value tuples
:return:
"""
if keys:
d = []
for key in keys:
try:
i = self.index(key)
except KeyError:
d.append(... |
Return the keys and values of this record as a dictionary,
optionally including only certain values by index or key. Keys
provided in the items that are not in the record will be
inserted with a value of :const:`None`; indexes provided
that are out of bounds will trigger an :exc:`IndexEr... | def data(self, *keys):
""" Return the keys and values of this record as a dictionary,
optionally including only certain values by index or key. Keys
provided in the items that are not in the record will be
inserted with a value of :const:`None`; indexes provided
that are out of b... |
Construct a Plan or ProfiledPlan from a dictionary of metadata values.
:param plan_dict:
:return: | def _make_plan(plan_dict):
""" Construct a Plan or ProfiledPlan from a dictionary of metadata values.
:param plan_dict:
:return:
"""
operator_type = plan_dict["operatorType"]
identifiers = plan_dict.get("identifiers", [])
arguments = plan_dict.get("args", [])
children = [_make_plan(chil... |
This function is a decorator for transaction functions that allows
extra control over how the transaction is carried out.
For example, a timeout (in seconds) may be applied::
@unit_of_work(timeout=25.0)
def count_people(tx):
return tx.run("MATCH (a:Person) RETURN count(a)").single(... | def unit_of_work(metadata=None, timeout=None):
""" This function is a decorator for transaction functions that allows
extra control over how the transaction is carried out.
For example, a timeout (in seconds) may be applied::
@unit_of_work(timeout=25.0)
def count_people(tx):
re... |
Close the session. This will release any borrowed resources,
such as connections, and will roll back any outstanding transactions. | def close(self):
""" Close the session. This will release any borrowed resources,
such as connections, and will roll back any outstanding transactions.
"""
from neobolt.exceptions import ConnectionExpired, CypherError, ServiceUnavailable
try:
if self.has_transaction()... |
Run a Cypher statement within an auto-commit transaction.
The statement is sent and the result header received
immediately but the :class:`.StatementResult` content is
fetched lazily as consumed by the client application.
If a statement is executed before a previous
:class:`.St... | def run(self, statement, parameters=None, **kwparameters):
""" Run a Cypher statement within an auto-commit transaction.
The statement is sent and the result header received
immediately but the :class:`.StatementResult` content is
fetched lazily as consumed by the client application.
... |
Send all outstanding requests. | def send(self):
""" Send all outstanding requests.
"""
from neobolt.exceptions import ConnectionExpired
if self._connection:
try:
self._connection.send()
except ConnectionExpired as error:
raise SessionExpired(*error.args) |
Attempt to fetch at least one more record.
:returns: number of records fetched | def fetch(self):
""" Attempt to fetch at least one more record.
:returns: number of records fetched
"""
from neobolt.exceptions import ConnectionExpired
if self._connection:
try:
detail_count, _ = self._connection.fetch()
except Connection... |
Detach a result from this session by fetching and buffering any
remaining records.
:param result:
:param sync:
:returns: number of records fetched | def detach(self, result, sync=True):
""" Detach a result from this session by fetching and buffering any
remaining records.
:param result:
:param sync:
:returns: number of records fetched
"""
count = 0
if sync and result.attached():
self.send... |
Create a new :class:`.Transaction` within this session.
Calling this method with a bookmark is equivalent to
:param bookmark: a bookmark to which the server should
synchronise before beginning the transaction
:param metadata:
:param timeout:
:returns: ne... | def begin_transaction(self, bookmark=None, metadata=None, timeout=None):
""" Create a new :class:`.Transaction` within this session.
Calling this method with a bookmark is equivalent to
:param bookmark: a bookmark to which the server should
synchronise before beginning ... |
Commit the current transaction.
:returns: the bookmark returned from the server, if any
:raise: :class:`.TransactionError` if no transaction is currently open | def commit_transaction(self):
""" Commit the current transaction.
:returns: the bookmark returned from the server, if any
:raise: :class:`.TransactionError` if no transaction is currently open
"""
self._assert_open()
if not self._transaction:
raise Transactio... |
Rollback the current transaction.
:raise: :class:`.TransactionError` if no transaction is currently open | def rollback_transaction(self):
""" Rollback the current transaction.
:raise: :class:`.TransactionError` if no transaction is currently open
"""
self._assert_open()
if not self._transaction:
raise TransactionError("No transaction to rollback")
cx = self._conn... |
Run a Cypher statement within the context of this transaction.
The statement is sent to the server lazily, when its result is
consumed. To force the statement to be sent to the server, use
the :meth:`.Transaction.sync` method.
Cypher is typically expressed as a statement template plus ... | def run(self, statement, parameters=None, **kwparameters):
""" Run a Cypher statement within the context of this transaction.
The statement is sent to the server lazily, when its result is
consumed. To force the statement to be sent to the server, use
the :meth:`.Transaction.sync` metho... |
Detach this result from its parent session by fetching the
remainder of this result from the network into the buffer.
:returns: number of records fetched | def detach(self, sync=True):
""" Detach this result from its parent session by fetching the
remainder of this result from the network into the buffer.
:returns: number of records fetched
"""
if self.attached():
return self._session.detach(self, sync=sync)
els... |
Close this transaction, triggering either a COMMIT or a ROLLBACK,
depending on the value of :attr:`.success`.
:raise TransactionError: if already closed | def close(self):
""" Close this transaction, triggering either a COMMIT or a ROLLBACK,
depending on the value of :attr:`.success`.
:raise TransactionError: if already closed
"""
from neobolt.exceptions import CypherError
self._assert_open()
try:
self.... |
The keys for the records in this result.
:returns: tuple of key names | def keys(self):
""" The keys for the records in this result.
:returns: tuple of key names
"""
try:
return self._metadata["fields"]
except KeyError:
if self.attached():
self._session.send()
while self.attached() and "fields" not... |
Generator for records obtained from this result.
:yields: iterable of :class:`.Record` objects | def records(self):
""" Generator for records obtained from this result.
:yields: iterable of :class:`.Record` objects
"""
records = self._records
next_record = records.popleft
while records:
yield next_record()
attached = self.attached
if atta... |
Obtain the summary of this result, buffering any remaining records.
:returns: The :class:`.ResultSummary` for this result | def summary(self):
""" Obtain the summary of this result, buffering any remaining records.
:returns: The :class:`.ResultSummary` for this result
"""
self.detach()
if self._summary is None:
self._summary = BoltStatementResultSummary(**self._metadata)
return se... |
Obtain the next and only remaining record from this result.
A warning is generated if more than one record is available but
the first of these is still returned.
:returns: the next :class:`.Record` or :const:`None` if none remain
:warns: if more than one record is available | def single(self):
""" Obtain the next and only remaining record from this result.
A warning is generated if more than one record is available but
the first of these is still returned.
:returns: the next :class:`.Record` or :const:`None` if none remain
:warns: if more than one r... |
Obtain the next record from this result without consuming it.
This leaves the record in the buffer for further processing.
:returns: the next :class:`.Record` or :const:`None` if none remain | def peek(self):
""" Obtain the next record from this result without consuming it.
This leaves the record in the buffer for further processing.
:returns: the next :class:`.Record` or :const:`None` if none remain
"""
records = self._records
if records:
return r... |
Return the remainder of the result as a list of values.
:param item: field to return for each remaining record
:param default: default value, used if the index of key is unavailable
:returns: list of individual values | def value(self, item=0, default=None):
""" Return the remainder of the result as a list of values.
:param item: field to return for each remaining record
:param default: default value, used if the index of key is unavailable
:returns: list of individual values
"""
return... |
Returns a generator containing the results of the next query in the pipeline | def pull(self):
"""Returns a generator containing the results of the next query in the pipeline"""
# n.b. pull is now somewhat misleadingly named because it doesn't do anything
# the connection isn't touched until you try and iterate the generator we return
lock_acquired = self._pull_loc... |
Decorator for deprecating functions and methods.
::
@deprecated("'foo' has been deprecated in favour of 'bar'")
def foo(x):
pass | def deprecated(message):
""" Decorator for deprecating functions and methods.
::
@deprecated("'foo' has been deprecated in favour of 'bar'")
def foo(x):
pass
"""
def f__(f):
def f_(*args, **kwargs):
from warnings import warn
warn(message, ca... |
Decorator for tagging experimental functions and methods.
::
@experimental("'foo' is an experimental function and may be "
"removed in a future release")
def foo(x):
pass | def experimental(message):
""" Decorator for tagging experimental functions and methods.
::
@experimental("'foo' is an experimental function and may be "
"removed in a future release")
def foo(x):
pass
"""
def f__(f):
def f_(*args, **kwargs):
... |
Obtain a :class:`.Relationship` subclass for a given
relationship type name. | def relationship_type(self, name):
""" Obtain a :class:`.Relationship` subclass for a given
relationship type name.
"""
try:
cls = self._relationship_types[name]
except KeyError:
cls = self._relationship_types[name] = type(str(name), (Relationship,), {})
... |
Hydrator for `Time` and `LocalTime` values.
:param nanoseconds:
:param tz:
:return: Time | def hydrate_time(nanoseconds, tz=None):
""" Hydrator for `Time` and `LocalTime` values.
:param nanoseconds:
:param tz:
:return: Time
"""
seconds, nanoseconds = map(int, divmod(nanoseconds, 1000000000))
minutes, seconds = map(int, divmod(seconds, 60))
hours, minutes = map(int, divmod(min... |
Dehydrator for `time` values.
:param value:
:type value: Time
:return: | def dehydrate_time(value):
""" Dehydrator for `time` values.
:param value:
:type value: Time
:return:
"""
if isinstance(value, Time):
nanoseconds = int(value.ticks * 1000000000)
elif isinstance(value, time):
nanoseconds = (3600000000000 * value.hour + 60000000000 * value.min... |
Hydrator for `DateTime` and `LocalDateTime` values.
:param seconds:
:param nanoseconds:
:param tz:
:return: datetime | def hydrate_datetime(seconds, nanoseconds, tz=None):
""" Hydrator for `DateTime` and `LocalDateTime` values.
:param seconds:
:param nanoseconds:
:param tz:
:return: datetime
"""
minutes, seconds = map(int, divmod(seconds, 60))
hours, minutes = map(int, divmod(minutes, 60))
days, hou... |
Dehydrator for `datetime` values.
:param value:
:type value: datetime
:return: | def dehydrate_datetime(value):
""" Dehydrator for `datetime` values.
:param value:
:type value: datetime
:return:
"""
def seconds_and_nanoseconds(dt):
if isinstance(dt, datetime):
dt = DateTime.from_native(dt)
zone_epoch = DateTime(1970, 1, 1, tzinfo=dt.tzinfo)
... |
Hydrator for `Duration` values.
:param months:
:param days:
:param seconds:
:param nanoseconds:
:return: `duration` namedtuple | def hydrate_duration(months, days, seconds, nanoseconds):
""" Hydrator for `Duration` values.
:param months:
:param days:
:param seconds:
:param nanoseconds:
:return: `duration` namedtuple
"""
return Duration(months=months, days=days, seconds=seconds, nanoseconds=nanoseconds) |
Dehydrator for `duration` values.
:param value:
:type value: Duration
:return: | def dehydrate_duration(value):
""" Dehydrator for `duration` values.
:param value:
:type value: Duration
:return:
"""
return Structure(b"E", value.months, value.days, value.seconds, int(1000000000 * value.subseconds)) |
Dehydrator for `timedelta` values.
:param value:
:type value: timedelta
:return: | def dehydrate_timedelta(value):
""" Dehydrator for `timedelta` values.
:param value:
:type value: timedelta
:return:
"""
months = 0
days = value.days
seconds = value.seconds
nanoseconds = 1000 * value.microseconds
return Structure(b"E", months, days, seconds, nanoseconds) |
Zooms in on an element a certain amount. | def zoom(self, locator, percent="200%", steps=1):
"""
Zooms in on an element a certain amount.
"""
driver = self._current_application()
element = self._element_find(locator, True, True)
driver.zoom(element=element, percent=percent, steps=steps) |
Swipe from one point to another point, for an optional duration.
Args:
- start_x - x-coordinate at which to start
- start_y - y-coordinate at which to start
- offset_x - x-coordinate distance from start_x at which to stop
- offset_y - y-coordinate distance from start_y... | def swipe(self, start_x, start_y, offset_x, offset_y, duration=1000):
"""
Swipe from one point to another point, for an optional duration.
Args:
- start_x - x-coordinate at which to start
- start_y - y-coordinate at which to start
- offset_x - x-coordinate dist... |
Swipe from one percent of the screen to another percent, for an optional duration.
Normal swipe fails to scale for different screen resolutions, this can be avoided using percent.
Args:
- start_x - x-percent at which to start
- start_y - y-percent at which to start
- en... | def swipe_by_percent(self, start_x, start_y, end_x, end_y, duration=1000):
"""
Swipe from one percent of the screen to another percent, for an optional duration.
Normal swipe fails to scale for different screen resolutions, this can be avoided using percent.
Args:
- start... |
Scrolls from one element to another
Key attributes for arbitrary elements are `id` and `name`. See
`introduction` for details about locating elements. | def scroll(self, start_locator, end_locator):
"""
Scrolls from one element to another
Key attributes for arbitrary elements are `id` and `name`. See
`introduction` for details about locating elements.
"""
el1 = self._element_find(start_locator, True, True)
... |
Scrolls up to element | def scroll_up(self, locator):
"""Scrolls up to element"""
driver = self._current_application()
element = self._element_find(locator, True, True)
driver.execute_script("mobile: scroll", {"direction": 'up', 'element': element.id}) |
Long press the element with optional duration | def long_press(self, locator, duration=1000):
""" Long press the element with optional duration """
driver = self._current_application()
element = self._element_find(locator, True, True)
action = TouchAction(driver)
action.press(element).wait(duration).release().perform() |
Tap element identified by ``locator``.
Args:
- ``x_offset`` - (optional) x coordinate to tap, relative to the top left corner of the element.
- ``y_offset`` - (optional) y coordinate. If y is used, x must also be set, and vice versa
- ``count`` - can be used for multiple times of t... | def tap(self, locator, x_offset=None, y_offset=None, count=1):
""" Tap element identified by ``locator``.
Args:
- ``x_offset`` - (optional) x coordinate to tap, relative to the top left corner of the element.
- ``y_offset`` - (optional) y coordinate. If y is used, x must also be se... |
Click on a point | def click_a_point(self, x=0, y=0, duration=100):
""" Click on a point"""
self._info("Clicking on a point (%s,%s)." % (x,y))
driver = self._current_application()
action = TouchAction(driver)
try:
action.press(x=float(x), y=float(y)).wait(float(duration)).release(... |
click element at a certain coordinate | def click_element_at_coordinates(self, coordinate_X, coordinate_Y):
""" click element at a certain coordinate """
self._info("Pressing at (%s, %s)." % (coordinate_X, coordinate_Y))
driver = self._current_application()
action = TouchAction(driver)
action.press(x=coordinate_X,... |
Waits until element specified with `locator` is visible.
Fails if `timeout` expires before the element is visible. See
`introduction` for more information about `timeout` and its
default value.
`error` can be used to override the default error message.
See also `Wait Until Pag... | def wait_until_element_is_visible(self, locator, timeout=None, error=None):
"""Waits until element specified with `locator` is visible.
Fails if `timeout` expires before the element is visible. See
`introduction` for more information about `timeout` and its
default value.
`erro... |
Waits until `text` appears on current page.
Fails if `timeout` expires before the text appears. See
`introduction` for more information about `timeout` and its
default value.
`error` can be used to override the default error message.
See also `Wait Until Page Does Not Contain`... | def wait_until_page_contains(self, text, timeout=None, error=None):
"""Waits until `text` appears on current page.
Fails if `timeout` expires before the text appears. See
`introduction` for more information about `timeout` and its
default value.
`error` can be used to override ... |
Waits until `text` disappears from current page.
Fails if `timeout` expires before the `text` disappears. See
`introduction` for more information about `timeout` and its
default value.
`error` can be used to override the default error message.
See also `Wait Until Page Contain... | def wait_until_page_does_not_contain(self, text, timeout=None, error=None):
"""Waits until `text` disappears from current page.
Fails if `timeout` expires before the `text` disappears. See
`introduction` for more information about `timeout` and its
default value.
`error` can be... |
Waits until element specified with `locator` disappears from current page.
Fails if `timeout` expires before the element disappears. See
`introduction` for more information about `timeout` and its
default value.
`error` can be used to override the default error message.
See al... | def wait_until_page_does_not_contain_element(self, locator, timeout=None, error=None):
"""Waits until element specified with `locator` disappears from current page.
Fails if `timeout` expires before the element disappears. See
`introduction` for more information about `timeout` and its
... |
Waits until element specified with `locator` appears on current page.
Fails if `timeout` expires before the element appears. See
`introduction` for more information about `timeout` and its
default value.
`error` can be used to override the default error message.
See also `Wait... | def wait_until_page_contains_element(self, locator, timeout=None, error=None):
"""Waits until element specified with `locator` appears on current page.
Fails if `timeout` expires before the element appears. See
`introduction` for more information about `timeout` and its
default value.
... |
Sets the network connection Status.
Android only.
Possible values:
| =Value= | =Alias= | =Data= | =Wifi= | =Airplane Mode= |
| 0 | (None) | 0 | 0 | 0 |
| 1 | (Airplane Mode) | 0 | 0 | 1 ... | def set_network_connection_status(self, connectionStatus):
"""Sets the network connection Status.
Android only.
Possible values:
| =Value= | =Alias= | =Data= | =Wifi= | =Airplane Mode= |
| 0 | (None) | 0 | 0 | 0 |
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.