id int32 0 252k | 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 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
245,300 | totalgood/nlpia | src/nlpia/book_parser.py | infer_url_title | 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 meta:
if meta.get('hostname', url) == 'drive.google.com':
title = get_url_title(url)
else:
title = meta.get('filename', meta['hostname']) or meta['hostname']
title, fileext = splitext(title)
else:
logging.error('Unable to retrieve URL: {}'.format(url))
return None
return delimit_slug(title, ' ') | python | def infer_url_title(url):
meta = get_url_filemeta(url)
title = ''
if meta:
if meta.get('hostname', url) == 'drive.google.com':
title = get_url_title(url)
else:
title = meta.get('filename', meta['hostname']) or meta['hostname']
title, fileext = splitext(title)
else:
logging.error('Unable to retrieve URL: {}'.format(url))
return None
return delimit_slug(title, ' ') | [
"def",
"infer_url_title",
"(",
"url",
")",
":",
"meta",
"=",
"get_url_filemeta",
"(",
"url",
")",
"title",
"=",
"''",
"if",
"meta",
":",
"if",
"meta",
".",
"get",
"(",
"'hostname'",
",",
"url",
")",
"==",
"'drive.google.com'",
":",
"title",
"=",
"get_u... | 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' | [
"Guess",
"what",
"the",
"page",
"title",
"is",
"going",
"to",
"be",
"from",
"the",
"path",
"and",
"FQDN",
"in",
"the",
"URL"
] | efa01126275e9cd3c3a5151a644f1c798a9ec53f | https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book_parser.py#L245-L262 |
245,301 | totalgood/nlpia | src/nlpia/book_parser.py | translate_book | 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(translate_book(book_dir=BOOK_PATH, dest='cleaned_hyperlinks'))
3
>>> rm_rf(os.path.join(BOOK_PATH, 'cleaned_hyperlinks'))
"""
if callable(translators) or not hasattr(translators, '__len__'):
translators = (translators,)
sections = get_tagged_sections(book_dir=book_dir, include_tags=include_tags)
file_line_maps = []
for fileid, (filepath, tagged_lines) in enumerate(sections):
logger.info('filepath={}'.format(filepath))
destpath = filepath
if not dest:
copyfile(filepath, filepath + '.' + ext.lstrip('.'))
elif os.path.sep in dest:
destpath = os.path.join(dest, os.path.basename(filepath))
else:
destpath = os.path.join(os.path.dirname(filepath), dest, os.path.basename(filepath))
ensure_dir_exists(os.path.dirname(destpath))
with open(destpath, 'w') as fout:
logger.info('destpath={}'.format(destpath))
for lineno, (tag, line) in enumerate(tagged_lines):
if (include_tags is None or tag in include_tags or
any((tag.startswith(t) for t in include_tags))):
for translate in translators:
new_line = translate(line) # TODO: be smarter about writing to files in-place
if line != new_line:
file_line_maps.append((fileid, lineno, filepath, destpath, line, new_line))
line = new_line
fout.write(line)
return file_line_maps | python | def translate_book(translators=(HyperlinkStyleCorrector().translate, translate_line_footnotes),
book_dir=BOOK_PATH, dest=None, include_tags=None,
ext='.nlpiabak', skip_untitled=True):
if callable(translators) or not hasattr(translators, '__len__'):
translators = (translators,)
sections = get_tagged_sections(book_dir=book_dir, include_tags=include_tags)
file_line_maps = []
for fileid, (filepath, tagged_lines) in enumerate(sections):
logger.info('filepath={}'.format(filepath))
destpath = filepath
if not dest:
copyfile(filepath, filepath + '.' + ext.lstrip('.'))
elif os.path.sep in dest:
destpath = os.path.join(dest, os.path.basename(filepath))
else:
destpath = os.path.join(os.path.dirname(filepath), dest, os.path.basename(filepath))
ensure_dir_exists(os.path.dirname(destpath))
with open(destpath, 'w') as fout:
logger.info('destpath={}'.format(destpath))
for lineno, (tag, line) in enumerate(tagged_lines):
if (include_tags is None or tag in include_tags or
any((tag.startswith(t) for t in include_tags))):
for translate in translators:
new_line = translate(line) # TODO: be smarter about writing to files in-place
if line != new_line:
file_line_maps.append((fileid, lineno, filepath, destpath, line, new_line))
line = new_line
fout.write(line)
return file_line_maps | [
"def",
"translate_book",
"(",
"translators",
"=",
"(",
"HyperlinkStyleCorrector",
"(",
")",
".",
"translate",
",",
"translate_line_footnotes",
")",
",",
"book_dir",
"=",
"BOOK_PATH",
",",
"dest",
"=",
"None",
",",
"include_tags",
"=",
"None",
",",
"ext",
"=",
... | 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')) | [
"Fix",
"any",
"style",
"corrections",
"listed",
"in",
"translate",
"list",
"of",
"translation",
"functions"
] | efa01126275e9cd3c3a5151a644f1c798a9ec53f | https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book_parser.py#L335-L371 |
245,302 | totalgood/nlpia | src/nlpia/book_parser.py | filter_lines | 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] | python | def filter_lines(input_file, output_file, translate=lambda line: line):
filepath, lines = get_lines([input_file])[0]
return filepath, [(tag, translate(line=line, tag=tag)) for (tag, line) in lines] | [
"def",
"filter_lines",
"(",
"input_file",
",",
"output_file",
",",
"translate",
"=",
"lambda",
"line",
":",
"line",
")",
":",
"filepath",
",",
"lines",
"=",
"get_lines",
"(",
"[",
"input_file",
"]",
")",
"[",
"0",
"]",
"return",
"filepath",
",",
"[",
"... | Translate all the lines of a single file | [
"Translate",
"all",
"the",
"lines",
"of",
"a",
"single",
"file"
] | efa01126275e9cd3c3a5151a644f1c798a9ec53f | https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book_parser.py#L407-L410 |
245,303 | totalgood/nlpia | src/nlpia/book_parser.py | filter_tagged_lines | 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_tagged_lines at ...>
>>> list(filter_tagged_lines([('natural', "Hello."), ('code', '[source,python]'), ('code', '>>> hello()')],
... include_tags='natural'))
[('natural', 'Hello.')]
"""
include_tags = (include_tags,) if isinstance(include_tags, str) else include_tags
exclude_tags = (exclude_tags,) if isinstance(exclude_tags, str) else exclude_tags
for tagged_line in tagged_lines:
if (include_tags is None or tagged_line[0] in include_tags or
any((tagged_line[0].startswith(t) for t in include_tags))):
if exclude_tags is None or not any((tagged_line[0].startswith(t) for t in exclude_tags)):
yield tagged_line
else:
logger.debug('skipping tag {} because it starts with one of the exclude_tags={}'.format(
tagged_line[0], exclude_tags))
else:
logger.debug('skipping tag {} because not in {}'.format(tagged_line[0], include_tags)) | python | 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_tagged_lines at ...>
>>> list(filter_tagged_lines([('natural', "Hello."), ('code', '[source,python]'), ('code', '>>> hello()')],
... include_tags='natural'))
[('natural', 'Hello.')]
"""
include_tags = (include_tags,) if isinstance(include_tags, str) else include_tags
exclude_tags = (exclude_tags,) if isinstance(exclude_tags, str) else exclude_tags
for tagged_line in tagged_lines:
if (include_tags is None or tagged_line[0] in include_tags or
any((tagged_line[0].startswith(t) for t in include_tags))):
if exclude_tags is None or not any((tagged_line[0].startswith(t) for t in exclude_tags)):
yield tagged_line
else:
logger.debug('skipping tag {} because it starts with one of the exclude_tags={}'.format(
tagged_line[0], exclude_tags))
else:
logger.debug('skipping tag {} because not in {}'.format(tagged_line[0], include_tags)) | [
"def",
"filter_tagged_lines",
"(",
"tagged_lines",
",",
"include_tags",
"=",
"None",
",",
"exclude_tags",
"=",
"None",
")",
":",
"include_tags",
"=",
"(",
"include_tags",
",",
")",
"if",
"isinstance",
"(",
"include_tags",
",",
"str",
")",
"else",
"include_tags... | 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."), ('code', '[source,python]'), ('code', '>>> hello()')],
... include_tags='natural'))
[('natural', 'Hello.')] | [
"r",
"Return",
"iterable",
"of",
"tagged",
"lines",
"where",
"the",
"tags",
"all",
"start",
"with",
"one",
"of",
"the",
"include_tags",
"prefixes"
] | efa01126275e9cd3c3a5151a644f1c798a9ec53f | https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book_parser.py#L413-L434 |
245,304 | totalgood/nlpia | src/nlpia/book/examples/ch04_catdog_lsa_sorted.py | accuracy_study | 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 verbosity:
print()
print('Sigma:')
print(smat.round(2))
print()
print('Sigma without zeroing any dim:')
print(np.diag(smat.round(2)))
tdm_prime = u.values.dot(smat.values).dot(vt.values)
if verbosity:
print()
print('Reconstructed Term-Document Matrix')
print(tdm_prime.round(2))
err = [np.sqrt(((tdm_prime - tdm).values.flatten() ** 2).sum() / np.product(tdm.shape))]
if verbosity:
print()
print('Error without reducing dimensions:')
print(err[-1])
# 2.3481474529927113e-15
smat2 = smat.copy()
for numdim in range(len(s) - 1, 0, -1):
smat2.iloc[numdim, numdim] = 0
if verbosity:
print('Sigma after zeroing out dim {}'.format(numdim))
print(np.diag(smat2.round(2)))
# d0 d1 d2 d3 d4 d5
# ship 2.16 0.00 0.0 0.0 0.0 0.0
# boat 0.00 1.59 0.0 0.0 0.0 0.0
# ocean 0.00 0.00 0.0 0.0 0.0 0.0
# voyage 0.00 0.00 0.0 0.0 0.0 0.0
# trip 0.00 0.00 0.0 0.0 0.0 0.0
tdm_prime2 = u.values.dot(smat2.values).dot(vt.values)
err += [np.sqrt(((tdm_prime2 - tdm).values.flatten() ** 2).sum() / np.product(tdm.shape))]
if verbosity:
print('Error after zeroing out dim {}'.format(numdim))
print(err[-1])
return err | python | def accuracy_study(tdm=None, u=None, s=None, vt=None, verbosity=0, **kwargs):
smat = np.zeros((len(u), len(vt)))
np.fill_diagonal(smat, s)
smat = pd.DataFrame(smat, columns=vt.index, index=u.index)
if verbosity:
print()
print('Sigma:')
print(smat.round(2))
print()
print('Sigma without zeroing any dim:')
print(np.diag(smat.round(2)))
tdm_prime = u.values.dot(smat.values).dot(vt.values)
if verbosity:
print()
print('Reconstructed Term-Document Matrix')
print(tdm_prime.round(2))
err = [np.sqrt(((tdm_prime - tdm).values.flatten() ** 2).sum() / np.product(tdm.shape))]
if verbosity:
print()
print('Error without reducing dimensions:')
print(err[-1])
# 2.3481474529927113e-15
smat2 = smat.copy()
for numdim in range(len(s) - 1, 0, -1):
smat2.iloc[numdim, numdim] = 0
if verbosity:
print('Sigma after zeroing out dim {}'.format(numdim))
print(np.diag(smat2.round(2)))
# d0 d1 d2 d3 d4 d5
# ship 2.16 0.00 0.0 0.0 0.0 0.0
# boat 0.00 1.59 0.0 0.0 0.0 0.0
# ocean 0.00 0.00 0.0 0.0 0.0 0.0
# voyage 0.00 0.00 0.0 0.0 0.0 0.0
# trip 0.00 0.00 0.0 0.0 0.0 0.0
tdm_prime2 = u.values.dot(smat2.values).dot(vt.values)
err += [np.sqrt(((tdm_prime2 - tdm).values.flatten() ** 2).sum() / np.product(tdm.shape))]
if verbosity:
print('Error after zeroing out dim {}'.format(numdim))
print(err[-1])
return err | [
"def",
"accuracy_study",
"(",
"tdm",
"=",
"None",
",",
"u",
"=",
"None",
",",
"s",
"=",
"None",
",",
"vt",
"=",
"None",
",",
"verbosity",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"smat",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"u",... | Reconstruct the term-document matrix and measure error as SVD terms are truncated | [
"Reconstruct",
"the",
"term",
"-",
"document",
"matrix",
"and",
"measure",
"error",
"as",
"SVD",
"terms",
"are",
"truncated"
] | efa01126275e9cd3c3a5151a644f1c798a9ec53f | https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book/examples/ch04_catdog_lsa_sorted.py#L143-L187 |
245,305 | totalgood/nlpia | src/nlpia/anki.py | get_anki_phrases | 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 single language and call it recursively if necessary
>>> get_anki_phrases('afr')[:2]
["'n Groen piesang is nie ryp genoeg om te eet nie.",
"'n Hond het agter die kat aan gehardloop."]
"""
lang = lang.strip().lower()[:3]
lang = LANG2ANKI[lang[:2]] if lang not in ANKI_LANGUAGES else lang
if lang[:2] == 'en':
return get_anki_phrases_english(limit=limit)
return sorted(get_data(lang).iloc[:, -1].str.strip().values) | python | def get_anki_phrases(lang='english', limit=None):
lang = lang.strip().lower()[:3]
lang = LANG2ANKI[lang[:2]] if lang not in ANKI_LANGUAGES else lang
if lang[:2] == 'en':
return get_anki_phrases_english(limit=limit)
return sorted(get_data(lang).iloc[:, -1].str.strip().values) | [
"def",
"get_anki_phrases",
"(",
"lang",
"=",
"'english'",
",",
"limit",
"=",
"None",
")",
":",
"lang",
"=",
"lang",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"[",
":",
"3",
"]",
"lang",
"=",
"LANG2ANKI",
"[",
"lang",
"[",
":",
"2",
"]",
"... | 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
>>> get_anki_phrases('afr')[:2]
["'n Groen piesang is nie ryp genoeg om te eet nie.",
"'n Hond het agter die kat aan gehardloop."] | [
"Retrieve",
"as",
"many",
"anki",
"paired",
"-",
"statement",
"corpora",
"as",
"you",
"can",
"for",
"the",
"requested",
"language"
] | efa01126275e9cd3c3a5151a644f1c798a9ec53f | https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/anki.py#L16-L30 |
245,306 | totalgood/nlpia | src/nlpia/anki.py | get_anki_phrases_english | 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
texts = texts.union(set(phrases))
if limit and len(texts) >= limit:
break
return sorted(texts) | python | def get_anki_phrases_english(limit=None):
texts = set()
for lang in ANKI_LANGUAGES:
df = get_data(lang)
phrases = df.eng.str.strip().values
texts = texts.union(set(phrases))
if limit and len(texts) >= limit:
break
return sorted(texts) | [
"def",
"get_anki_phrases_english",
"(",
"limit",
"=",
"None",
")",
":",
"texts",
"=",
"set",
"(",
")",
"for",
"lang",
"in",
"ANKI_LANGUAGES",
":",
"df",
"=",
"get_data",
"(",
"lang",
")",
"phrases",
"=",
"df",
".",
"eng",
".",
"str",
".",
"strip",
"(... | Return all the English phrases in the Anki translation flashcards
>>> len(get_anki_phrases_english(limit=100)) > 700
True | [
"Return",
"all",
"the",
"English",
"phrases",
"in",
"the",
"Anki",
"translation",
"flashcards"
] | efa01126275e9cd3c3a5151a644f1c798a9ec53f | https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/anki.py#L33-L46 |
245,307 | totalgood/nlpia | src/nlpia/anki.py | get_vocab | 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 . punct O 0.0
1 Hey INTJ UH intj O 0.0
2 Man NOUN NN ROOT PERSON I 0.0
3 Mr. PROPN NNP compound O 0.0
4 Tangerine PROPN NNP compound PERSON B 0.0
"""
if isinstance(docs, spacy.tokens.doc.Doc):
return get_vocab([docs])
vocab = set()
for doc in tqdm(docs):
for tok in doc:
vocab.add((tok.text, tok.pos_, tok.tag_, tok.dep_, tok.ent_type_, tok.ent_iob_, tok.sentiment))
# TODO: add ent type info and other flags, e.g. like_url, like_email, etc
return pd.DataFrame(sorted(vocab), columns='word pos tag dep ent_type ent_iob sentiment'.split()) | python | def get_vocab(docs):
if isinstance(docs, spacy.tokens.doc.Doc):
return get_vocab([docs])
vocab = set()
for doc in tqdm(docs):
for tok in doc:
vocab.add((tok.text, tok.pos_, tok.tag_, tok.dep_, tok.ent_type_, tok.ent_iob_, tok.sentiment))
# TODO: add ent type info and other flags, e.g. like_url, like_email, etc
return pd.DataFrame(sorted(vocab), columns='word pos tag dep ent_type ent_iob sentiment'.split()) | [
"def",
"get_vocab",
"(",
"docs",
")",
":",
"if",
"isinstance",
"(",
"docs",
",",
"spacy",
".",
"tokens",
".",
"doc",
".",
"Doc",
")",
":",
"return",
"get_vocab",
"(",
"[",
"docs",
"]",
")",
"vocab",
"=",
"set",
"(",
")",
"for",
"doc",
"in",
"tqdm... | 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.0
1 Hey INTJ UH intj O 0.0
2 Man NOUN NN ROOT PERSON I 0.0
3 Mr. PROPN NNP compound O 0.0
4 Tangerine PROPN NNP compound PERSON B 0.0 | [
"Build",
"a",
"DataFrame",
"containing",
"all",
"the",
"words",
"in",
"the",
"docs",
"provided",
"along",
"with",
"their",
"POS",
"tags",
"etc"
] | efa01126275e9cd3c3a5151a644f1c798a9ec53f | https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/anki.py#L49-L70 |
245,308 | totalgood/nlpia | src/nlpia/anki.py | get_word_vectors | 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 in variations:
if w in wv:
vectors[i, :] = wv[w]
if not np.sum(np.abs(vectors[i])):
logger.warning('Unable to find {}, {}, or {} in word2vec.'.format(*variations))
return vectors | python | def get_word_vectors(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 in variations:
if w in wv:
vectors[i, :] = wv[w]
if not np.sum(np.abs(vectors[i])):
logger.warning('Unable to find {}, {}, or {} in word2vec.'.format(*variations))
return vectors | [
"def",
"get_word_vectors",
"(",
"vocab",
")",
":",
"wv",
"=",
"get_data",
"(",
"'word2vec'",
")",
"vectors",
"=",
"np",
".",
"array",
"(",
"len",
"(",
"vocab",
")",
",",
"len",
"(",
"wv",
"[",
"'the'",
"]",
")",
")",
"for",
"i",
",",
"tok",
"in",... | Create a word2vec embedding matrix for all the words in the vocab | [
"Create",
"a",
"word2vec",
"embedding",
"matrix",
"for",
"all",
"the",
"words",
"in",
"the",
"vocab"
] | efa01126275e9cd3c3a5151a644f1c798a9ec53f | https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/anki.py#L73-L85 |
245,309 | totalgood/nlpia | src/nlpia/anki.py | get_anki_vocab | 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, limit=limit)
docs = nlp(texts, lang=lang)
vocab = get_vocab(docs)
vocab['vector'] = get_word_vectors(vocab) # TODO: turn this into a KeyedVectors object
if filename:
vocab.to_csv(os.path.join(BIGDATA_PATH, filename))
return vocab | python | def get_anki_vocab(lang=['eng'], limit=None, filename='anki_en_vocabulary.csv'):
texts = get_anki_phrases(lang=lang, limit=limit)
docs = nlp(texts, lang=lang)
vocab = get_vocab(docs)
vocab['vector'] = get_word_vectors(vocab) # TODO: turn this into a KeyedVectors object
if filename:
vocab.to_csv(os.path.join(BIGDATA_PATH, filename))
return vocab | [
"def",
"get_anki_vocab",
"(",
"lang",
"=",
"[",
"'eng'",
"]",
",",
"limit",
"=",
"None",
",",
"filename",
"=",
"'anki_en_vocabulary.csv'",
")",
":",
"texts",
"=",
"get_anki_phrases",
"(",
"lang",
"=",
"lang",
",",
"limit",
"=",
"limit",
")",
"docs",
"=",... | 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 | [
"Get",
"all",
"the",
"vocab",
"words",
"+",
"tags",
"+",
"wordvectors",
"for",
"the",
"tokens",
"in",
"the",
"Anki",
"translation",
"corpus"
] | efa01126275e9cd3c3a5151a644f1c798a9ec53f | https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/anki.py#L88-L99 |
245,310 | totalgood/nlpia | src/nlpia/scripts/lsa_tweets.py | lsa_twitter | 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 None:
cased_tokens = ('PyConOpenSpaces PyCon PyCon2017 PyCon2018 PyCon2016 PyCon2015 OpenSpace PyconTutorial ' +
'NLP NaturalLanguageProcessing NLPInAction NaturalLanguageProcessingInAction NLPIA Twote Twip'
).split()
cased_tokens += [s + 's' for s in cased_tokens]
cased_tokens += 'TotalGood TotalGoods HobsonLane Hob Hobs TotalGood.com ' \
'www.TotalGood.com http://www.TotalGood.com https://www.TotalGood.com'.split()
allcase_tokens = cased_tokens + [s.lower() for s in cased_tokens]
allcase_tokens += [s.title() for s in cased_tokens]
allcase_tokens += [s.upper() for s in cased_tokens]
KEEP_TOKENS = allcase_tokens + ['#' + s for s in allcase_tokens]
# takes 15 minutes and 10GB of RAM for 500k tweets if you keep all 20M unique tokens/names URLs
vocab_path = os.path.join(BIGDATA_PATH, 'vocab939370.pkl')
if os.path.isfile(vocab_path):
print('Loading vocab: {} ...'.format(vocab_path))
vocab = Dictionary.load(vocab_path)
print(' len(vocab) loaded: {}'.format(len(vocab.dfs)))
else:
tweets_path = os.path.join(BIGDATA_PATH, 'tweets.csv.gz')
print('Loading tweets: {} ...'.format(tweets_path))
tweets = read_csv(tweets_path)
tweets = pd.np.array(tweets.text.str.split())
with gzip.open(os.path.join(BIGDATA_PATH, 'tweets.txt.gz'), 'w') as f:
for tokens in tweets:
f.write((' '.join(tokens) + '\n').encode('utf-8'))
# tweets['text'] = tweets.text.apply(lambda s: eval(s).decode('utf-8'))
# tweets['user'] = tweets.user.apply(lambda s: eval(s).decode('utf-8'))
# tweets.to_csv('tweets.csv.gz', compression='gzip')
print('Computing vocab from {} tweets...'.format(len(tweets)))
vocab = Dictionary(tweets, no_below=NO_BELOW, no_above=NO_ABOVE, keep_tokens=set(KEEP_TOKENS))
vocab.filter_extremes(no_below=NO_BELOW, no_above=NO_ABOVE, keep_n=KEEP_N, keep_tokens=set(KEEP_TOKENS))
print(' len(vocab) after filtering: {}'.format(len(vocab.dfs)))
# no time at all, just a bookeeping step, doesn't actually compute anything
tfidf = TfidfModel(id2word=vocab, dictionary=vocab)
tfidf.save(os.path.join(BIGDATA_PATH, 'tfidf{}.pkl'.format(len(vocab.dfs))))
tweets = [vocab.doc2bow(tw) for tw in tweets]
json.dump(tweets, gzip.open(os.path.join(BIGDATA_PATH, 'tweet_bows.json.gz'), 'w'))
gc.collect()
# LSA is more useful name than LSA
lsa = LsiModel(tfidf[tweets], num_topics=200, id2word=vocab, extra_samples=100, power_iters=2)
return lsa | python | def lsa_twitter(cased_tokens):
# Only 5 of these tokens are saved for a no_below=2 filter:
# PyCons NLPS #PyCon2016 #NaturalLanguageProcessing #naturallanguageprocessing
if cased_tokens is None:
cased_tokens = ('PyConOpenSpaces PyCon PyCon2017 PyCon2018 PyCon2016 PyCon2015 OpenSpace PyconTutorial ' +
'NLP NaturalLanguageProcessing NLPInAction NaturalLanguageProcessingInAction NLPIA Twote Twip'
).split()
cased_tokens += [s + 's' for s in cased_tokens]
cased_tokens += 'TotalGood TotalGoods HobsonLane Hob Hobs TotalGood.com ' \
'www.TotalGood.com http://www.TotalGood.com https://www.TotalGood.com'.split()
allcase_tokens = cased_tokens + [s.lower() for s in cased_tokens]
allcase_tokens += [s.title() for s in cased_tokens]
allcase_tokens += [s.upper() for s in cased_tokens]
KEEP_TOKENS = allcase_tokens + ['#' + s for s in allcase_tokens]
# takes 15 minutes and 10GB of RAM for 500k tweets if you keep all 20M unique tokens/names URLs
vocab_path = os.path.join(BIGDATA_PATH, 'vocab939370.pkl')
if os.path.isfile(vocab_path):
print('Loading vocab: {} ...'.format(vocab_path))
vocab = Dictionary.load(vocab_path)
print(' len(vocab) loaded: {}'.format(len(vocab.dfs)))
else:
tweets_path = os.path.join(BIGDATA_PATH, 'tweets.csv.gz')
print('Loading tweets: {} ...'.format(tweets_path))
tweets = read_csv(tweets_path)
tweets = pd.np.array(tweets.text.str.split())
with gzip.open(os.path.join(BIGDATA_PATH, 'tweets.txt.gz'), 'w') as f:
for tokens in tweets:
f.write((' '.join(tokens) + '\n').encode('utf-8'))
# tweets['text'] = tweets.text.apply(lambda s: eval(s).decode('utf-8'))
# tweets['user'] = tweets.user.apply(lambda s: eval(s).decode('utf-8'))
# tweets.to_csv('tweets.csv.gz', compression='gzip')
print('Computing vocab from {} tweets...'.format(len(tweets)))
vocab = Dictionary(tweets, no_below=NO_BELOW, no_above=NO_ABOVE, keep_tokens=set(KEEP_TOKENS))
vocab.filter_extremes(no_below=NO_BELOW, no_above=NO_ABOVE, keep_n=KEEP_N, keep_tokens=set(KEEP_TOKENS))
print(' len(vocab) after filtering: {}'.format(len(vocab.dfs)))
# no time at all, just a bookeeping step, doesn't actually compute anything
tfidf = TfidfModel(id2word=vocab, dictionary=vocab)
tfidf.save(os.path.join(BIGDATA_PATH, 'tfidf{}.pkl'.format(len(vocab.dfs))))
tweets = [vocab.doc2bow(tw) for tw in tweets]
json.dump(tweets, gzip.open(os.path.join(BIGDATA_PATH, 'tweet_bows.json.gz'), 'w'))
gc.collect()
# LSA is more useful name than LSA
lsa = LsiModel(tfidf[tweets], num_topics=200, id2word=vocab, extra_samples=100, power_iters=2)
return lsa | [
"def",
"lsa_twitter",
"(",
"cased_tokens",
")",
":",
"# Only 5 of these tokens are saved for a no_below=2 filter:",
"# PyCons NLPS #PyCon2016 #NaturalLanguageProcessing #naturallanguageprocessing",
"if",
"cased_tokens",
"is",
"None",
":",
"cased_tokens",
"=",
"(",
"'PyConOpenSpaces... | Latent Sentiment Analyis on random sampling of twitter search results for words listed in cased_tokens | [
"Latent",
"Sentiment",
"Analyis",
"on",
"random",
"sampling",
"of",
"twitter",
"search",
"results",
"for",
"words",
"listed",
"in",
"cased_tokens"
] | efa01126275e9cd3c3a5151a644f1c798a9ec53f | https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/scripts/lsa_tweets.py#L18-L72 |
245,311 | totalgood/nlpia | src/nlpia/futil.py | wc | 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)
7037
"""
tqdm_prog = tqdm if verbose else no_tqdm
with ensure_open(f, mode='r') as fin:
for i, line in tqdm_prog(enumerate(fin)):
if nrows is not None and i >= nrows - 1:
break
# fin.seek(0)
return i + 1 | python | 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)
7037
"""
tqdm_prog = tqdm if verbose else no_tqdm
with ensure_open(f, mode='r') as fin:
for i, line in tqdm_prog(enumerate(fin)):
if nrows is not None and i >= nrows - 1:
break
# fin.seek(0)
return i + 1 | [
"def",
"wc",
"(",
"f",
",",
"verbose",
"=",
"False",
",",
"nrows",
"=",
"None",
")",
":",
"tqdm_prog",
"=",
"tqdm",
"if",
"verbose",
"else",
"no_tqdm",
"with",
"ensure_open",
"(",
"f",
",",
"mode",
"=",
"'r'",
")",
"as",
"fin",
":",
"for",
"i",
"... | 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 | [
"r",
"Count",
"lines",
"in",
"a",
"text",
"file"
] | efa01126275e9cd3c3a5151a644f1c798a9ec53f | https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/futil.py#L36-L54 |
245,312 | totalgood/nlpia | src/nlpia/futil.py | normalize_filepath | 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.bin.gz'
"""
filename = os.path.basename(filepath)
dirpath = filepath[:-len(filename)]
cre_controlspace = re.compile(r'[\t\r\n\f]+')
new_filename = cre_controlspace.sub('', filename)
if not new_filename == filename:
logger.warning('Stripping whitespace from filename: {} => {}'.format(
repr(filename), repr(new_filename)))
filename = new_filename
filename = filename.lower()
filename = normalize_ext(filename)
if dirpath:
dirpath = dirpath[:-1] # get rid of the trailing os.path.sep
return os.path.join(dirpath, filename)
return filename | python | 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.bin.gz'
"""
filename = os.path.basename(filepath)
dirpath = filepath[:-len(filename)]
cre_controlspace = re.compile(r'[\t\r\n\f]+')
new_filename = cre_controlspace.sub('', filename)
if not new_filename == filename:
logger.warning('Stripping whitespace from filename: {} => {}'.format(
repr(filename), repr(new_filename)))
filename = new_filename
filename = filename.lower()
filename = normalize_ext(filename)
if dirpath:
dirpath = dirpath[:-1] # get rid of the trailing os.path.sep
return os.path.join(dirpath, filename)
return filename | [
"def",
"normalize_filepath",
"(",
"filepath",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"filepath",
")",
"dirpath",
"=",
"filepath",
"[",
":",
"-",
"len",
"(",
"filename",
")",
"]",
"cre_controlspace",
"=",
"re",
".",
"compile",... | 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' | [
"r",
"Lowercase",
"the",
"filename",
"and",
"ext",
"expanding",
"extensions",
"like",
".",
"tgz",
"to",
".",
"tar",
".",
"gz",
"."
] | efa01126275e9cd3c3a5151a644f1c798a9ec53f | https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/futil.py#L278-L299 |
245,313 | totalgood/nlpia | src/nlpia/futil.py | find_filepath | 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_filepath(os.path.join(DATA_PATH, 'iq_test.csv'))
True
>>> p[-len('iq_test.csv'):]
'iq_test.csv'
>>> find_filepath('exponentially-crazy-filename-2.718281828459045.nonexistent')
False
"""
if os.path.isfile(filename):
return filename
for basedir in basepaths:
fullpath = expand_filepath(os.path.join(basedir, filename))
if os.path.isfile(fullpath):
return fullpath
return False | python | def find_filepath(
filename,
basepaths=(os.path.curdir, DATA_PATH, BIGDATA_PATH, BASE_DIR, '~', '~/Downloads', os.path.join('/', 'tmp'), '..')):
if os.path.isfile(filename):
return filename
for basedir in basepaths:
fullpath = expand_filepath(os.path.join(basedir, filename))
if os.path.isfile(fullpath):
return fullpath
return False | [
"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_filepath(os.path.join(DATA_PATH, 'iq_test.csv'))
True
>>> p[-len('iq_test.csv'):]
'iq_test.csv'
>>> find_filepath('exponentially-crazy-filename-2.718281828459045.nonexistent')
False | [
"Given",
"a",
"filename",
"or",
"path",
"see",
"if",
"it",
"exists",
"in",
"any",
"of",
"the",
"common",
"places",
"datafiles",
"might",
"be"
] | efa01126275e9cd3c3a5151a644f1c798a9ec53f | https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/futil.py#L302-L321 |
245,314 | neo4j/neo4j-python-driver | neo4j/__init__.py | Driver.close | 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 | python | def close(self):
if not self._closed:
self._closed = True
if self._pool is not None:
self._pool.close()
self._pool = None | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_closed",
":",
"self",
".",
"_closed",
"=",
"True",
"if",
"self",
".",
"_pool",
"is",
"not",
"None",
":",
"self",
".",
"_pool",
".",
"close",
"(",
")",
"self",
".",
"_pool",
"=",
... | Shut down, closing any open connections in the pool. | [
"Shut",
"down",
"closing",
"any",
"open",
"connections",
"in",
"the",
"pool",
"."
] | 0c641e826765e86ff5454dae57c99521db8ca45c | https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/__init__.py#L163-L170 |
245,315 | neo4j/neo4j-python-driver | neo4j/types/spatial.py | hydrate_point | 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 KeyError:
point = Point(coordinates)
point.srid = srid
return point
else:
if len(coordinates) != dim:
raise ValueError("SRID %d requires %d coordinates (%d provided)" % (srid, dim, len(coordinates)))
return point_class(coordinates) | python | def hydrate_point(srid, *coordinates):
try:
point_class, dim = __srid_table[srid]
except KeyError:
point = Point(coordinates)
point.srid = srid
return point
else:
if len(coordinates) != dim:
raise ValueError("SRID %d requires %d coordinates (%d provided)" % (srid, dim, len(coordinates)))
return point_class(coordinates) | [
"def",
"hydrate_point",
"(",
"srid",
",",
"*",
"coordinates",
")",
":",
"try",
":",
"point_class",
",",
"dim",
"=",
"__srid_table",
"[",
"srid",
"]",
"except",
"KeyError",
":",
"point",
"=",
"Point",
"(",
"coordinates",
")",
"point",
".",
"srid",
"=",
... | 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. | [
"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",
... | 0c641e826765e86ff5454dae57c99521db8ca45c | https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/types/spatial.py#L104-L119 |
245,316 | neo4j/neo4j-python-driver | neo4j/types/spatial.py | dehydrate_point | 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("Cannot dehydrate Point with %d dimensions" % dim) | python | def dehydrate_point(value):
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("Cannot dehydrate Point with %d dimensions" % dim) | [
"def",
"dehydrate_point",
"(",
"value",
")",
":",
"dim",
"=",
"len",
"(",
"value",
")",
"if",
"dim",
"==",
"2",
":",
"return",
"Structure",
"(",
"b\"X\"",
",",
"value",
".",
"srid",
",",
"*",
"value",
")",
"elif",
"dim",
"==",
"3",
":",
"return",
... | Dehydrator for Point data.
:param value:
:type value: Point
:return: | [
"Dehydrator",
"for",
"Point",
"data",
"."
] | 0c641e826765e86ff5454dae57c99521db8ca45c | https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/types/spatial.py#L122-L135 |
245,317 | neo4j/neo4j-python-driver | neo4j/types/__init__.py | PackStreamDehydrator.dehydrate | 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 is None:
return None
elif isinstance(obj, bool):
return obj
elif isinstance(obj, int):
if INT64_MIN <= obj <= INT64_MAX:
return obj
raise ValueError("Integer out of bounds (64-bit signed integer values only)")
elif isinstance(obj, float):
return obj
elif isinstance(obj, str):
return obj
elif isinstance(obj, (bytes, bytearray)): # order is important here - bytes must be checked after string
if self.supports_bytes:
return obj
else:
raise TypeError("This PackSteam channel does not support BYTES (consider upgrading to Neo4j 3.2+)")
elif isinstance(obj, (list, map_type)):
return list(map(dehydrate_, obj))
elif isinstance(obj, dict):
if any(not isinstance(key, str) for key in obj.keys()):
raise TypeError("Non-string dictionary keys are not supported")
return {key: dehydrate_(value) for key, value in obj.items()}
else:
raise TypeError(obj)
return tuple(map(dehydrate_, values)) | python | def dehydrate(self, values):
def dehydrate_(obj):
try:
f = self.dehydration_functions[type(obj)]
except KeyError:
pass
else:
return f(obj)
if obj is None:
return None
elif isinstance(obj, bool):
return obj
elif isinstance(obj, int):
if INT64_MIN <= obj <= INT64_MAX:
return obj
raise ValueError("Integer out of bounds (64-bit signed integer values only)")
elif isinstance(obj, float):
return obj
elif isinstance(obj, str):
return obj
elif isinstance(obj, (bytes, bytearray)): # order is important here - bytes must be checked after string
if self.supports_bytes:
return obj
else:
raise TypeError("This PackSteam channel does not support BYTES (consider upgrading to Neo4j 3.2+)")
elif isinstance(obj, (list, map_type)):
return list(map(dehydrate_, obj))
elif isinstance(obj, dict):
if any(not isinstance(key, str) for key in obj.keys()):
raise TypeError("Non-string dictionary keys are not supported")
return {key: dehydrate_(value) for key, value in obj.items()}
else:
raise TypeError(obj)
return tuple(map(dehydrate_, values)) | [
"def",
"dehydrate",
"(",
"self",
",",
"values",
")",
":",
"def",
"dehydrate_",
"(",
"obj",
")",
":",
"try",
":",
"f",
"=",
"self",
".",
"dehydration_functions",
"[",
"type",
"(",
"obj",
")",
"]",
"except",
"KeyError",
":",
"pass",
"else",
":",
"retur... | Convert native values into PackStream values. | [
"Convert",
"native",
"values",
"into",
"PackStream",
"values",
"."
] | 0c641e826765e86ff5454dae57c99521db8ca45c | https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/types/__init__.py#L97-L134 |
245,318 | neo4j/neo4j-python-driver | neo4j/types/__init__.py | Record.get | 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 default
if 0 <= index < len(self):
return super(Record, self).__getitem__(index)
else:
return default | python | def get(self, key, default=None):
try:
index = self.__keys.index(str(key))
except ValueError:
return default
if 0 <= index < len(self):
return super(Record, self).__getitem__(index)
else:
return default | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"try",
":",
"index",
"=",
"self",
".",
"__keys",
".",
"index",
"(",
"str",
"(",
"key",
")",
")",
"except",
"ValueError",
":",
"return",
"default",
"if",
"0",
"<=",
"ind... | Obtain a value from the record by key, returning a default
value if the key does not exist.
:param key:
:param default:
:return: | [
"Obtain",
"a",
"value",
"from",
"the",
"record",
"by",
"key",
"returning",
"a",
"default",
"value",
"if",
"the",
"key",
"does",
"not",
"exist",
"."
] | 0c641e826765e86ff5454dae57c99521db8ca45c | https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/types/__init__.py#L202-L217 |
245,319 | neo4j/neo4j-python-driver | neo4j/types/__init__.py | Record.index | 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:
return self.__keys.index(key)
except ValueError:
raise KeyError(key)
else:
raise TypeError(key) | python | def index(self, key):
if isinstance(key, int):
if 0 <= key < len(self.__keys):
return key
raise IndexError(key)
elif isinstance(key, str):
try:
return self.__keys.index(key)
except ValueError:
raise KeyError(key)
else:
raise TypeError(key) | [
"def",
"index",
"(",
"self",
",",
"key",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"int",
")",
":",
"if",
"0",
"<=",
"key",
"<",
"len",
"(",
"self",
".",
"__keys",
")",
":",
"return",
"key",
"raise",
"IndexError",
"(",
"key",
")",
"elif",
... | Return the index of the given item.
:param key:
:return: | [
"Return",
"the",
"index",
"of",
"the",
"given",
"item",
"."
] | 0c641e826765e86ff5454dae57c99521db8ca45c | https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/types/__init__.py#L219-L235 |
245,320 | neo4j/neo4j-python-driver | neo4j/types/__init__.py | Record.value | 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:
"""
try:
index = self.index(key)
except (IndexError, KeyError):
return default
else:
return self[index] | python | def value(self, key=0, default=None):
try:
index = self.index(key)
except (IndexError, KeyError):
return default
else:
return self[index] | [
"def",
"value",
"(",
"self",
",",
"key",
"=",
"0",
",",
"default",
"=",
"None",
")",
":",
"try",
":",
"index",
"=",
"self",
".",
"index",
"(",
"key",
")",
"except",
"(",
"IndexError",
",",
"KeyError",
")",
":",
"return",
"default",
"else",
":",
"... | 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: | [
"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",
"... | 0c641e826765e86ff5454dae57c99521db8ca45c | https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/types/__init__.py#L237-L251 |
245,321 | neo4j/neo4j-python-driver | neo4j/types/__init__.py | Record.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
"""
if keys:
d = []
for key in keys:
try:
i = self.index(key)
except KeyError:
d.append(None)
else:
d.append(self[i])
return d
return list(self) | python | def values(self, *keys):
if keys:
d = []
for key in keys:
try:
i = self.index(key)
except KeyError:
d.append(None)
else:
d.append(self[i])
return d
return list(self) | [
"def",
"values",
"(",
"self",
",",
"*",
"keys",
")",
":",
"if",
"keys",
":",
"d",
"=",
"[",
"]",
"for",
"key",
"in",
"keys",
":",
"try",
":",
"i",
"=",
"self",
".",
"index",
"(",
"key",
")",
"except",
"KeyError",
":",
"d",
".",
"append",
"(",... | 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",
"values",
"of",
"the",
"record",
"optionally",
"filtering",
"to",
"include",
"only",
"certain",
"values",
"by",
"index",
"or",
"key",
"."
] | 0c641e826765e86ff5454dae57c99521db8ca45c | https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/types/__init__.py#L260-L278 |
245,322 | neo4j/neo4j-python-driver | neo4j/types/__init__.py | Record.items | 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((key, None))
else:
d.append((self.__keys[i], self[i]))
return d
return list((self.__keys[i], super(Record, self).__getitem__(i)) for i in range(len(self))) | python | def items(self, *keys):
if keys:
d = []
for key in keys:
try:
i = self.index(key)
except KeyError:
d.append((key, None))
else:
d.append((self.__keys[i], self[i]))
return d
return list((self.__keys[i], super(Record, self).__getitem__(i)) for i in range(len(self))) | [
"def",
"items",
"(",
"self",
",",
"*",
"keys",
")",
":",
"if",
"keys",
":",
"d",
"=",
"[",
"]",
"for",
"key",
"in",
"keys",
":",
"try",
":",
"i",
"=",
"self",
".",
"index",
"(",
"key",
")",
"except",
"KeyError",
":",
"d",
".",
"append",
"(",
... | Return the fields of the record as a list of key and value tuples
:return: | [
"Return",
"the",
"fields",
"of",
"the",
"record",
"as",
"a",
"list",
"of",
"key",
"and",
"value",
"tuples"
] | 0c641e826765e86ff5454dae57c99521db8ca45c | https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/types/__init__.py#L280-L295 |
245,323 | neo4j/neo4j-python-driver | neo4j/blocking.py | _make_plan | 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(child) for child in plan_dict.get("children", [])]
if "dbHits" in plan_dict or "rows" in plan_dict:
db_hits = plan_dict.get("dbHits", 0)
rows = plan_dict.get("rows", 0)
return ProfiledPlan(operator_type, identifiers, arguments, children, db_hits, rows)
else:
return Plan(operator_type, identifiers, arguments, children) | python | def _make_plan(plan_dict):
operator_type = plan_dict["operatorType"]
identifiers = plan_dict.get("identifiers", [])
arguments = plan_dict.get("args", [])
children = [_make_plan(child) for child in plan_dict.get("children", [])]
if "dbHits" in plan_dict or "rows" in plan_dict:
db_hits = plan_dict.get("dbHits", 0)
rows = plan_dict.get("rows", 0)
return ProfiledPlan(operator_type, identifiers, arguments, children, db_hits, rows)
else:
return Plan(operator_type, identifiers, arguments, children) | [
"def",
"_make_plan",
"(",
"plan_dict",
")",
":",
"operator_type",
"=",
"plan_dict",
"[",
"\"operatorType\"",
"]",
"identifiers",
"=",
"plan_dict",
".",
"get",
"(",
"\"identifiers\"",
",",
"[",
"]",
")",
"arguments",
"=",
"plan_dict",
".",
"get",
"(",
"\"args... | Construct a Plan or ProfiledPlan from a dictionary of metadata values.
:param plan_dict:
:return: | [
"Construct",
"a",
"Plan",
"or",
"ProfiledPlan",
"from",
"a",
"dictionary",
"of",
"metadata",
"values",
"."
] | 0c641e826765e86ff5454dae57c99521db8ca45c | https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/blocking.py#L962-L977 |
245,324 | neo4j/neo4j-python-driver | neo4j/blocking.py | unit_of_work | 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):
return tx.run("MATCH (a:Person) RETURN count(a)").single().value()
"""
def wrapper(f):
def wrapped(*args, **kwargs):
return f(*args, **kwargs)
wrapped.metadata = metadata
wrapped.timeout = timeout
return wrapped
return wrapper | python | def unit_of_work(metadata=None, timeout=None):
def wrapper(f):
def wrapped(*args, **kwargs):
return f(*args, **kwargs)
wrapped.metadata = metadata
wrapped.timeout = timeout
return wrapped
return wrapper | [
"def",
"unit_of_work",
"(",
"metadata",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"def",
"wrapper",
"(",
"f",
")",
":",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"f",
"(",
"*",
"args",
",",
"*",
... | 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().value() | [
"This",
"function",
"is",
"a",
"decorator",
"for",
"transaction",
"functions",
"that",
"allows",
"extra",
"control",
"over",
"how",
"the",
"transaction",
"is",
"carried",
"out",
"."
] | 0c641e826765e86ff5454dae57c99521db8ca45c | https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/blocking.py#L1007-L1028 |
245,325 | neo4j/neo4j-python-driver | neo4j/blocking.py | Session.close | 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():
try:
self.rollback_transaction()
except (CypherError, TransactionError, SessionError, ConnectionExpired, ServiceUnavailable):
pass
finally:
self._closed = True
self._disconnect(sync=True) | python | def close(self):
from neobolt.exceptions import ConnectionExpired, CypherError, ServiceUnavailable
try:
if self.has_transaction():
try:
self.rollback_transaction()
except (CypherError, TransactionError, SessionError, ConnectionExpired, ServiceUnavailable):
pass
finally:
self._closed = True
self._disconnect(sync=True) | [
"def",
"close",
"(",
"self",
")",
":",
"from",
"neobolt",
".",
"exceptions",
"import",
"ConnectionExpired",
",",
"CypherError",
",",
"ServiceUnavailable",
"try",
":",
"if",
"self",
".",
"has_transaction",
"(",
")",
":",
"try",
":",
"self",
".",
"rollback_tra... | Close the session. This will release any borrowed resources,
such as connections, and will roll back any outstanding transactions. | [
"Close",
"the",
"session",
".",
"This",
"will",
"release",
"any",
"borrowed",
"resources",
"such",
"as",
"connections",
"and",
"will",
"roll",
"back",
"any",
"outstanding",
"transactions",
"."
] | 0c641e826765e86ff5454dae57c99521db8ca45c | https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/blocking.py#L144-L157 |
245,326 | neo4j/neo4j-python-driver | neo4j/blocking.py | Session.run | 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.
If a statement is executed before a previous
:class:`.StatementResult` in the same :class:`.Session` has
been fully consumed, the first result will be fully fetched
and buffered. Note therefore that the generally recommended
pattern of usage is to fully consume one result before
executing a subsequent statement. If two results need to be
consumed in parallel, multiple :class:`.Session` objects
can be used as an alternative to result buffering.
For more usage details, see :meth:`.Transaction.run`.
:param statement: template Cypher statement
:param parameters: dictionary of parameters
:param kwparameters: additional keyword parameters
:returns: :class:`.StatementResult` object
"""
from neobolt.exceptions import ConnectionExpired
self._assert_open()
if not statement:
raise ValueError("Cannot run an empty statement")
if not isinstance(statement, (str, Statement)):
raise TypeError("Statement must be a string or a Statement instance")
if not self._connection:
self._connect()
cx = self._connection
protocol_version = cx.protocol_version
server = cx.server
has_transaction = self.has_transaction()
statement_text = str(statement)
statement_metadata = getattr(statement, "metadata", None)
statement_timeout = getattr(statement, "timeout", None)
parameters = fix_parameters(dict(parameters or {}, **kwparameters), protocol_version,
supports_bytes=server.supports("bytes"))
def fail(_):
self._close_transaction()
hydrant = PackStreamHydrator(protocol_version)
result_metadata = {
"statement": statement_text,
"parameters": parameters,
"server": server,
"protocol_version": protocol_version,
}
run_metadata = {
"metadata": statement_metadata,
"timeout": statement_timeout,
"on_success": result_metadata.update,
"on_failure": fail,
}
def done(summary_metadata):
result_metadata.update(summary_metadata)
bookmark = result_metadata.get("bookmark")
if bookmark:
self._bookmarks_in = tuple([bookmark])
self._bookmark_out = bookmark
self._last_result = result = BoltStatementResult(self, hydrant, result_metadata)
if has_transaction:
if statement_metadata:
raise ValueError("Metadata can only be attached at transaction level")
if statement_timeout:
raise ValueError("Timeouts only apply at transaction level")
else:
run_metadata["bookmarks"] = self._bookmarks_in
cx.run(statement_text, parameters, **run_metadata)
cx.pull_all(
on_records=lambda records: result._records.extend(
hydrant.hydrate_records(result.keys(), records)),
on_success=done,
on_failure=fail,
on_summary=lambda: result.detach(sync=False),
)
if not has_transaction:
try:
self._connection.send()
self._connection.fetch()
except ConnectionExpired as error:
raise SessionExpired(*error.args)
return result | python | def run(self, statement, parameters=None, **kwparameters):
from neobolt.exceptions import ConnectionExpired
self._assert_open()
if not statement:
raise ValueError("Cannot run an empty statement")
if not isinstance(statement, (str, Statement)):
raise TypeError("Statement must be a string or a Statement instance")
if not self._connection:
self._connect()
cx = self._connection
protocol_version = cx.protocol_version
server = cx.server
has_transaction = self.has_transaction()
statement_text = str(statement)
statement_metadata = getattr(statement, "metadata", None)
statement_timeout = getattr(statement, "timeout", None)
parameters = fix_parameters(dict(parameters or {}, **kwparameters), protocol_version,
supports_bytes=server.supports("bytes"))
def fail(_):
self._close_transaction()
hydrant = PackStreamHydrator(protocol_version)
result_metadata = {
"statement": statement_text,
"parameters": parameters,
"server": server,
"protocol_version": protocol_version,
}
run_metadata = {
"metadata": statement_metadata,
"timeout": statement_timeout,
"on_success": result_metadata.update,
"on_failure": fail,
}
def done(summary_metadata):
result_metadata.update(summary_metadata)
bookmark = result_metadata.get("bookmark")
if bookmark:
self._bookmarks_in = tuple([bookmark])
self._bookmark_out = bookmark
self._last_result = result = BoltStatementResult(self, hydrant, result_metadata)
if has_transaction:
if statement_metadata:
raise ValueError("Metadata can only be attached at transaction level")
if statement_timeout:
raise ValueError("Timeouts only apply at transaction level")
else:
run_metadata["bookmarks"] = self._bookmarks_in
cx.run(statement_text, parameters, **run_metadata)
cx.pull_all(
on_records=lambda records: result._records.extend(
hydrant.hydrate_records(result.keys(), records)),
on_success=done,
on_failure=fail,
on_summary=lambda: result.detach(sync=False),
)
if not has_transaction:
try:
self._connection.send()
self._connection.fetch()
except ConnectionExpired as error:
raise SessionExpired(*error.args)
return result | [
"def",
"run",
"(",
"self",
",",
"statement",
",",
"parameters",
"=",
"None",
",",
"*",
"*",
"kwparameters",
")",
":",
"from",
"neobolt",
".",
"exceptions",
"import",
"ConnectionExpired",
"self",
".",
"_assert_open",
"(",
")",
"if",
"not",
"statement",
":",... | 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:`.StatementResult` in the same :class:`.Session` has
been fully consumed, the first result will be fully fetched
and buffered. Note therefore that the generally recommended
pattern of usage is to fully consume one result before
executing a subsequent statement. If two results need to be
consumed in parallel, multiple :class:`.Session` objects
can be used as an alternative to result buffering.
For more usage details, see :meth:`.Transaction.run`.
:param statement: template Cypher statement
:param parameters: dictionary of parameters
:param kwparameters: additional keyword parameters
:returns: :class:`.StatementResult` object | [
"Run",
"a",
"Cypher",
"statement",
"within",
"an",
"auto",
"-",
"commit",
"transaction",
"."
] | 0c641e826765e86ff5454dae57c99521db8ca45c | https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/blocking.py#L166-L261 |
245,327 | neo4j/neo4j-python-driver | neo4j/blocking.py | Session.send | 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) | python | def send(self):
from neobolt.exceptions import ConnectionExpired
if self._connection:
try:
self._connection.send()
except ConnectionExpired as error:
raise SessionExpired(*error.args) | [
"def",
"send",
"(",
"self",
")",
":",
"from",
"neobolt",
".",
"exceptions",
"import",
"ConnectionExpired",
"if",
"self",
".",
"_connection",
":",
"try",
":",
"self",
".",
"_connection",
".",
"send",
"(",
")",
"except",
"ConnectionExpired",
"as",
"error",
"... | Send all outstanding requests. | [
"Send",
"all",
"outstanding",
"requests",
"."
] | 0c641e826765e86ff5454dae57c99521db8ca45c | https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/blocking.py#L263-L271 |
245,328 | neo4j/neo4j-python-driver | neo4j/blocking.py | Session.fetch | 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 ConnectionExpired as error:
raise SessionExpired(*error.args)
else:
return detail_count
return 0 | python | def fetch(self):
from neobolt.exceptions import ConnectionExpired
if self._connection:
try:
detail_count, _ = self._connection.fetch()
except ConnectionExpired as error:
raise SessionExpired(*error.args)
else:
return detail_count
return 0 | [
"def",
"fetch",
"(",
"self",
")",
":",
"from",
"neobolt",
".",
"exceptions",
"import",
"ConnectionExpired",
"if",
"self",
".",
"_connection",
":",
"try",
":",
"detail_count",
",",
"_",
"=",
"self",
".",
"_connection",
".",
"fetch",
"(",
")",
"except",
"C... | Attempt to fetch at least one more record.
:returns: number of records fetched | [
"Attempt",
"to",
"fetch",
"at",
"least",
"one",
"more",
"record",
"."
] | 0c641e826765e86ff5454dae57c99521db8ca45c | https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/blocking.py#L273-L286 |
245,329 | neo4j/neo4j-python-driver | neo4j/blocking.py | Session.detach | 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()
fetch = self.fetch
while result.attached():
count += fetch()
if self._last_result is result:
self._last_result = None
if not self.has_transaction():
self._disconnect(sync=False)
result._session = None
return count | python | def detach(self, result, sync=True):
count = 0
if sync and result.attached():
self.send()
fetch = self.fetch
while result.attached():
count += fetch()
if self._last_result is result:
self._last_result = None
if not self.has_transaction():
self._disconnect(sync=False)
result._session = None
return count | [
"def",
"detach",
"(",
"self",
",",
"result",
",",
"sync",
"=",
"True",
")",
":",
"count",
"=",
"0",
"if",
"sync",
"and",
"result",
".",
"attached",
"(",
")",
":",
"self",
".",
"send",
"(",
")",
"fetch",
"=",
"self",
".",
"fetch",
"while",
"result... | Detach a result from this session by fetching and buffering any
remaining records.
:param result:
:param sync:
:returns: number of records fetched | [
"Detach",
"a",
"result",
"from",
"this",
"session",
"by",
"fetching",
"and",
"buffering",
"any",
"remaining",
"records",
"."
] | 0c641e826765e86ff5454dae57c99521db8ca45c | https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/blocking.py#L303-L325 |
245,330 | neo4j/neo4j-python-driver | neo4j/blocking.py | Transaction.run | 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` method.
Cypher is typically expressed as a statement template plus a
set of named parameters. In Python, parameters may be expressed
through a dictionary of parameters, through individual parameter
arguments, or as a mixture of both. For example, the `run`
statements below are all equivalent::
>>> statement = "CREATE (a:Person {name:{name}, age:{age}})"
>>> tx.run(statement, {"name": "Alice", "age": 33})
>>> tx.run(statement, {"name": "Alice"}, age=33)
>>> tx.run(statement, name="Alice", age=33)
Parameter values can be of any type supported by the Neo4j type
system. In Python, this includes :class:`bool`, :class:`int`,
:class:`str`, :class:`list` and :class:`dict`. Note however that
:class:`list` properties must be homogenous.
:param statement: template Cypher statement
:param parameters: dictionary of parameters
:param kwparameters: additional keyword parameters
:returns: :class:`.StatementResult` object
:raise TransactionError: if the transaction is closed
"""
self._assert_open()
return self.session.run(statement, parameters, **kwparameters) | python | def run(self, statement, parameters=None, **kwparameters):
self._assert_open()
return self.session.run(statement, parameters, **kwparameters) | [
"def",
"run",
"(",
"self",
",",
"statement",
",",
"parameters",
"=",
"None",
",",
"*",
"*",
"kwparameters",
")",
":",
"self",
".",
"_assert_open",
"(",
")",
"return",
"self",
".",
"session",
".",
"run",
"(",
"statement",
",",
"parameters",
",",
"*",
... | 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 a
set of named parameters. In Python, parameters may be expressed
through a dictionary of parameters, through individual parameter
arguments, or as a mixture of both. For example, the `run`
statements below are all equivalent::
>>> statement = "CREATE (a:Person {name:{name}, age:{age}})"
>>> tx.run(statement, {"name": "Alice", "age": 33})
>>> tx.run(statement, {"name": "Alice"}, age=33)
>>> tx.run(statement, name="Alice", age=33)
Parameter values can be of any type supported by the Neo4j type
system. In Python, this includes :class:`bool`, :class:`int`,
:class:`str`, :class:`list` and :class:`dict`. Note however that
:class:`list` properties must be homogenous.
:param statement: template Cypher statement
:param parameters: dictionary of parameters
:param kwparameters: additional keyword parameters
:returns: :class:`.StatementResult` object
:raise TransactionError: if the transaction is closed | [
"Run",
"a",
"Cypher",
"statement",
"within",
"the",
"context",
"of",
"this",
"transaction",
"."
] | 0c641e826765e86ff5454dae57c99521db8ca45c | https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/blocking.py#L497-L527 |
245,331 | neo4j/neo4j-python-driver | neo4j/blocking.py | StatementResult.detach | 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)
else:
return 0 | python | def detach(self, sync=True):
if self.attached():
return self._session.detach(self, sync=sync)
else:
return 0 | [
"def",
"detach",
"(",
"self",
",",
"sync",
"=",
"True",
")",
":",
"if",
"self",
".",
"attached",
"(",
")",
":",
"return",
"self",
".",
"_session",
".",
"detach",
"(",
"self",
",",
"sync",
"=",
"sync",
")",
"else",
":",
"return",
"0"
] | 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 | [
"Detach",
"this",
"result",
"from",
"its",
"parent",
"session",
"by",
"fetching",
"the",
"remainder",
"of",
"this",
"result",
"from",
"the",
"network",
"into",
"the",
"buffer",
"."
] | 0c641e826765e86ff5454dae57c99521db8ca45c | https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/blocking.py#L653-L662 |
245,332 | neo4j/neo4j-python-driver | neo4j/blocking.py | StatementResult.keys | 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 in self._metadata:
self._session.fetch()
return self._metadata.get("fields") | python | def keys(self):
try:
return self._metadata["fields"]
except KeyError:
if self.attached():
self._session.send()
while self.attached() and "fields" not in self._metadata:
self._session.fetch()
return self._metadata.get("fields") | [
"def",
"keys",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_metadata",
"[",
"\"fields\"",
"]",
"except",
"KeyError",
":",
"if",
"self",
".",
"attached",
"(",
")",
":",
"self",
".",
"_session",
".",
"send",
"(",
")",
"while",
"self",
... | The keys for the records in this result.
:returns: tuple of key names | [
"The",
"keys",
"for",
"the",
"records",
"in",
"this",
"result",
"."
] | 0c641e826765e86ff5454dae57c99521db8ca45c | https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/blocking.py#L664-L676 |
245,333 | neo4j/neo4j-python-driver | neo4j/blocking.py | StatementResult.records | 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 attached():
self._session.send()
while attached():
self._session.fetch()
while records:
yield next_record() | python | def records(self):
records = self._records
next_record = records.popleft
while records:
yield next_record()
attached = self.attached
if attached():
self._session.send()
while attached():
self._session.fetch()
while records:
yield next_record() | [
"def",
"records",
"(",
"self",
")",
":",
"records",
"=",
"self",
".",
"_records",
"next_record",
"=",
"records",
".",
"popleft",
"while",
"records",
":",
"yield",
"next_record",
"(",
")",
"attached",
"=",
"self",
".",
"attached",
"if",
"attached",
"(",
"... | Generator for records obtained from this result.
:yields: iterable of :class:`.Record` objects | [
"Generator",
"for",
"records",
"obtained",
"from",
"this",
"result",
"."
] | 0c641e826765e86ff5454dae57c99521db8ca45c | https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/blocking.py#L678-L693 |
245,334 | neo4j/neo4j-python-driver | neo4j/blocking.py | StatementResult.summary | 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 self._summary | python | def summary(self):
self.detach()
if self._summary is None:
self._summary = BoltStatementResultSummary(**self._metadata)
return self._summary | [
"def",
"summary",
"(",
"self",
")",
":",
"self",
".",
"detach",
"(",
")",
"if",
"self",
".",
"_summary",
"is",
"None",
":",
"self",
".",
"_summary",
"=",
"BoltStatementResultSummary",
"(",
"*",
"*",
"self",
".",
"_metadata",
")",
"return",
"self",
".",... | Obtain the summary of this result, buffering any remaining records.
:returns: The :class:`.ResultSummary` for this result | [
"Obtain",
"the",
"summary",
"of",
"this",
"result",
"buffering",
"any",
"remaining",
"records",
"."
] | 0c641e826765e86ff5454dae57c99521db8ca45c | https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/blocking.py#L695-L703 |
245,335 | neo4j/neo4j-python-driver | neo4j/blocking.py | StatementResult.single | 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 record is available
"""
records = list(self)
size = len(records)
if size == 0:
return None
if size != 1:
warn("Expected a result with a single record, but this result contains %d" % size)
return records[0] | python | def single(self):
records = list(self)
size = len(records)
if size == 0:
return None
if size != 1:
warn("Expected a result with a single record, but this result contains %d" % size)
return records[0] | [
"def",
"single",
"(",
"self",
")",
":",
"records",
"=",
"list",
"(",
"self",
")",
"size",
"=",
"len",
"(",
"records",
")",
"if",
"size",
"==",
"0",
":",
"return",
"None",
"if",
"size",
"!=",
"1",
":",
"warn",
"(",
"\"Expected a result with a single rec... | 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 | [
"Obtain",
"the",
"next",
"and",
"only",
"remaining",
"record",
"from",
"this",
"result",
"."
] | 0c641e826765e86ff5454dae57c99521db8ca45c | https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/blocking.py#L715-L730 |
245,336 | neo4j/neo4j-python-driver | neo4j/blocking.py | StatementResult.peek | 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 records[0]
if not self.attached():
return None
if self.attached():
self._session.send()
while self.attached() and not records:
self._session.fetch()
if records:
return records[0]
return None | python | def peek(self):
records = self._records
if records:
return records[0]
if not self.attached():
return None
if self.attached():
self._session.send()
while self.attached() and not records:
self._session.fetch()
if records:
return records[0]
return None | [
"def",
"peek",
"(",
"self",
")",
":",
"records",
"=",
"self",
".",
"_records",
"if",
"records",
":",
"return",
"records",
"[",
"0",
"]",
"if",
"not",
"self",
".",
"attached",
"(",
")",
":",
"return",
"None",
"if",
"self",
".",
"attached",
"(",
")",... | 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 | [
"Obtain",
"the",
"next",
"record",
"from",
"this",
"result",
"without",
"consuming",
"it",
".",
"This",
"leaves",
"the",
"record",
"in",
"the",
"buffer",
"for",
"further",
"processing",
"."
] | 0c641e826765e86ff5454dae57c99521db8ca45c | https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/blocking.py#L732-L749 |
245,337 | neo4j/neo4j-python-driver | neo4j/blocking.py | BoltStatementResult.value | 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 [record.value(item, default) for record in self.records()] | python | def value(self, item=0, default=None):
return [record.value(item, default) for record in self.records()] | [
"def",
"value",
"(",
"self",
",",
"item",
"=",
"0",
",",
"default",
"=",
"None",
")",
":",
"return",
"[",
"record",
".",
"value",
"(",
"item",
",",
"default",
")",
"for",
"record",
"in",
"self",
".",
"records",
"(",
")",
"]"
] | 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",
"the",
"remainder",
"of",
"the",
"result",
"as",
"a",
"list",
"of",
"values",
"."
] | 0c641e826765e86ff5454dae57c99521db8ca45c | https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/blocking.py#L769-L776 |
245,338 | neo4j/neo4j-python-driver | neo4j/pipelining.py | Pipeline.pull | 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_lock.acquire(blocking=False)
if not lock_acquired:
raise PullOrderException()
return self._results_generator() | python | def pull(self):
# 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_lock.acquire(blocking=False)
if not lock_acquired:
raise PullOrderException()
return self._results_generator() | [
"def",
"pull",
"(",
"self",
")",
":",
"# 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_lock",
".",
"acquire",
"(",
"blocking",... | Returns a generator containing the results of the next query in the pipeline | [
"Returns",
"a",
"generator",
"containing",
"the",
"results",
"of",
"the",
"next",
"query",
"in",
"the",
"pipeline"
] | 0c641e826765e86ff5454dae57c99521db8ca45c | https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/pipelining.py#L61-L68 |
245,339 | neo4j/neo4j-python-driver | neo4j/meta.py | deprecated | 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, category=DeprecationWarning, stacklevel=2)
return f(*args, **kwargs)
f_.__name__ = f.__name__
f_.__doc__ = f.__doc__
f_.__dict__.update(f.__dict__)
return f_
return f__ | python | def deprecated(message):
def f__(f):
def f_(*args, **kwargs):
from warnings import warn
warn(message, category=DeprecationWarning, stacklevel=2)
return f(*args, **kwargs)
f_.__name__ = f.__name__
f_.__doc__ = f.__doc__
f_.__dict__.update(f.__dict__)
return f_
return f__ | [
"def",
"deprecated",
"(",
"message",
")",
":",
"def",
"f__",
"(",
"f",
")",
":",
"def",
"f_",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"warnings",
"import",
"warn",
"warn",
"(",
"message",
",",
"category",
"=",
"DeprecationWarning... | Decorator for deprecating functions and methods.
::
@deprecated("'foo' has been deprecated in favour of 'bar'")
def foo(x):
pass | [
"Decorator",
"for",
"deprecating",
"functions",
"and",
"methods",
"."
] | 0c641e826765e86ff5454dae57c99521db8ca45c | https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/meta.py#L27-L46 |
245,340 | neo4j/neo4j-python-driver | neo4j/meta.py | experimental | 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):
from warnings import warn
warn(message, category=ExperimentalWarning, stacklevel=2)
return f(*args, **kwargs)
f_.__name__ = f.__name__
f_.__doc__ = f.__doc__
f_.__dict__.update(f.__dict__)
return f_
return f__ | python | def experimental(message):
def f__(f):
def f_(*args, **kwargs):
from warnings import warn
warn(message, category=ExperimentalWarning, stacklevel=2)
return f(*args, **kwargs)
f_.__name__ = f.__name__
f_.__doc__ = f.__doc__
f_.__dict__.update(f.__dict__)
return f_
return f__ | [
"def",
"experimental",
"(",
"message",
")",
":",
"def",
"f__",
"(",
"f",
")",
":",
"def",
"f_",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"warnings",
"import",
"warn",
"warn",
"(",
"message",
",",
"category",
"=",
"ExperimentalWarn... | 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 | [
"Decorator",
"for",
"tagging",
"experimental",
"functions",
"and",
"methods",
"."
] | 0c641e826765e86ff5454dae57c99521db8ca45c | https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/meta.py#L54-L74 |
245,341 | neo4j/neo4j-python-driver | neo4j/types/temporal.py | hydrate_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(minutes, 60))
seconds = (1000000000 * seconds + nanoseconds) / 1000000000
t = Time(hours, minutes, seconds)
if tz is None:
return t
tz_offset_minutes, tz_offset_seconds = divmod(tz, 60)
zone = FixedOffset(tz_offset_minutes)
return zone.localize(t) | python | def hydrate_time(nanoseconds, tz=None):
seconds, nanoseconds = map(int, divmod(nanoseconds, 1000000000))
minutes, seconds = map(int, divmod(seconds, 60))
hours, minutes = map(int, divmod(minutes, 60))
seconds = (1000000000 * seconds + nanoseconds) / 1000000000
t = Time(hours, minutes, seconds)
if tz is None:
return t
tz_offset_minutes, tz_offset_seconds = divmod(tz, 60)
zone = FixedOffset(tz_offset_minutes)
return zone.localize(t) | [
"def",
"hydrate_time",
"(",
"nanoseconds",
",",
"tz",
"=",
"None",
")",
":",
"seconds",
",",
"nanoseconds",
"=",
"map",
"(",
"int",
",",
"divmod",
"(",
"nanoseconds",
",",
"1000000000",
")",
")",
"minutes",
",",
"seconds",
"=",
"map",
"(",
"int",
",",
... | Hydrator for `Time` and `LocalTime` values.
:param nanoseconds:
:param tz:
:return: Time | [
"Hydrator",
"for",
"Time",
"and",
"LocalTime",
"values",
"."
] | 0c641e826765e86ff5454dae57c99521db8ca45c | https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/types/temporal.py#L61-L77 |
245,342 | neo4j/neo4j-python-driver | neo4j/types/temporal.py | dehydrate_time | 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.minute +
1000000000 * value.second + 1000 * value.microsecond)
else:
raise TypeError("Value must be a neotime.Time or a datetime.time")
if value.tzinfo:
return Structure(b"T", nanoseconds, value.tzinfo.utcoffset(value).seconds)
else:
return Structure(b"t", nanoseconds) | python | def dehydrate_time(value):
if isinstance(value, Time):
nanoseconds = int(value.ticks * 1000000000)
elif isinstance(value, time):
nanoseconds = (3600000000000 * value.hour + 60000000000 * value.minute +
1000000000 * value.second + 1000 * value.microsecond)
else:
raise TypeError("Value must be a neotime.Time or a datetime.time")
if value.tzinfo:
return Structure(b"T", nanoseconds, value.tzinfo.utcoffset(value).seconds)
else:
return Structure(b"t", nanoseconds) | [
"def",
"dehydrate_time",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"Time",
")",
":",
"nanoseconds",
"=",
"int",
"(",
"value",
".",
"ticks",
"*",
"1000000000",
")",
"elif",
"isinstance",
"(",
"value",
",",
"time",
")",
":",
"nanosec... | Dehydrator for `time` values.
:param value:
:type value: Time
:return: | [
"Dehydrator",
"for",
"time",
"values",
"."
] | 0c641e826765e86ff5454dae57c99521db8ca45c | https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/types/temporal.py#L80-L97 |
245,343 | neo4j/neo4j-python-driver | neo4j/types/temporal.py | hydrate_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, hours = map(int, divmod(hours, 24))
seconds = (1000000000 * seconds + nanoseconds) / 1000000000
t = DateTime.combine(Date.from_ordinal(UNIX_EPOCH_DATE_ORDINAL + days), Time(hours, minutes, seconds))
if tz is None:
return t
if isinstance(tz, int):
tz_offset_minutes, tz_offset_seconds = divmod(tz, 60)
zone = FixedOffset(tz_offset_minutes)
else:
zone = timezone(tz)
return zone.localize(t) | python | def hydrate_datetime(seconds, nanoseconds, tz=None):
minutes, seconds = map(int, divmod(seconds, 60))
hours, minutes = map(int, divmod(minutes, 60))
days, hours = map(int, divmod(hours, 24))
seconds = (1000000000 * seconds + nanoseconds) / 1000000000
t = DateTime.combine(Date.from_ordinal(UNIX_EPOCH_DATE_ORDINAL + days), Time(hours, minutes, seconds))
if tz is None:
return t
if isinstance(tz, int):
tz_offset_minutes, tz_offset_seconds = divmod(tz, 60)
zone = FixedOffset(tz_offset_minutes)
else:
zone = timezone(tz)
return zone.localize(t) | [
"def",
"hydrate_datetime",
"(",
"seconds",
",",
"nanoseconds",
",",
"tz",
"=",
"None",
")",
":",
"minutes",
",",
"seconds",
"=",
"map",
"(",
"int",
",",
"divmod",
"(",
"seconds",
",",
"60",
")",
")",
"hours",
",",
"minutes",
"=",
"map",
"(",
"int",
... | Hydrator for `DateTime` and `LocalDateTime` values.
:param seconds:
:param nanoseconds:
:param tz:
:return: datetime | [
"Hydrator",
"for",
"DateTime",
"and",
"LocalDateTime",
"values",
"."
] | 0c641e826765e86ff5454dae57c99521db8ca45c | https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/types/temporal.py#L100-L120 |
245,344 | neo4j/neo4j-python-driver | neo4j/types/temporal.py | dehydrate_datetime | 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)
t = dt.to_clock_time() - zone_epoch.to_clock_time()
return t.seconds, t.nanoseconds
tz = value.tzinfo
if tz is None:
# without time zone
value = utc.localize(value)
seconds, nanoseconds = seconds_and_nanoseconds(value)
return Structure(b"d", seconds, nanoseconds)
elif hasattr(tz, "zone") and tz.zone:
# with named time zone
seconds, nanoseconds = seconds_and_nanoseconds(value)
return Structure(b"f", seconds, nanoseconds, tz.zone)
else:
# with time offset
seconds, nanoseconds = seconds_and_nanoseconds(value)
return Structure(b"F", seconds, nanoseconds, tz.utcoffset(value).seconds) | python | def dehydrate_datetime(value):
def seconds_and_nanoseconds(dt):
if isinstance(dt, datetime):
dt = DateTime.from_native(dt)
zone_epoch = DateTime(1970, 1, 1, tzinfo=dt.tzinfo)
t = dt.to_clock_time() - zone_epoch.to_clock_time()
return t.seconds, t.nanoseconds
tz = value.tzinfo
if tz is None:
# without time zone
value = utc.localize(value)
seconds, nanoseconds = seconds_and_nanoseconds(value)
return Structure(b"d", seconds, nanoseconds)
elif hasattr(tz, "zone") and tz.zone:
# with named time zone
seconds, nanoseconds = seconds_and_nanoseconds(value)
return Structure(b"f", seconds, nanoseconds, tz.zone)
else:
# with time offset
seconds, nanoseconds = seconds_and_nanoseconds(value)
return Structure(b"F", seconds, nanoseconds, tz.utcoffset(value).seconds) | [
"def",
"dehydrate_datetime",
"(",
"value",
")",
":",
"def",
"seconds_and_nanoseconds",
"(",
"dt",
")",
":",
"if",
"isinstance",
"(",
"dt",
",",
"datetime",
")",
":",
"dt",
"=",
"DateTime",
".",
"from_native",
"(",
"dt",
")",
"zone_epoch",
"=",
"DateTime",
... | Dehydrator for `datetime` values.
:param value:
:type value: datetime
:return: | [
"Dehydrator",
"for",
"datetime",
"values",
"."
] | 0c641e826765e86ff5454dae57c99521db8ca45c | https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/types/temporal.py#L123-L151 |
245,345 | neo4j/neo4j-python-driver | neo4j/types/temporal.py | hydrate_duration | 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) | python | def hydrate_duration(months, days, seconds, nanoseconds):
return Duration(months=months, days=days, seconds=seconds, nanoseconds=nanoseconds) | [
"def",
"hydrate_duration",
"(",
"months",
",",
"days",
",",
"seconds",
",",
"nanoseconds",
")",
":",
"return",
"Duration",
"(",
"months",
"=",
"months",
",",
"days",
"=",
"days",
",",
"seconds",
"=",
"seconds",
",",
"nanoseconds",
"=",
"nanoseconds",
")"
] | Hydrator for `Duration` values.
:param months:
:param days:
:param seconds:
:param nanoseconds:
:return: `duration` namedtuple | [
"Hydrator",
"for",
"Duration",
"values",
"."
] | 0c641e826765e86ff5454dae57c99521db8ca45c | https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/types/temporal.py#L154-L163 |
245,346 | neo4j/neo4j-python-driver | neo4j/types/temporal.py | dehydrate_duration | 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)) | python | def dehydrate_duration(value):
return Structure(b"E", value.months, value.days, value.seconds, int(1000000000 * value.subseconds)) | [
"def",
"dehydrate_duration",
"(",
"value",
")",
":",
"return",
"Structure",
"(",
"b\"E\"",
",",
"value",
".",
"months",
",",
"value",
".",
"days",
",",
"value",
".",
"seconds",
",",
"int",
"(",
"1000000000",
"*",
"value",
".",
"subseconds",
")",
")"
] | Dehydrator for `duration` values.
:param value:
:type value: Duration
:return: | [
"Dehydrator",
"for",
"duration",
"values",
"."
] | 0c641e826765e86ff5454dae57c99521db8ca45c | https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/types/temporal.py#L166-L173 |
245,347 | neo4j/neo4j-python-driver | neo4j/types/temporal.py | dehydrate_timedelta | 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) | python | def dehydrate_timedelta(value):
months = 0
days = value.days
seconds = value.seconds
nanoseconds = 1000 * value.microseconds
return Structure(b"E", months, days, seconds, nanoseconds) | [
"def",
"dehydrate_timedelta",
"(",
"value",
")",
":",
"months",
"=",
"0",
"days",
"=",
"value",
".",
"days",
"seconds",
"=",
"value",
".",
"seconds",
"nanoseconds",
"=",
"1000",
"*",
"value",
".",
"microseconds",
"return",
"Structure",
"(",
"b\"E\"",
",",
... | Dehydrator for `timedelta` values.
:param value:
:type value: timedelta
:return: | [
"Dehydrator",
"for",
"timedelta",
"values",
"."
] | 0c641e826765e86ff5454dae57c99521db8ca45c | https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/types/temporal.py#L176-L187 |
245,348 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_touch.py | _TouchKeywords.zoom | 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) | python | def zoom(self, locator, percent="200%", steps=1):
driver = self._current_application()
element = self._element_find(locator, True, True)
driver.zoom(element=element, percent=percent, steps=steps) | [
"def",
"zoom",
"(",
"self",
",",
"locator",
",",
"percent",
"=",
"\"200%\"",
",",
"steps",
"=",
"1",
")",
":",
"driver",
"=",
"self",
".",
"_current_application",
"(",
")",
"element",
"=",
"self",
".",
"_element_find",
"(",
"locator",
",",
"True",
",",... | Zooms in on an element a certain amount. | [
"Zooms",
"in",
"on",
"an",
"element",
"a",
"certain",
"amount",
"."
] | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_touch.py#L15-L21 |
245,349 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_touch.py | _TouchKeywords.scroll | 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)
el2 = self._element_find(end_locator, True, True)
driver = self._current_application()
driver.scroll(el1, el2) | python | def scroll(self, start_locator, end_locator):
el1 = self._element_find(start_locator, True, True)
el2 = self._element_find(end_locator, True, True)
driver = self._current_application()
driver.scroll(el1, el2) | [
"def",
"scroll",
"(",
"self",
",",
"start_locator",
",",
"end_locator",
")",
":",
"el1",
"=",
"self",
".",
"_element_find",
"(",
"start_locator",
",",
"True",
",",
"True",
")",
"el2",
"=",
"self",
".",
"_element_find",
"(",
"end_locator",
",",
"True",
",... | Scrolls from one element to another
Key attributes for arbitrary elements are `id` and `name`. See
`introduction` for details about locating elements. | [
"Scrolls",
"from",
"one",
"element",
"to",
"another",
"Key",
"attributes",
"for",
"arbitrary",
"elements",
"are",
"id",
"and",
"name",
".",
"See",
"introduction",
"for",
"details",
"about",
"locating",
"elements",
"."
] | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_touch.py#L85-L94 |
245,350 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_touch.py | _TouchKeywords.scroll_up | 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}) | python | def scroll_up(self, locator):
driver = self._current_application()
element = self._element_find(locator, True, True)
driver.execute_script("mobile: scroll", {"direction": 'up', 'element': element.id}) | [
"def",
"scroll_up",
"(",
"self",
",",
"locator",
")",
":",
"driver",
"=",
"self",
".",
"_current_application",
"(",
")",
"element",
"=",
"self",
".",
"_element_find",
"(",
"locator",
",",
"True",
",",
"True",
")",
"driver",
".",
"execute_script",
"(",
"\... | Scrolls up to element | [
"Scrolls",
"up",
"to",
"element"
] | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_touch.py#L102-L106 |
245,351 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_touch.py | _TouchKeywords.long_press | 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() | python | def long_press(self, locator, duration=1000):
driver = self._current_application()
element = self._element_find(locator, True, True)
action = TouchAction(driver)
action.press(element).wait(duration).release().perform() | [
"def",
"long_press",
"(",
"self",
",",
"locator",
",",
"duration",
"=",
"1000",
")",
":",
"driver",
"=",
"self",
".",
"_current_application",
"(",
")",
"element",
"=",
"self",
".",
"_element_find",
"(",
"locator",
",",
"True",
",",
"True",
")",
"action",... | Long press the element with optional duration | [
"Long",
"press",
"the",
"element",
"with",
"optional",
"duration"
] | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_touch.py#L108-L113 |
245,352 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_touch.py | _TouchKeywords.click_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().perform()
except:
assert False, "Can't click on a point at (%s,%s)" % (x,y) | python | def click_a_point(self, x=0, y=0, duration=100):
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().perform()
except:
assert False, "Can't click on a point at (%s,%s)" % (x,y) | [
"def",
"click_a_point",
"(",
"self",
",",
"x",
"=",
"0",
",",
"y",
"=",
"0",
",",
"duration",
"=",
"100",
")",
":",
"self",
".",
"_info",
"(",
"\"Clicking on a point (%s,%s).\"",
"%",
"(",
"x",
",",
"y",
")",
")",
"driver",
"=",
"self",
".",
"_curr... | Click on a point | [
"Click",
"on",
"a",
"point"
] | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_touch.py#L128-L136 |
245,353 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_touch.py | _TouchKeywords.click_element_at_coordinates | 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, y=coordinate_Y).release().perform() | python | def click_element_at_coordinates(self, coordinate_X, coordinate_Y):
self._info("Pressing at (%s, %s)." % (coordinate_X, coordinate_Y))
driver = self._current_application()
action = TouchAction(driver)
action.press(x=coordinate_X, y=coordinate_Y).release().perform() | [
"def",
"click_element_at_coordinates",
"(",
"self",
",",
"coordinate_X",
",",
"coordinate_Y",
")",
":",
"self",
".",
"_info",
"(",
"\"Pressing at (%s, %s).\"",
"%",
"(",
"coordinate_X",
",",
"coordinate_Y",
")",
")",
"driver",
"=",
"self",
".",
"_current_applicati... | click element at a certain coordinate | [
"click",
"element",
"at",
"a",
"certain",
"coordinate"
] | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_touch.py#L138-L143 |
245,354 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_waiting.py | _WaitingKeywords.wait_until_element_is_visible | 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.
`error` can be used to override the default error message.
See also `Wait Until Page Contains`, `Wait Until Page Contains
Element`, `Wait For Condition` and BuiltIn keyword `Wait Until Keyword
Succeeds`.
"""
def check_visibility():
visible = self._is_visible(locator)
if visible:
return
elif visible is None:
return error or "Element locator '%s' did not match any elements after %s" % (locator, self._format_timeout(timeout))
else:
return error or "Element '%s' was not visible in %s" % (locator, self._format_timeout(timeout))
self._wait_until_no_error(timeout, check_visibility) | python | def wait_until_element_is_visible(self, locator, timeout=None, error=None):
def check_visibility():
visible = self._is_visible(locator)
if visible:
return
elif visible is None:
return error or "Element locator '%s' did not match any elements after %s" % (locator, self._format_timeout(timeout))
else:
return error or "Element '%s' was not visible in %s" % (locator, self._format_timeout(timeout))
self._wait_until_no_error(timeout, check_visibility) | [
"def",
"wait_until_element_is_visible",
"(",
"self",
",",
"locator",
",",
"timeout",
"=",
"None",
",",
"error",
"=",
"None",
")",
":",
"def",
"check_visibility",
"(",
")",
":",
"visible",
"=",
"self",
".",
"_is_visible",
"(",
"locator",
")",
"if",
"visible... | 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 Page Contains`, `Wait Until Page Contains
Element`, `Wait For Condition` and BuiltIn keyword `Wait Until Keyword
Succeeds`. | [
"Waits",
"until",
"element",
"specified",
"with",
"locator",
"is",
"visible",
"."
] | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_waiting.py#L7-L28 |
245,355 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_waiting.py | _WaitingKeywords.wait_until_page_contains | 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 the default error message.
See also `Wait Until Page Does Not Contain`,
`Wait Until Page Contains Element`,
`Wait Until Page Does Not Contain Element` and
BuiltIn keyword `Wait Until Keyword Succeeds`.
"""
if not error:
error = "Text '%s' did not appear in <TIMEOUT>" % text
self._wait_until(timeout, error, self._is_text_present, text) | python | def wait_until_page_contains(self, text, timeout=None, error=None):
if not error:
error = "Text '%s' did not appear in <TIMEOUT>" % text
self._wait_until(timeout, error, self._is_text_present, text) | [
"def",
"wait_until_page_contains",
"(",
"self",
",",
"text",
",",
"timeout",
"=",
"None",
",",
"error",
"=",
"None",
")",
":",
"if",
"not",
"error",
":",
"error",
"=",
"\"Text '%s' did not appear in <TIMEOUT>\"",
"%",
"text",
"self",
".",
"_wait_until",
"(",
... | 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`,
`Wait Until Page Contains Element`,
`Wait Until Page Does Not Contain Element` and
BuiltIn keyword `Wait Until Keyword Succeeds`. | [
"Waits",
"until",
"text",
"appears",
"on",
"current",
"page",
"."
] | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_waiting.py#L30-L46 |
245,356 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_waiting.py | _WaitingKeywords.wait_until_page_does_not_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 used to override the default error message.
See also `Wait Until Page Contains`,
`Wait Until Page Contains Element`,
`Wait Until Page Does Not Contain Element` and
BuiltIn keyword `Wait Until Keyword Succeeds`.
"""
def check_present():
present = self._is_text_present(text)
if not present:
return
else:
return error or "Text '%s' did not disappear in %s" % (text, self._format_timeout(timeout))
self._wait_until_no_error(timeout, check_present) | python | def wait_until_page_does_not_contain(self, text, timeout=None, error=None):
def check_present():
present = self._is_text_present(text)
if not present:
return
else:
return error or "Text '%s' did not disappear in %s" % (text, self._format_timeout(timeout))
self._wait_until_no_error(timeout, check_present) | [
"def",
"wait_until_page_does_not_contain",
"(",
"self",
",",
"text",
",",
"timeout",
"=",
"None",
",",
"error",
"=",
"None",
")",
":",
"def",
"check_present",
"(",
")",
":",
"present",
"=",
"self",
".",
"_is_text_present",
"(",
"text",
")",
"if",
"not",
... | 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 Contains`,
`Wait Until Page Contains Element`,
`Wait Until Page Does Not Contain Element` and
BuiltIn keyword `Wait Until Keyword Succeeds`. | [
"Waits",
"until",
"text",
"disappears",
"from",
"current",
"page",
"."
] | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_waiting.py#L48-L70 |
245,357 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_waiting.py | _WaitingKeywords.wait_until_page_contains_element | 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.
`error` can be used to override the default error message.
See also `Wait Until Page Contains`,
`Wait Until Page Does Not Contain`
`Wait Until Page Does Not Contain Element`
and BuiltIn keyword `Wait Until Keyword Succeeds`.
"""
if not error:
error = "Element '%s' did not appear in <TIMEOUT>" % locator
self._wait_until(timeout, error, self._is_element_present, locator) | python | def wait_until_page_contains_element(self, locator, timeout=None, error=None):
if not error:
error = "Element '%s' did not appear in <TIMEOUT>" % locator
self._wait_until(timeout, error, self._is_element_present, locator) | [
"def",
"wait_until_page_contains_element",
"(",
"self",
",",
"locator",
",",
"timeout",
"=",
"None",
",",
"error",
"=",
"None",
")",
":",
"if",
"not",
"error",
":",
"error",
"=",
"\"Element '%s' did not appear in <TIMEOUT>\"",
"%",
"locator",
"self",
".",
"_wait... | 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 Until Page Contains`,
`Wait Until Page Does Not Contain`
`Wait Until Page Does Not Contain Element`
and BuiltIn keyword `Wait Until Keyword Succeeds`. | [
"Waits",
"until",
"element",
"specified",
"with",
"locator",
"appears",
"on",
"current",
"page",
"."
] | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_waiting.py#L72-L88 |
245,358 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_waiting.py | _WaitingKeywords.wait_until_page_does_not_contain_element | 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
default value.
`error` can be used to override the default error message.
See also `Wait Until Page Contains`,
`Wait Until Page Does Not Contain`,
`Wait Until Page Contains Element` and
BuiltIn keyword `Wait Until Keyword Succeeds`.
"""
def check_present():
present = self._is_element_present(locator)
if not present:
return
else:
return error or "Element '%s' did not disappear in %s" % (locator, self._format_timeout(timeout))
self._wait_until_no_error(timeout, check_present) | python | def wait_until_page_does_not_contain_element(self, locator, timeout=None, error=None):
def check_present():
present = self._is_element_present(locator)
if not present:
return
else:
return error or "Element '%s' did not disappear in %s" % (locator, self._format_timeout(timeout))
self._wait_until_no_error(timeout, check_present) | [
"def",
"wait_until_page_does_not_contain_element",
"(",
"self",
",",
"locator",
",",
"timeout",
"=",
"None",
",",
"error",
"=",
"None",
")",
":",
"def",
"check_present",
"(",
")",
":",
"present",
"=",
"self",
".",
"_is_element_present",
"(",
"locator",
")",
... | 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 also `Wait Until Page Contains`,
`Wait Until Page Does Not Contain`,
`Wait Until Page Contains Element` and
BuiltIn keyword `Wait Until Keyword Succeeds`. | [
"Waits",
"until",
"element",
"specified",
"with",
"locator",
"disappears",
"from",
"current",
"page",
"."
] | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_waiting.py#L90-L112 |
245,359 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_android_utils.py | _AndroidUtilsKeywords.set_network_connection_status | 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 |
| 1 | (Airplane Mode) | 0 | 0 | 1 |
| 2 | (Wifi only) | 0 | 1 | 0 |
| 4 | (Data only) | 1 | 0 | 0 |
| 6 | (All network on) | 1 | 1 | 0 |
"""
driver = self._current_application()
return driver.set_network_connection(int(connectionStatus)) | python | def set_network_connection_status(self, connectionStatus):
driver = self._current_application()
return driver.set_network_connection(int(connectionStatus)) | [
"def",
"set_network_connection_status",
"(",
"self",
",",
"connectionStatus",
")",
":",
"driver",
"=",
"self",
".",
"_current_application",
"(",
")",
"return",
"driver",
".",
"set_network_connection",
"(",
"int",
"(",
"connectionStatus",
")",
")"
] | 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 |
| 2 | (Wifi only) | 0 | 1 | 0 |
| 4 | (Data only) | 1 | 0 | 0 |
| 6 | (All network on) | 1 | 1 | 0 | | [
"Sets",
"the",
"network",
"connection",
"Status",
"."
] | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_android_utils.py#L21-L35 |
245,360 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_android_utils.py | _AndroidUtilsKeywords.pull_file | def pull_file(self, path, decode=False):
"""Retrieves the file at `path` and return it's content.
Android only.
- _path_ - the path to the file on the device
- _decode_ - True/False decode the data (base64) before returning it (default=False)
"""
driver = self._current_application()
theFile = driver.pull_file(path)
if decode:
theFile = base64.b64decode(theFile)
return str(theFile) | python | def pull_file(self, path, decode=False):
driver = self._current_application()
theFile = driver.pull_file(path)
if decode:
theFile = base64.b64decode(theFile)
return str(theFile) | [
"def",
"pull_file",
"(",
"self",
",",
"path",
",",
"decode",
"=",
"False",
")",
":",
"driver",
"=",
"self",
".",
"_current_application",
"(",
")",
"theFile",
"=",
"driver",
".",
"pull_file",
"(",
"path",
")",
"if",
"decode",
":",
"theFile",
"=",
"base6... | Retrieves the file at `path` and return it's content.
Android only.
- _path_ - the path to the file on the device
- _decode_ - True/False decode the data (base64) before returning it (default=False) | [
"Retrieves",
"the",
"file",
"at",
"path",
"and",
"return",
"it",
"s",
"content",
"."
] | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_android_utils.py#L37-L49 |
245,361 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_android_utils.py | _AndroidUtilsKeywords.pull_folder | def pull_folder(self, path, decode=False):
"""Retrieves a folder at `path`. Returns the folder's contents zipped.
Android only.
- _path_ - the path to the folder on the device
- _decode_ - True/False decode the data (base64) before returning it (default=False)
"""
driver = self._current_application()
theFolder = driver.pull_folder(path)
if decode:
theFolder = base64.b64decode(theFolder)
return theFolder | python | def pull_folder(self, path, decode=False):
driver = self._current_application()
theFolder = driver.pull_folder(path)
if decode:
theFolder = base64.b64decode(theFolder)
return theFolder | [
"def",
"pull_folder",
"(",
"self",
",",
"path",
",",
"decode",
"=",
"False",
")",
":",
"driver",
"=",
"self",
".",
"_current_application",
"(",
")",
"theFolder",
"=",
"driver",
".",
"pull_folder",
"(",
"path",
")",
"if",
"decode",
":",
"theFolder",
"=",
... | Retrieves a folder at `path`. Returns the folder's contents zipped.
Android only.
- _path_ - the path to the folder on the device
- _decode_ - True/False decode the data (base64) before returning it (default=False) | [
"Retrieves",
"a",
"folder",
"at",
"path",
".",
"Returns",
"the",
"folder",
"s",
"contents",
"zipped",
"."
] | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_android_utils.py#L51-L63 |
245,362 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_android_utils.py | _AndroidUtilsKeywords.push_file | def push_file(self, path, data, encode=False):
"""Puts the data in the file specified as `path`.
Android only.
- _path_ - the path on the device
- _data_ - data to be written to the file
- _encode_ - True/False encode the data as base64 before writing it to the file (default=False)
"""
driver = self._current_application()
data = to_bytes(data)
if encode:
data = base64.b64encode(data)
driver.push_file(path, data) | python | def push_file(self, path, data, encode=False):
driver = self._current_application()
data = to_bytes(data)
if encode:
data = base64.b64encode(data)
driver.push_file(path, data) | [
"def",
"push_file",
"(",
"self",
",",
"path",
",",
"data",
",",
"encode",
"=",
"False",
")",
":",
"driver",
"=",
"self",
".",
"_current_application",
"(",
")",
"data",
"=",
"to_bytes",
"(",
"data",
")",
"if",
"encode",
":",
"data",
"=",
"base64",
"."... | Puts the data in the file specified as `path`.
Android only.
- _path_ - the path on the device
- _data_ - data to be written to the file
- _encode_ - True/False encode the data as base64 before writing it to the file (default=False) | [
"Puts",
"the",
"data",
"in",
"the",
"file",
"specified",
"as",
"path",
"."
] | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_android_utils.py#L65-L78 |
245,363 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_android_utils.py | _AndroidUtilsKeywords.start_activity | def start_activity(self, appPackage, appActivity, **opts):
"""Opens an arbitrary activity during a test. If the activity belongs to
another application, that application is started and the activity is opened.
Android only.
- _appPackage_ - The package containing the activity to start.
- _appActivity_ - The activity to start.
- _appWaitPackage_ - Begin automation after this package starts (optional).
- _appWaitActivity_ - Begin automation after this activity starts (optional).
- _intentAction_ - Intent to start (opt_ional).
- _intentCategory_ - Intent category to start (optional).
- _intentFlags_ - Flags to send to the intent (optional).
- _optionalIntentArguments_ - Optional arguments to the intent (optional).
- _stopAppOnReset_ - Should the app be stopped on reset (optional)?
"""
# Almost the same code as in appium's start activity,
# just to keep the same keyword names as in open application
arguments = {
'app_wait_package': 'appWaitPackage',
'app_wait_activity': 'appWaitActivity',
'intent_action': 'intentAction',
'intent_category': 'intentCategory',
'intent_flags': 'intentFlags',
'optional_intent_arguments': 'optionalIntentArguments',
'stop_app_on_reset': 'stopAppOnReset'
}
data = {}
for key, value in arguments.items():
if value in opts:
data[key] = opts[value]
driver = self._current_application()
driver.start_activity(app_package=appPackage, app_activity=appActivity, **data) | python | def start_activity(self, appPackage, appActivity, **opts):
# Almost the same code as in appium's start activity,
# just to keep the same keyword names as in open application
arguments = {
'app_wait_package': 'appWaitPackage',
'app_wait_activity': 'appWaitActivity',
'intent_action': 'intentAction',
'intent_category': 'intentCategory',
'intent_flags': 'intentFlags',
'optional_intent_arguments': 'optionalIntentArguments',
'stop_app_on_reset': 'stopAppOnReset'
}
data = {}
for key, value in arguments.items():
if value in opts:
data[key] = opts[value]
driver = self._current_application()
driver.start_activity(app_package=appPackage, app_activity=appActivity, **data) | [
"def",
"start_activity",
"(",
"self",
",",
"appPackage",
",",
"appActivity",
",",
"*",
"*",
"opts",
")",
":",
"# Almost the same code as in appium's start activity,",
"# just to keep the same keyword names as in open application",
"arguments",
"=",
"{",
"'app_wait_package'",
... | Opens an arbitrary activity during a test. If the activity belongs to
another application, that application is started and the activity is opened.
Android only.
- _appPackage_ - The package containing the activity to start.
- _appActivity_ - The activity to start.
- _appWaitPackage_ - Begin automation after this package starts (optional).
- _appWaitActivity_ - Begin automation after this activity starts (optional).
- _intentAction_ - Intent to start (opt_ional).
- _intentCategory_ - Intent category to start (optional).
- _intentFlags_ - Flags to send to the intent (optional).
- _optionalIntentArguments_ - Optional arguments to the intent (optional).
- _stopAppOnReset_ - Should the app be stopped on reset (optional)? | [
"Opens",
"an",
"arbitrary",
"activity",
"during",
"a",
"test",
".",
"If",
"the",
"activity",
"belongs",
"to",
"another",
"application",
"that",
"application",
"is",
"started",
"and",
"the",
"activity",
"is",
"opened",
"."
] | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_android_utils.py#L89-L128 |
245,364 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_android_utils.py | _AndroidUtilsKeywords.install_app | def install_app(self, app_path, app_package):
""" Install App via Appium
Android only.
- app_path - path to app
- app_package - package of install app to verify
"""
driver = self._current_application()
driver.install_app(app_path)
return driver.is_app_installed(app_package) | python | def install_app(self, app_path, app_package):
driver = self._current_application()
driver.install_app(app_path)
return driver.is_app_installed(app_package) | [
"def",
"install_app",
"(",
"self",
",",
"app_path",
",",
"app_package",
")",
":",
"driver",
"=",
"self",
".",
"_current_application",
"(",
")",
"driver",
".",
"install_app",
"(",
"app_path",
")",
"return",
"driver",
".",
"is_app_installed",
"(",
"app_package",... | Install App via Appium
Android only.
- app_path - path to app
- app_package - package of install app to verify | [
"Install",
"App",
"via",
"Appium",
"Android",
"only",
"."
] | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_android_utils.py#L148-L158 |
245,365 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_element.py | _ElementKeywords.click_element | def click_element(self, locator):
"""Click element identified by `locator`.
Key attributes for arbitrary elements are `index` and `name`. See
`introduction` for details about locating elements.
"""
self._info("Clicking element '%s'." % locator)
self._element_find(locator, True, True).click() | python | def click_element(self, locator):
self._info("Clicking element '%s'." % locator)
self._element_find(locator, True, True).click() | [
"def",
"click_element",
"(",
"self",
",",
"locator",
")",
":",
"self",
".",
"_info",
"(",
"\"Clicking element '%s'.\"",
"%",
"locator",
")",
"self",
".",
"_element_find",
"(",
"locator",
",",
"True",
",",
"True",
")",
".",
"click",
"(",
")"
] | Click element identified by `locator`.
Key attributes for arbitrary elements are `index` and `name`. See
`introduction` for details about locating elements. | [
"Click",
"element",
"identified",
"by",
"locator",
".",
"Key",
"attributes",
"for",
"arbitrary",
"elements",
"are",
"index",
"and",
"name",
".",
"See",
"introduction",
"for",
"details",
"about",
"locating",
"elements",
"."
] | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_element.py#L35-L42 |
245,366 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_element.py | _ElementKeywords.click_text | def click_text(self, text, exact_match=False):
"""Click text identified by ``text``.
By default tries to click first text involves given ``text``, if you would
like to click exactly matching text, then set ``exact_match`` to `True`.
If there are multiple use of ``text`` and you do not want first one,
use `locator` with `Get Web Elements` instead.
"""
self._element_find_by_text(text,exact_match).click() | python | def click_text(self, text, exact_match=False):
self._element_find_by_text(text,exact_match).click() | [
"def",
"click_text",
"(",
"self",
",",
"text",
",",
"exact_match",
"=",
"False",
")",
":",
"self",
".",
"_element_find_by_text",
"(",
"text",
",",
"exact_match",
")",
".",
"click",
"(",
")"
] | Click text identified by ``text``.
By default tries to click first text involves given ``text``, if you would
like to click exactly matching text, then set ``exact_match`` to `True`.
If there are multiple use of ``text`` and you do not want first one,
use `locator` with `Get Web Elements` instead. | [
"Click",
"text",
"identified",
"by",
"text",
".",
"By",
"default",
"tries",
"to",
"click",
"first",
"text",
"involves",
"given",
"text",
"if",
"you",
"would",
"like",
"to",
"click",
"exactly",
"matching",
"text",
"then",
"set",
"exact_match",
"to",
"True",
... | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_element.py#L52-L62 |
245,367 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_element.py | _ElementKeywords.input_text | def input_text(self, locator, text):
"""Types the given `text` into text field identified by `locator`.
See `introduction` for details about locating elements.
"""
self._info("Typing text '%s' into text field '%s'" % (text, locator))
self._element_input_text_by_locator(locator, text) | python | def input_text(self, locator, text):
self._info("Typing text '%s' into text field '%s'" % (text, locator))
self._element_input_text_by_locator(locator, text) | [
"def",
"input_text",
"(",
"self",
",",
"locator",
",",
"text",
")",
":",
"self",
".",
"_info",
"(",
"\"Typing text '%s' into text field '%s'\"",
"%",
"(",
"text",
",",
"locator",
")",
")",
"self",
".",
"_element_input_text_by_locator",
"(",
"locator",
",",
"te... | Types the given `text` into text field identified by `locator`.
See `introduction` for details about locating elements. | [
"Types",
"the",
"given",
"text",
"into",
"text",
"field",
"identified",
"by",
"locator",
".",
"See",
"introduction",
"for",
"details",
"about",
"locating",
"elements",
"."
] | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_element.py#L64-L70 |
245,368 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_element.py | _ElementKeywords.input_password | def input_password(self, locator, text):
"""Types the given password into text field identified by `locator`.
Difference between this keyword and `Input Text` is that this keyword
does not log the given password. See `introduction` for details about
locating elements.
"""
self._info("Typing password into text field '%s'" % locator)
self._element_input_text_by_locator(locator, text) | python | def input_password(self, locator, text):
self._info("Typing password into text field '%s'" % locator)
self._element_input_text_by_locator(locator, text) | [
"def",
"input_password",
"(",
"self",
",",
"locator",
",",
"text",
")",
":",
"self",
".",
"_info",
"(",
"\"Typing password into text field '%s'\"",
"%",
"locator",
")",
"self",
".",
"_element_input_text_by_locator",
"(",
"locator",
",",
"text",
")"
] | Types the given password into text field identified by `locator`.
Difference between this keyword and `Input Text` is that this keyword
does not log the given password. See `introduction` for details about
locating elements. | [
"Types",
"the",
"given",
"password",
"into",
"text",
"field",
"identified",
"by",
"locator",
".",
"Difference",
"between",
"this",
"keyword",
"and",
"Input",
"Text",
"is",
"that",
"this",
"keyword",
"does",
"not",
"log",
"the",
"given",
"password",
".",
"See... | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_element.py#L72-L80 |
245,369 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_element.py | _ElementKeywords.input_value | def input_value(self, locator, text):
"""Sets the given value into text field identified by `locator`. This is an IOS only keyword, input value makes use of set_value
See `introduction` for details about locating elements.
"""
self._info("Setting text '%s' into text field '%s'" % (text, locator))
self._element_input_value_by_locator(locator, text) | python | def input_value(self, locator, text):
self._info("Setting text '%s' into text field '%s'" % (text, locator))
self._element_input_value_by_locator(locator, text) | [
"def",
"input_value",
"(",
"self",
",",
"locator",
",",
"text",
")",
":",
"self",
".",
"_info",
"(",
"\"Setting text '%s' into text field '%s'\"",
"%",
"(",
"text",
",",
"locator",
")",
")",
"self",
".",
"_element_input_value_by_locator",
"(",
"locator",
",",
... | Sets the given value into text field identified by `locator`. This is an IOS only keyword, input value makes use of set_value
See `introduction` for details about locating elements. | [
"Sets",
"the",
"given",
"value",
"into",
"text",
"field",
"identified",
"by",
"locator",
".",
"This",
"is",
"an",
"IOS",
"only",
"keyword",
"input",
"value",
"makes",
"use",
"of",
"set_value",
"See",
"introduction",
"for",
"details",
"about",
"locating",
"el... | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_element.py#L82-L88 |
245,370 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_element.py | _ElementKeywords.page_should_contain_text | def page_should_contain_text(self, text, loglevel='INFO'):
"""Verifies that current page contains `text`.
If this keyword fails, it automatically logs the page source
using the log level specified with the optional `loglevel` argument.
Giving `NONE` as level disables logging.
"""
if not self._is_text_present(text):
self.log_source(loglevel)
raise AssertionError("Page should have contained text '%s' "
"but did not" % text)
self._info("Current page contains text '%s'." % text) | python | def page_should_contain_text(self, text, loglevel='INFO'):
if not self._is_text_present(text):
self.log_source(loglevel)
raise AssertionError("Page should have contained text '%s' "
"but did not" % text)
self._info("Current page contains text '%s'." % text) | [
"def",
"page_should_contain_text",
"(",
"self",
",",
"text",
",",
"loglevel",
"=",
"'INFO'",
")",
":",
"if",
"not",
"self",
".",
"_is_text_present",
"(",
"text",
")",
":",
"self",
".",
"log_source",
"(",
"loglevel",
")",
"raise",
"AssertionError",
"(",
"\"... | Verifies that current page contains `text`.
If this keyword fails, it automatically logs the page source
using the log level specified with the optional `loglevel` argument.
Giving `NONE` as level disables logging. | [
"Verifies",
"that",
"current",
"page",
"contains",
"text",
".",
"If",
"this",
"keyword",
"fails",
"it",
"automatically",
"logs",
"the",
"page",
"source",
"using",
"the",
"log",
"level",
"specified",
"with",
"the",
"optional",
"loglevel",
"argument",
".",
"Givi... | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_element.py#L97-L108 |
245,371 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_element.py | _ElementKeywords.page_should_not_contain_text | def page_should_not_contain_text(self, text, loglevel='INFO'):
"""Verifies that current page not contains `text`.
If this keyword fails, it automatically logs the page source
using the log level specified with the optional `loglevel` argument.
Giving `NONE` as level disables logging.
"""
if self._is_text_present(text):
self.log_source(loglevel)
raise AssertionError("Page should not have contained text '%s'" % text)
self._info("Current page does not contains text '%s'." % text) | python | def page_should_not_contain_text(self, text, loglevel='INFO'):
if self._is_text_present(text):
self.log_source(loglevel)
raise AssertionError("Page should not have contained text '%s'" % text)
self._info("Current page does not contains text '%s'." % text) | [
"def",
"page_should_not_contain_text",
"(",
"self",
",",
"text",
",",
"loglevel",
"=",
"'INFO'",
")",
":",
"if",
"self",
".",
"_is_text_present",
"(",
"text",
")",
":",
"self",
".",
"log_source",
"(",
"loglevel",
")",
"raise",
"AssertionError",
"(",
"\"Page ... | Verifies that current page not contains `text`.
If this keyword fails, it automatically logs the page source
using the log level specified with the optional `loglevel` argument.
Giving `NONE` as level disables logging. | [
"Verifies",
"that",
"current",
"page",
"not",
"contains",
"text",
".",
"If",
"this",
"keyword",
"fails",
"it",
"automatically",
"logs",
"the",
"page",
"source",
"using",
"the",
"log",
"level",
"specified",
"with",
"the",
"optional",
"loglevel",
"argument",
"."... | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_element.py#L110-L120 |
245,372 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_element.py | _ElementKeywords.page_should_contain_element | def page_should_contain_element(self, locator, loglevel='INFO'):
"""Verifies that current page contains `locator` element.
If this keyword fails, it automatically logs the page source
using the log level specified with the optional `loglevel` argument.
Giving `NONE` as level disables logging.
"""
if not self._is_element_present(locator):
self.log_source(loglevel)
raise AssertionError("Page should have contained element '%s' "
"but did not" % locator)
self._info("Current page contains element '%s'." % locator) | python | def page_should_contain_element(self, locator, loglevel='INFO'):
if not self._is_element_present(locator):
self.log_source(loglevel)
raise AssertionError("Page should have contained element '%s' "
"but did not" % locator)
self._info("Current page contains element '%s'." % locator) | [
"def",
"page_should_contain_element",
"(",
"self",
",",
"locator",
",",
"loglevel",
"=",
"'INFO'",
")",
":",
"if",
"not",
"self",
".",
"_is_element_present",
"(",
"locator",
")",
":",
"self",
".",
"log_source",
"(",
"loglevel",
")",
"raise",
"AssertionError",
... | Verifies that current page contains `locator` element.
If this keyword fails, it automatically logs the page source
using the log level specified with the optional `loglevel` argument.
Giving `NONE` as level disables logging. | [
"Verifies",
"that",
"current",
"page",
"contains",
"locator",
"element",
".",
"If",
"this",
"keyword",
"fails",
"it",
"automatically",
"logs",
"the",
"page",
"source",
"using",
"the",
"log",
"level",
"specified",
"with",
"the",
"optional",
"loglevel",
"argument"... | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_element.py#L122-L133 |
245,373 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_element.py | _ElementKeywords.page_should_not_contain_element | def page_should_not_contain_element(self, locator, loglevel='INFO'):
"""Verifies that current page not contains `locator` element.
If this keyword fails, it automatically logs the page source
using the log level specified with the optional `loglevel` argument.
Giving `NONE` as level disables logging.
"""
if self._is_element_present(locator):
self.log_source(loglevel)
raise AssertionError("Page should not have contained element '%s'" % locator)
self._info("Current page not contains element '%s'." % locator) | python | def page_should_not_contain_element(self, locator, loglevel='INFO'):
if self._is_element_present(locator):
self.log_source(loglevel)
raise AssertionError("Page should not have contained element '%s'" % locator)
self._info("Current page not contains element '%s'." % locator) | [
"def",
"page_should_not_contain_element",
"(",
"self",
",",
"locator",
",",
"loglevel",
"=",
"'INFO'",
")",
":",
"if",
"self",
".",
"_is_element_present",
"(",
"locator",
")",
":",
"self",
".",
"log_source",
"(",
"loglevel",
")",
"raise",
"AssertionError",
"("... | Verifies that current page not contains `locator` element.
If this keyword fails, it automatically logs the page source
using the log level specified with the optional `loglevel` argument.
Giving `NONE` as level disables logging. | [
"Verifies",
"that",
"current",
"page",
"not",
"contains",
"locator",
"element",
".",
"If",
"this",
"keyword",
"fails",
"it",
"automatically",
"logs",
"the",
"page",
"source",
"using",
"the",
"log",
"level",
"specified",
"with",
"the",
"optional",
"loglevel",
"... | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_element.py#L135-L145 |
245,374 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_element.py | _ElementKeywords.element_should_be_disabled | def element_should_be_disabled(self, locator, loglevel='INFO'):
"""Verifies that element identified with locator is disabled.
Key attributes for arbitrary elements are `id` and `name`. See
`introduction` for details about locating elements.
"""
if self._element_find(locator, True, True).is_enabled():
self.log_source(loglevel)
raise AssertionError("Element '%s' should be disabled "
"but did not" % locator)
self._info("Element '%s' is disabled ." % locator) | python | def element_should_be_disabled(self, locator, loglevel='INFO'):
if self._element_find(locator, True, True).is_enabled():
self.log_source(loglevel)
raise AssertionError("Element '%s' should be disabled "
"but did not" % locator)
self._info("Element '%s' is disabled ." % locator) | [
"def",
"element_should_be_disabled",
"(",
"self",
",",
"locator",
",",
"loglevel",
"=",
"'INFO'",
")",
":",
"if",
"self",
".",
"_element_find",
"(",
"locator",
",",
"True",
",",
"True",
")",
".",
"is_enabled",
"(",
")",
":",
"self",
".",
"log_source",
"(... | Verifies that element identified with locator is disabled.
Key attributes for arbitrary elements are `id` and `name`. See
`introduction` for details about locating elements. | [
"Verifies",
"that",
"element",
"identified",
"with",
"locator",
"is",
"disabled",
".",
"Key",
"attributes",
"for",
"arbitrary",
"elements",
"are",
"id",
"and",
"name",
".",
"See",
"introduction",
"for",
"details",
"about",
"locating",
"elements",
"."
] | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_element.py#L147-L157 |
245,375 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_element.py | _ElementKeywords.element_should_be_visible | def element_should_be_visible(self, locator, loglevel='INFO'):
"""Verifies that element identified with locator is visible.
Key attributes for arbitrary elements are `id` and `name`. See
`introduction` for details about locating elements.
New in AppiumLibrary 1.4.5
"""
if not self._element_find(locator, True, True).is_displayed():
self.log_source(loglevel)
raise AssertionError("Element '%s' should be visible "
"but did not" % locator) | python | def element_should_be_visible(self, locator, loglevel='INFO'):
if not self._element_find(locator, True, True).is_displayed():
self.log_source(loglevel)
raise AssertionError("Element '%s' should be visible "
"but did not" % locator) | [
"def",
"element_should_be_visible",
"(",
"self",
",",
"locator",
",",
"loglevel",
"=",
"'INFO'",
")",
":",
"if",
"not",
"self",
".",
"_element_find",
"(",
"locator",
",",
"True",
",",
"True",
")",
".",
"is_displayed",
"(",
")",
":",
"self",
".",
"log_sou... | Verifies that element identified with locator is visible.
Key attributes for arbitrary elements are `id` and `name`. See
`introduction` for details about locating elements.
New in AppiumLibrary 1.4.5 | [
"Verifies",
"that",
"element",
"identified",
"with",
"locator",
"is",
"visible",
".",
"Key",
"attributes",
"for",
"arbitrary",
"elements",
"are",
"id",
"and",
"name",
".",
"See",
"introduction",
"for",
"details",
"about",
"locating",
"elements",
".",
"New",
"i... | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_element.py#L171-L182 |
245,376 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_element.py | _ElementKeywords.element_text_should_be | def element_text_should_be(self, locator, expected, message=''):
"""Verifies element identified by ``locator`` exactly contains text ``expected``.
In contrast to `Element Should Contain Text`, this keyword does not try
a substring match but an exact match on the element identified by ``locator``.
``message`` can be used to override the default error message.
New in AppiumLibrary 1.4.
"""
self._info("Verifying element '%s' contains exactly text '%s'."
% (locator, expected))
element = self._element_find(locator, True, True)
actual = element.text
if expected != actual:
if not message:
message = "The text of element '%s' should have been '%s' but "\
"in fact it was '%s'." % (locator, expected, actual)
raise AssertionError(message) | python | def element_text_should_be(self, locator, expected, message=''):
self._info("Verifying element '%s' contains exactly text '%s'."
% (locator, expected))
element = self._element_find(locator, True, True)
actual = element.text
if expected != actual:
if not message:
message = "The text of element '%s' should have been '%s' but "\
"in fact it was '%s'." % (locator, expected, actual)
raise AssertionError(message) | [
"def",
"element_text_should_be",
"(",
"self",
",",
"locator",
",",
"expected",
",",
"message",
"=",
"''",
")",
":",
"self",
".",
"_info",
"(",
"\"Verifying element '%s' contains exactly text '%s'.\"",
"%",
"(",
"locator",
",",
"expected",
")",
")",
"element",
"=... | Verifies element identified by ``locator`` exactly contains text ``expected``.
In contrast to `Element Should Contain Text`, this keyword does not try
a substring match but an exact match on the element identified by ``locator``.
``message`` can be used to override the default error message.
New in AppiumLibrary 1.4. | [
"Verifies",
"element",
"identified",
"by",
"locator",
"exactly",
"contains",
"text",
"expected",
".",
"In",
"contrast",
"to",
"Element",
"Should",
"Contain",
"Text",
"this",
"keyword",
"does",
"not",
"try",
"a",
"substring",
"match",
"but",
"an",
"exact",
"mat... | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_element.py#L312-L330 |
245,377 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_element.py | _ElementKeywords.get_element_location | def get_element_location(self, locator):
"""Get element location
Key attributes for arbitrary elements are `id` and `name`. See
`introduction` for details about locating elements.
"""
element = self._element_find(locator, True, True)
element_location = element.location
self._info("Element '%s' location: %s " % (locator, element_location))
return element_location | python | def get_element_location(self, locator):
element = self._element_find(locator, True, True)
element_location = element.location
self._info("Element '%s' location: %s " % (locator, element_location))
return element_location | [
"def",
"get_element_location",
"(",
"self",
",",
"locator",
")",
":",
"element",
"=",
"self",
".",
"_element_find",
"(",
"locator",
",",
"True",
",",
"True",
")",
"element_location",
"=",
"element",
".",
"location",
"self",
".",
"_info",
"(",
"\"Element '%s'... | Get element location
Key attributes for arbitrary elements are `id` and `name`. See
`introduction` for details about locating elements. | [
"Get",
"element",
"location",
"Key",
"attributes",
"for",
"arbitrary",
"elements",
"are",
"id",
"and",
"name",
".",
"See",
"introduction",
"for",
"details",
"about",
"locating",
"elements",
"."
] | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_element.py#L380-L389 |
245,378 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_element.py | _ElementKeywords.get_element_size | def get_element_size(self, locator):
"""Get element size
Key attributes for arbitrary elements are `id` and `name`. See
`introduction` for details about locating elements.
"""
element = self._element_find(locator, True, True)
element_size = element.size
self._info("Element '%s' size: %s " % (locator, element_size))
return element_size | python | def get_element_size(self, locator):
element = self._element_find(locator, True, True)
element_size = element.size
self._info("Element '%s' size: %s " % (locator, element_size))
return element_size | [
"def",
"get_element_size",
"(",
"self",
",",
"locator",
")",
":",
"element",
"=",
"self",
".",
"_element_find",
"(",
"locator",
",",
"True",
",",
"True",
")",
"element_size",
"=",
"element",
".",
"size",
"self",
".",
"_info",
"(",
"\"Element '%s' size: %s \"... | Get element size
Key attributes for arbitrary elements are `id` and `name`. See
`introduction` for details about locating elements. | [
"Get",
"element",
"size",
"Key",
"attributes",
"for",
"arbitrary",
"elements",
"are",
"id",
"and",
"name",
".",
"See",
"introduction",
"for",
"details",
"about",
"locating",
"elements",
"."
] | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_element.py#L391-L400 |
245,379 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_element.py | _ElementKeywords.text_should_be_visible | def text_should_be_visible(self, text, exact_match=False, loglevel='INFO'):
"""Verifies that element identified with text is visible.
New in AppiumLibrary 1.4.5
"""
if not self._element_find_by_text(text, exact_match).is_displayed():
self.log_source(loglevel)
raise AssertionError("Text '%s' should be visible "
"but did not" % text) | python | def text_should_be_visible(self, text, exact_match=False, loglevel='INFO'):
if not self._element_find_by_text(text, exact_match).is_displayed():
self.log_source(loglevel)
raise AssertionError("Text '%s' should be visible "
"but did not" % text) | [
"def",
"text_should_be_visible",
"(",
"self",
",",
"text",
",",
"exact_match",
"=",
"False",
",",
"loglevel",
"=",
"'INFO'",
")",
":",
"if",
"not",
"self",
".",
"_element_find_by_text",
"(",
"text",
",",
"exact_match",
")",
".",
"is_displayed",
"(",
")",
"... | Verifies that element identified with text is visible.
New in AppiumLibrary 1.4.5 | [
"Verifies",
"that",
"element",
"identified",
"with",
"text",
"is",
"visible",
".",
"New",
"in",
"AppiumLibrary",
"1",
".",
"4",
".",
"5"
] | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_element.py#L433-L441 |
245,380 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_applicationmanagement.py | _ApplicationManagementKeywords.close_application | def close_application(self):
"""Closes the current application and also close webdriver session."""
self._debug('Closing application with session id %s' % self._current_application().session_id)
self._cache.close() | python | def close_application(self):
self._debug('Closing application with session id %s' % self._current_application().session_id)
self._cache.close() | [
"def",
"close_application",
"(",
"self",
")",
":",
"self",
".",
"_debug",
"(",
"'Closing application with session id %s'",
"%",
"self",
".",
"_current_application",
"(",
")",
".",
"session_id",
")",
"self",
".",
"_cache",
".",
"close",
"(",
")"
] | Closes the current application and also close webdriver session. | [
"Closes",
"the",
"current",
"application",
"and",
"also",
"close",
"webdriver",
"session",
"."
] | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_applicationmanagement.py#L20-L23 |
245,381 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_applicationmanagement.py | _ApplicationManagementKeywords.get_appium_sessionId | def get_appium_sessionId(self):
"""Returns the current session ID as a reference"""
self._info("Appium Session ID: " + self._current_application().session_id)
return self._current_application().session_id | python | def get_appium_sessionId(self):
self._info("Appium Session ID: " + self._current_application().session_id)
return self._current_application().session_id | [
"def",
"get_appium_sessionId",
"(",
"self",
")",
":",
"self",
".",
"_info",
"(",
"\"Appium Session ID: \"",
"+",
"self",
".",
"_current_application",
"(",
")",
".",
"session_id",
")",
"return",
"self",
".",
"_current_application",
"(",
")",
".",
"session_id"
] | Returns the current session ID as a reference | [
"Returns",
"the",
"current",
"session",
"ID",
"as",
"a",
"reference"
] | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_applicationmanagement.py#L163-L166 |
245,382 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_applicationmanagement.py | _ApplicationManagementKeywords.lock | def lock(self, seconds=5):
"""
Lock the device for a certain period of time. iOS only.
"""
self._current_application().lock(robot.utils.timestr_to_secs(seconds)) | python | def lock(self, seconds=5):
self._current_application().lock(robot.utils.timestr_to_secs(seconds)) | [
"def",
"lock",
"(",
"self",
",",
"seconds",
"=",
"5",
")",
":",
"self",
".",
"_current_application",
"(",
")",
".",
"lock",
"(",
"robot",
".",
"utils",
".",
"timestr_to_secs",
"(",
"seconds",
")",
")"
] | Lock the device for a certain period of time. iOS only. | [
"Lock",
"the",
"device",
"for",
"a",
"certain",
"period",
"of",
"time",
".",
"iOS",
"only",
"."
] | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_applicationmanagement.py#L221-L225 |
245,383 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_applicationmanagement.py | _ApplicationManagementKeywords.get_capability | def get_capability(self, capability_name):
"""
Return the desired capability value by desired capability name
"""
try:
capability = self._current_application().capabilities[capability_name]
except Exception as e:
raise e
return capability | python | def get_capability(self, capability_name):
try:
capability = self._current_application().capabilities[capability_name]
except Exception as e:
raise e
return capability | [
"def",
"get_capability",
"(",
"self",
",",
"capability_name",
")",
":",
"try",
":",
"capability",
"=",
"self",
".",
"_current_application",
"(",
")",
".",
"capabilities",
"[",
"capability_name",
"]",
"except",
"Exception",
"as",
"e",
":",
"raise",
"e",
"retu... | Return the desired capability value by desired capability name | [
"Return",
"the",
"desired",
"capability",
"value",
"by",
"desired",
"capability",
"name"
] | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_applicationmanagement.py#L317-L325 |
245,384 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/locators/elementfinder.py | ElementFinder._find_by_android | def _find_by_android(self, browser, criteria, tag, constraints):
"""Find element matches by UI Automator."""
return self._filter_elements(
browser.find_elements_by_android_uiautomator(criteria),
tag, constraints) | python | def _find_by_android(self, browser, criteria, tag, constraints):
return self._filter_elements(
browser.find_elements_by_android_uiautomator(criteria),
tag, constraints) | [
"def",
"_find_by_android",
"(",
"self",
",",
"browser",
",",
"criteria",
",",
"tag",
",",
"constraints",
")",
":",
"return",
"self",
".",
"_filter_elements",
"(",
"browser",
".",
"find_elements_by_android_uiautomator",
"(",
"criteria",
")",
",",
"tag",
",",
"c... | Find element matches by UI Automator. | [
"Find",
"element",
"matches",
"by",
"UI",
"Automator",
"."
] | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/locators/elementfinder.py#L98-L102 |
245,385 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/locators/elementfinder.py | ElementFinder._find_by_ios | def _find_by_ios(self, browser, criteria, tag, constraints):
"""Find element matches by UI Automation."""
return self._filter_elements(
browser.find_elements_by_ios_uiautomation(criteria),
tag, constraints) | python | def _find_by_ios(self, browser, criteria, tag, constraints):
return self._filter_elements(
browser.find_elements_by_ios_uiautomation(criteria),
tag, constraints) | [
"def",
"_find_by_ios",
"(",
"self",
",",
"browser",
",",
"criteria",
",",
"tag",
",",
"constraints",
")",
":",
"return",
"self",
".",
"_filter_elements",
"(",
"browser",
".",
"find_elements_by_ios_uiautomation",
"(",
"criteria",
")",
",",
"tag",
",",
"constrai... | Find element matches by UI Automation. | [
"Find",
"element",
"matches",
"by",
"UI",
"Automation",
"."
] | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/locators/elementfinder.py#L104-L108 |
245,386 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/locators/elementfinder.py | ElementFinder._find_by_nsp | def _find_by_nsp(self, browser, criteria, tag, constraints):
"""Find element matches by iOSNsPredicateString."""
return self._filter_elements(
browser.find_elements_by_ios_predicate(criteria),
tag, constraints) | python | def _find_by_nsp(self, browser, criteria, tag, constraints):
return self._filter_elements(
browser.find_elements_by_ios_predicate(criteria),
tag, constraints) | [
"def",
"_find_by_nsp",
"(",
"self",
",",
"browser",
",",
"criteria",
",",
"tag",
",",
"constraints",
")",
":",
"return",
"self",
".",
"_filter_elements",
"(",
"browser",
".",
"find_elements_by_ios_predicate",
"(",
"criteria",
")",
",",
"tag",
",",
"constraints... | Find element matches by iOSNsPredicateString. | [
"Find",
"element",
"matches",
"by",
"iOSNsPredicateString",
"."
] | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/locators/elementfinder.py#L110-L114 |
245,387 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/locators/elementfinder.py | ElementFinder._find_by_chain | def _find_by_chain(self, browser, criteria, tag, constraints):
"""Find element matches by iOSChainString."""
return self._filter_elements(
browser.find_elements_by_ios_class_chain(criteria),
tag, constraints) | python | def _find_by_chain(self, browser, criteria, tag, constraints):
return self._filter_elements(
browser.find_elements_by_ios_class_chain(criteria),
tag, constraints) | [
"def",
"_find_by_chain",
"(",
"self",
",",
"browser",
",",
"criteria",
",",
"tag",
",",
"constraints",
")",
":",
"return",
"self",
".",
"_filter_elements",
"(",
"browser",
".",
"find_elements_by_ios_class_chain",
"(",
"criteria",
")",
",",
"tag",
",",
"constra... | Find element matches by iOSChainString. | [
"Find",
"element",
"matches",
"by",
"iOSChainString",
"."
] | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/locators/elementfinder.py#L116-L120 |
245,388 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_keyevent.py | _KeyeventKeywords.press_keycode | def press_keycode(self, keycode, metastate=None):
"""Sends a press of keycode to the device.
Android only.
Possible keycodes & meta states can be found in
http://developer.android.com/reference/android/view/KeyEvent.html
Meta state describe the pressed state of key modifiers such as
Shift, Ctrl & Alt keys. The Meta State is an integer in which each
bit set to 1 represents a pressed meta key.
For example
- META_SHIFT_ON = 1
- META_ALT_ON = 2
| metastate=1 --> Shift is pressed
| metastate=2 --> Alt is pressed
| metastate=3 --> Shift+Alt is pressed
- _keycode- - the keycode to be sent to the device
- _metastate- - status of the meta keys
"""
driver = self._current_application()
driver.press_keycode(keycode, metastate) | python | def press_keycode(self, keycode, metastate=None):
driver = self._current_application()
driver.press_keycode(keycode, metastate) | [
"def",
"press_keycode",
"(",
"self",
",",
"keycode",
",",
"metastate",
"=",
"None",
")",
":",
"driver",
"=",
"self",
".",
"_current_application",
"(",
")",
"driver",
".",
"press_keycode",
"(",
"keycode",
",",
"metastate",
")"
] | Sends a press of keycode to the device.
Android only.
Possible keycodes & meta states can be found in
http://developer.android.com/reference/android/view/KeyEvent.html
Meta state describe the pressed state of key modifiers such as
Shift, Ctrl & Alt keys. The Meta State is an integer in which each
bit set to 1 represents a pressed meta key.
For example
- META_SHIFT_ON = 1
- META_ALT_ON = 2
| metastate=1 --> Shift is pressed
| metastate=2 --> Alt is pressed
| metastate=3 --> Shift+Alt is pressed
- _keycode- - the keycode to be sent to the device
- _metastate- - status of the meta keys | [
"Sends",
"a",
"press",
"of",
"keycode",
"to",
"the",
"device",
"."
] | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_keyevent.py#L9-L33 |
245,389 | serhatbolsu/robotframework-appiumlibrary | AppiumLibrary/keywords/_keyevent.py | _KeyeventKeywords.long_press_keycode | def long_press_keycode(self, keycode, metastate=None):
"""Sends a long press of keycode to the device.
Android only.
See `press keycode` for more details.
"""
driver = self._current_application()
driver.long_press_keycode(int(keycode), metastate) | python | def long_press_keycode(self, keycode, metastate=None):
driver = self._current_application()
driver.long_press_keycode(int(keycode), metastate) | [
"def",
"long_press_keycode",
"(",
"self",
",",
"keycode",
",",
"metastate",
"=",
"None",
")",
":",
"driver",
"=",
"self",
".",
"_current_application",
"(",
")",
"driver",
".",
"long_press_keycode",
"(",
"int",
"(",
"keycode",
")",
",",
"metastate",
")"
] | Sends a long press of keycode to the device.
Android only.
See `press keycode` for more details. | [
"Sends",
"a",
"long",
"press",
"of",
"keycode",
"to",
"the",
"device",
"."
] | 91c808cf0602af6be8135ac529fa488fded04a85 | https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_keyevent.py#L35-L43 |
245,390 | amanusk/s-tui | s_tui/sources/rapl_read.py | rapl_read | def rapl_read():
""" Read power stats and return dictionary"""
basenames = glob.glob('/sys/class/powercap/intel-rapl:*/')
basenames = sorted(set({x for x in basenames}))
pjoin = os.path.join
ret = list()
for path in basenames:
name = None
try:
name = cat(pjoin(path, 'name'), fallback=None, binary=False)
except (IOError, OSError, ValueError) as err:
logging.warning("ignoring %r for file %r",
(err, path), RuntimeWarning)
continue
if name:
try:
current = cat(pjoin(path, 'energy_uj'))
max_reading = 0.0
ret.append(RaplStats(name, float(current), max_reading))
except (IOError, OSError, ValueError) as err:
logging.warning("ignoring %r for file %r",
(err, path), RuntimeWarning)
return ret | python | def rapl_read():
basenames = glob.glob('/sys/class/powercap/intel-rapl:*/')
basenames = sorted(set({x for x in basenames}))
pjoin = os.path.join
ret = list()
for path in basenames:
name = None
try:
name = cat(pjoin(path, 'name'), fallback=None, binary=False)
except (IOError, OSError, ValueError) as err:
logging.warning("ignoring %r for file %r",
(err, path), RuntimeWarning)
continue
if name:
try:
current = cat(pjoin(path, 'energy_uj'))
max_reading = 0.0
ret.append(RaplStats(name, float(current), max_reading))
except (IOError, OSError, ValueError) as err:
logging.warning("ignoring %r for file %r",
(err, path), RuntimeWarning)
return ret | [
"def",
"rapl_read",
"(",
")",
":",
"basenames",
"=",
"glob",
".",
"glob",
"(",
"'/sys/class/powercap/intel-rapl:*/'",
")",
"basenames",
"=",
"sorted",
"(",
"set",
"(",
"{",
"x",
"for",
"x",
"in",
"basenames",
"}",
")",
")",
"pjoin",
"=",
"os",
".",
"pa... | Read power stats and return dictionary | [
"Read",
"power",
"stats",
"and",
"return",
"dictionary"
] | 5e89d15081e716024db28ec03b1e3a7710330951 | https://github.com/amanusk/s-tui/blob/5e89d15081e716024db28ec03b1e3a7710330951/s_tui/sources/rapl_read.py#L35-L58 |
245,391 | amanusk/s-tui | s_tui/sturwid/complex_bar_graph.py | ScalableBarGraph.calculate_bar_widths | def calculate_bar_widths(self, size, bardata):
"""
Return a list of bar widths, one for each bar in data.
If self.bar_width is None this implementation will stretch
the bars across the available space specified by maxcol.
"""
(maxcol, _) = size
if self.bar_width is not None:
return [self.bar_width] * min(
len(bardata), int(maxcol / self.bar_width))
if len(bardata) >= maxcol:
return [1] * maxcol
widths = []
grow = maxcol
remain = len(bardata)
for _ in bardata:
w = int(float(grow) / remain + 0.5)
widths.append(w)
grow -= w
remain -= 1
return widths | python | def calculate_bar_widths(self, size, bardata):
(maxcol, _) = size
if self.bar_width is not None:
return [self.bar_width] * min(
len(bardata), int(maxcol / self.bar_width))
if len(bardata) >= maxcol:
return [1] * maxcol
widths = []
grow = maxcol
remain = len(bardata)
for _ in bardata:
w = int(float(grow) / remain + 0.5)
widths.append(w)
grow -= w
remain -= 1
return widths | [
"def",
"calculate_bar_widths",
"(",
"self",
",",
"size",
",",
"bardata",
")",
":",
"(",
"maxcol",
",",
"_",
")",
"=",
"size",
"if",
"self",
".",
"bar_width",
"is",
"not",
"None",
":",
"return",
"[",
"self",
".",
"bar_width",
"]",
"*",
"min",
"(",
"... | Return a list of bar widths, one for each bar in data.
If self.bar_width is None this implementation will stretch
the bars across the available space specified by maxcol. | [
"Return",
"a",
"list",
"of",
"bar",
"widths",
"one",
"for",
"each",
"bar",
"in",
"data",
"."
] | 5e89d15081e716024db28ec03b1e3a7710330951 | https://github.com/amanusk/s-tui/blob/5e89d15081e716024db28ec03b1e3a7710330951/s_tui/sturwid/complex_bar_graph.py#L43-L67 |
245,392 | amanusk/s-tui | s_tui/sturwid/complex_bar_graph.py | LabeledBarGraphVector.set_visible_graphs | def set_visible_graphs(self, visible_graph_list=None):
"""Show a column of the graph selected for display"""
if visible_graph_list is None:
visible_graph_list = self.visible_graph_list
vline = urwid.AttrWrap(urwid.SolidFill(u'|'), 'line')
graph_vector_column_list = []
for state, graph, sub_title in zip(visible_graph_list,
self.bar_graph_vector,
self.sub_title_list):
if state:
text_w = urwid.Text(sub_title, align='center')
sub_title_widget = urwid.ListBox([text_w])
graph_a = [('fixed', 1, sub_title_widget),
('weight', 1, graph)]
graph_and_title = urwid.Pile(graph_a)
graph_vector_column_list.append(('weight', 1, graph_and_title))
graph_vector_column_list.append(('fixed', 1, vline))
# if all sub graph are disabled
if not graph_vector_column_list:
self.visible_graph_list = visible_graph_list
self.original_widget = urwid.Pile([])
return
# remove the last vertical line separator
graph_vector_column_list.pop()
y_label_a = ('weight', 1, urwid.Columns(graph_vector_column_list))
y_label_and_graphs = [self.y_label,
y_label_a]
column_w = urwid.Columns(y_label_and_graphs, dividechars=1)
y_label_and_graphs_widget = urwid.WidgetPlaceholder(column_w)
init_widget = urwid.Pile([('fixed', 1, self.title),
('weight', 1, y_label_and_graphs_widget)])
self.visible_graph_list = visible_graph_list
self.original_widget = init_widget | python | def set_visible_graphs(self, visible_graph_list=None):
if visible_graph_list is None:
visible_graph_list = self.visible_graph_list
vline = urwid.AttrWrap(urwid.SolidFill(u'|'), 'line')
graph_vector_column_list = []
for state, graph, sub_title in zip(visible_graph_list,
self.bar_graph_vector,
self.sub_title_list):
if state:
text_w = urwid.Text(sub_title, align='center')
sub_title_widget = urwid.ListBox([text_w])
graph_a = [('fixed', 1, sub_title_widget),
('weight', 1, graph)]
graph_and_title = urwid.Pile(graph_a)
graph_vector_column_list.append(('weight', 1, graph_and_title))
graph_vector_column_list.append(('fixed', 1, vline))
# if all sub graph are disabled
if not graph_vector_column_list:
self.visible_graph_list = visible_graph_list
self.original_widget = urwid.Pile([])
return
# remove the last vertical line separator
graph_vector_column_list.pop()
y_label_a = ('weight', 1, urwid.Columns(graph_vector_column_list))
y_label_and_graphs = [self.y_label,
y_label_a]
column_w = urwid.Columns(y_label_and_graphs, dividechars=1)
y_label_and_graphs_widget = urwid.WidgetPlaceholder(column_w)
init_widget = urwid.Pile([('fixed', 1, self.title),
('weight', 1, y_label_and_graphs_widget)])
self.visible_graph_list = visible_graph_list
self.original_widget = init_widget | [
"def",
"set_visible_graphs",
"(",
"self",
",",
"visible_graph_list",
"=",
"None",
")",
":",
"if",
"visible_graph_list",
"is",
"None",
":",
"visible_graph_list",
"=",
"self",
".",
"visible_graph_list",
"vline",
"=",
"urwid",
".",
"AttrWrap",
"(",
"urwid",
".",
... | Show a column of the graph selected for display | [
"Show",
"a",
"column",
"of",
"the",
"graph",
"selected",
"for",
"display"
] | 5e89d15081e716024db28ec03b1e3a7710330951 | https://github.com/amanusk/s-tui/blob/5e89d15081e716024db28ec03b1e3a7710330951/s_tui/sturwid/complex_bar_graph.py#L135-L174 |
245,393 | amanusk/s-tui | s_tui/helper_functions.py | get_processor_name | def get_processor_name():
""" Returns the processor name in the system """
if platform.system() == "Linux":
with open("/proc/cpuinfo", "rb") as cpuinfo:
all_info = cpuinfo.readlines()
for line in all_info:
if b'model name' in line:
return re.sub(b'.*model name.*:', b'', line, 1)
return platform.processor() | python | def get_processor_name():
if platform.system() == "Linux":
with open("/proc/cpuinfo", "rb") as cpuinfo:
all_info = cpuinfo.readlines()
for line in all_info:
if b'model name' in line:
return re.sub(b'.*model name.*:', b'', line, 1)
return platform.processor() | [
"def",
"get_processor_name",
"(",
")",
":",
"if",
"platform",
".",
"system",
"(",
")",
"==",
"\"Linux\"",
":",
"with",
"open",
"(",
"\"/proc/cpuinfo\"",
",",
"\"rb\"",
")",
"as",
"cpuinfo",
":",
"all_info",
"=",
"cpuinfo",
".",
"readlines",
"(",
")",
"fo... | Returns the processor name in the system | [
"Returns",
"the",
"processor",
"name",
"in",
"the",
"system"
] | 5e89d15081e716024db28ec03b1e3a7710330951 | https://github.com/amanusk/s-tui/blob/5e89d15081e716024db28ec03b1e3a7710330951/s_tui/helper_functions.py#L47-L56 |
245,394 | amanusk/s-tui | s_tui/helper_functions.py | kill_child_processes | def kill_child_processes(parent_proc):
""" Kills a process and all its children """
logging.debug("Killing stress process")
try:
for proc in parent_proc.children(recursive=True):
logging.debug('Killing %s', proc)
proc.kill()
parent_proc.kill()
except AttributeError:
logging.debug('No such process')
logging.debug('Could not kill process') | python | def kill_child_processes(parent_proc):
logging.debug("Killing stress process")
try:
for proc in parent_proc.children(recursive=True):
logging.debug('Killing %s', proc)
proc.kill()
parent_proc.kill()
except AttributeError:
logging.debug('No such process')
logging.debug('Could not kill process') | [
"def",
"kill_child_processes",
"(",
"parent_proc",
")",
":",
"logging",
".",
"debug",
"(",
"\"Killing stress process\"",
")",
"try",
":",
"for",
"proc",
"in",
"parent_proc",
".",
"children",
"(",
"recursive",
"=",
"True",
")",
":",
"logging",
".",
"debug",
"... | Kills a process and all its children | [
"Kills",
"a",
"process",
"and",
"all",
"its",
"children"
] | 5e89d15081e716024db28ec03b1e3a7710330951 | https://github.com/amanusk/s-tui/blob/5e89d15081e716024db28ec03b1e3a7710330951/s_tui/helper_functions.py#L59-L69 |
245,395 | amanusk/s-tui | s_tui/helper_functions.py | output_to_csv | def output_to_csv(sources, csv_writeable_file):
"""Print statistics to csv file"""
file_exists = os.path.isfile(csv_writeable_file)
with open(csv_writeable_file, 'a') as csvfile:
csv_dict = OrderedDict()
csv_dict.update({'Time': time.strftime("%Y-%m-%d_%H:%M:%S")})
summaries = [val for key, val in sources.items()]
for summarie in summaries:
csv_dict.update(summarie.source.get_sensors_summary())
fieldnames = [key for key, val in csv_dict.items()]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
if not file_exists:
writer.writeheader() # file doesn't exist yet, write a header
writer.writerow(csv_dict) | python | def output_to_csv(sources, csv_writeable_file):
file_exists = os.path.isfile(csv_writeable_file)
with open(csv_writeable_file, 'a') as csvfile:
csv_dict = OrderedDict()
csv_dict.update({'Time': time.strftime("%Y-%m-%d_%H:%M:%S")})
summaries = [val for key, val in sources.items()]
for summarie in summaries:
csv_dict.update(summarie.source.get_sensors_summary())
fieldnames = [key for key, val in csv_dict.items()]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
if not file_exists:
writer.writeheader() # file doesn't exist yet, write a header
writer.writerow(csv_dict) | [
"def",
"output_to_csv",
"(",
"sources",
",",
"csv_writeable_file",
")",
":",
"file_exists",
"=",
"os",
".",
"path",
".",
"isfile",
"(",
"csv_writeable_file",
")",
"with",
"open",
"(",
"csv_writeable_file",
",",
"'a'",
")",
"as",
"csvfile",
":",
"csv_dict",
"... | Print statistics to csv file | [
"Print",
"statistics",
"to",
"csv",
"file"
] | 5e89d15081e716024db28ec03b1e3a7710330951 | https://github.com/amanusk/s-tui/blob/5e89d15081e716024db28ec03b1e3a7710330951/s_tui/helper_functions.py#L72-L88 |
245,396 | amanusk/s-tui | s_tui/helper_functions.py | output_to_terminal | def output_to_terminal(sources):
"""Print statistics to the terminal"""
results = OrderedDict()
for source in sources:
if source.get_is_available():
source.update()
results.update(source.get_summary())
for key, value in results.items():
sys.stdout.write(str(key) + ": " + str(value) + ", ")
sys.stdout.write("\n")
sys.exit() | python | def output_to_terminal(sources):
results = OrderedDict()
for source in sources:
if source.get_is_available():
source.update()
results.update(source.get_summary())
for key, value in results.items():
sys.stdout.write(str(key) + ": " + str(value) + ", ")
sys.stdout.write("\n")
sys.exit() | [
"def",
"output_to_terminal",
"(",
"sources",
")",
":",
"results",
"=",
"OrderedDict",
"(",
")",
"for",
"source",
"in",
"sources",
":",
"if",
"source",
".",
"get_is_available",
"(",
")",
":",
"source",
".",
"update",
"(",
")",
"results",
".",
"update",
"(... | Print statistics to the terminal | [
"Print",
"statistics",
"to",
"the",
"terminal"
] | 5e89d15081e716024db28ec03b1e3a7710330951 | https://github.com/amanusk/s-tui/blob/5e89d15081e716024db28ec03b1e3a7710330951/s_tui/helper_functions.py#L91-L101 |
245,397 | amanusk/s-tui | s_tui/helper_functions.py | output_to_json | def output_to_json(sources):
"""Print statistics to the terminal in Json format"""
results = OrderedDict()
for source in sources:
if source.get_is_available():
source.update()
source_name = source.get_source_name()
results[source_name] = source.get_sensors_summary()
print(json.dumps(results, indent=4))
sys.exit() | python | def output_to_json(sources):
results = OrderedDict()
for source in sources:
if source.get_is_available():
source.update()
source_name = source.get_source_name()
results[source_name] = source.get_sensors_summary()
print(json.dumps(results, indent=4))
sys.exit() | [
"def",
"output_to_json",
"(",
"sources",
")",
":",
"results",
"=",
"OrderedDict",
"(",
")",
"for",
"source",
"in",
"sources",
":",
"if",
"source",
".",
"get_is_available",
"(",
")",
":",
"source",
".",
"update",
"(",
")",
"source_name",
"=",
"source",
".... | Print statistics to the terminal in Json format | [
"Print",
"statistics",
"to",
"the",
"terminal",
"in",
"Json",
"format"
] | 5e89d15081e716024db28ec03b1e3a7710330951 | https://github.com/amanusk/s-tui/blob/5e89d15081e716024db28ec03b1e3a7710330951/s_tui/helper_functions.py#L104-L113 |
245,398 | amanusk/s-tui | s_tui/helper_functions.py | make_user_config_dir | def make_user_config_dir():
"""
Create the user s-tui config directory if it doesn't exist
"""
config_path = get_user_config_dir()
if not user_config_dir_exists():
try:
os.mkdir(config_path)
os.mkdir(os.path.join(config_path, 'hooks.d'))
except OSError:
return None
return config_path | python | def make_user_config_dir():
config_path = get_user_config_dir()
if not user_config_dir_exists():
try:
os.mkdir(config_path)
os.mkdir(os.path.join(config_path, 'hooks.d'))
except OSError:
return None
return config_path | [
"def",
"make_user_config_dir",
"(",
")",
":",
"config_path",
"=",
"get_user_config_dir",
"(",
")",
"if",
"not",
"user_config_dir_exists",
"(",
")",
":",
"try",
":",
"os",
".",
"mkdir",
"(",
"config_path",
")",
"os",
".",
"mkdir",
"(",
"os",
".",
"path",
... | Create the user s-tui config directory if it doesn't exist | [
"Create",
"the",
"user",
"s",
"-",
"tui",
"config",
"directory",
"if",
"it",
"doesn",
"t",
"exist"
] | 5e89d15081e716024db28ec03b1e3a7710330951 | https://github.com/amanusk/s-tui/blob/5e89d15081e716024db28ec03b1e3a7710330951/s_tui/helper_functions.py#L157-L170 |
245,399 | amanusk/s-tui | s_tui/sources/script_hook_loader.py | ScriptHookLoader.load_script | def load_script(self, source_name, timeoutMilliseconds=0):
"""
Return ScriptHook for source_name Source and with a ready timeout
of timeoutMilliseconds
"""
script_path = os.path.join(self.scripts_dir_path,
self._source_to_script_name(source_name))
if os.path.isfile(script_path):
return ScriptHook(script_path, timeoutMilliseconds)
return None | python | def load_script(self, source_name, timeoutMilliseconds=0):
script_path = os.path.join(self.scripts_dir_path,
self._source_to_script_name(source_name))
if os.path.isfile(script_path):
return ScriptHook(script_path, timeoutMilliseconds)
return None | [
"def",
"load_script",
"(",
"self",
",",
"source_name",
",",
"timeoutMilliseconds",
"=",
"0",
")",
":",
"script_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"scripts_dir_path",
",",
"self",
".",
"_source_to_script_name",
"(",
"source_name",
"... | Return ScriptHook for source_name Source and with a ready timeout
of timeoutMilliseconds | [
"Return",
"ScriptHook",
"for",
"source_name",
"Source",
"and",
"with",
"a",
"ready",
"timeout",
"of",
"timeoutMilliseconds"
] | 5e89d15081e716024db28ec03b1e3a7710330951 | https://github.com/amanusk/s-tui/blob/5e89d15081e716024db28ec03b1e3a7710330951/s_tui/sources/script_hook_loader.py#L31-L42 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.