repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
totalgood/nlpia
src/nlpia/loaders.py
normalize_column_names
def normalize_column_names(df): r""" Clean up whitespace in column names. See better version at `pugnlp.clean_columns` >>> df = pd.DataFrame([[1, 2], [3, 4]], columns=['Hello World', 'not here']) >>> normalize_column_names(df) ['hello_world', 'not_here'] """ columns = df.columns if hasattr(df, ...
python
def normalize_column_names(df): r""" Clean up whitespace in column names. See better version at `pugnlp.clean_columns` >>> df = pd.DataFrame([[1, 2], [3, 4]], columns=['Hello World', 'not here']) >>> normalize_column_names(df) ['hello_world', 'not_here'] """ columns = df.columns if hasattr(df, ...
[ "def", "normalize_column_names", "(", "df", ")", ":", "r", "columns", "=", "df", ".", "columns", "if", "hasattr", "(", "df", ",", "'columns'", ")", "else", "df", "columns", "=", "[", "c", ".", "lower", "(", ")", ".", "replace", "(", "' '", ",", "'_...
r""" Clean up whitespace in column names. See better version at `pugnlp.clean_columns` >>> df = pd.DataFrame([[1, 2], [3, 4]], columns=['Hello World', 'not here']) >>> normalize_column_names(df) ['hello_world', 'not_here']
[ "r", "Clean", "up", "whitespace", "in", "column", "names", ".", "See", "better", "version", "at", "pugnlp", ".", "clean_columns" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L1167-L1176
train
totalgood/nlpia
src/nlpia/loaders.py
clean_column_values
def clean_column_values(df, inplace=True): r""" Convert dollar value strings, numbers with commas, and percents into floating point values >>> df = get_data('us_gov_deficits_raw') >>> df2 = clean_column_values(df, inplace=False) >>> df2.iloc[0] Fiscal year ...
python
def clean_column_values(df, inplace=True): r""" Convert dollar value strings, numbers with commas, and percents into floating point values >>> df = get_data('us_gov_deficits_raw') >>> df2 = clean_column_values(df, inplace=False) >>> df2.iloc[0] Fiscal year ...
[ "def", "clean_column_values", "(", "df", ",", "inplace", "=", "True", ")", ":", "r", "dollars_percents", "=", "re", ".", "compile", "(", "r'[%$,;\\s]+'", ")", "if", "not", "inplace", ":", "df", "=", "df", ".", "copy", "(", ")", "for", "c", "in", "df"...
r""" Convert dollar value strings, numbers with commas, and percents into floating point values >>> df = get_data('us_gov_deficits_raw') >>> df2 = clean_column_values(df, inplace=False) >>> df2.iloc[0] Fiscal year 10/2017-3/2018 Presiden...
[ "r", "Convert", "dollar", "value", "strings", "numbers", "with", "commas", "and", "percents", "into", "floating", "point", "values" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L1179-L1222
train
totalgood/nlpia
src/nlpia/loaders.py
isglove
def isglove(filepath): """ Get the first word vector in a GloVE file and return its dimensionality or False if not a vector >>> isglove(os.path.join(DATA_PATH, 'cats_and_dogs.txt')) False """ with ensure_open(filepath, 'r') as f: header_line = f.readline() vector_line = f.readline(...
python
def isglove(filepath): """ Get the first word vector in a GloVE file and return its dimensionality or False if not a vector >>> isglove(os.path.join(DATA_PATH, 'cats_and_dogs.txt')) False """ with ensure_open(filepath, 'r') as f: header_line = f.readline() vector_line = f.readline(...
[ "def", "isglove", "(", "filepath", ")", ":", "with", "ensure_open", "(", "filepath", ",", "'r'", ")", "as", "f", ":", "header_line", "=", "f", ".", "readline", "(", ")", "vector_line", "=", "f", ".", "readline", "(", ")", "try", ":", "num_vectors", "...
Get the first word vector in a GloVE file and return its dimensionality or False if not a vector >>> isglove(os.path.join(DATA_PATH, 'cats_and_dogs.txt')) False
[ "Get", "the", "first", "word", "vector", "in", "a", "GloVE", "file", "and", "return", "its", "dimensionality", "or", "False", "if", "not", "a", "vector" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L1320-L1346
train
totalgood/nlpia
src/nlpia/loaders.py
nlp
def nlp(texts, lang='en', linesep=None, verbose=True): r""" Use the SpaCy parser to parse and tag natural language strings. Load the SpaCy parser language model lazily and share it among all nlpia modules. Probably unnecessary, since SpaCy probably takes care of this with `spacy.load()` >>> _parse is ...
python
def nlp(texts, lang='en', linesep=None, verbose=True): r""" Use the SpaCy parser to parse and tag natural language strings. Load the SpaCy parser language model lazily and share it among all nlpia modules. Probably unnecessary, since SpaCy probably takes care of this with `spacy.load()` >>> _parse is ...
[ "def", "nlp", "(", "texts", ",", "lang", "=", "'en'", ",", "linesep", "=", "None", ",", "verbose", "=", "True", ")", ":", "r", "linesep", "=", "os", ".", "linesep", "if", "linesep", "in", "(", "'default'", ",", "True", ",", "1", ",", "'os'", ")",...
r""" Use the SpaCy parser to parse and tag natural language strings. Load the SpaCy parser language model lazily and share it among all nlpia modules. Probably unnecessary, since SpaCy probably takes care of this with `spacy.load()` >>> _parse is None True >>> doc = nlp("Domo arigatto Mr. Roboto."...
[ "r", "Use", "the", "SpaCy", "parser", "to", "parse", "and", "tag", "natural", "language", "strings", "." ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L1349-L1405
train
totalgood/nlpia
src/nlpia/talk.py
get_decoder
def get_decoder(libdir=None, modeldir=None, lang='en-us'): """ Create a decoder with the requested language model """ modeldir = modeldir or (os.path.join(libdir, 'model') if libdir else MODELDIR) libdir = os.path.dirname(modeldir) config = ps.Decoder.default_config() config.set_string('-hmm', os.pa...
python
def get_decoder(libdir=None, modeldir=None, lang='en-us'): """ Create a decoder with the requested language model """ modeldir = modeldir or (os.path.join(libdir, 'model') if libdir else MODELDIR) libdir = os.path.dirname(modeldir) config = ps.Decoder.default_config() config.set_string('-hmm', os.pa...
[ "def", "get_decoder", "(", "libdir", "=", "None", ",", "modeldir", "=", "None", ",", "lang", "=", "'en-us'", ")", ":", "modeldir", "=", "modeldir", "or", "(", "os", ".", "path", ".", "join", "(", "libdir", ",", "'model'", ")", "if", "libdir", "else",...
Create a decoder with the requested language model
[ "Create", "a", "decoder", "with", "the", "requested", "language", "model" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/talk.py#L43-L52
train
totalgood/nlpia
src/nlpia/talk.py
transcribe
def transcribe(decoder, audio_file, libdir=None): """ Decode streaming audio data from raw binary file on disk. """ decoder = get_decoder() decoder.start_utt() stream = open(audio_file, 'rb') while True: buf = stream.read(1024) if buf: decoder.process_raw(buf, False, Fal...
python
def transcribe(decoder, audio_file, libdir=None): """ Decode streaming audio data from raw binary file on disk. """ decoder = get_decoder() decoder.start_utt() stream = open(audio_file, 'rb') while True: buf = stream.read(1024) if buf: decoder.process_raw(buf, False, Fal...
[ "def", "transcribe", "(", "decoder", ",", "audio_file", ",", "libdir", "=", "None", ")", ":", "decoder", "=", "get_decoder", "(", ")", "decoder", ".", "start_utt", "(", ")", "stream", "=", "open", "(", "audio_file", ",", "'rb'", ")", "while", "True", "...
Decode streaming audio data from raw binary file on disk.
[ "Decode", "streaming", "audio", "data", "from", "raw", "binary", "file", "on", "disk", "." ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/talk.py#L67-L80
train
totalgood/nlpia
src/nlpia/book/examples/ch09.py
pre_process_data
def pre_process_data(filepath): """ This is dependent on your training data source but we will try to generalize it as best as possible. """ positive_path = os.path.join(filepath, 'pos') negative_path = os.path.join(filepath, 'neg') pos_label = 1 neg_label = 0 dataset = [] for fil...
python
def pre_process_data(filepath): """ This is dependent on your training data source but we will try to generalize it as best as possible. """ positive_path = os.path.join(filepath, 'pos') negative_path = os.path.join(filepath, 'neg') pos_label = 1 neg_label = 0 dataset = [] for fil...
[ "def", "pre_process_data", "(", "filepath", ")", ":", "positive_path", "=", "os", ".", "path", ".", "join", "(", "filepath", ",", "'pos'", ")", "negative_path", "=", "os", ".", "path", ".", "join", "(", "filepath", ",", "'neg'", ")", "pos_label", "=", ...
This is dependent on your training data source but we will try to generalize it as best as possible.
[ "This", "is", "dependent", "on", "your", "training", "data", "source", "but", "we", "will", "try", "to", "generalize", "it", "as", "best", "as", "possible", "." ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book/examples/ch09.py#L141-L163
train
totalgood/nlpia
src/nlpia/book/examples/ch09.py
pad_trunc
def pad_trunc(data, maxlen): """ For a given dataset pad with zero vectors or truncate to maxlen """ new_data = [] # Create a vector of 0's the length of our word vectors zero_vector = [] for _ in range(len(data[0][0])): zero_vector.append(0.0) for sample in data: if len(sampl...
python
def pad_trunc(data, maxlen): """ For a given dataset pad with zero vectors or truncate to maxlen """ new_data = [] # Create a vector of 0's the length of our word vectors zero_vector = [] for _ in range(len(data[0][0])): zero_vector.append(0.0) for sample in data: if len(sampl...
[ "def", "pad_trunc", "(", "data", ",", "maxlen", ")", ":", "new_data", "=", "[", "]", "zero_vector", "=", "[", "]", "for", "_", "in", "range", "(", "len", "(", "data", "[", "0", "]", "[", "0", "]", ")", ")", ":", "zero_vector", ".", "append", "(...
For a given dataset pad with zero vectors or truncate to maxlen
[ "For", "a", "given", "dataset", "pad", "with", "zero", "vectors", "or", "truncate", "to", "maxlen" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book/examples/ch09.py#L207-L228
train
totalgood/nlpia
src/nlpia/book/examples/ch09.py
clean_data
def clean_data(data): """ Shift to lower case, replace unknowns with UNK, and listify """ new_data = [] VALID = 'abcdefghijklmnopqrstuvwxyz123456789"\'?!.,:; ' for sample in data: new_sample = [] for char in sample[1].lower(): # Just grab the string, not the label if char in...
python
def clean_data(data): """ Shift to lower case, replace unknowns with UNK, and listify """ new_data = [] VALID = 'abcdefghijklmnopqrstuvwxyz123456789"\'?!.,:; ' for sample in data: new_sample = [] for char in sample[1].lower(): # Just grab the string, not the label if char in...
[ "def", "clean_data", "(", "data", ")", ":", "new_data", "=", "[", "]", "VALID", "=", "'abcdefghijklmnopqrstuvwxyz123456789\"\\'?!.,:; '", "for", "sample", "in", "data", ":", "new_sample", "=", "[", "]", "for", "char", "in", "sample", "[", "1", "]", ".", "l...
Shift to lower case, replace unknowns with UNK, and listify
[ "Shift", "to", "lower", "case", "replace", "unknowns", "with", "UNK", "and", "listify" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book/examples/ch09.py#L436-L449
train
totalgood/nlpia
src/nlpia/book/examples/ch09.py
char_pad_trunc
def char_pad_trunc(data, maxlen): """ We truncate to maxlen or add in PAD tokens """ new_dataset = [] for sample in data: if len(sample) > maxlen: new_data = sample[:maxlen] elif len(sample) < maxlen: pads = maxlen - len(sample) new_data = sample + ['PAD']...
python
def char_pad_trunc(data, maxlen): """ We truncate to maxlen or add in PAD tokens """ new_dataset = [] for sample in data: if len(sample) > maxlen: new_data = sample[:maxlen] elif len(sample) < maxlen: pads = maxlen - len(sample) new_data = sample + ['PAD']...
[ "def", "char_pad_trunc", "(", "data", ",", "maxlen", ")", ":", "new_dataset", "=", "[", "]", "for", "sample", "in", "data", ":", "if", "len", "(", "sample", ")", ">", "maxlen", ":", "new_data", "=", "sample", "[", ":", "maxlen", "]", "elif", "len", ...
We truncate to maxlen or add in PAD tokens
[ "We", "truncate", "to", "maxlen", "or", "add", "in", "PAD", "tokens" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book/examples/ch09.py#L458-L470
train
totalgood/nlpia
src/nlpia/book/examples/ch09.py
create_dicts
def create_dicts(data): """ Modified from Keras LSTM example""" chars = set() for sample in data: chars.update(set(sample)) char_indices = dict((c, i) for i, c in enumerate(chars)) indices_char = dict((i, c) for i, c in enumerate(chars)) return char_indices, indices_char
python
def create_dicts(data): """ Modified from Keras LSTM example""" chars = set() for sample in data: chars.update(set(sample)) char_indices = dict((c, i) for i, c in enumerate(chars)) indices_char = dict((i, c) for i, c in enumerate(chars)) return char_indices, indices_char
[ "def", "create_dicts", "(", "data", ")", ":", "chars", "=", "set", "(", ")", "for", "sample", "in", "data", ":", "chars", ".", "update", "(", "set", "(", "sample", ")", ")", "char_indices", "=", "dict", "(", "(", "c", ",", "i", ")", "for", "i", ...
Modified from Keras LSTM example
[ "Modified", "from", "Keras", "LSTM", "example" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book/examples/ch09.py#L479-L486
train
totalgood/nlpia
src/nlpia/book/examples/ch09.py
onehot_encode
def onehot_encode(dataset, char_indices, maxlen): """ One hot encode the tokens Args: dataset list of lists of tokens char_indices dictionary of {key=character, value=index to use encoding vector} maxlen int Length of each sample Return: np array of shape (samples, ...
python
def onehot_encode(dataset, char_indices, maxlen): """ One hot encode the tokens Args: dataset list of lists of tokens char_indices dictionary of {key=character, value=index to use encoding vector} maxlen int Length of each sample Return: np array of shape (samples, ...
[ "def", "onehot_encode", "(", "dataset", ",", "char_indices", ",", "maxlen", ")", ":", "X", "=", "np", ".", "zeros", "(", "(", "len", "(", "dataset", ")", ",", "maxlen", ",", "len", "(", "char_indices", ".", "keys", "(", ")", ")", ")", ")", "for", ...
One hot encode the tokens Args: dataset list of lists of tokens char_indices dictionary of {key=character, value=index to use encoding vector} maxlen int Length of each sample Return: np array of shape (samples, tokens, encoding length)
[ "One", "hot", "encode", "the", "tokens" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book/examples/ch09.py#L495-L510
train
totalgood/nlpia
src/nlpia/book/examples/ch04_sklearn_pca_source.py
_fit_full
def _fit_full(self=self, X=X, n_components=6): """Fit the model by computing full SVD on X""" n_samples, n_features = X.shape # Center data self.mean_ = np.mean(X, axis=0) print(self.mean_) X -= self.mean_ print(X.round(2)) U, S, V = linalg.svd(X, full_matrices=False) print(V.round...
python
def _fit_full(self=self, X=X, n_components=6): """Fit the model by computing full SVD on X""" n_samples, n_features = X.shape # Center data self.mean_ = np.mean(X, axis=0) print(self.mean_) X -= self.mean_ print(X.round(2)) U, S, V = linalg.svd(X, full_matrices=False) print(V.round...
[ "def", "_fit_full", "(", "self", "=", "self", ",", "X", "=", "X", ",", "n_components", "=", "6", ")", ":", "n_samples", ",", "n_features", "=", "X", ".", "shape", "self", ".", "mean_", "=", "np", ".", "mean", "(", "X", ",", "axis", "=", "0", ")...
Fit the model by computing full SVD on X
[ "Fit", "the", "model", "by", "computing", "full", "SVD", "on", "X" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book/examples/ch04_sklearn_pca_source.py#L136-L186
train
totalgood/nlpia
src/nlpia/clean_alice.py
extract_aiml
def extract_aiml(path='aiml-en-us-foundation-alice.v1-9'): """ Extract an aiml.zip file if it hasn't been already and return a list of aiml file paths """ path = find_data_path(path) or path if os.path.isdir(path): paths = os.listdir(path) paths = [os.path.join(path, p) for p in paths] e...
python
def extract_aiml(path='aiml-en-us-foundation-alice.v1-9'): """ Extract an aiml.zip file if it hasn't been already and return a list of aiml file paths """ path = find_data_path(path) or path if os.path.isdir(path): paths = os.listdir(path) paths = [os.path.join(path, p) for p in paths] e...
[ "def", "extract_aiml", "(", "path", "=", "'aiml-en-us-foundation-alice.v1-9'", ")", ":", "path", "=", "find_data_path", "(", "path", ")", "or", "path", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "paths", "=", "os", ".", "listdir", "(",...
Extract an aiml.zip file if it hasn't been already and return a list of aiml file paths
[ "Extract", "an", "aiml", ".", "zip", "file", "if", "it", "hasn", "t", "been", "already", "and", "return", "a", "list", "of", "aiml", "file", "paths" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/clean_alice.py#L85-L98
train
totalgood/nlpia
src/nlpia/clean_alice.py
create_brain
def create_brain(path='aiml-en-us-foundation-alice.v1-9.zip'): """ Create an aiml_bot.Bot brain from an AIML zip file or directory of AIML files """ path = find_data_path(path) or path bot = Bot() num_templates = bot._brain.template_count paths = extract_aiml(path=path) for path in paths: ...
python
def create_brain(path='aiml-en-us-foundation-alice.v1-9.zip'): """ Create an aiml_bot.Bot brain from an AIML zip file or directory of AIML files """ path = find_data_path(path) or path bot = Bot() num_templates = bot._brain.template_count paths = extract_aiml(path=path) for path in paths: ...
[ "def", "create_brain", "(", "path", "=", "'aiml-en-us-foundation-alice.v1-9.zip'", ")", ":", "path", "=", "find_data_path", "(", "path", ")", "or", "path", "bot", "=", "Bot", "(", ")", "num_templates", "=", "bot", ".", "_brain", ".", "template_count", "paths",...
Create an aiml_bot.Bot brain from an AIML zip file or directory of AIML files
[ "Create", "an", "aiml_bot", ".", "Bot", "brain", "from", "an", "AIML", "zip", "file", "or", "directory", "of", "AIML", "files" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/clean_alice.py#L101-L119
train
totalgood/nlpia
src/nlpia/transcoders.py
minify_urls
def minify_urls(filepath, ext='asc', url_regex=None, output_ext='.urls_minified', access_token=None): """ Use bitly or similar minifier to shrink all URLs in text files within a folder structure. Used for the NLPIA manuscript directory for Manning Publishing bitly API: https://dev.bitly.com/links.html ...
python
def minify_urls(filepath, ext='asc', url_regex=None, output_ext='.urls_minified', access_token=None): """ Use bitly or similar minifier to shrink all URLs in text files within a folder structure. Used for the NLPIA manuscript directory for Manning Publishing bitly API: https://dev.bitly.com/links.html ...
[ "def", "minify_urls", "(", "filepath", ",", "ext", "=", "'asc'", ",", "url_regex", "=", "None", ",", "output_ext", "=", "'.urls_minified'", ",", "access_token", "=", "None", ")", ":", "access_token", "=", "access_token", "or", "secrets", ".", "bitly", ".", ...
Use bitly or similar minifier to shrink all URLs in text files within a folder structure. Used for the NLPIA manuscript directory for Manning Publishing bitly API: https://dev.bitly.com/links.html Args: path (str): Directory or file path ext (str): File name extension to filter text files by....
[ "Use", "bitly", "or", "similar", "minifier", "to", "shrink", "all", "URLs", "in", "text", "files", "within", "a", "folder", "structure", "." ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/transcoders.py#L22-L59
train
totalgood/nlpia
src/nlpia/transcoders.py
delimit_slug
def delimit_slug(slug, sep=' '): """ Return a str of separated tokens found within a slugLike_This => 'slug Like This' >>> delimit_slug("slugLike_ThisW/aTLA's") 'slug Like This W a TLA s' >>> delimit_slug('slugLike_ThisW/aTLA', '|') 'slug|Like|This|W|a|TLA' """ hyphenated_slug = re.sub(CRE_...
python
def delimit_slug(slug, sep=' '): """ Return a str of separated tokens found within a slugLike_This => 'slug Like This' >>> delimit_slug("slugLike_ThisW/aTLA's") 'slug Like This W a TLA s' >>> delimit_slug('slugLike_ThisW/aTLA', '|') 'slug|Like|This|W|a|TLA' """ hyphenated_slug = re.sub(CRE_...
[ "def", "delimit_slug", "(", "slug", ",", "sep", "=", "' '", ")", ":", "hyphenated_slug", "=", "re", ".", "sub", "(", "CRE_SLUG_DELIMITTER", ",", "sep", ",", "slug", ")", "return", "hyphenated_slug" ]
Return a str of separated tokens found within a slugLike_This => 'slug Like This' >>> delimit_slug("slugLike_ThisW/aTLA's") 'slug Like This W a TLA s' >>> delimit_slug('slugLike_ThisW/aTLA', '|') 'slug|Like|This|W|a|TLA'
[ "Return", "a", "str", "of", "separated", "tokens", "found", "within", "a", "slugLike_This", "=", ">", "slug", "Like", "This" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/transcoders.py#L62-L71
train
totalgood/nlpia
src/nlpia/transcoders.py
clean_asciidoc
def clean_asciidoc(text): r""" Transform asciidoc text into ASCII text that NL parsers can handle TODO: Tag lines and words with meta data like italics, underlined, bold, title, heading 1, etc >>> clean_asciidoc('**Hello** _world_!') '"Hello" "world"!' """ text = re.sub(r'(\b|^)[\[_*]{1,...
python
def clean_asciidoc(text): r""" Transform asciidoc text into ASCII text that NL parsers can handle TODO: Tag lines and words with meta data like italics, underlined, bold, title, heading 1, etc >>> clean_asciidoc('**Hello** _world_!') '"Hello" "world"!' """ text = re.sub(r'(\b|^)[\[_*]{1,...
[ "def", "clean_asciidoc", "(", "text", ")", ":", "r", "text", "=", "re", ".", "sub", "(", "r'(\\b|^)[\\[_*]{1,2}([a-zA-Z0-9])'", ",", "r'\"\\2'", ",", "text", ")", "text", "=", "re", ".", "sub", "(", "r'([a-zA-Z0-9])[\\]_*]{1,2}'", ",", "r'\\1\"'", ",", "text...
r""" Transform asciidoc text into ASCII text that NL parsers can handle TODO: Tag lines and words with meta data like italics, underlined, bold, title, heading 1, etc >>> clean_asciidoc('**Hello** _world_!') '"Hello" "world"!'
[ "r", "Transform", "asciidoc", "text", "into", "ASCII", "text", "that", "NL", "parsers", "can", "handle" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/transcoders.py#L121-L132
train
totalgood/nlpia
src/nlpia/transcoders.py
split_sentences_regex
def split_sentences_regex(text): """ Use dead-simple regex to split text into sentences. Very poor accuracy. >>> split_sentences_regex("Hello World. I'm I.B.M.'s Watson. --Watson") ['Hello World.', "I'm I.B.M.'s Watson.", '--Watson'] """ parts = regex.split(r'([a-zA-Z0-9][.?!])[\s$]', text) sen...
python
def split_sentences_regex(text): """ Use dead-simple regex to split text into sentences. Very poor accuracy. >>> split_sentences_regex("Hello World. I'm I.B.M.'s Watson. --Watson") ['Hello World.', "I'm I.B.M.'s Watson.", '--Watson'] """ parts = regex.split(r'([a-zA-Z0-9][.?!])[\s$]', text) sen...
[ "def", "split_sentences_regex", "(", "text", ")", ":", "parts", "=", "regex", ".", "split", "(", "r'([a-zA-Z0-9][.?!])[\\s$]'", ",", "text", ")", "sentences", "=", "[", "''", ".", "join", "(", "s", ")", "for", "s", "in", "zip", "(", "parts", "[", "0", ...
Use dead-simple regex to split text into sentences. Very poor accuracy. >>> split_sentences_regex("Hello World. I'm I.B.M.'s Watson. --Watson") ['Hello World.', "I'm I.B.M.'s Watson.", '--Watson']
[ "Use", "dead", "-", "simple", "regex", "to", "split", "text", "into", "sentences", ".", "Very", "poor", "accuracy", "." ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/transcoders.py#L157-L165
train
totalgood/nlpia
src/nlpia/transcoders.py
split_sentences_spacy
def split_sentences_spacy(text, language_model='en'): r""" You must download a spacy language model with python -m download 'en' The default English language model for spacy tends to be a lot more agressive than NLTK's punkt: >>> split_sentences_nltk("Hi Ms. Lovelace.\nI'm a wanna-\nbe human @ I.B.M. ;) -...
python
def split_sentences_spacy(text, language_model='en'): r""" You must download a spacy language model with python -m download 'en' The default English language model for spacy tends to be a lot more agressive than NLTK's punkt: >>> split_sentences_nltk("Hi Ms. Lovelace.\nI'm a wanna-\nbe human @ I.B.M. ;) -...
[ "def", "split_sentences_spacy", "(", "text", ",", "language_model", "=", "'en'", ")", ":", "r", "doc", "=", "nlp", "(", "text", ")", "sentences", "=", "[", "]", "if", "not", "hasattr", "(", "doc", ",", "'sents'", ")", ":", "logger", ".", "warning", "...
r""" You must download a spacy language model with python -m download 'en' The default English language model for spacy tends to be a lot more agressive than NLTK's punkt: >>> split_sentences_nltk("Hi Ms. Lovelace.\nI'm a wanna-\nbe human @ I.B.M. ;) --Watson 2.0") ['Hi Ms. Lovelace.', "I'm a wanna-\nbe h...
[ "r", "You", "must", "download", "a", "spacy", "language", "model", "with", "python", "-", "m", "download", "en" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/transcoders.py#L168-L192
train
totalgood/nlpia
src/nlpia/transcoders.py
segment_sentences
def segment_sentences(path=os.path.join(DATA_PATH, 'book'), splitter=split_sentences_nltk, **find_files_kwargs): """ Return a list of all sentences and empty lines. TODO: 1. process each line with an aggressive sentence segmenter, like DetectorMorse 2. process our manuscript to create a complet...
python
def segment_sentences(path=os.path.join(DATA_PATH, 'book'), splitter=split_sentences_nltk, **find_files_kwargs): """ Return a list of all sentences and empty lines. TODO: 1. process each line with an aggressive sentence segmenter, like DetectorMorse 2. process our manuscript to create a complet...
[ "def", "segment_sentences", "(", "path", "=", "os", ".", "path", ".", "join", "(", "DATA_PATH", ",", "'book'", ")", ",", "splitter", "=", "split_sentences_nltk", ",", "**", "find_files_kwargs", ")", ":", "sentences", "=", "[", "]", "if", "os", ".", "path...
Return a list of all sentences and empty lines. TODO: 1. process each line with an aggressive sentence segmenter, like DetectorMorse 2. process our manuscript to create a complete-sentence and heading training set normalized/simplified syntax net tree is the input feature set common word...
[ "Return", "a", "list", "of", "all", "sentences", "and", "empty", "lines", "." ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/transcoders.py#L216-L267
train
totalgood/nlpia
src/nlpia/transcoders.py
fix_hunspell_json
def fix_hunspell_json(badjson_path='en_us.json', goodjson_path='en_us_fixed.json'): """Fix the invalid hunspellToJSON.py json format by inserting double-quotes in list of affix strings Args: badjson_path (str): path to input json file that doesn't properly quote goodjson_path (str): path to output ...
python
def fix_hunspell_json(badjson_path='en_us.json', goodjson_path='en_us_fixed.json'): """Fix the invalid hunspellToJSON.py json format by inserting double-quotes in list of affix strings Args: badjson_path (str): path to input json file that doesn't properly quote goodjson_path (str): path to output ...
[ "def", "fix_hunspell_json", "(", "badjson_path", "=", "'en_us.json'", ",", "goodjson_path", "=", "'en_us_fixed.json'", ")", ":", "with", "open", "(", "badjson_path", ",", "'r'", ")", "as", "fin", ":", "with", "open", "(", "goodjson_path", ",", "'w'", ")", "a...
Fix the invalid hunspellToJSON.py json format by inserting double-quotes in list of affix strings Args: badjson_path (str): path to input json file that doesn't properly quote goodjson_path (str): path to output json file with properly quoted strings in list of affixes Returns: list of all w...
[ "Fix", "the", "invalid", "hunspellToJSON", ".", "py", "json", "format", "by", "inserting", "double", "-", "quotes", "in", "list", "of", "affix", "strings" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/transcoders.py#L295-L327
train
totalgood/nlpia
src/nlpia/book/examples/ch12_retrieval.py
format_ubuntu_dialog
def format_ubuntu_dialog(df): """ Print statements paired with replies, formatted for easy review """ s = '' for i, record in df.iterrows(): statement = list(split_turns(record.Context))[-1] # <1> reply = list(split_turns(record.Utterance))[-1] # <2> s += 'Statement: {}\n'.format(s...
python
def format_ubuntu_dialog(df): """ Print statements paired with replies, formatted for easy review """ s = '' for i, record in df.iterrows(): statement = list(split_turns(record.Context))[-1] # <1> reply = list(split_turns(record.Utterance))[-1] # <2> s += 'Statement: {}\n'.format(s...
[ "def", "format_ubuntu_dialog", "(", "df", ")", ":", "s", "=", "''", "for", "i", ",", "record", "in", "df", ".", "iterrows", "(", ")", ":", "statement", "=", "list", "(", "split_turns", "(", "record", ".", "Context", ")", ")", "[", "-", "1", "]", ...
Print statements paired with replies, formatted for easy review
[ "Print", "statements", "paired", "with", "replies", "formatted", "for", "easy", "review" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book/examples/ch12_retrieval.py#L40-L48
train
totalgood/nlpia
src/nlpia/regexes.py
splitext
def splitext(filepath): """ Like os.path.splitext except splits compound extensions as one long one >>> splitext('~/.bashrc.asciidoc.ext.ps4.42') ('~/.bashrc', '.asciidoc.ext.ps4.42') >>> splitext('~/.bash_profile') ('~/.bash_profile', '') """ exts = getattr(CRE_FILENAME_EXT.search(filepath...
python
def splitext(filepath): """ Like os.path.splitext except splits compound extensions as one long one >>> splitext('~/.bashrc.asciidoc.ext.ps4.42') ('~/.bashrc', '.asciidoc.ext.ps4.42') >>> splitext('~/.bash_profile') ('~/.bash_profile', '') """ exts = getattr(CRE_FILENAME_EXT.search(filepath...
[ "def", "splitext", "(", "filepath", ")", ":", "exts", "=", "getattr", "(", "CRE_FILENAME_EXT", ".", "search", "(", "filepath", ")", ",", "'group'", ",", "str", ")", "(", ")", "return", "(", "filepath", "[", ":", "(", "-", "len", "(", "exts", ")", "...
Like os.path.splitext except splits compound extensions as one long one >>> splitext('~/.bashrc.asciidoc.ext.ps4.42') ('~/.bashrc', '.asciidoc.ext.ps4.42') >>> splitext('~/.bash_profile') ('~/.bash_profile', '')
[ "Like", "os", ".", "path", ".", "splitext", "except", "splits", "compound", "extensions", "as", "one", "long", "one" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/regexes.py#L109-L118
train
totalgood/nlpia
src/nlpia/plots.py
offline_plotly_scatter3d
def offline_plotly_scatter3d(df, x=0, y=1, z=-1): """ Plot an offline scatter plot colored according to the categories in the 'name' column. >> df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/iris.csv') >> offline_plotly(df) """ data = [] # clusters = [] colors = ...
python
def offline_plotly_scatter3d(df, x=0, y=1, z=-1): """ Plot an offline scatter plot colored according to the categories in the 'name' column. >> df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/iris.csv') >> offline_plotly(df) """ data = [] # clusters = [] colors = ...
[ "def", "offline_plotly_scatter3d", "(", "df", ",", "x", "=", "0", ",", "y", "=", "1", ",", "z", "=", "-", "1", ")", ":", "data", "=", "[", "]", "colors", "=", "[", "'rgb(228,26,28)'", ",", "'rgb(55,126,184)'", ",", "'rgb(77,175,74)'", "]", "x", "=", ...
Plot an offline scatter plot colored according to the categories in the 'name' column. >> df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/iris.csv') >> offline_plotly(df)
[ "Plot", "an", "offline", "scatter", "plot", "colored", "according", "to", "the", "categories", "in", "the", "name", "column", "." ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/plots.py#L107-L172
train
totalgood/nlpia
src/nlpia/plots.py
offline_plotly_data
def offline_plotly_data(data, filename=None, config=None, validate=True, default_width='100%', default_height=525, global_requirejs=False): r""" Write a plotly scatter plot to HTML file that doesn't require server >>> from nlpia.loaders import get_data >>> df = get_data('etpinard') ...
python
def offline_plotly_data(data, filename=None, config=None, validate=True, default_width='100%', default_height=525, global_requirejs=False): r""" Write a plotly scatter plot to HTML file that doesn't require server >>> from nlpia.loaders import get_data >>> df = get_data('etpinard') ...
[ "def", "offline_plotly_data", "(", "data", ",", "filename", "=", "None", ",", "config", "=", "None", ",", "validate", "=", "True", ",", "default_width", "=", "'100%'", ",", "default_height", "=", "525", ",", "global_requirejs", "=", "False", ")", ":", "r",...
r""" Write a plotly scatter plot to HTML file that doesn't require server >>> from nlpia.loaders import get_data >>> df = get_data('etpinard') # pd.read_csv('https://plot.ly/~etpinard/191.csv') >>> df.columns = [eval(c) if c[0] in '"\'' else str(c) for c in df.columns] >>> data = {'data': [ ... ...
[ "r", "Write", "a", "plotly", "scatter", "plot", "to", "HTML", "file", "that", "doesn", "t", "require", "server" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/plots.py#L189-L223
train
totalgood/nlpia
src/nlpia/plots.py
normalize_etpinard_df
def normalize_etpinard_df(df='https://plot.ly/~etpinard/191.csv', columns='x y size text'.split(), category_col='category', possible_categories=['Africa', 'Americas', 'Asia', 'Europe', 'Oceania']): """Reformat a dataframe in etpinard's format for use in plot functions and sklearn models"""...
python
def normalize_etpinard_df(df='https://plot.ly/~etpinard/191.csv', columns='x y size text'.split(), category_col='category', possible_categories=['Africa', 'Americas', 'Asia', 'Europe', 'Oceania']): """Reformat a dataframe in etpinard's format for use in plot functions and sklearn models"""...
[ "def", "normalize_etpinard_df", "(", "df", "=", "'https://plot.ly/~etpinard/191.csv'", ",", "columns", "=", "'x y size text'", ".", "split", "(", ")", ",", "category_col", "=", "'category'", ",", "possible_categories", "=", "[", "'Africa'", ",", "'Americas'", ",", ...
Reformat a dataframe in etpinard's format for use in plot functions and sklearn models
[ "Reformat", "a", "dataframe", "in", "etpinard", "s", "format", "for", "use", "in", "plot", "functions", "and", "sklearn", "models" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/plots.py#L226-L239
train
totalgood/nlpia
src/nlpia/plots.py
offline_plotly_scatter_bubble
def offline_plotly_scatter_bubble(df, x='x', y='y', size_col='size', text_col='text', category_col='category', possible_categories=None, filename=None, config={'displaylogo': False}, x...
python
def offline_plotly_scatter_bubble(df, x='x', y='y', size_col='size', text_col='text', category_col='category', possible_categories=None, filename=None, config={'displaylogo': False}, x...
[ "def", "offline_plotly_scatter_bubble", "(", "df", ",", "x", "=", "'x'", ",", "y", "=", "'y'", ",", "size_col", "=", "'size'", ",", "text_col", "=", "'text'", ",", "category_col", "=", "'category'", ",", "possible_categories", "=", "None", ",", "filename", ...
r"""Interactive scatterplot of a DataFrame with the size and color of circles linke to two columns config keys: fillFrame setBackground displaylogo sendData showLink linkText staticPlot scrollZoom plot3dPixelRatio displayModeBar showTips workspace doubleClick autosizable editable layout keys: ...
[ "r", "Interactive", "scatterplot", "of", "a", "DataFrame", "with", "the", "size", "and", "color", "of", "circles", "linke", "to", "two", "columns" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/plots.py#L242-L316
train
totalgood/nlpia
src/nlpia/data_utils.py
format_hex
def format_hex(i, num_bytes=4, prefix='0x'): """ Format hexidecimal string from decimal integer value >>> format_hex(42, num_bytes=8, prefix=None) '0000002a' >>> format_hex(23) '0x0017' """ prefix = str(prefix or '') i = int(i or 0) return prefix + '{0:0{1}x}'.format(i, num_bytes)
python
def format_hex(i, num_bytes=4, prefix='0x'): """ Format hexidecimal string from decimal integer value >>> format_hex(42, num_bytes=8, prefix=None) '0000002a' >>> format_hex(23) '0x0017' """ prefix = str(prefix or '') i = int(i or 0) return prefix + '{0:0{1}x}'.format(i, num_bytes)
[ "def", "format_hex", "(", "i", ",", "num_bytes", "=", "4", ",", "prefix", "=", "'0x'", ")", ":", "prefix", "=", "str", "(", "prefix", "or", "''", ")", "i", "=", "int", "(", "i", "or", "0", ")", "return", "prefix", "+", "'{0:0{1}x}'", ".", "format...
Format hexidecimal string from decimal integer value >>> format_hex(42, num_bytes=8, prefix=None) '0000002a' >>> format_hex(23) '0x0017'
[ "Format", "hexidecimal", "string", "from", "decimal", "integer", "value" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/data_utils.py#L38-L48
train
totalgood/nlpia
src/nlpia/data_utils.py
is_up_url
def is_up_url(url, allow_redirects=False, timeout=5): r""" Check URL to see if it is a valid web page, return the redirected location if it is Returns: None if ConnectionError False if url is invalid (any HTTP error code) cleaned up URL (following redirects and possibly adding HTTP schema "ht...
python
def is_up_url(url, allow_redirects=False, timeout=5): r""" Check URL to see if it is a valid web page, return the redirected location if it is Returns: None if ConnectionError False if url is invalid (any HTTP error code) cleaned up URL (following redirects and possibly adding HTTP schema "ht...
[ "def", "is_up_url", "(", "url", ",", "allow_redirects", "=", "False", ",", "timeout", "=", "5", ")", ":", "r", "if", "not", "isinstance", "(", "url", ",", "basestring", ")", "or", "'.'", "not", "in", "url", ":", "return", "False", "normalized_url", "="...
r""" Check URL to see if it is a valid web page, return the redirected location if it is Returns: None if ConnectionError False if url is invalid (any HTTP error code) cleaned up URL (following redirects and possibly adding HTTP schema "http://") >>> is_up_url("duckduckgo.com") # a more pri...
[ "r", "Check", "URL", "to", "see", "if", "it", "is", "a", "valid", "web", "page", "return", "the", "redirected", "location", "if", "it", "is" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/data_utils.py#L83-L122
train
totalgood/nlpia
src/nlpia/data_utils.py
get_markdown_levels
def get_markdown_levels(lines, levels=set((0, 1, 2, 3, 4, 5, 6))): r""" Return a list of 2-tuples with a level integer for the heading levels >>> get_markdown_levels('paragraph \n##bad\n# hello\n ### world\n') [(0, 'paragraph '), (2, 'bad'), (0, '# hello'), (3, 'world')] >>> get_markdown_levels('- bul...
python
def get_markdown_levels(lines, levels=set((0, 1, 2, 3, 4, 5, 6))): r""" Return a list of 2-tuples with a level integer for the heading levels >>> get_markdown_levels('paragraph \n##bad\n# hello\n ### world\n') [(0, 'paragraph '), (2, 'bad'), (0, '# hello'), (3, 'world')] >>> get_markdown_levels('- bul...
[ "def", "get_markdown_levels", "(", "lines", ",", "levels", "=", "set", "(", "(", "0", ",", "1", ",", "2", ",", "3", ",", "4", ",", "5", ",", "6", ")", ")", ")", ":", "r", "if", "isinstance", "(", "levels", ",", "(", "int", ",", "float", ",", ...
r""" Return a list of 2-tuples with a level integer for the heading levels >>> get_markdown_levels('paragraph \n##bad\n# hello\n ### world\n') [(0, 'paragraph '), (2, 'bad'), (0, '# hello'), (3, 'world')] >>> get_markdown_levels('- bullet \n##bad\n# hello\n ### world\n') [(0, '- bullet '), (2, 'bad')...
[ "r", "Return", "a", "list", "of", "2", "-", "tuples", "with", "a", "level", "integer", "for", "the", "heading", "levels" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/data_utils.py#L125-L155
train
totalgood/nlpia
src/nlpia/data_utils.py
iter_lines
def iter_lines(url_or_text, ext=None, mode='rt'): r""" Return an iterator over the lines of a file or URI response. >>> len(list(iter_lines('cats_and_dogs.txt'))) 263 >>> len(list(iter_lines(list('abcdefgh')))) 8 >>> len(list(iter_lines('abc\n def\n gh\n'))) 3 >>> len(list(iter_lines('a...
python
def iter_lines(url_or_text, ext=None, mode='rt'): r""" Return an iterator over the lines of a file or URI response. >>> len(list(iter_lines('cats_and_dogs.txt'))) 263 >>> len(list(iter_lines(list('abcdefgh')))) 8 >>> len(list(iter_lines('abc\n def\n gh\n'))) 3 >>> len(list(iter_lines('a...
[ "def", "iter_lines", "(", "url_or_text", ",", "ext", "=", "None", ",", "mode", "=", "'rt'", ")", ":", "r", "if", "url_or_text", "is", "None", "or", "not", "url_or_text", ":", "return", "[", "]", "elif", "isinstance", "(", "url_or_text", ",", "(", "str"...
r""" Return an iterator over the lines of a file or URI response. >>> len(list(iter_lines('cats_and_dogs.txt'))) 263 >>> len(list(iter_lines(list('abcdefgh')))) 8 >>> len(list(iter_lines('abc\n def\n gh\n'))) 3 >>> len(list(iter_lines('abc\n def\n gh'))) 3 >>> 20000 > len(list(iter_...
[ "r", "Return", "an", "iterator", "over", "the", "lines", "of", "a", "file", "or", "URI", "response", "." ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/data_utils.py#L186-L224
train
totalgood/nlpia
src/nlpia/data_utils.py
parse_utf_html
def parse_utf_html(url=os.path.join(DATA_PATH, 'utf8_table.html')): """ Parse HTML table UTF8 char descriptions returning DataFrame with `ascii` and `mutliascii` """ utf = pd.read_html(url) utf = [df for df in utf if len(df) > 1023 and len(df.columns) > 2][0] utf = utf.iloc[:1024] if len(utf) == 1025 el...
python
def parse_utf_html(url=os.path.join(DATA_PATH, 'utf8_table.html')): """ Parse HTML table UTF8 char descriptions returning DataFrame with `ascii` and `mutliascii` """ utf = pd.read_html(url) utf = [df for df in utf if len(df) > 1023 and len(df.columns) > 2][0] utf = utf.iloc[:1024] if len(utf) == 1025 el...
[ "def", "parse_utf_html", "(", "url", "=", "os", ".", "path", ".", "join", "(", "DATA_PATH", ",", "'utf8_table.html'", ")", ")", ":", "utf", "=", "pd", ".", "read_html", "(", "url", ")", "utf", "=", "[", "df", "for", "df", "in", "utf", "if", "len", ...
Parse HTML table UTF8 char descriptions returning DataFrame with `ascii` and `mutliascii`
[ "Parse", "HTML", "table", "UTF8", "char", "descriptions", "returning", "DataFrame", "with", "ascii", "and", "mutliascii" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/data_utils.py#L227-L291
train
totalgood/nlpia
src/nlpia/data_utils.py
clean_csvs
def clean_csvs(dialogpath=None): """ Translate non-ASCII characters to spaces or equivalent ASCII characters """ dialogdir = os.dirname(dialogpath) if os.path.isfile(dialogpath) else dialogpath filenames = [dialogpath.split(os.path.sep)[-1]] if os.path.isfile(dialogpath) else os.listdir(dialogpath) for ...
python
def clean_csvs(dialogpath=None): """ Translate non-ASCII characters to spaces or equivalent ASCII characters """ dialogdir = os.dirname(dialogpath) if os.path.isfile(dialogpath) else dialogpath filenames = [dialogpath.split(os.path.sep)[-1]] if os.path.isfile(dialogpath) else os.listdir(dialogpath) for ...
[ "def", "clean_csvs", "(", "dialogpath", "=", "None", ")", ":", "dialogdir", "=", "os", ".", "dirname", "(", "dialogpath", ")", "if", "os", ".", "path", ".", "isfile", "(", "dialogpath", ")", "else", "dialogpath", "filenames", "=", "[", "dialogpath", ".",...
Translate non-ASCII characters to spaces or equivalent ASCII characters
[ "Translate", "non", "-", "ASCII", "characters", "to", "spaces", "or", "equivalent", "ASCII", "characters" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/data_utils.py#L294-L302
train
totalgood/nlpia
src/nlpia/data_utils.py
unicode2ascii
def unicode2ascii(text, expand=True): r""" Translate UTF8 characters to ASCII >> unicode2ascii("żółw") zozw utf8_letters = 'ą ę ć ź ż ó ł ń ś “ ” ’'.split() ascii_letters = 'a e c z z o l n s " " \'' """ translate = UTF8_TO_ASCII if not expand else UTF8_TO_MULTIASCII output = '' f...
python
def unicode2ascii(text, expand=True): r""" Translate UTF8 characters to ASCII >> unicode2ascii("żółw") zozw utf8_letters = 'ą ę ć ź ż ó ł ń ś “ ” ’'.split() ascii_letters = 'a e c z z o l n s " " \'' """ translate = UTF8_TO_ASCII if not expand else UTF8_TO_MULTIASCII output = '' f...
[ "def", "unicode2ascii", "(", "text", ",", "expand", "=", "True", ")", ":", "r", "translate", "=", "UTF8_TO_ASCII", "if", "not", "expand", "else", "UTF8_TO_MULTIASCII", "output", "=", "''", "for", "c", "in", "text", ":", "if", "not", "c", "or", "ord", "...
r""" Translate UTF8 characters to ASCII >> unicode2ascii("żółw") zozw utf8_letters = 'ą ę ć ź ż ó ł ń ś “ ” ’'.split() ascii_letters = 'a e c z z o l n s " " \''
[ "r", "Translate", "UTF8", "characters", "to", "ASCII" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/data_utils.py#L305-L321
train
totalgood/nlpia
src/nlpia/data_utils.py
clean_df
def clean_df(df, header=None, **read_csv_kwargs): """ Convert UTF8 characters in a CSV file or dataframe into ASCII Args: df (DataFrame or str): DataFrame or path or url to CSV """ df = read_csv(df, header=header, **read_csv_kwargs) df = df.fillna(' ') for col in df.columns: df[co...
python
def clean_df(df, header=None, **read_csv_kwargs): """ Convert UTF8 characters in a CSV file or dataframe into ASCII Args: df (DataFrame or str): DataFrame or path or url to CSV """ df = read_csv(df, header=header, **read_csv_kwargs) df = df.fillna(' ') for col in df.columns: df[co...
[ "def", "clean_df", "(", "df", ",", "header", "=", "None", ",", "**", "read_csv_kwargs", ")", ":", "df", "=", "read_csv", "(", "df", ",", "header", "=", "header", ",", "**", "read_csv_kwargs", ")", "df", "=", "df", ".", "fillna", "(", "' '", ")", "f...
Convert UTF8 characters in a CSV file or dataframe into ASCII Args: df (DataFrame or str): DataFrame or path or url to CSV
[ "Convert", "UTF8", "characters", "in", "a", "CSV", "file", "or", "dataframe", "into", "ASCII" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/data_utils.py#L324-L334
train
totalgood/nlpia
src/nlpia/book_parser.py
get_acronyms
def get_acronyms(manuscript=os.path.expanduser('~/code/nlpia/lane/manuscript')): """ Find all the 2 and 3-letter acronyms in the manuscript and return as a sorted list of tuples """ acronyms = [] for f, lines in get_lines(manuscript): for line in lines: matches = CRE_ACRONYM.finditer(lin...
python
def get_acronyms(manuscript=os.path.expanduser('~/code/nlpia/lane/manuscript')): """ Find all the 2 and 3-letter acronyms in the manuscript and return as a sorted list of tuples """ acronyms = [] for f, lines in get_lines(manuscript): for line in lines: matches = CRE_ACRONYM.finditer(lin...
[ "def", "get_acronyms", "(", "manuscript", "=", "os", ".", "path", ".", "expanduser", "(", "'~/code/nlpia/lane/manuscript'", ")", ")", ":", "acronyms", "=", "[", "]", "for", "f", ",", "lines", "in", "get_lines", "(", "manuscript", ")", ":", "for", "line", ...
Find all the 2 and 3-letter acronyms in the manuscript and return as a sorted list of tuples
[ "Find", "all", "the", "2", "and", "3", "-", "letter", "acronyms", "in", "the", "manuscript", "and", "return", "as", "a", "sorted", "list", "of", "tuples" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book_parser.py#L90-L107
train
totalgood/nlpia
src/nlpia/book_parser.py
write_glossary
def write_glossary(manuscript=os.path.expanduser('~/code/nlpia/lane/manuscript'), linesep=None): """ Compose an asciidoc string with acronyms culled from the manuscript """ linesep = linesep or os.linesep lines = ['[acronyms]', '== Acronyms', '', '[acronyms,template="glossary",id="terms"]'] acronyms = g...
python
def write_glossary(manuscript=os.path.expanduser('~/code/nlpia/lane/manuscript'), linesep=None): """ Compose an asciidoc string with acronyms culled from the manuscript """ linesep = linesep or os.linesep lines = ['[acronyms]', '== Acronyms', '', '[acronyms,template="glossary",id="terms"]'] acronyms = g...
[ "def", "write_glossary", "(", "manuscript", "=", "os", ".", "path", ".", "expanduser", "(", "'~/code/nlpia/lane/manuscript'", ")", ",", "linesep", "=", "None", ")", ":", "linesep", "=", "linesep", "or", "os", ".", "linesep", "lines", "=", "[", "'[acronyms]'"...
Compose an asciidoc string with acronyms culled from the manuscript
[ "Compose", "an", "asciidoc", "string", "with", "acronyms", "culled", "from", "the", "manuscript" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book_parser.py#L110-L117
train
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...
python
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...
[ "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
train
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...
python
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...
[ "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
train
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): """ 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]
[ "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
train
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_ta...
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_ta...
[ "def", "filter_tagged_lines", "(", "tagged_lines", ",", "include_tags", "=", "None", ",", "exclude_tags", "=", "None", ")", ":", "r", "include_tags", "=", "(", "include_tags", ",", ")", "if", "isinstance", "(", "include_tags", ",", "str", ")", "else", "inclu...
r""" Return iterable of tagged lines where the tags all start with one of the include_tags prefixes >>> filter_tagged_lines([('natural', "Hello."), ('code', '[source,python]'), ('code', '>>> hello()')]) <generator object filter_tagged_lines at ...> >>> list(filter_tagged_lines([('natural', "Hello."), ('cod...
[ "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
train
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 verbo...
python
def accuracy_study(tdm=None, u=None, s=None, vt=None, verbosity=0, **kwargs): """ Reconstruct the term-document matrix and measure error as SVD terms are truncated """ smat = np.zeros((len(u), len(vt))) np.fill_diagonal(smat, s) smat = pd.DataFrame(smat, columns=vt.index, index=u.index) if verbo...
[ "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
train
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 sing...
python
def get_anki_phrases(lang='english', limit=None): """ Retrieve as many anki paired-statement corpora as you can for the requested language If `ankis` (requested languages) is more than one, then get the english texts associated with those languages. TODO: improve modularity: def function that takes a sing...
[ "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 >>> g...
[ "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
train
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 ...
python
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 ...
[ "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
train
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 . pun...
python
def get_vocab(docs): """ Build a DataFrame containing all the words in the docs provided along with their POS tags etc >>> doc = nlp("Hey Mr. Tangerine Man!") <BLANKLINE> ... >>> get_vocab([doc]) word pos tag dep ent_type ent_iob sentiment 0 ! PUNCT . pun...
[ "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....
[ "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
train
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...
python
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...
[ "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
train
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,...
python
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,...
[ "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
train
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 N...
python
def lsa_twitter(cased_tokens): """ Latent Sentiment Analyis on random sampling of twitter search results for words listed in cased_tokens """ # Only 5 of these tokens are saved for a no_below=2 filter: # PyCons NLPS #PyCon2016 #NaturalLanguageProcessing #naturallanguageprocessing if cased_tokens is N...
[ "def", "lsa_twitter", "(", "cased_tokens", ")", ":", "if", "cased_tokens", "is", "None", ":", "cased_tokens", "=", "(", "'PyConOpenSpaces PyCon PyCon2017 PyCon2018 PyCon2016 PyCon2015 OpenSpace PyconTutorial '", "+", "'NLP NaturalLanguageProcessing NLPInAction NaturalLanguageProcessi...
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
train
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) ...
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) ...
[ "def", "wc", "(", "f", ",", "verbose", "=", "False", ",", "nrows", "=", "None", ")", ":", "r", "tqdm_prog", "=", "tqdm", "if", "verbose", "else", "no_tqdm", "with", "ensure_open", "(", "f", ",", "mode", "=", "'r'", ")", "as", "fin", ":", "for", "...
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
train
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.bi...
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.bi...
[ "def", "normalize_filepath", "(", "filepath", ")", ":", "r", "filename", "=", "os", ".", "path", ".", "basename", "(", "filepath", ")", "dirpath", "=", "filepath", "[", ":", "-", "len", "(", "filename", ")", "]", "cre_controlspace", "=", "re", ".", "co...
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
train
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_...
python
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_...
[ "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.7182818...
[ "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
train
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): """ 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
[ "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
train
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 KeyE...
python
def hydrate_point(srid, *coordinates): """ Create a new instance of a Point subclass from a raw set of fields. The subclass chosen is determined by the given SRID; a ValueError will be raised if no such subclass can be found. """ try: point_class, dim = __srid_table[srid] except KeyE...
[ "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
train
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(...
python
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(...
[ "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
train
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...
python
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...
[ "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
train
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: ...
python
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: ...
[ "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
train
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: ...
python
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: ...
[ "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
train
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: ...
python
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: ...
[ "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
train
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 ...
python
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 ...
[ "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
train
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(...
python
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(...
[ "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
train
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(chil...
python
def _make_plan(plan_dict): """ Construct a Plan or ProfiledPlan from a dictionary of metadata values. :param plan_dict: :return: """ operator_type = plan_dict["operatorType"] identifiers = plan_dict.get("identifiers", []) arguments = plan_dict.get("args", []) children = [_make_plan(chil...
[ "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
train
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): re...
python
def unit_of_work(metadata=None, timeout=None): """ This function is a decorator for transaction functions that allows extra control over how the transaction is carried out. For example, a timeout (in seconds) may be applied:: @unit_of_work(timeout=25.0) def count_people(tx): re...
[ "def", "unit_of_work", "(", "metadata", "=", "None", ",", "timeout", "=", "None", ")", ":", "def", "wrapper", "(", "f", ")", ":", "def", "wrapped", "(", "*", "args", ",", "**", "kwargs", ")", ":", "return", "f", "(", "*", "args", ",", "**", "kwar...
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(...
[ "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
train
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()...
python
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()...
[ "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
train
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. ...
python
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. ...
[ "def", "run", "(", "self", ",", "statement", ",", "parameters", "=", "None", ",", "**", "kwparameters", ")", ":", "from", "neobolt", ".", "exceptions", "import", "ConnectionExpired", "self", ".", "_assert_open", "(", ")", "if", "not", "statement", ":", "ra...
Run a Cypher statement within an auto-commit transaction. The statement is sent and the result header received immediately but the :class:`.StatementResult` content is fetched lazily as consumed by the client application. If a statement is executed before a previous :class:`.St...
[ "Run", "a", "Cypher", "statement", "within", "an", "auto", "-", "commit", "transaction", "." ]
0c641e826765e86ff5454dae57c99521db8ca45c
https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/blocking.py#L166-L261
train
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): """ Send all outstanding requests. """ 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
train
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 Connection...
python
def fetch(self): """ Attempt to fetch at least one more record. :returns: number of records fetched """ from neobolt.exceptions import ConnectionExpired if self._connection: try: detail_count, _ = self._connection.fetch() except Connection...
[ "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
train
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...
python
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...
[ "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
train
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` metho...
python
def run(self, statement, parameters=None, **kwparameters): """ Run a Cypher statement within the context of this transaction. The statement is sent to the server lazily, when its result is consumed. To force the statement to be sent to the server, use the :meth:`.Transaction.sync` metho...
[ "def", "run", "(", "self", ",", "statement", ",", "parameters", "=", "None", ",", "**", "kwparameters", ")", ":", "self", ".", "_assert_open", "(", ")", "return", "self", ".", "session", ".", "run", "(", "statement", ",", "parameters", ",", "**", "kwpa...
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 ...
[ "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
train
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) els...
python
def detach(self, sync=True): """ Detach this result from its parent session by fetching the remainder of this result from the network into the buffer. :returns: number of records fetched """ if self.attached(): return self._session.detach(self, sync=sync) els...
[ "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
train
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...
python
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...
[ "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
train
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 atta...
python
def records(self): """ Generator for records obtained from this result. :yields: iterable of :class:`.Record` objects """ records = self._records next_record = records.popleft while records: yield next_record() attached = self.attached if atta...
[ "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
train
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 se...
python
def summary(self): """ Obtain the summary of this result, buffering any remaining records. :returns: The :class:`.ResultSummary` for this result """ self.detach() if self._summary is None: self._summary = BoltStatementResultSummary(**self._metadata) return se...
[ "def", "summary", "(", "self", ")", ":", "self", ".", "detach", "(", ")", "if", "self", ".", "_summary", "is", "None", ":", "self", ".", "_summary", "=", "BoltStatementResultSummary", "(", "**", "self", ".", "_metadata", ")", "return", "self", ".", "_s...
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
train
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 r...
python
def single(self): """ Obtain the next and only remaining record from this result. A warning is generated if more than one record is available but the first of these is still returned. :returns: the next :class:`.Record` or :const:`None` if none remain :warns: if more than one r...
[ "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
train
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 r...
python
def peek(self): """ Obtain the next record from this result without consuming it. This leaves the record in the buffer for further processing. :returns: the next :class:`.Record` or :const:`None` if none remain """ records = self._records if records: return r...
[ "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
train
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...
python
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...
[ "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
train
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_loc...
python
def pull(self): """Returns a generator containing the results of the next query in the pipeline""" # n.b. pull is now somewhat misleadingly named because it doesn't do anything # the connection isn't touched until you try and iterate the generator we return lock_acquired = self._pull_loc...
[ "def", "pull", "(", "self", ")", ":", "lock_acquired", "=", "self", ".", "_pull_lock", ".", "acquire", "(", "blocking", "=", "False", ")", "if", "not", "lock_acquired", ":", "raise", "PullOrderException", "(", ")", "return", "self", ".", "_results_generator"...
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
train
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, ca...
python
def deprecated(message): """ Decorator for deprecating functions and methods. :: @deprecated("'foo' has been deprecated in favour of 'bar'") def foo(x): pass """ def f__(f): def f_(*args, **kwargs): from warnings import warn warn(message, ca...
[ "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
train
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): ...
python
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): ...
[ "def", "experimental", "(", "message", ")", ":", "def", "f__", "(", "f", ")", ":", "def", "f_", "(", "*", "args", ",", "**", "kwargs", ")", ":", "from", "warnings", "import", "warn", "warn", "(", "message", ",", "category", "=", "ExperimentalWarning", ...
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
train
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(min...
python
def hydrate_time(nanoseconds, tz=None): """ Hydrator for `Time` and `LocalTime` values. :param nanoseconds: :param tz: :return: Time """ seconds, nanoseconds = map(int, divmod(nanoseconds, 1000000000)) minutes, seconds = map(int, divmod(seconds, 60)) hours, minutes = map(int, divmod(min...
[ "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
train
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.min...
python
def dehydrate_time(value): """ Dehydrator for `time` values. :param value: :type value: Time :return: """ if isinstance(value, Time): nanoseconds = int(value.ticks * 1000000000) elif isinstance(value, time): nanoseconds = (3600000000000 * value.hour + 60000000000 * value.min...
[ "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
train
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, hou...
python
def hydrate_datetime(seconds, nanoseconds, tz=None): """ Hydrator for `DateTime` and `LocalDateTime` values. :param seconds: :param nanoseconds: :param tz: :return: datetime """ minutes, seconds = map(int, divmod(seconds, 60)) hours, minutes = map(int, divmod(minutes, 60)) days, hou...
[ "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
train
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) ...
python
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) ...
[ "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
train
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): """ 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)
[ "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
train
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): """ Dehydrator for `duration` values. :param value: :type value: Duration :return: """ 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
train
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): """ 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)
[ "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
train
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): """ 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)
[ "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
train
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) ...
python
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) ...
[ "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
train
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): """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})
[ "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
train
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): """ 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()
[ "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
train
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(...
python
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(...
[ "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
train
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,...
python
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,...
[ "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
train
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. `erro...
python
def wait_until_element_is_visible(self, locator, timeout=None, error=None): """Waits until element specified with `locator` is visible. Fails if `timeout` expires before the element is visible. See `introduction` for more information about `timeout` and its default value. `erro...
[ "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 Pag...
[ "Waits", "until", "element", "specified", "with", "locator", "is", "visible", "." ]
91c808cf0602af6be8135ac529fa488fded04a85
https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_waiting.py#L7-L28
train
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 ...
python
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 ...
[ "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`...
[ "Waits", "until", "text", "appears", "on", "current", "page", "." ]
91c808cf0602af6be8135ac529fa488fded04a85
https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_waiting.py#L30-L46
train
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...
python
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...
[ "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 Contain...
[ "Waits", "until", "text", "disappears", "from", "current", "page", "." ]
91c808cf0602af6be8135ac529fa488fded04a85
https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_waiting.py#L48-L70
train
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. ...
python
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. ...
[ "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...
[ "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
train
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 ...
python
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 ...
[ "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 al...
[ "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
train
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 | ...
python
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 | ...
[ "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 ...
[ "Sets", "the", "network", "connection", "Status", "." ]
91c808cf0602af6be8135ac529fa488fded04a85
https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_android_utils.py#L21-L35
train
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._curre...
python
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._curre...
[ "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
train
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) """ dri...
python
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) """ dri...
[ "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
train