code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def check_compatibility_between_conll_and_brat_text(conll_filepath, brat_folder):
'''
check if token offsets match between conll and brat .txt files.
conll_filepath: path to conll file
brat_folder: folder that contains the .txt (and .ann) files that are formatted according to brat.
... |
check if token offsets match between conll and brat .txt files.
conll_filepath: path to conll file
brat_folder: folder that contains the .txt (and .ann) files that are formatted according to brat.
| check_compatibility_between_conll_and_brat_text | python | Franck-Dernoncourt/NeuroNER | neuroner/conll_to_brat.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/conll_to_brat.py | MIT |
def conll_to_brat(conll_input_filepath, conll_output_filepath, brat_original_folder, brat_output_folder, overwrite=False):
'''
convert conll file in conll-filepath to brat annotations and output to brat_output_folder,
with reference to the existing text files in brat_original_folder
if brat_original_f... |
convert conll file in conll-filepath to brat annotations and output to brat_output_folder,
with reference to the existing text files in brat_original_folder
if brat_original_folder does not exist or contain any text file, then the text files are generated from conll files,
and conll file is updated w... | conll_to_brat | python | Franck-Dernoncourt/NeuroNER | neuroner/conll_to_brat.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/conll_to_brat.py | MIT |
def update_dataset(self, dataset_filepaths, dataset_types):
'''
dataset_filepaths : dictionary with keys 'train', 'valid', 'test', 'deploy'
Overwrites the data of type specified in dataset_types using the existing token_to_index, character_to_index, and label_to_index mappings.
'''
... |
dataset_filepaths : dictionary with keys 'train', 'valid', 'test', 'deploy'
Overwrites the data of type specified in dataset_types using the existing token_to_index, character_to_index, and label_to_index mappings.
| update_dataset | python | Franck-Dernoncourt/NeuroNER | neuroner/dataset.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/dataset.py | MIT |
def load_dataset(self, dataset_filepaths, parameters, token_to_vector=None):
'''
dataset_filepaths : dictionary with keys 'train', 'valid', 'test', 'deploy'
'''
start_time = time.time()
print('Load dataset... ', end='', flush=True)
if parameters['token_pretrained_embeddin... |
dataset_filepaths : dictionary with keys 'train', 'valid', 'test', 'deploy'
| load_dataset | python | Franck-Dernoncourt/NeuroNER | neuroner/dataset.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/dataset.py | MIT |
def plot_f1_vs_epoch(results, stats_graph_folder, metric, parameters, from_json=False):
'''
Takes results dictionary and saves the f1 vs epoch plot in stats_graph_folder.
from_json indicates if the results dictionary was loaded from results.json file.
In this case, dictionary indexes are mapped from str... |
Takes results dictionary and saves the f1 vs epoch plot in stats_graph_folder.
from_json indicates if the results dictionary was loaded from results.json file.
In this case, dictionary indexes are mapped from string to int.
metric can be f1_score or accuracy
| plot_f1_vs_epoch | python | Franck-Dernoncourt/NeuroNER | neuroner/evaluate.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/evaluate.py | MIT |
def result_to_plot(folder_name=None):
'''
Loads results.json file in the ../stats_graphs/folder_name, and plot f1 vs epoch.
Use for debugging purposes, or in case the program stopped due to error in plot_f1_vs_epoch.
'''
stats_graph_folder=os.path.join('.', 'stats_graphs')
if folder_name == None... |
Loads results.json file in the ../stats_graphs/folder_name, and plot f1 vs epoch.
Use for debugging purposes, or in case the program stopped due to error in plot_f1_vs_epoch.
| result_to_plot | python | Franck-Dernoncourt/NeuroNER | neuroner/evaluate.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/evaluate.py | MIT |
def remap_labels(y_pred, y_true, dataset, evaluation_mode='bio'):
'''
y_pred: list of predicted labels
y_true: list of gold labels
evaluation_mode: 'bio', 'token', or 'binary'
Both y_pred and y_true must use label indices and names specified in the dataset
# (dataset.unique_label_indices_of_int... |
y_pred: list of predicted labels
y_true: list of gold labels
evaluation_mode: 'bio', 'token', or 'binary'
Both y_pred and y_true must use label indices and names specified in the dataset
# (dataset.unique_label_indices_of_interest, dataset.unique_label_indices_of_interest).
| remap_labels | python | Franck-Dernoncourt/NeuroNER | neuroner/evaluate.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/evaluate.py | MIT |
def fetch_model(name):
"""
Fetch a pre-trained model and copy to a local "trained_models" folder
If name is provided, fetch from the package folder.
Args:
name (str): Name of a model folder.
"""
# get content from package and write to local dir
# model comprises of:
# dataset.p... |
Fetch a pre-trained model and copy to a local "trained_models" folder
If name is provided, fetch from the package folder.
Args:
name (str): Name of a model folder.
| fetch_model | python | Franck-Dernoncourt/NeuroNER | neuroner/neuromodel.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/neuromodel.py | MIT |
def _fetch(name, content_type=None):
"""
Load data or models from the package folder.
Args:
name (str): name of the resource
content_type (str): either "data" or "trained_models"
Returns:
fileset (dict): dictionary containing the file content
"""
package_name = 'neurone... |
Load data or models from the package folder.
Args:
name (str): name of the resource
content_type (str): either "data" or "trained_models"
Returns:
fileset (dict): dictionary containing the file content
| _fetch | python | Franck-Dernoncourt/NeuroNER | neuroner/neuromodel.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/neuromodel.py | MIT |
def _get_config_param(param_filepath=None):
"""
Get the parameters from the config file.
"""
param = {}
# If a parameter file is specified, load it
if param_filepath:
param_file_txt = configparser.ConfigParser()
param_file_txt.read(param_filepath, encoding="UTF-8")
neste... |
Get the parameters from the config file.
| _get_config_param | python | Franck-Dernoncourt/NeuroNER | neuroner/neuromodel.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/neuromodel.py | MIT |
def _clean_param_dtypes(param):
"""
Ensure data types are correct in the parameter dictionary.
Args:
param (dict): dictionary of parameter settings.
"""
# Set the data type
for k, v in param.items():
v = str(v)
# If the value is a list delimited with a comma, choose one... |
Ensure data types are correct in the parameter dictionary.
Args:
param (dict): dictionary of parameter settings.
| _clean_param_dtypes | python | Franck-Dernoncourt/NeuroNER | neuroner/neuromodel.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/neuromodel.py | MIT |
def load_parameters(**kwargs):
'''
Load parameters from the ini file if specified, take into account any
command line argument, and ensure that each parameter is cast to the
correct type.
Command line arguments take precedence over parameters specified in the
parameter file.
'''
param =... |
Load parameters from the ini file if specified, take into account any
command line argument, and ensure that each parameter is cast to the
correct type.
Command line arguments take precedence over parameters specified in the
parameter file.
| load_parameters | python | Franck-Dernoncourt/NeuroNER | neuroner/neuromodel.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/neuromodel.py | MIT |
def get_valid_dataset_filepaths(parameters):
"""
Get valid filepaths for the datasets.
"""
dataset_filepaths = {}
dataset_brat_folders = {}
for dataset_type in ['train', 'valid', 'test', 'deploy']:
dataset_filepaths[dataset_type] = os.path.join(parameters['dataset_text_folder'],
... |
Get valid filepaths for the datasets.
| get_valid_dataset_filepaths | python | Franck-Dernoncourt/NeuroNER | neuroner/neuromodel.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/neuromodel.py | MIT |
def _get_valid_dataset_filepaths(self, parameters, dataset_types=['train', 'valid', 'test', 'deploy']):
"""
Get paths for the datasets.
Args:
parameters (type): description.
dataset_types (type): description.
"""
dataset_filepaths = {}
dataset_bra... |
Get paths for the datasets.
Args:
parameters (type): description.
dataset_types (type): description.
| _get_valid_dataset_filepaths | python | Franck-Dernoncourt/NeuroNER | neuroner/neuromodel.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/neuromodel.py | MIT |
def trim_dataset_pickle(input_dataset_filepath, output_dataset_filepath=None, delete_token_mappings=False):
'''
Remove the dataset and labels from dataset.pickle.
If delete_token_mappings = True, then also remove token_to_index and index_to_token except for UNK.
'''
print("Trimming dataset.pickle..... |
Remove the dataset and labels from dataset.pickle.
If delete_token_mappings = True, then also remove token_to_index and index_to_token except for UNK.
| trim_dataset_pickle | python | Franck-Dernoncourt/NeuroNER | neuroner/prepare_pretrained_model.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/prepare_pretrained_model.py | MIT |
def trim_model_checkpoint(parameters_filepath, dataset_filepath, input_checkpoint_filepath,
output_checkpoint_filepath):
'''
Remove all token embeddings except UNK.
'''
parameters, _ = neuromodel.load_parameters(parameters_filepath=parameters_filepath)
dataset = pickle.load(open(dataset_filepat... |
Remove all token embeddings except UNK.
| trim_model_checkpoint | python | Franck-Dernoncourt/NeuroNER | neuroner/prepare_pretrained_model.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/prepare_pretrained_model.py | MIT |
def prepare_pretrained_model_for_restoring(output_folder_name, epoch_number,
model_name, delete_token_mappings=False):
'''
Copy the dataset.pickle, parameters.ini, and model checkpoint files after
removing the data used for training.
The dataset and labels are deleted from dataset.pickle by d... |
Copy the dataset.pickle, parameters.ini, and model checkpoint files after
removing the data used for training.
The dataset and labels are deleted from dataset.pickle by default. The only
information about the dataset that remain in the pretrained model
is the list of tokens that appears in t... | prepare_pretrained_model_for_restoring | python | Franck-Dernoncourt/NeuroNER | neuroner/prepare_pretrained_model.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/prepare_pretrained_model.py | MIT |
def check_contents_of_dataset_and_model_checkpoint(model_folder):
'''
Check the contents of dataset.pickle and model_xxx.ckpt.
model_folder: folder containing dataset.pickle and model_xxx.ckpt to be checked.
'''
dataset_filepath = os.path.join(model_folder, 'dataset.pickle')
dataset = pickle.lo... |
Check the contents of dataset.pickle and model_xxx.ckpt.
model_folder: folder containing dataset.pickle and model_xxx.ckpt to be checked.
| check_contents_of_dataset_and_model_checkpoint | python | Franck-Dernoncourt/NeuroNER | neuroner/prepare_pretrained_model.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/prepare_pretrained_model.py | MIT |
def order_dictionary(dictionary, mode, reverse=False):
'''
Order a dictionary by 'key' or 'value'.
mode should be either 'key' or 'value'
http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value
'''
if mode =='key':
return collections.OrderedDict(sorted(dictionary.ite... |
Order a dictionary by 'key' or 'value'.
mode should be either 'key' or 'value'
http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value
| order_dictionary | python | Franck-Dernoncourt/NeuroNER | neuroner/utils.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/utils.py | MIT |
def reverse_dictionary(dictionary):
'''
http://stackoverflow.com/questions/483666/python-reverse-inverse-a-mapping
http://stackoverflow.com/questions/25480089/right-way-to-initialize-an-ordereddict-using-its-constructor-such-that-it-retain
'''
#print('type(dictionary): {0}'.format(type(dictionary)))... |
http://stackoverflow.com/questions/483666/python-reverse-inverse-a-mapping
http://stackoverflow.com/questions/25480089/right-way-to-initialize-an-ordereddict-using-its-constructor-such-that-it-retain
| reverse_dictionary | python | Franck-Dernoncourt/NeuroNER | neuroner/utils.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/utils.py | MIT |
def merge_dictionaries(*dict_args):
'''
http://stackoverflow.com/questions/38987/how-can-i-merge-two-python-dictionaries-in-a-single-expression
Given any number of dicts, shallow copy and merge into a new dict,
precedence goes to key value pairs in latter dicts.
'''
result = {}
for dictionar... |
http://stackoverflow.com/questions/38987/how-can-i-merge-two-python-dictionaries-in-a-single-expression
Given any number of dicts, shallow copy and merge into a new dict,
precedence goes to key value pairs in latter dicts.
| merge_dictionaries | python | Franck-Dernoncourt/NeuroNER | neuroner/utils.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/utils.py | MIT |
def pad_list(old_list, padding_size, padding_value):
'''
http://stackoverflow.com/questions/3438756/some-built-in-to-pad-a-list-in-python
Example: pad_list([6,2,3], 5, 0) returns [6,2,3,0,0]
'''
assert padding_size >= len(old_list)
return old_list + [padding_value] * (padding_size-len(old_list)) |
http://stackoverflow.com/questions/3438756/some-built-in-to-pad-a-list-in-python
Example: pad_list([6,2,3], 5, 0) returns [6,2,3,0,0]
| pad_list | python | Franck-Dernoncourt/NeuroNER | neuroner/utils.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/utils.py | MIT |
def copytree(src, dst, symlinks=False, ignore=None):
'''
http://stackoverflow.com/questions/1868714/how-do-i-copy-an-entire-directory-of-files-into-an-existing-directory-using-pyth
'''
for item in os.listdir(src):
s = os.path.join(src, item)
d = os.path.join(dst, item)
if os.path... |
http://stackoverflow.com/questions/1868714/how-do-i-copy-an-entire-directory-of-files-into-an-existing-directory-using-pyth
| copytree | python | Franck-Dernoncourt/NeuroNER | neuroner/utils.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/utils.py | MIT |
def get_cmap():
'''
http://stackoverflow.com/questions/37517587/how-can-i-change-the-intensity-of-a-colormap-in-matplotlib
'''
cmap = cm.get_cmap('RdBu', 256) # set how many colors you want in color map
# modify colormap
alpha = 1.0
colors = []
for ind in range(cmap.N):
c = []
... |
http://stackoverflow.com/questions/37517587/how-can-i-change-the-intensity-of-a-colormap-in-matplotlib
| get_cmap | python | Franck-Dernoncourt/NeuroNER | neuroner/utils_plots.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/utils_plots.py | MIT |
def show_values(pc, fmt="%.2f", **kw):
'''
Heatmap with text in each cell with matplotlib's pyplot
Source: http://stackoverflow.com/a/25074150/395857
By HYRY
'''
pc.update_scalarmappable()
ax = pc.axes
for p, color, value in zip(pc.get_paths(), pc.get_facecolors(), pc.get_array()):
... |
Heatmap with text in each cell with matplotlib's pyplot
Source: http://stackoverflow.com/a/25074150/395857
By HYRY
| show_values | python | Franck-Dernoncourt/NeuroNER | neuroner/utils_plots.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/utils_plots.py | MIT |
def cm2inch(*tupl):
'''
Specify figure size in centimeter in matplotlib
Source: http://stackoverflow.com/a/22787457/395857
By gns-ank
'''
inch = 2.54
if type(tupl[0]) == tuple:
return tuple(i/inch for i in tupl[0])
else:
return tuple(i/inch for i in tupl) |
Specify figure size in centimeter in matplotlib
Source: http://stackoverflow.com/a/22787457/395857
By gns-ank
| cm2inch | python | Franck-Dernoncourt/NeuroNER | neuroner/utils_plots.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/utils_plots.py | MIT |
def heatmap(AUC, title, xlabel, ylabel, xticklabels, yticklabels, figure_width=40, figure_height=20, correct_orientation=False, cmap='RdBu', fmt="%.2f", graph_filepath='', normalize=False, remove_diagonal=False):
'''
Inspired by:
- http://stackoverflow.com/a/16124677/395857
- http://stackoverflow.com/a/... |
Inspired by:
- http://stackoverflow.com/a/16124677/395857
- http://stackoverflow.com/a/25074150/395857
| heatmap | python | Franck-Dernoncourt/NeuroNER | neuroner/utils_plots.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/utils_plots.py | MIT |
def plot_classification_report(classification_report, title='Classification report ', cmap='RdBu', from_conll_json=False):
'''
Plot scikit-learn classification report.
Extension based on http://stackoverflow.com/a/31689645/395857
'''
classes = []
plotMat = []
support = []
class_names = [... |
Plot scikit-learn classification report.
Extension based on http://stackoverflow.com/a/31689645/395857
| plot_classification_report | python | Franck-Dernoncourt/NeuroNER | neuroner/utils_plots.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/utils_plots.py | MIT |
def variable_summaries(var):
'''
Attach a lot of summaries to a Tensor (for TensorBoard visualization).
From https://www.tensorflow.org/get_started/summaries_and_tensorboard
'''
with tf.name_scope('summaries'):
mean = tf.reduce_mean(var)
tf.summary.scalar('mean', mean)
with t... |
Attach a lot of summaries to a Tensor (for TensorBoard visualization).
From https://www.tensorflow.org/get_started/summaries_and_tensorboard
| variable_summaries | python | Franck-Dernoncourt/NeuroNER | neuroner/utils_tf.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/utils_tf.py | MIT |
def parse_arguments(arguments=None):
"""
Parse the NeuroNER arguments
arguments:
arguments the arguments, optionally given as argument
"""
parser = argparse.ArgumentParser(description='''NeuroNER CLI''', formatter_class=RawTextHelpFormatter)
parser.add_argument('--parameters_filepath'... |
Parse the NeuroNER arguments
arguments:
arguments the arguments, optionally given as argument
| parse_arguments | python | Franck-Dernoncourt/NeuroNER | neuroner/__main__.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/__main__.py | MIT |
def main(argv=sys.argv):
''' NeuroNER main method
Args:
parameters_filepath the path to the parameters file
output_folder the path to the output folder
'''
arguments = parse_arguments(argv[1:])
# fetch data and models from the package
if arguments['fetch_data'] or arguments['fe... | NeuroNER main method
Args:
parameters_filepath the path to the parameters file
output_folder the path to the output folder
| main | python | Franck-Dernoncourt/NeuroNER | neuroner/__main__.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/__main__.py | MIT |
def test_ProvideOutputDir_CorrectlyOutputsToDir(self):
"""
Sanity test to check if all proper model output files are created in the output folder
"""
nn = neuromodel.NeuroNER(output_folder=self.outputFolder, parameters_filepath=self.test_param_file)
nn.fit()
# find the n... |
Sanity test to check if all proper model output files are created in the output folder
| test_ProvideOutputDir_CorrectlyOutputsToDir | python | Franck-Dernoncourt/NeuroNER | test/test_main.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/test/test_main.py | MIT |
def connect(host="localhost", user=None, password="",
db=None, port=3306, unix_socket=None,
charset='', sql_mode=None,
read_default_file=None, conv=decoders, use_unicode=None,
client_flag=0, cursorclass=Cursor, init_command=None,
connect_timeout=None, read_def... | See connections.Connection.__init__() for information about
defaults. | connect | python | aio-libs/aiomysql | aiomysql/connection.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/connection.py | MIT |
async def ensure_closed(self):
"""Send quit command and then close socket connection"""
if self._writer is None:
# connection has been closed
return
send_data = struct.pack('<i', 1) + bytes([COMMAND.COM_QUIT])
self._writer.write(send_data)
await self._writ... | Send quit command and then close socket connection | ensure_closed | python | aio-libs/aiomysql | aiomysql/connection.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/connection.py | MIT |
def escape(self, obj):
""" Escape whatever value you pass to it"""
if isinstance(obj, str):
return "'" + self.escape_string(obj) + "'"
if isinstance(obj, bytes):
return escape_bytes_prefixed(obj)
return escape_item(obj, self._charset) | Escape whatever value you pass to it | escape | python | aio-libs/aiomysql | aiomysql/connection.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/connection.py | MIT |
def cursor(self, *cursors):
"""Instantiates and returns a cursor
By default, :class:`Cursor` is returned. It is possible to also give a
custom cursor through the cursor_class parameter, but it needs to
be a subclass of :class:`Cursor`
:param cursor: custom cursor class.
... | Instantiates and returns a cursor
By default, :class:`Cursor` is returned. It is possible to also give a
custom cursor through the cursor_class parameter, but it needs to
be a subclass of :class:`Cursor`
:param cursor: custom cursor class.
:returns: instance of cursor, by defa... | cursor | python | aio-libs/aiomysql | aiomysql/connection.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/connection.py | MIT |
async def ping(self, reconnect=True):
"""Check if the server is alive"""
if self._writer is None and self._reader is None:
if reconnect:
await self._connect()
reconnect = False
else:
raise Error("Already closed")
try:
... | Check if the server is alive | ping | python | aio-libs/aiomysql | aiomysql/connection.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/connection.py | MIT |
async def set_charset(self, charset):
"""Sets the character set for the current connection"""
# Make sure charset is supported.
encoding = charset_by_name(charset).encoding
await self._execute_command(COMMAND.COM_QUERY, "SET NAMES %s"
% self.escape(cha... | Sets the character set for the current connection | set_charset | python | aio-libs/aiomysql | aiomysql/connection.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/connection.py | MIT |
def write_packet(self, payload):
"""Writes an entire "mysql packet" in its entirety to the network
addings its length and sequence number.
"""
# Internal note: when you build packet manually and calls
# _write_bytes() directly, you should set self._next_seq_id properly.
d... | Writes an entire "mysql packet" in its entirety to the network
addings its length and sequence number.
| write_packet | python | aio-libs/aiomysql | aiomysql/connection.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/connection.py | MIT |
async def _read_packet(self, packet_type=MysqlPacket):
"""Read an entire "mysql packet" in its entirety from the network
and return a MysqlPacket type that represents the results.
"""
buff = b''
while True:
try:
packet_header = await self._read_bytes(4... | Read an entire "mysql packet" in its entirety from the network
and return a MysqlPacket type that represents the results.
| _read_packet | python | aio-libs/aiomysql | aiomysql/connection.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/connection.py | MIT |
async def _read_rowdata_packet(self):
"""Read a rowdata packet for each data row in the result set."""
rows = []
while True:
packet = await self.connection._read_packet()
if self._check_packet_is_eof(packet):
# release reference to kill cyclic reference.
... | Read a rowdata packet for each data row in the result set. | _read_rowdata_packet | python | aio-libs/aiomysql | aiomysql/connection.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/connection.py | MIT |
async def _get_descriptions(self):
"""Read a column descriptor packet for each column in the result."""
self.fields = []
self.converters = []
use_unicode = self.connection.use_unicode
conn_encoding = self.connection.encoding
description = []
for i in range(self.fi... | Read a column descriptor packet for each column in the result. | _get_descriptions | python | aio-libs/aiomysql | aiomysql/connection.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/connection.py | MIT |
async def send_data(self):
"""Send data packets from the local file to the server"""
self.connection._ensure_alive()
conn = self.connection
try:
await self._open_file()
with self._file_object:
chunk_size = MAX_PACKET_LEN
while True... | Send data packets from the local file to the server | send_data | python | aio-libs/aiomysql | aiomysql/connection.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/connection.py | MIT |
def __init__(self, connection, echo=False):
"""Do not create an instance of a Cursor yourself. Call
connections.Connection.cursor().
"""
self._connection = connection
self._loop = self._connection.loop
self._description = None
self._rownumber = 0
self._row... | Do not create an instance of a Cursor yourself. Call
connections.Connection.cursor().
| __init__ | python | aio-libs/aiomysql | aiomysql/cursors.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/cursors.py | MIT |
async def close(self):
"""Closing a cursor just exhausts all remaining data."""
conn = self._connection
if conn is None:
return
try:
while (await self.nextset()):
pass
finally:
self._connection = None | Closing a cursor just exhausts all remaining data. | close | python | aio-libs/aiomysql | aiomysql/cursors.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/cursors.py | MIT |
def mogrify(self, query, args=None):
""" Returns the exact string that is sent to the database by calling
the execute() method. This method follows the extension to the DB
API 2.0 followed by Psycopg.
:param query: ``str`` sql statement
:param args: ``tuple`` or ``list`` of argu... | Returns the exact string that is sent to the database by calling
the execute() method. This method follows the extension to the DB
API 2.0 followed by Psycopg.
:param query: ``str`` sql statement
:param args: ``tuple`` or ``list`` of arguments for sql query
| mogrify | python | aio-libs/aiomysql | aiomysql/cursors.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/cursors.py | MIT |
async def execute(self, query, args=None):
"""Executes the given operation
Executes the given operation substituting any markers with
the given parameters.
For example, getting all rows where id is 5:
cursor.execute("SELECT * FROM t1 WHERE id = %s", (5,))
:param quer... | Executes the given operation
Executes the given operation substituting any markers with
the given parameters.
For example, getting all rows where id is 5:
cursor.execute("SELECT * FROM t1 WHERE id = %s", (5,))
:param query: ``str`` sql statement
:param args: ``tuple`... | execute | python | aio-libs/aiomysql | aiomysql/cursors.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/cursors.py | MIT |
async def executemany(self, query, args):
"""Execute the given operation multiple times
The executemany() method will execute the operation iterating
over the list of parameters in seq_params.
Example: Inserting 3 new employees and their phone number
data = [
... | Execute the given operation multiple times
The executemany() method will execute the operation iterating
over the list of parameters in seq_params.
Example: Inserting 3 new employees and their phone number
data = [
('Jane','555-001'),
('Joe', '555-0... | executemany | python | aio-libs/aiomysql | aiomysql/cursors.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/cursors.py | MIT |
async def callproc(self, procname, args=()):
"""Execute stored procedure procname with args
Compatibility warning: PEP-249 specifies that any modified
parameters must be returned. This is currently impossible
as they are only available by storing them in a server
variable and th... | Execute stored procedure procname with args
Compatibility warning: PEP-249 specifies that any modified
parameters must be returned. This is currently impossible
as they are only available by storing them in a server
variable and then retrieved by a query. Since stored
procedures... | callproc | python | aio-libs/aiomysql | aiomysql/cursors.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/cursors.py | MIT |
def fetchmany(self, size=None):
"""Returns the next set of rows of a query result, returning a
list of tuples. When no more rows are available, it returns an
empty list.
The number of rows returned can be specified using the size argument,
which defaults to one
:param s... | Returns the next set of rows of a query result, returning a
list of tuples. When no more rows are available, it returns an
empty list.
The number of rows returned can be specified using the size argument,
which defaults to one
:param size: ``int`` number of rows to return
... | fetchmany | python | aio-libs/aiomysql | aiomysql/cursors.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/cursors.py | MIT |
def fetchall(self):
"""Returns all rows of a query result set
:returns: ``list`` of fetched rows
"""
self._check_executed()
fut = self._loop.create_future()
if self._rows is None:
fut.set_result([])
return fut
if self._rownumber:
... | Returns all rows of a query result set
:returns: ``list`` of fetched rows
| fetchall | python | aio-libs/aiomysql | aiomysql/cursors.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/cursors.py | MIT |
def scroll(self, value, mode='relative'):
"""Scroll the cursor in the result set to a new position according
to mode.
If mode is relative (default), value is taken as offset to the
current position in the result set, if set to absolute, value
states an absolute target position.... | Scroll the cursor in the result set to a new position according
to mode.
If mode is relative (default), value is taken as offset to the
current position in the result set, if set to absolute, value
states an absolute target position. An IndexError should be raised in
case a scr... | scroll | python | aio-libs/aiomysql | aiomysql/cursors.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/cursors.py | MIT |
async def fetchall(self):
"""Fetch all, as per MySQLdb. Pretty useless for large queries, as
it is buffered.
"""
rows = []
while True:
row = await self.fetchone()
if row is None:
break
rows.append(row)
return rows | Fetch all, as per MySQLdb. Pretty useless for large queries, as
it is buffered.
| fetchall | python | aio-libs/aiomysql | aiomysql/cursors.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/cursors.py | MIT |
async def scroll(self, value, mode='relative'):
"""Scroll the cursor in the result set to a new position
according to mode . Same as :meth:`Cursor.scroll`, but move cursor
on server side one by one row. If you want to move 20 rows forward
scroll will make 20 queries to move cursor. Curre... | Scroll the cursor in the result set to a new position
according to mode . Same as :meth:`Cursor.scroll`, but move cursor
on server side one by one row. If you want to move 20 rows forward
scroll will make 20 queries to move cursor. Currently only forward
scrolling is supported.
... | scroll | python | aio-libs/aiomysql | aiomysql/cursors.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/cursors.py | MIT |
async def clear(self):
"""Close all free connections in pool."""
async with self._cond:
while self._free:
conn = self._free.popleft()
await conn.ensure_closed()
self._cond.notify() | Close all free connections in pool. | clear | python | aio-libs/aiomysql | aiomysql/pool.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/pool.py | MIT |
def close(self):
"""Close pool.
Mark all pool connections to be closed on getting back to pool.
Closed pool doesn't allow to acquire new connections.
"""
if self._closed:
return
self._closing = True | Close pool.
Mark all pool connections to be closed on getting back to pool.
Closed pool doesn't allow to acquire new connections.
| close | python | aio-libs/aiomysql | aiomysql/pool.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/pool.py | MIT |
def terminate(self):
"""Terminate pool.
Close pool with instantly closing all acquired connections also.
"""
self.close()
for conn in list(self._used):
conn.close()
self._terminated.add(conn)
self._used.clear() | Terminate pool.
Close pool with instantly closing all acquired connections also.
| terminate | python | aio-libs/aiomysql | aiomysql/pool.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/pool.py | MIT |
async def wait_closed(self):
"""Wait for closing all pool's connections."""
if self._closed:
return
if not self._closing:
raise RuntimeError(".wait_closed() should be called "
"after .close()")
while self._free:
conn = ... | Wait for closing all pool's connections. | wait_closed | python | aio-libs/aiomysql | aiomysql/pool.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/pool.py | MIT |
def acquire(self):
"""Acquire free connection from the pool."""
coro = self._acquire()
return _PoolAcquireContextManager(coro, self) | Acquire free connection from the pool. | acquire | python | aio-libs/aiomysql | aiomysql/pool.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/pool.py | MIT |
def release(self, conn):
"""Release free connection back to the connection pool.
This is **NOT** a coroutine.
"""
fut = self._loop.create_future()
fut.set_result(None)
if conn in self._terminated:
assert conn.closed, conn
self._terminated.remove(... | Release free connection back to the connection pool.
This is **NOT** a coroutine.
| release | python | aio-libs/aiomysql | aiomysql/pool.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/pool.py | MIT |
async def scalar(self, query, *multiparams, **params):
"""Executes a SQL query and returns a scalar value."""
res = await self.execute(query, *multiparams, **params)
return (await res.scalar()) | Executes a SQL query and returns a scalar value. | scalar | python | aio-libs/aiomysql | aiomysql/sa/connection.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/sa/connection.py | MIT |
async def begin_twophase(self, xid=None):
"""Begin a two-phase or XA transaction and return a transaction
handle.
The returned object is an instance of
TwoPhaseTransaction, which in addition to the
methods provided by Transaction, also provides a
TwoPhaseTransaction.prep... | Begin a two-phase or XA transaction and return a transaction
handle.
The returned object is an instance of
TwoPhaseTransaction, which in addition to the
methods provided by Transaction, also provides a
TwoPhaseTransaction.prepare() method.
xid - the two phase transactio... | begin_twophase | python | aio-libs/aiomysql | aiomysql/sa/connection.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/sa/connection.py | MIT |
async def recover_twophase(self):
"""Return a list of prepared twophase transaction ids."""
result = await self.execute("XA RECOVER;")
return [row[0] for row in result] | Return a list of prepared twophase transaction ids. | recover_twophase | python | aio-libs/aiomysql | aiomysql/sa/connection.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/sa/connection.py | MIT |
async def close(self):
"""Close this SAConnection.
This results in a release of the underlying database
resources, that is, the underlying connection referenced
internally. The underlying connection is typically restored
back to the connection-holding Pool referenced by the Engi... | Close this SAConnection.
This results in a release of the underlying database
resources, that is, the underlying connection referenced
internally. The underlying connection is typically restored
back to the connection-holding Pool referenced by the Engine
that produced this SACo... | close | python | aio-libs/aiomysql | aiomysql/sa/connection.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/sa/connection.py | MIT |
def _distill_params(multiparams, params):
"""Given arguments from the calling form *multiparams, **params,
return a list of bind parameter structures, usually a list of
dictionaries.
In the case of 'raw' execution which accepts positional parameters,
it may be a list of tuples or lists.
"""
... | Given arguments from the calling form *multiparams, **params,
return a list of bind parameter structures, usually a list of
dictionaries.
In the case of 'raw' execution which accepts positional parameters,
it may be a list of tuples or lists.
| _distill_params | python | aio-libs/aiomysql | aiomysql/sa/connection.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/sa/connection.py | MIT |
def create_engine(minsize=1, maxsize=10, loop=None,
dialect=_dialect, pool_recycle=-1, compiled_cache=None,
**kwargs):
"""A coroutine for Engine creation.
Returns Engine instance with embedded connection pool.
The pool has *minsize* opened connections to MySQL server.
... | A coroutine for Engine creation.
Returns Engine instance with embedded connection pool.
The pool has *minsize* opened connections to MySQL server.
| create_engine | python | aio-libs/aiomysql | aiomysql/sa/engine.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/sa/engine.py | MIT |
async def wait_closed(self):
"""Wait for closing all engine's connections."""
await self._pool.wait_closed() | Wait for closing all engine's connections. | wait_closed | python | aio-libs/aiomysql | aiomysql/sa/engine.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/sa/engine.py | MIT |
def __init__(self, result_proxy, row, processors, keymap):
"""RowProxy objects are constructed by ResultProxy objects."""
self._result_proxy = result_proxy
self._row = row
self._processors = processors
self._keymap = keymap | RowProxy objects are constructed by ResultProxy objects. | __init__ | python | aio-libs/aiomysql | aiomysql/sa/result.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/sa/result.py | MIT |
def keys(self):
"""Return the current set of string keys for rows."""
if self._metadata:
return tuple(self._metadata.keys)
else:
return () | Return the current set of string keys for rows. | keys | python | aio-libs/aiomysql | aiomysql/sa/result.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/sa/result.py | MIT |
async def close(self):
"""Close this ResultProxy.
Closes the underlying DBAPI cursor corresponding to the execution.
Note that any data cached within this ResultProxy is still available.
For some types of results, this may include buffered rows.
If this ResultProxy was generat... | Close this ResultProxy.
Closes the underlying DBAPI cursor corresponding to the execution.
Note that any data cached within this ResultProxy is still available.
For some types of results, this may include buffered rows.
If this ResultProxy was generated from an implicit execution,
... | close | python | aio-libs/aiomysql | aiomysql/sa/result.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/sa/result.py | MIT |
async def fetchall(self):
"""Fetch all rows, just like DB-API cursor.fetchall()."""
try:
rows = await self._cursor.fetchall()
except AttributeError:
self._non_result()
else:
ret = self._process_rows(rows)
await self.close()
retu... | Fetch all rows, just like DB-API cursor.fetchall(). | fetchall | python | aio-libs/aiomysql | aiomysql/sa/result.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/sa/result.py | MIT |
async def fetchone(self):
"""Fetch one row, just like DB-API cursor.fetchone().
If a row is present, the cursor remains open after this is called.
Else the cursor is automatically closed and None is returned.
"""
try:
row = await self._cursor.fetchone()
excep... | Fetch one row, just like DB-API cursor.fetchone().
If a row is present, the cursor remains open after this is called.
Else the cursor is automatically closed and None is returned.
| fetchone | python | aio-libs/aiomysql | aiomysql/sa/result.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/sa/result.py | MIT |
async def fetchmany(self, size=None):
"""Fetch many rows, just like DB-API
cursor.fetchmany(size=cursor.arraysize).
If rows are present, the cursor remains open after this is called.
Else the cursor is automatically closed and an empty list is returned.
"""
try:
... | Fetch many rows, just like DB-API
cursor.fetchmany(size=cursor.arraysize).
If rows are present, the cursor remains open after this is called.
Else the cursor is automatically closed and an empty list is returned.
| fetchmany | python | aio-libs/aiomysql | aiomysql/sa/result.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/sa/result.py | MIT |
async def first(self):
"""Fetch the first row and then close the result set unconditionally.
Returns None if no row is present.
"""
if self._metadata is None:
self._non_result()
try:
return (await self.fetchone())
finally:
await self.c... | Fetch the first row and then close the result set unconditionally.
Returns None if no row is present.
| first | python | aio-libs/aiomysql | aiomysql/sa/result.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/sa/result.py | MIT |
async def scalar(self):
"""Fetch the first column of the first row, and close the result set.
Returns None if no row is present.
"""
row = await self.first()
if row is not None:
return row[0]
else:
return None | Fetch the first column of the first row, and close the result set.
Returns None if no row is present.
| scalar | python | aio-libs/aiomysql | aiomysql/sa/result.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/sa/result.py | MIT |
def pytest_pyfunc_call(pyfuncitem):
"""
Run asyncio marked test functions in an event loop instead of a normal
function call.
"""
if 'run_loop' in pyfuncitem.keywords:
funcargs = pyfuncitem.funcargs
loop = funcargs['loop']
testargs = {arg: funcargs[arg]
fo... |
Run asyncio marked test functions in an event loop instead of a normal
function call.
| pytest_pyfunc_call | python | aio-libs/aiomysql | tests/conftest.py | https://github.com/aio-libs/aiomysql/blob/master/tests/conftest.py | MIT |
def mysql_server_is(server_version, version_tuple):
"""Return True if the given connection is on the version given or
greater.
e.g.::
if self.mysql_server_is(conn, (5, 6, 4)):
# do something for MySQL 5.6.4 and above
"""
server_version_tuple = tuple(
(int(dig) if dig is n... | Return True if the given connection is on the version given or
greater.
e.g.::
if self.mysql_server_is(conn, (5, 6, 4)):
# do something for MySQL 5.6.4 and above
| mysql_server_is | python | aio-libs/aiomysql | tests/test_basic.py | https://github.com/aio-libs/aiomysql/blob/master/tests/test_basic.py | MIT |
async def test_issue_8(connection):
""" Primary Key and Index error when selecting data """
conn = connection
c = await conn.cursor()
await c.execute("drop table if exists test")
await c.execute("""CREATE TABLE `test` (
`station` int(10) NOT NULL DEFAULT '0',
`dh` datetime NOT NULL D... | Primary Key and Index error when selecting data | test_issue_8 | python | aio-libs/aiomysql | tests/test_issues.py | https://github.com/aio-libs/aiomysql/blob/master/tests/test_issues.py | MIT |
async def test_issue_15(connection):
""" query should be expanded before perform character encoding """
conn = connection
c = await conn.cursor()
await c.execute("drop table if exists issue15")
await c.execute("create table issue15 (t varchar(32))")
try:
await c.execute("insert into issu... | query should be expanded before perform character encoding | test_issue_15 | python | aio-libs/aiomysql | tests/test_issues.py | https://github.com/aio-libs/aiomysql/blob/master/tests/test_issues.py | MIT |
async def test_issue_16(connection):
""" Patch for string and tuple escaping """
conn = connection
c = await conn.cursor()
await c.execute("drop table if exists issue16")
await c.execute("create table issue16 (name varchar(32) "
"primary key, email varchar(32))")
try:
... | Patch for string and tuple escaping | test_issue_16 | python | aio-libs/aiomysql | tests/test_issues.py | https://github.com/aio-libs/aiomysql/blob/master/tests/test_issues.py | MIT |
async def test_issue_17(connection, connection_creator, mysql_params):
""" could not connect mysql use passwod """
conn = connection
c = await conn.cursor()
db = mysql_params['db']
# grant access to a table to a user with a password
try:
await c.execute("drop table if exists issue17")
... | could not connect mysql use passwod | test_issue_17 | python | aio-libs/aiomysql | tests/test_issues.py | https://github.com/aio-libs/aiomysql/blob/master/tests/test_issues.py | MIT |
async def test_issue_79(connection):
""" Duplicate field overwrites the previous one in the result
of DictCursor """
conn = connection
c = await conn.cursor(aiomysql.cursors.DictCursor)
await c.execute("drop table if exists a")
await c.execute("drop table if exists b")
await c.execute("""CR... | Duplicate field overwrites the previous one in the result
of DictCursor | test_issue_79 | python | aio-libs/aiomysql | tests/test_issues.py | https://github.com/aio-libs/aiomysql/blob/master/tests/test_issues.py | MIT |
async def test_issue_95(connection):
""" Leftover trailing OK packet for "CALL my_sp" queries """
conn = connection
cur = await conn.cursor()
await cur.execute("DROP PROCEDURE IF EXISTS `foo`")
await cur.execute("""CREATE PROCEDURE `foo` ()
BEGIN
SELECT 1;
END""")
try:
aw... | Leftover trailing OK packet for "CALL my_sp" queries | test_issue_95 | python | aio-libs/aiomysql | tests/test_issues.py | https://github.com/aio-libs/aiomysql/blob/master/tests/test_issues.py | MIT |
async def test_issue_175(connection):
""" The number of fields returned by server is read in wrong way """
conn = connection
cur = await conn.cursor()
for length in (200, 300):
cols = ', '.join(f'c{i} integer' for i in range(length))
sql = f'create table test_field_count ({cols})'
... | The number of fields returned by server is read in wrong way | test_issue_175 | python | aio-libs/aiomysql | tests/test_issues.py | https://github.com/aio-libs/aiomysql/blob/master/tests/test_issues.py | MIT |
def lstm(inputs, hparams, train, name, initial_state=None):
'''Run LSTM cell on inputs, assuming they are [batch x time x size].'''
def dropout_lstm_cell():
return tf.contrib.rnn.DropoutWrapper(
tf.contrib.cudnn_rnn.CudnnCompatibleLSTMCell(hparams.hidden_size),
input_keep_prob=1.0 - hparams.dro... | Run LSTM cell on inputs, assuming they are [batch x time x size]. | lstm | python | ricsinaruto/Seq2seqChatbots | t2t_csaky/models/gradient_checkpointed_seq2seq.py | https://github.com/ricsinaruto/Seq2seqChatbots/blob/master/t2t_csaky/models/gradient_checkpointed_seq2seq.py | MIT |
def lstm_seq2seq_internal_dynamic(inputs, targets, hparams, train):
'''The basic LSTM seq2seq model, main step used for training.'''
with tf.variable_scope('lstm_seq2seq'):
if inputs is not None:
# Flatten inputs.
inputs = common_layers.flatten4d3d(inputs)
# LSTM encoder.
_, final_encode... | The basic LSTM seq2seq model, main step used for training. | lstm_seq2seq_internal_dynamic | python | ricsinaruto/Seq2seqChatbots | t2t_csaky/models/gradient_checkpointed_seq2seq.py | https://github.com/ricsinaruto/Seq2seqChatbots/blob/master/t2t_csaky/models/gradient_checkpointed_seq2seq.py | MIT |
def generator(self, data_dir, tmp_dir, train):
'''
Generate the vocab and then build train and validation t2t-datagen files.
Four .txt files have to be present in the data_dir directory:
trainSource.txt
trainTarget.txt
devSource.txt
devTarget.txt
Params:
:train: Whether we... |
Generate the vocab and then build train and validation t2t-datagen files.
Four .txt files have to be present in the data_dir directory:
trainSource.txt
trainTarget.txt
devSource.txt
devTarget.txt
Params:
:train: Whether we are in train mode or not.
| generator | python | ricsinaruto/Seq2seqChatbots | t2t_csaky/problems/character_chatbot.py | https://github.com/ricsinaruto/Seq2seqChatbots/blob/master/t2t_csaky/problems/character_chatbot.py | MIT |
def preprocess_data(self, train_mode):
'''
Params:
:train_mode: Whether we are in train or dev mode.
'''
# Set the raw data directory and data.
self.raw_data_dir = os.path.join('/'.join(self._data_dir.split('/')[:-1]),
'raw_data')
self.raw_data = os.pa... |
Params:
:train_mode: Whether we are in train or dev mode.
| preprocess_data | python | ricsinaruto/Seq2seqChatbots | t2t_csaky/problems/cornell_chatbots.py | https://github.com/ricsinaruto/Seq2seqChatbots/blob/master/t2t_csaky/problems/cornell_chatbots.py | MIT |
def clean_line(self, line):
'''
Params:
:line: Line to be processed and returned.
'''
# 2 functions for more complex replacing.
def replace(matchobj):
return re.sub("'", " '", str(matchobj.group(0)))
def replace_null(matchobj):
return re.sub("'", '', str(matchobj.group(0)))
... |
Params:
:line: Line to be processed and returned.
| clean_line | python | ricsinaruto/Seq2seqChatbots | t2t_csaky/problems/cornell_chatbots.py | https://github.com/ricsinaruto/Seq2seqChatbots/blob/master/t2t_csaky/problems/cornell_chatbots.py | MIT |
def replace_names(self, line_dict, name_vocab):
'''
Params:
:line_dict: Dictionary containing all the parsed lines.
:name_vocab: The vocabulary of names.
'''
name_list = []
for name, _ in name_vocab.most_common(self.targeted_name_vocab_size - 1):
name_list.append(name)
for... |
Params:
:line_dict: Dictionary containing all the parsed lines.
:name_vocab: The vocabulary of names.
| replace_names | python | ricsinaruto/Seq2seqChatbots | t2t_csaky/problems/cornell_chatbots.py | https://github.com/ricsinaruto/Seq2seqChatbots/blob/master/t2t_csaky/problems/cornell_chatbots.py | MIT |
def save_vocab(self, vocab, name_vocab):
'''
Params:
:vocab: Vocabulary list.
:name_vocab: Name vocabulary.
'''
voc_file = open(os.path.join(self._data_dir, self.vocab_file), 'w')
# put the reserved tokens in
voc_file.write('<pad>\n')
voc_file.write('<EOS>\n')
# basi... |
Params:
:vocab: Vocabulary list.
:name_vocab: Name vocabulary.
| save_vocab | python | ricsinaruto/Seq2seqChatbots | t2t_csaky/problems/cornell_chatbots.py | https://github.com/ricsinaruto/Seq2seqChatbots/blob/master/t2t_csaky/problems/cornell_chatbots.py | MIT |
def data_pipeline_status(self, train_mode):
'''
This function first check recursively at which point in the
data processing point are we (what files can be found on the disk),
and then proceeds from there.
Params:
:train_mode: Whether we are in train or dev mode.
'''
# Build the sour... |
This function first check recursively at which point in the
data processing point are we (what files can be found on the disk),
and then proceeds from there.
Params:
:train_mode: Whether we are in train or dev mode.
| data_pipeline_status | python | ricsinaruto/Seq2seqChatbots | t2t_csaky/problems/opensubtitles_chatbot.py | https://github.com/ricsinaruto/Seq2seqChatbots/blob/master/t2t_csaky/problems/opensubtitles_chatbot.py | MIT |
def download_data(self, train_mode):
'''
Params:
:train_mode: Whether we are in train or dev mode.
'''
# Open the url and download the data with progress bars.
data_stream = requests.get(self._url, stream=True)
with open(self._zipped_data, 'wb') as file:
total_length = int(data_str... |
Params:
:train_mode: Whether we are in train or dev mode.
| download_data | python | ricsinaruto/Seq2seqChatbots | t2t_csaky/problems/opensubtitles_chatbot.py | https://github.com/ricsinaruto/Seq2seqChatbots/blob/master/t2t_csaky/problems/opensubtitles_chatbot.py | MIT |
def generate_samples(self, data_dir, tmp_dir, data_split):
'''
The function assumes that if you have data at one level of the pipeline,
you don't want to re-generate it, so for example if the 4 txt files exist,
the function continues by generating the t2t-datagen format files.
So if you want to re-d... |
The function assumes that if you have data at one level of the pipeline,
you don't want to re-generate it, so for example if the 4 txt files exist,
the function continues by generating the t2t-datagen format files.
So if you want to re-download or re-generate data,
you have to delete it first from ... | generate_samples | python | ricsinaruto/Seq2seqChatbots | t2t_csaky/problems/word_chatbot.py | https://github.com/ricsinaruto/Seq2seqChatbots/blob/master/t2t_csaky/problems/word_chatbot.py | MIT |
def compute_gradients(self, loss, var_list=None,
gate_gradients=tf.train.Optimizer.GATE_OP,
aggregation_method=None,
colocate_gradients_with_ops=False,
grad_loss=None):
'''Compute gradients of `loss` for the variables in... | Compute gradients of `loss` for the variables in `var_list`.
This is the first part of `minimize()`. It returns a list
of (gradient, variable) pairs where 'gradient' is the gradient
for 'variable'. Note that 'gradient' can be a `Tensor`, an
`IndexedSlices`, or `None` if there is no gradient for the
... | compute_gradients | python | ricsinaruto/Seq2seqChatbots | t2t_csaky/utils/optimizer.py | https://github.com/ricsinaruto/Seq2seqChatbots/blob/master/t2t_csaky/utils/optimizer.py | MIT |
def create_app(path=None, user_content=False, context=None, username=None,
password=None, render_offline=False, render_wide=False,
render_inline=False, api_url=None, title=None, text=None,
autorefresh=None, quiet=None, theme='light', grip_class=None):
"""
Creates a G... |
Creates a Grip application with the specified overrides.
| create_app | python | joeyespo/grip | grip/api.py | https://github.com/joeyespo/grip/blob/master/grip/api.py | MIT |
def serve(path=None, host=None, port=None, user_content=False, context=None,
username=None, password=None, render_offline=False,
render_wide=False, render_inline=False, api_url=None, title=None,
autorefresh=True, browser=False, quiet=None, theme='light', grip_class=None):
"""
Start... |
Starts a server to render the specified file or directory containing
a README.
| serve | python | joeyespo/grip | grip/api.py | https://github.com/joeyespo/grip/blob/master/grip/api.py | MIT |
def clear_cache(grip_class=None):
"""
Clears the cached styles and assets.
"""
if grip_class is None:
grip_class = Grip
grip_class(StdinReader()).clear_cache() |
Clears the cached styles and assets.
| clear_cache | python | joeyespo/grip | grip/api.py | https://github.com/joeyespo/grip/blob/master/grip/api.py | MIT |
def render_page(path=None, user_content=False, context=None,
username=None, password=None,
render_offline=False, render_wide=False, render_inline=False,
api_url=None, title=None, text=None, quiet=None, theme='light',
grip_class=None):
"""
Renders t... |
Renders the specified markup text to an HTML page and returns it.
| render_page | python | joeyespo/grip | grip/api.py | https://github.com/joeyespo/grip/blob/master/grip/api.py | MIT |
def render_content(text, user_content=False, context=None, username=None,
password=None, render_offline=False, api_url=None):
"""
Renders the specified markup and returns the result.
"""
renderer = (GitHubRenderer(user_content, context, api_url)
if not render_offline e... |
Renders the specified markup and returns the result.
| render_content | python | joeyespo/grip | grip/api.py | https://github.com/joeyespo/grip/blob/master/grip/api.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.