partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
compare
Performs passed-in comparison op between every element in the passed-in array and other, and returns an array of booleans. Args: array (WeldObject / Numpy.ndarray): Input array other (WeldObject / Numpy.ndarray): Second input array op (str): Op string used for element-wise comparison (=...
python/grizzly/grizzly/grizzly_impl.py
def compare(array, other, op, ty_str): """ Performs passed-in comparison op between every element in the passed-in array and other, and returns an array of booleans. Args: array (WeldObject / Numpy.ndarray): Input array other (WeldObject / Numpy.ndarray): Second input array op (...
def compare(array, other, op, ty_str): """ Performs passed-in comparison op between every element in the passed-in array and other, and returns an array of booleans. Args: array (WeldObject / Numpy.ndarray): Input array other (WeldObject / Numpy.ndarray): Second input array op (...
[ "Performs", "passed", "-", "in", "comparison", "op", "between", "every", "element", "in", "the", "passed", "-", "in", "array", "and", "other", "and", "returns", "an", "array", "of", "booleans", "." ]
weld-project/weld
python
https://github.com/weld-project/weld/blob/8ddd6db6b28878bef0892da44b1d2002b564389c/python/grizzly/grizzly/grizzly_impl.py#L469-L510
[ "def", "compare", "(", "array", ",", "other", ",", "op", ",", "ty_str", ")", ":", "weld_obj", "=", "WeldObject", "(", "encoder_", ",", "decoder_", ")", "array_var", "=", "weld_obj", ".", "update", "(", "array", ")", "if", "isinstance", "(", "array", ",...
8ddd6db6b28878bef0892da44b1d2002b564389c
train
slice
Returns a new array-of-arrays with each array truncated, starting at index `start` for `length` characters. Args: array (WeldObject / Numpy.ndarray): Input array start (int): starting index size (int): length to truncate at ty (WeldType): Type of each element in the input array ...
python/grizzly/grizzly/grizzly_impl.py
def slice(array, start, size, ty): """ Returns a new array-of-arrays with each array truncated, starting at index `start` for `length` characters. Args: array (WeldObject / Numpy.ndarray): Input array start (int): starting index size (int): length to truncate at ty (Weld...
def slice(array, start, size, ty): """ Returns a new array-of-arrays with each array truncated, starting at index `start` for `length` characters. Args: array (WeldObject / Numpy.ndarray): Input array start (int): starting index size (int): length to truncate at ty (Weld...
[ "Returns", "a", "new", "array", "-", "of", "-", "arrays", "with", "each", "array", "truncated", "starting", "at", "index", "start", "for", "length", "characters", "." ]
weld-project/weld
python
https://github.com/weld-project/weld/blob/8ddd6db6b28878bef0892da44b1d2002b564389c/python/grizzly/grizzly/grizzly_impl.py#L513-L543
[ "def", "slice", "(", "array", ",", "start", ",", "size", ",", "ty", ")", ":", "weld_obj", "=", "WeldObject", "(", "encoder_", ",", "decoder_", ")", "array_var", "=", "weld_obj", ".", "update", "(", "array", ")", "if", "isinstance", "(", "array", ",", ...
8ddd6db6b28878bef0892da44b1d2002b564389c
train
contains
Checks if given string is contained in each string in the array. Output is a vec of booleans. Args: array (WeldObject / Numpy.ndarray): Input array start (int): starting index size (int): length to truncate at ty (WeldType): Type of each element in the input array Returns: ...
python/grizzly/grizzly/grizzly_impl.py
def contains(array, ty, string): """ Checks if given string is contained in each string in the array. Output is a vec of booleans. Args: array (WeldObject / Numpy.ndarray): Input array start (int): starting index size (int): length to truncate at ty (WeldType): Type of e...
def contains(array, ty, string): """ Checks if given string is contained in each string in the array. Output is a vec of booleans. Args: array (WeldObject / Numpy.ndarray): Input array start (int): starting index size (int): length to truncate at ty (WeldType): Type of e...
[ "Checks", "if", "given", "string", "is", "contained", "in", "each", "string", "in", "the", "array", ".", "Output", "is", "a", "vec", "of", "booleans", "." ]
weld-project/weld
python
https://github.com/weld-project/weld/blob/8ddd6db6b28878bef0892da44b1d2002b564389c/python/grizzly/grizzly/grizzly_impl.py#L575-L626
[ "def", "contains", "(", "array", ",", "ty", ",", "string", ")", ":", "weld_obj", "=", "WeldObject", "(", "encoder_", ",", "decoder_", ")", "string_obj", "=", "weld_obj", ".", "update", "(", "string", ")", "if", "isinstance", "(", "string", ",", "WeldObje...
8ddd6db6b28878bef0892da44b1d2002b564389c
train
join
Computes a join on two tables
python/grizzly/grizzly/grizzly_impl.py
def join(expr1, expr2, d1_keys, d2_keys, keys_type, d1_vals, df1_vals_ty, d2_vals, df2_vals_ty): """ Computes a join on two tables """ weld_obj = WeldObject(encoder_, decoder_) df1_var = weld_obj.update(expr1) if isinstance(expr1, WeldObject): df1_var = expr1.obj_id weld_obj....
def join(expr1, expr2, d1_keys, d2_keys, keys_type, d1_vals, df1_vals_ty, d2_vals, df2_vals_ty): """ Computes a join on two tables """ weld_obj = WeldObject(encoder_, decoder_) df1_var = weld_obj.update(expr1) if isinstance(expr1, WeldObject): df1_var = expr1.obj_id weld_obj....
[ "Computes", "a", "join", "on", "two", "tables" ]
weld-project/weld
python
https://github.com/weld-project/weld/blob/8ddd6db6b28878bef0892da44b1d2002b564389c/python/grizzly/grizzly/grizzly_impl.py#L656-L721
[ "def", "join", "(", "expr1", ",", "expr2", ",", "d1_keys", ",", "d2_keys", ",", "keys_type", ",", "d1_vals", ",", "df1_vals_ty", ",", "d2_vals", ",", "df2_vals_ty", ")", ":", "weld_obj", "=", "WeldObject", "(", "encoder_", ",", "decoder_", ")", "df1_var", ...
8ddd6db6b28878bef0892da44b1d2002b564389c
train
pivot_table
Constructs a pivot table where the index_index and columns_index are used as keys and the value_index is used as the value which is aggregated.
python/grizzly/grizzly/grizzly_impl.py
def pivot_table(expr, value_index, value_ty, index_index, index_ty, columns_index, columns_ty, aggfunc): """ Constructs a pivot table where the index_index and columns_index are used as keys and the value_index is used as the value which is aggregated. """ weld_obj = WeldObject(encoder_, decoder_) ...
def pivot_table(expr, value_index, value_ty, index_index, index_ty, columns_index, columns_ty, aggfunc): """ Constructs a pivot table where the index_index and columns_index are used as keys and the value_index is used as the value which is aggregated. """ weld_obj = WeldObject(encoder_, decoder_) ...
[ "Constructs", "a", "pivot", "table", "where", "the", "index_index", "and", "columns_index", "are", "used", "as", "keys", "and", "the", "value_index", "is", "used", "as", "the", "value", "which", "is", "aggregated", "." ]
weld-project/weld
python
https://github.com/weld-project/weld/blob/8ddd6db6b28878bef0892da44b1d2002b564389c/python/grizzly/grizzly/grizzly_impl.py#L723-L786
[ "def", "pivot_table", "(", "expr", ",", "value_index", ",", "value_ty", ",", "index_index", ",", "index_ty", ",", "columns_index", ",", "columns_ty", ",", "aggfunc", ")", ":", "weld_obj", "=", "WeldObject", "(", "encoder_", ",", "decoder_", ")", "zip_var", "...
8ddd6db6b28878bef0892da44b1d2002b564389c
train
groupby_size
Groups the given columns by the corresponding grouping column value, and aggregate by summing values. Args: columns (List<WeldObject>): List of columns as WeldObjects column_tys (List<str>): List of each column data ty grouping_column (WeldObject): Column to group rest of columns by ...
python/grizzly/grizzly/grizzly_impl.py
def groupby_size(columns, column_tys, grouping_columns, grouping_column_tys): """ Groups the given columns by the corresponding grouping column value, and aggregate by summing values. Args: columns (List<WeldObject>): List of columns as WeldObjects column_tys (List<str>): List of each c...
def groupby_size(columns, column_tys, grouping_columns, grouping_column_tys): """ Groups the given columns by the corresponding grouping column value, and aggregate by summing values. Args: columns (List<WeldObject>): List of columns as WeldObjects column_tys (List<str>): List of each c...
[ "Groups", "the", "given", "columns", "by", "the", "corresponding", "grouping", "column", "value", "and", "aggregate", "by", "summing", "values", "." ]
weld-project/weld
python
https://github.com/weld-project/weld/blob/8ddd6db6b28878bef0892da44b1d2002b564389c/python/grizzly/grizzly/grizzly_impl.py#L1188-L1248
[ "def", "groupby_size", "(", "columns", ",", "column_tys", ",", "grouping_columns", ",", "grouping_column_tys", ")", ":", "weld_obj", "=", "WeldObject", "(", "encoder_", ",", "decoder_", ")", "if", "len", "(", "grouping_columns", ")", "==", "1", "and", "len", ...
8ddd6db6b28878bef0892da44b1d2002b564389c
train
groupby_sort
Groups the given columns by the corresponding grouping column value, and aggregate by summing values. Args: columns (List<WeldObject>): List of columns as WeldObjects column_tys (List<str>): List of each column data ty grouping_column (WeldObject): Column to group rest of columns by ...
python/grizzly/grizzly/grizzly_impl.py
def groupby_sort(columns, column_tys, grouping_columns, grouping_column_tys, key_index, ascending): """ Groups the given columns by the corresponding grouping column value, and aggregate by summing values. Args: columns (List<WeldObject>): List of columns as WeldObjects column_tys (List...
def groupby_sort(columns, column_tys, grouping_columns, grouping_column_tys, key_index, ascending): """ Groups the given columns by the corresponding grouping column value, and aggregate by summing values. Args: columns (List<WeldObject>): List of columns as WeldObjects column_tys (List...
[ "Groups", "the", "given", "columns", "by", "the", "corresponding", "grouping", "column", "value", "and", "aggregate", "by", "summing", "values", "." ]
weld-project/weld
python
https://github.com/weld-project/weld/blob/8ddd6db6b28878bef0892da44b1d2002b564389c/python/grizzly/grizzly/grizzly_impl.py#L1250-L1364
[ "def", "groupby_sort", "(", "columns", ",", "column_tys", ",", "grouping_columns", ",", "grouping_column_tys", ",", "key_index", ",", "ascending", ")", ":", "weld_obj", "=", "WeldObject", "(", "encoder_", ",", "decoder_", ")", "if", "len", "(", "grouping_columns...
8ddd6db6b28878bef0892da44b1d2002b564389c
train
flatten_group
Groups the given columns by the corresponding grouping column value, and aggregate by summing values. Args: columns (List<WeldObject>): List of columns as WeldObjects column_tys (List<str>): List of each column data ty grouping_column (WeldObject): Column to group rest of columns by ...
python/grizzly/grizzly/grizzly_impl.py
def flatten_group(expr, column_tys, grouping_column_tys): """ Groups the given columns by the corresponding grouping column value, and aggregate by summing values. Args: columns (List<WeldObject>): List of columns as WeldObjects column_tys (List<str>): List of each column data ty ...
def flatten_group(expr, column_tys, grouping_column_tys): """ Groups the given columns by the corresponding grouping column value, and aggregate by summing values. Args: columns (List<WeldObject>): List of columns as WeldObjects column_tys (List<str>): List of each column data ty ...
[ "Groups", "the", "given", "columns", "by", "the", "corresponding", "grouping", "column", "value", "and", "aggregate", "by", "summing", "values", "." ]
weld-project/weld
python
https://github.com/weld-project/weld/blob/8ddd6db6b28878bef0892da44b1d2002b564389c/python/grizzly/grizzly/grizzly_impl.py#L1366-L1421
[ "def", "flatten_group", "(", "expr", ",", "column_tys", ",", "grouping_column_tys", ")", ":", "weld_obj", "=", "WeldObject", "(", "encoder_", ",", "decoder_", ")", "group_var", "=", "weld_obj", ".", "update", "(", "expr", ")", "num_group_cols", "=", "len", "...
8ddd6db6b28878bef0892da44b1d2002b564389c
train
grouped_slice
Groups the given columns by the corresponding grouping column value, and aggregate by summing values. Args: columns (List<WeldObject>): List of columns as WeldObjects column_tys (List<str>): List of each column data ty grouping_column (WeldObject): Column to group rest of columns by ...
python/grizzly/grizzly/grizzly_impl.py
def grouped_slice(expr, type, start, size): """ Groups the given columns by the corresponding grouping column value, and aggregate by summing values. Args: columns (List<WeldObject>): List of columns as WeldObjects column_tys (List<str>): List of each column data ty grouping_col...
def grouped_slice(expr, type, start, size): """ Groups the given columns by the corresponding grouping column value, and aggregate by summing values. Args: columns (List<WeldObject>): List of columns as WeldObjects column_tys (List<str>): List of each column data ty grouping_col...
[ "Groups", "the", "given", "columns", "by", "the", "corresponding", "grouping", "column", "value", "and", "aggregate", "by", "summing", "values", "." ]
weld-project/weld
python
https://github.com/weld-project/weld/blob/8ddd6db6b28878bef0892da44b1d2002b564389c/python/grizzly/grizzly/grizzly_impl.py#L1423-L1449
[ "def", "grouped_slice", "(", "expr", ",", "type", ",", "start", ",", "size", ")", ":", "weld_obj", "=", "WeldObject", "(", "encoder_", ",", "decoder_", ")", "weld_obj", ".", "update", "(", "expr", ")", "weld_template", "=", "\"\"\"\n map(\n %(v...
8ddd6db6b28878bef0892da44b1d2002b564389c
train
get_column
Get column corresponding to passed-in index from ptr returned by groupBySum. Args: columns (List<WeldObject>): List of columns as WeldObjects column_tys (List<str>): List of each column data ty index (int): index of selected column Returns: A WeldObject representing this co...
python/grizzly/grizzly/grizzly_impl.py
def get_column(columns, column_tys, index): """ Get column corresponding to passed-in index from ptr returned by groupBySum. Args: columns (List<WeldObject>): List of columns as WeldObjects column_tys (List<str>): List of each column data ty index (int): index of selected column...
def get_column(columns, column_tys, index): """ Get column corresponding to passed-in index from ptr returned by groupBySum. Args: columns (List<WeldObject>): List of columns as WeldObjects column_tys (List<str>): List of each column data ty index (int): index of selected column...
[ "Get", "column", "corresponding", "to", "passed", "-", "in", "index", "from", "ptr", "returned", "by", "groupBySum", "." ]
weld-project/weld
python
https://github.com/weld-project/weld/blob/8ddd6db6b28878bef0892da44b1d2002b564389c/python/grizzly/grizzly/grizzly_impl.py#L1452-L1481
[ "def", "get_column", "(", "columns", ",", "column_tys", ",", "index", ")", ":", "weld_obj", "=", "WeldObject", "(", "encoder_", ",", "decoder_", ")", "columns_var", "=", "weld_obj", ".", "update", "(", "columns", ",", "tys", "=", "WeldVec", "(", "column_ty...
8ddd6db6b28878bef0892da44b1d2002b564389c
train
dot
Computes the dot product between a matrix and a vector. TODO: Make this more generic Args: matrix (TYPE): Description vector (TYPE): Description
python/grizzly/grizzly/numpy_weld.py
def dot(matrix, vector): """ Computes the dot product between a matrix and a vector. TODO: Make this more generic Args: matrix (TYPE): Description vector (TYPE): Description """ matrix_weld_type = None vector_weld_type = None if isinstance(matrix, LazyOpResult): ...
def dot(matrix, vector): """ Computes the dot product between a matrix and a vector. TODO: Make this more generic Args: matrix (TYPE): Description vector (TYPE): Description """ matrix_weld_type = None vector_weld_type = None if isinstance(matrix, LazyOpResult): ...
[ "Computes", "the", "dot", "product", "between", "a", "matrix", "and", "a", "vector", ".", "TODO", ":", "Make", "this", "more", "generic" ]
weld-project/weld
python
https://github.com/weld-project/weld/blob/8ddd6db6b28878bef0892da44b1d2002b564389c/python/grizzly/grizzly/numpy_weld.py#L67-L99
[ "def", "dot", "(", "matrix", ",", "vector", ")", ":", "matrix_weld_type", "=", "None", "vector_weld_type", "=", "None", "if", "isinstance", "(", "matrix", ",", "LazyOpResult", ")", ":", "matrix_weld_type", "=", "matrix", ".", "weld_type", "matrix", "=", "mat...
8ddd6db6b28878bef0892da44b1d2002b564389c
train
exp
Computes a per-element exponent of the passed-in vector. Args: vector (TYPE): Description
python/grizzly/grizzly/numpy_weld.py
def exp(vector): """ Computes a per-element exponent of the passed-in vector. Args: vector (TYPE): Description """ weld_type = None if isinstance(vector, LazyOpResult): weld_type = vector.weld_type vector = vector.expr elif isinstance(vector, np.ndarray): wel...
def exp(vector): """ Computes a per-element exponent of the passed-in vector. Args: vector (TYPE): Description """ weld_type = None if isinstance(vector, LazyOpResult): weld_type = vector.weld_type vector = vector.expr elif isinstance(vector, np.ndarray): wel...
[ "Computes", "a", "per", "-", "element", "exponent", "of", "the", "passed", "-", "in", "vector", "." ]
weld-project/weld
python
https://github.com/weld-project/weld/blob/8ddd6db6b28878bef0892da44b1d2002b564389c/python/grizzly/grizzly/numpy_weld.py#L102-L116
[ "def", "exp", "(", "vector", ")", ":", "weld_type", "=", "None", "if", "isinstance", "(", "vector", ",", "LazyOpResult", ")", ":", "weld_type", "=", "vector", ".", "weld_type", "vector", "=", "vector", ".", "expr", "elif", "isinstance", "(", "vector", ",...
8ddd6db6b28878bef0892da44b1d2002b564389c
train
NumpyArrayWeld.sum
Summary Returns: TYPE: Description
python/grizzly/grizzly/numpy_weld.py
def sum(self): """Summary Returns: TYPE: Description """ return NumpyArrayWeld( numpy_weld_impl.aggr( self.expr, "+", 0, self.weld_type ), self.weld_type, 0 ...
def sum(self): """Summary Returns: TYPE: Description """ return NumpyArrayWeld( numpy_weld_impl.aggr( self.expr, "+", 0, self.weld_type ), self.weld_type, 0 ...
[ "Summary" ]
weld-project/weld
python
https://github.com/weld-project/weld/blob/8ddd6db6b28878bef0892da44b1d2002b564389c/python/grizzly/grizzly/numpy_weld.py#L49-L64
[ "def", "sum", "(", "self", ")", ":", "return", "NumpyArrayWeld", "(", "numpy_weld_impl", ".", "aggr", "(", "self", ".", "expr", ",", "\"+\"", ",", "0", ",", "self", ".", "weld_type", ")", ",", "self", ".", "weld_type", ",", "0", ")" ]
8ddd6db6b28878bef0892da44b1d2002b564389c
train
array
Wrapper around weldarray - first create np.array and then convert to weldarray.
python/numpy/weldnumpy/__init__.py
def array(arr, *args, **kwargs): ''' Wrapper around weldarray - first create np.array and then convert to weldarray. ''' return weldarray(np.array(arr, *args, **kwargs))
def array(arr, *args, **kwargs): ''' Wrapper around weldarray - first create np.array and then convert to weldarray. ''' return weldarray(np.array(arr, *args, **kwargs))
[ "Wrapper", "around", "weldarray", "-", "first", "create", "np", ".", "array", "and", "then", "convert", "to", "weldarray", "." ]
weld-project/weld
python
https://github.com/weld-project/weld/blob/8ddd6db6b28878bef0892da44b1d2002b564389c/python/numpy/weldnumpy/__init__.py#L13-L18
[ "def", "array", "(", "arr", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "weldarray", "(", "np", ".", "array", "(", "arr", ",", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
8ddd6db6b28878bef0892da44b1d2002b564389c
train
NumPyEncoder.py_to_weld_type
Summary Args: obj (TYPE): Description Returns: TYPE: Description Raises: Exception: Description
python/grizzly/grizzly/encoders.py
def py_to_weld_type(self, obj): """Summary Args: obj (TYPE): Description Returns: TYPE: Description Raises: Exception: Description """ if isinstance(obj, np.ndarray): dtype = str(obj.dtype) if dtype == 'int16'...
def py_to_weld_type(self, obj): """Summary Args: obj (TYPE): Description Returns: TYPE: Description Raises: Exception: Description """ if isinstance(obj, np.ndarray): dtype = str(obj.dtype) if dtype == 'int16'...
[ "Summary" ]
weld-project/weld
python
https://github.com/weld-project/weld/blob/8ddd6db6b28878bef0892da44b1d2002b564389c/python/grizzly/grizzly/encoders.py#L54-L88
[ "def", "py_to_weld_type", "(", "self", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "np", ".", "ndarray", ")", ":", "dtype", "=", "str", "(", "obj", ".", "dtype", ")", "if", "dtype", "==", "'int16'", ":", "base", "=", "WeldInt16", "("...
8ddd6db6b28878bef0892da44b1d2002b564389c
train
NumPyEncoder.encode
Converts Python object to Weld object. Args: obj: Python object that needs to be converted to Weld format Returns: Weld formatted object
python/grizzly/grizzly/encoders.py
def encode(self, obj): """Converts Python object to Weld object. Args: obj: Python object that needs to be converted to Weld format Returns: Weld formatted object """ if isinstance(obj, np.ndarray): if obj.ndim == 1 and obj.dtype == 'int16': ...
def encode(self, obj): """Converts Python object to Weld object. Args: obj: Python object that needs to be converted to Weld format Returns: Weld formatted object """ if isinstance(obj, np.ndarray): if obj.ndim == 1 and obj.dtype == 'int16': ...
[ "Converts", "Python", "object", "to", "Weld", "object", "." ]
weld-project/weld
python
https://github.com/weld-project/weld/blob/8ddd6db6b28878bef0892da44b1d2002b564389c/python/grizzly/grizzly/encoders.py#L90-L134
[ "def", "encode", "(", "self", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "np", ".", "ndarray", ")", ":", "if", "obj", ".", "ndim", "==", "1", "and", "obj", ".", "dtype", "==", "'int16'", ":", "numpy_to_weld", "=", "self", ".", "ut...
8ddd6db6b28878bef0892da44b1d2002b564389c
train
NumPyDecoder.decode
Converts Weld object to Python object. Args: obj: Result of Weld computation that needs to be decoded restype: Type of Weld computation result raw_ptr: Boolean indicating whether obj needs to be extracted from WeldValue or not Returns: ...
python/grizzly/grizzly/encoders.py
def decode(self, obj, restype, raw_ptr=False): """Converts Weld object to Python object. Args: obj: Result of Weld computation that needs to be decoded restype: Type of Weld computation result raw_ptr: Boolean indicating whether obj needs to be extracted ...
def decode(self, obj, restype, raw_ptr=False): """Converts Weld object to Python object. Args: obj: Result of Weld computation that needs to be decoded restype: Type of Weld computation result raw_ptr: Boolean indicating whether obj needs to be extracted ...
[ "Converts", "Weld", "object", "to", "Python", "object", "." ]
weld-project/weld
python
https://github.com/weld-project/weld/blob/8ddd6db6b28878bef0892da44b1d2002b564389c/python/grizzly/grizzly/encoders.py#L151-L238
[ "def", "decode", "(", "self", ",", "obj", ",", "restype", ",", "raw_ptr", "=", "False", ")", ":", "if", "raw_ptr", ":", "data", "=", "obj", "else", ":", "data", "=", "cweld", ".", "WeldValue", "(", "obj", ")", ".", "data", "(", ")", "result", "="...
8ddd6db6b28878bef0892da44b1d2002b564389c
train
cleanup
Tries to remove temp files by filename wildcard path.
src/pytesseract.py
def cleanup(temp_name): ''' Tries to remove temp files by filename wildcard path. ''' for filename in iglob(temp_name + '*' if temp_name else temp_name): try: os.remove(filename) except OSError: pass
def cleanup(temp_name): ''' Tries to remove temp files by filename wildcard path. ''' for filename in iglob(temp_name + '*' if temp_name else temp_name): try: os.remove(filename) except OSError: pass
[ "Tries", "to", "remove", "temp", "files", "by", "filename", "wildcard", "path", "." ]
madmaze/pytesseract
python
https://github.com/madmaze/pytesseract/blob/dd7dffc227480e9de024e99a5e10e7664f42b2de/src/pytesseract.py#L97-L103
[ "def", "cleanup", "(", "temp_name", ")", ":", "for", "filename", "in", "iglob", "(", "temp_name", "+", "'*'", "if", "temp_name", "else", "temp_name", ")", ":", "try", ":", "os", ".", "remove", "(", "filename", ")", "except", "OSError", ":", "pass" ]
dd7dffc227480e9de024e99a5e10e7664f42b2de
train
get_tesseract_version
Returns LooseVersion object of the Tesseract version
src/pytesseract.py
def get_tesseract_version(): ''' Returns LooseVersion object of the Tesseract version ''' try: return LooseVersion( subprocess.check_output( [tesseract_cmd, '--version'], stderr=subprocess.STDOUT ).decode('utf-8').split()[1].lstrip(string.printable[10:]) ...
def get_tesseract_version(): ''' Returns LooseVersion object of the Tesseract version ''' try: return LooseVersion( subprocess.check_output( [tesseract_cmd, '--version'], stderr=subprocess.STDOUT ).decode('utf-8').split()[1].lstrip(string.printable[10:]) ...
[ "Returns", "LooseVersion", "object", "of", "the", "Tesseract", "version" ]
madmaze/pytesseract
python
https://github.com/madmaze/pytesseract/blob/dd7dffc227480e9de024e99a5e10e7664f42b2de/src/pytesseract.py#L281-L292
[ "def", "get_tesseract_version", "(", ")", ":", "try", ":", "return", "LooseVersion", "(", "subprocess", ".", "check_output", "(", "[", "tesseract_cmd", ",", "'--version'", "]", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", ".", "decode", "(", "'utf-8...
dd7dffc227480e9de024e99a5e10e7664f42b2de
train
image_to_string
Returns the result of a Tesseract OCR run on the provided image to string
src/pytesseract.py
def image_to_string(image, lang=None, config='', nice=0, output_type=Output.STRING): ''' Returns the result of a Tesseract OCR run on the provided image to string ''' args = [image, 'txt', lang, config, nice] return { ...
def image_to_string(image, lang=None, config='', nice=0, output_type=Output.STRING): ''' Returns the result of a Tesseract OCR run on the provided image to string ''' args = [image, 'txt', lang, config, nice] return { ...
[ "Returns", "the", "result", "of", "a", "Tesseract", "OCR", "run", "on", "the", "provided", "image", "to", "string" ]
madmaze/pytesseract
python
https://github.com/madmaze/pytesseract/blob/dd7dffc227480e9de024e99a5e10e7664f42b2de/src/pytesseract.py#L295-L309
[ "def", "image_to_string", "(", "image", ",", "lang", "=", "None", ",", "config", "=", "''", ",", "nice", "=", "0", ",", "output_type", "=", "Output", ".", "STRING", ")", ":", "args", "=", "[", "image", ",", "'txt'", ",", "lang", ",", "config", ",",...
dd7dffc227480e9de024e99a5e10e7664f42b2de
train
image_to_pdf_or_hocr
Returns the result of a Tesseract OCR run on the provided image to pdf/hocr
src/pytesseract.py
def image_to_pdf_or_hocr(image, lang=None, config='', nice=0, extension='pdf'): ''' Returns the result of a Tesseract OCR run on the provided image to pdf/hocr ''' if extension not in {'pdf', 'hocr'}: raise ValueErr...
def image_to_pdf_or_hocr(image, lang=None, config='', nice=0, extension='pdf'): ''' Returns the result of a Tesseract OCR run on the provided image to pdf/hocr ''' if extension not in {'pdf', 'hocr'}: raise ValueErr...
[ "Returns", "the", "result", "of", "a", "Tesseract", "OCR", "run", "on", "the", "provided", "image", "to", "pdf", "/", "hocr" ]
madmaze/pytesseract
python
https://github.com/madmaze/pytesseract/blob/dd7dffc227480e9de024e99a5e10e7664f42b2de/src/pytesseract.py#L312-L325
[ "def", "image_to_pdf_or_hocr", "(", "image", ",", "lang", "=", "None", ",", "config", "=", "''", ",", "nice", "=", "0", ",", "extension", "=", "'pdf'", ")", ":", "if", "extension", "not", "in", "{", "'pdf'", ",", "'hocr'", "}", ":", "raise", "ValueEr...
dd7dffc227480e9de024e99a5e10e7664f42b2de
train
image_to_data
Returns string containing box boundaries, confidences, and other information. Requires Tesseract 3.05+
src/pytesseract.py
def image_to_data(image, lang=None, config='', nice=0, output_type=Output.STRING): ''' Returns string containing box boundaries, confidences, and other information. Requires Tesseract 3.05+ ''' if get_tesseract_version() < '3.0...
def image_to_data(image, lang=None, config='', nice=0, output_type=Output.STRING): ''' Returns string containing box boundaries, confidences, and other information. Requires Tesseract 3.05+ ''' if get_tesseract_version() < '3.0...
[ "Returns", "string", "containing", "box", "boundaries", "confidences", "and", "other", "information", ".", "Requires", "Tesseract", "3", ".", "05", "+" ]
madmaze/pytesseract
python
https://github.com/madmaze/pytesseract/blob/dd7dffc227480e9de024e99a5e10e7664f42b2de/src/pytesseract.py#L360-L381
[ "def", "image_to_data", "(", "image", ",", "lang", "=", "None", ",", "config", "=", "''", ",", "nice", "=", "0", ",", "output_type", "=", "Output", ".", "STRING", ")", ":", "if", "get_tesseract_version", "(", ")", "<", "'3.05'", ":", "raise", "TSVNotSu...
dd7dffc227480e9de024e99a5e10e7664f42b2de
train
image_to_osd
Returns string containing the orientation and script detection (OSD)
src/pytesseract.py
def image_to_osd(image, lang='osd', config='', nice=0, output_type=Output.STRING): ''' Returns string containing the orientation and script detection (OSD) ''' config = '{}-psm 0 {}'.format( '' if get_tesseract_version() < '3.05...
def image_to_osd(image, lang='osd', config='', nice=0, output_type=Output.STRING): ''' Returns string containing the orientation and script detection (OSD) ''' config = '{}-psm 0 {}'.format( '' if get_tesseract_version() < '3.05...
[ "Returns", "string", "containing", "the", "orientation", "and", "script", "detection", "(", "OSD", ")" ]
madmaze/pytesseract
python
https://github.com/madmaze/pytesseract/blob/dd7dffc227480e9de024e99a5e10e7664f42b2de/src/pytesseract.py#L384-L402
[ "def", "image_to_osd", "(", "image", ",", "lang", "=", "'osd'", ",", "config", "=", "''", ",", "nice", "=", "0", ",", "output_type", "=", "Output", ".", "STRING", ")", ":", "config", "=", "'{}-psm 0 {}'", ".", "format", "(", "''", "if", "get_tesseract_...
dd7dffc227480e9de024e99a5e10e7664f42b2de
train
parse_uri
This function parses and validates a WebSocket URI. If the URI is valid, it returns a :class:`WebSocketURI`. Otherwise it raises an :exc:`~websockets.exceptions.InvalidURI` exception.
src/websockets/uri.py
def parse_uri(uri: str) -> WebSocketURI: """ This function parses and validates a WebSocket URI. If the URI is valid, it returns a :class:`WebSocketURI`. Otherwise it raises an :exc:`~websockets.exceptions.InvalidURI` exception. """ parsed = urllib.parse.urlparse(uri) try: assert ...
def parse_uri(uri: str) -> WebSocketURI: """ This function parses and validates a WebSocket URI. If the URI is valid, it returns a :class:`WebSocketURI`. Otherwise it raises an :exc:`~websockets.exceptions.InvalidURI` exception. """ parsed = urllib.parse.urlparse(uri) try: assert ...
[ "This", "function", "parses", "and", "validates", "a", "WebSocket", "URI", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/uri.py#L46-L73
[ "def", "parse_uri", "(", "uri", ":", "str", ")", "->", "WebSocketURI", ":", "parsed", "=", "urllib", ".", "parse", ".", "urlparse", "(", "uri", ")", "try", ":", "assert", "parsed", ".", "scheme", "in", "[", "\"ws\"", ",", "\"wss\"", "]", "assert", "p...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
prepare_data
Convert a string or byte-like object to an opcode and a bytes-like object. This function is designed for data frames. If ``data`` is a :class:`str`, return ``OP_TEXT`` and a :class:`bytes` object encoding ``data`` in UTF-8. If ``data`` is a bytes-like object, return ``OP_BINARY`` and a bytes-like ...
src/websockets/framing.py
def prepare_data(data: Data) -> Tuple[int, bytes]: """ Convert a string or byte-like object to an opcode and a bytes-like object. This function is designed for data frames. If ``data`` is a :class:`str`, return ``OP_TEXT`` and a :class:`bytes` object encoding ``data`` in UTF-8. If ``data`` is...
def prepare_data(data: Data) -> Tuple[int, bytes]: """ Convert a string or byte-like object to an opcode and a bytes-like object. This function is designed for data frames. If ``data`` is a :class:`str`, return ``OP_TEXT`` and a :class:`bytes` object encoding ``data`` in UTF-8. If ``data`` is...
[ "Convert", "a", "string", "or", "byte", "-", "like", "object", "to", "an", "opcode", "and", "a", "bytes", "-", "like", "object", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/framing.py#L268-L293
[ "def", "prepare_data", "(", "data", ":", "Data", ")", "->", "Tuple", "[", "int", ",", "bytes", "]", ":", "if", "isinstance", "(", "data", ",", "str", ")", ":", "return", "OP_TEXT", ",", "data", ".", "encode", "(", "\"utf-8\"", ")", "elif", "isinstanc...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
encode_data
Convert a string or byte-like object to bytes. This function is designed for ping and pon g frames. If ``data`` is a :class:`str`, return a :class:`bytes` object encoding ``data`` in UTF-8. If ``data`` is a bytes-like object, return a :class:`bytes` object. Raise :exc:`TypeError` for other input...
src/websockets/framing.py
def encode_data(data: Data) -> bytes: """ Convert a string or byte-like object to bytes. This function is designed for ping and pon g frames. If ``data`` is a :class:`str`, return a :class:`bytes` object encoding ``data`` in UTF-8. If ``data`` is a bytes-like object, return a :class:`bytes` o...
def encode_data(data: Data) -> bytes: """ Convert a string or byte-like object to bytes. This function is designed for ping and pon g frames. If ``data`` is a :class:`str`, return a :class:`bytes` object encoding ``data`` in UTF-8. If ``data`` is a bytes-like object, return a :class:`bytes` o...
[ "Convert", "a", "string", "or", "byte", "-", "like", "object", "to", "bytes", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/framing.py#L296-L317
[ "def", "encode_data", "(", "data", ":", "Data", ")", "->", "bytes", ":", "if", "isinstance", "(", "data", ",", "str", ")", ":", "return", "data", ".", "encode", "(", "\"utf-8\"", ")", "elif", "isinstance", "(", "data", ",", "(", "bytes", ",", "bytear...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
parse_close
Parse the data in a close frame. Return ``(code, reason)`` when ``code`` is an :class:`int` and ``reason`` a :class:`str`. Raise :exc:`~websockets.exceptions.WebSocketProtocolError` or :exc:`UnicodeDecodeError` if the data is invalid.
src/websockets/framing.py
def parse_close(data: bytes) -> Tuple[int, str]: """ Parse the data in a close frame. Return ``(code, reason)`` when ``code`` is an :class:`int` and ``reason`` a :class:`str`. Raise :exc:`~websockets.exceptions.WebSocketProtocolError` or :exc:`UnicodeDecodeError` if the data is invalid. "...
def parse_close(data: bytes) -> Tuple[int, str]: """ Parse the data in a close frame. Return ``(code, reason)`` when ``code`` is an :class:`int` and ``reason`` a :class:`str`. Raise :exc:`~websockets.exceptions.WebSocketProtocolError` or :exc:`UnicodeDecodeError` if the data is invalid. "...
[ "Parse", "the", "data", "in", "a", "close", "frame", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/framing.py#L320-L341
[ "def", "parse_close", "(", "data", ":", "bytes", ")", "->", "Tuple", "[", "int", ",", "str", "]", ":", "length", "=", "len", "(", "data", ")", "if", "length", ">=", "2", ":", "code", ",", "=", "struct", ".", "unpack", "(", "\"!H\"", ",", "data", ...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
serialize_close
Serialize the data for a close frame. This is the reverse of :func:`parse_close`.
src/websockets/framing.py
def serialize_close(code: int, reason: str) -> bytes: """ Serialize the data for a close frame. This is the reverse of :func:`parse_close`. """ check_close(code) return struct.pack("!H", code) + reason.encode("utf-8")
def serialize_close(code: int, reason: str) -> bytes: """ Serialize the data for a close frame. This is the reverse of :func:`parse_close`. """ check_close(code) return struct.pack("!H", code) + reason.encode("utf-8")
[ "Serialize", "the", "data", "for", "a", "close", "frame", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/framing.py#L344-L352
[ "def", "serialize_close", "(", "code", ":", "int", ",", "reason", ":", "str", ")", "->", "bytes", ":", "check_close", "(", "code", ")", "return", "struct", ".", "pack", "(", "\"!H\"", ",", "code", ")", "+", "reason", ".", "encode", "(", "\"utf-8\"", ...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
Frame.read
Read a WebSocket frame and return a :class:`Frame` object. ``reader`` is a coroutine taking an integer argument and reading exactly this number of bytes, unless the end of file is reached. ``mask`` is a :class:`bool` telling whether the frame should be masked i.e. whether the read happ...
src/websockets/framing.py
async def read( cls, reader: Callable[[int], Awaitable[bytes]], *, mask: bool, max_size: Optional[int] = None, extensions: Optional[Sequence["websockets.extensions.base.Extension"]] = None, ) -> "Frame": """ Read a WebSocket frame and return a :class:`...
async def read( cls, reader: Callable[[int], Awaitable[bytes]], *, mask: bool, max_size: Optional[int] = None, extensions: Optional[Sequence["websockets.extensions.base.Extension"]] = None, ) -> "Frame": """ Read a WebSocket frame and return a :class:`...
[ "Read", "a", "WebSocket", "frame", "and", "return", "a", ":", "class", ":", "Frame", "object", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/framing.py#L95-L166
[ "async", "def", "read", "(", "cls", ",", "reader", ":", "Callable", "[", "[", "int", "]", ",", "Awaitable", "[", "bytes", "]", "]", ",", "*", ",", "mask", ":", "bool", ",", "max_size", ":", "Optional", "[", "int", "]", "=", "None", ",", "extensio...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
Frame.write
Write a WebSocket frame. ``frame`` is the :class:`Frame` object to write. ``writer`` is a function accepting bytes. ``mask`` is a :class:`bool` telling whether the frame should be masked i.e. whether the write happens on the client side. If ``extensions`` is provided, it's a ...
src/websockets/framing.py
def write( frame, writer: Callable[[bytes], Any], *, mask: bool, extensions: Optional[Sequence["websockets.extensions.base.Extension"]] = None, ) -> None: """ Write a WebSocket frame. ``frame`` is the :class:`Frame` object to write. ``writer`...
def write( frame, writer: Callable[[bytes], Any], *, mask: bool, extensions: Optional[Sequence["websockets.extensions.base.Extension"]] = None, ) -> None: """ Write a WebSocket frame. ``frame`` is the :class:`Frame` object to write. ``writer`...
[ "Write", "a", "WebSocket", "frame", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/framing.py#L168-L241
[ "def", "write", "(", "frame", ",", "writer", ":", "Callable", "[", "[", "bytes", "]", ",", "Any", "]", ",", "*", ",", "mask", ":", "bool", ",", "extensions", ":", "Optional", "[", "Sequence", "[", "\"websockets.extensions.base.Extension\"", "]", "]", "="...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
Frame.check
Check that this frame contains acceptable values. Raise :exc:`~websockets.exceptions.WebSocketProtocolError` if this frame contains incorrect values.
src/websockets/framing.py
def check(frame) -> None: """ Check that this frame contains acceptable values. Raise :exc:`~websockets.exceptions.WebSocketProtocolError` if this frame contains incorrect values. """ # The first parameter is called `frame` rather than `self`, # but it's the ins...
def check(frame) -> None: """ Check that this frame contains acceptable values. Raise :exc:`~websockets.exceptions.WebSocketProtocolError` if this frame contains incorrect values. """ # The first parameter is called `frame` rather than `self`, # but it's the ins...
[ "Check", "that", "this", "frame", "contains", "acceptable", "values", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/framing.py#L243-L265
[ "def", "check", "(", "frame", ")", "->", "None", ":", "# The first parameter is called `frame` rather than `self`,", "# but it's the instance of class to which this method is bound.", "if", "frame", ".", "rsv1", "or", "frame", ".", "rsv2", "or", "frame", ".", "rsv3", ":",...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
read_request
Read an HTTP/1.1 GET request from ``stream``. ``stream`` is an :class:`~asyncio.StreamReader`. Return ``(path, headers)`` where ``path`` is a :class:`str` and ``headers`` is a :class:`Headers` instance. ``path`` isn't URL-decoded or validated in any way. Non-ASCII characters are represented with...
src/websockets/http.py
async def read_request(stream: asyncio.StreamReader) -> Tuple[str, "Headers"]: """ Read an HTTP/1.1 GET request from ``stream``. ``stream`` is an :class:`~asyncio.StreamReader`. Return ``(path, headers)`` where ``path`` is a :class:`str` and ``headers`` is a :class:`Headers` instance. ``path`...
async def read_request(stream: asyncio.StreamReader) -> Tuple[str, "Headers"]: """ Read an HTTP/1.1 GET request from ``stream``. ``stream`` is an :class:`~asyncio.StreamReader`. Return ``(path, headers)`` where ``path`` is a :class:`str` and ``headers`` is a :class:`Headers` instance. ``path`...
[ "Read", "an", "HTTP", "/", "1", ".", "1", "GET", "request", "from", "stream", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/http.py#L62-L101
[ "async", "def", "read_request", "(", "stream", ":", "asyncio", ".", "StreamReader", ")", "->", "Tuple", "[", "str", ",", "\"Headers\"", "]", ":", "# https://tools.ietf.org/html/rfc7230#section-3.1.1", "# Parsing is simple because fixed values are expected for method and", "# ...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
read_response
Read an HTTP/1.1 response from ``stream``. ``stream`` is an :class:`~asyncio.StreamReader`. Return ``(status_code, reason, headers)`` where ``status_code`` is an :class:`int`, ``reason`` is a :class:`str`, and ``headers`` is a :class:`Headers` instance. Non-ASCII characters are represented with s...
src/websockets/http.py
async def read_response(stream: asyncio.StreamReader) -> Tuple[int, str, "Headers"]: """ Read an HTTP/1.1 response from ``stream``. ``stream`` is an :class:`~asyncio.StreamReader`. Return ``(status_code, reason, headers)`` where ``status_code`` is an :class:`int`, ``reason`` is a :class:`str`, and...
async def read_response(stream: asyncio.StreamReader) -> Tuple[int, str, "Headers"]: """ Read an HTTP/1.1 response from ``stream``. ``stream`` is an :class:`~asyncio.StreamReader`. Return ``(status_code, reason, headers)`` where ``status_code`` is an :class:`int`, ``reason`` is a :class:`str`, and...
[ "Read", "an", "HTTP", "/", "1", ".", "1", "response", "from", "stream", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/http.py#L104-L145
[ "async", "def", "read_response", "(", "stream", ":", "asyncio", ".", "StreamReader", ")", "->", "Tuple", "[", "int", ",", "str", ",", "\"Headers\"", "]", ":", "# https://tools.ietf.org/html/rfc7230#section-3.1.2", "# As in read_request, parsing is simple because a fixed val...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
read_headers
Read HTTP headers from ``stream``. ``stream`` is an :class:`~asyncio.StreamReader`. Return a :class:`Headers` instance Non-ASCII characters are represented with surrogate escapes.
src/websockets/http.py
async def read_headers(stream: asyncio.StreamReader) -> "Headers": """ Read HTTP headers from ``stream``. ``stream`` is an :class:`~asyncio.StreamReader`. Return a :class:`Headers` instance Non-ASCII characters are represented with surrogate escapes. """ # https://tools.ietf.org/html/rfc...
async def read_headers(stream: asyncio.StreamReader) -> "Headers": """ Read HTTP headers from ``stream``. ``stream`` is an :class:`~asyncio.StreamReader`. Return a :class:`Headers` instance Non-ASCII characters are represented with surrogate escapes. """ # https://tools.ietf.org/html/rfc...
[ "Read", "HTTP", "headers", "from", "stream", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/http.py#L148-L184
[ "async", "def", "read_headers", "(", "stream", ":", "asyncio", ".", "StreamReader", ")", "->", "\"Headers\"", ":", "# https://tools.ietf.org/html/rfc7230#section-3.2", "# We don't attempt to support obsolete line folding.", "headers", "=", "Headers", "(", ")", "for", "_", ...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
read_line
Read a single line from ``stream``. ``stream`` is an :class:`~asyncio.StreamReader`. Return :class:`bytes` without CRLF.
src/websockets/http.py
async def read_line(stream: asyncio.StreamReader) -> bytes: """ Read a single line from ``stream``. ``stream`` is an :class:`~asyncio.StreamReader`. Return :class:`bytes` without CRLF. """ # Security: this is bounded by the StreamReader's limit (default = 32 KiB). line = await stream.read...
async def read_line(stream: asyncio.StreamReader) -> bytes: """ Read a single line from ``stream``. ``stream`` is an :class:`~asyncio.StreamReader`. Return :class:`bytes` without CRLF. """ # Security: this is bounded by the StreamReader's limit (default = 32 KiB). line = await stream.read...
[ "Read", "a", "single", "line", "from", "stream", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/http.py#L187-L204
[ "async", "def", "read_line", "(", "stream", ":", "asyncio", ".", "StreamReader", ")", "->", "bytes", ":", "# Security: this is bounded by the StreamReader's limit (default = 32 KiB).", "line", "=", "await", "stream", ".", "readline", "(", ")", "# Security: this guarantees...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
Headers.get_all
Return the (possibly empty) list of all values for a header.
src/websockets/http.py
def get_all(self, key: str) -> List[str]: """ Return the (possibly empty) list of all values for a header. """ return self._dict.get(key.lower(), [])
def get_all(self, key: str) -> List[str]: """ Return the (possibly empty) list of all values for a header. """ return self._dict.get(key.lower(), [])
[ "Return", "the", "(", "possibly", "empty", ")", "list", "of", "all", "values", "for", "a", "header", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/http.py#L322-L327
[ "def", "get_all", "(", "self", ",", "key", ":", "str", ")", "->", "List", "[", "str", "]", ":", "return", "self", ".", "_dict", ".", "get", "(", "key", ".", "lower", "(", ")", ",", "[", "]", ")" ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
peek_ahead
Return the next character from ``header`` at the given position. Return ``None`` at the end of ``header``. We never need to peek more than one character ahead.
src/websockets/headers.py
def peek_ahead(header: str, pos: int) -> Optional[str]: """ Return the next character from ``header`` at the given position. Return ``None`` at the end of ``header``. We never need to peek more than one character ahead. """ return None if pos == len(header) else header[pos]
def peek_ahead(header: str, pos: int) -> Optional[str]: """ Return the next character from ``header`` at the given position. Return ``None`` at the end of ``header``. We never need to peek more than one character ahead. """ return None if pos == len(header) else header[pos]
[ "Return", "the", "next", "character", "from", "header", "at", "the", "given", "position", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/headers.py#L39-L48
[ "def", "peek_ahead", "(", "header", ":", "str", ",", "pos", ":", "int", ")", "->", "Optional", "[", "str", "]", ":", "return", "None", "if", "pos", "==", "len", "(", "header", ")", "else", "header", "[", "pos", "]" ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
parse_OWS
Parse optional whitespace from ``header`` at the given position. Return the new position. The whitespace itself isn't returned because it isn't significant.
src/websockets/headers.py
def parse_OWS(header: str, pos: int) -> int: """ Parse optional whitespace from ``header`` at the given position. Return the new position. The whitespace itself isn't returned because it isn't significant. """ # There's always a match, possibly empty, whose content doesn't matter. match =...
def parse_OWS(header: str, pos: int) -> int: """ Parse optional whitespace from ``header`` at the given position. Return the new position. The whitespace itself isn't returned because it isn't significant. """ # There's always a match, possibly empty, whose content doesn't matter. match =...
[ "Parse", "optional", "whitespace", "from", "header", "at", "the", "given", "position", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/headers.py#L54-L66
[ "def", "parse_OWS", "(", "header", ":", "str", ",", "pos", ":", "int", ")", "->", "int", ":", "# There's always a match, possibly empty, whose content doesn't matter.", "match", "=", "_OWS_re", ".", "match", "(", "header", ",", "pos", ")", "assert", "match", "is...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
parse_token
Parse a token from ``header`` at the given position. Return the token value and the new position. Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs.
src/websockets/headers.py
def parse_token(header: str, pos: int, header_name: str) -> Tuple[str, int]: """ Parse a token from ``header`` at the given position. Return the token value and the new position. Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs. """ match = _token_re.match(header, pos...
def parse_token(header: str, pos: int, header_name: str) -> Tuple[str, int]: """ Parse a token from ``header`` at the given position. Return the token value and the new position. Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs. """ match = _token_re.match(header, pos...
[ "Parse", "a", "token", "from", "header", "at", "the", "given", "position", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/headers.py#L72-L84
[ "def", "parse_token", "(", "header", ":", "str", ",", "pos", ":", "int", ",", "header_name", ":", "str", ")", "->", "Tuple", "[", "str", ",", "int", "]", ":", "match", "=", "_token_re", ".", "match", "(", "header", ",", "pos", ")", "if", "match", ...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
parse_quoted_string
Parse a quoted string from ``header`` at the given position. Return the unquoted value and the new position. Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs.
src/websockets/headers.py
def parse_quoted_string(header: str, pos: int, header_name: str) -> Tuple[str, int]: """ Parse a quoted string from ``header`` at the given position. Return the unquoted value and the new position. Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs. """ match = _quoted_...
def parse_quoted_string(header: str, pos: int, header_name: str) -> Tuple[str, int]: """ Parse a quoted string from ``header`` at the given position. Return the unquoted value and the new position. Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs. """ match = _quoted_...
[ "Parse", "a", "quoted", "string", "from", "header", "at", "the", "given", "position", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/headers.py#L95-L107
[ "def", "parse_quoted_string", "(", "header", ":", "str", ",", "pos", ":", "int", ",", "header_name", ":", "str", ")", "->", "Tuple", "[", "str", ",", "int", "]", ":", "match", "=", "_quoted_string_re", ".", "match", "(", "header", ",", "pos", ")", "i...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
parse_list
Parse a comma-separated list from ``header`` at the given position. This is appropriate for parsing values with the following grammar: 1#item ``parse_item`` parses one item. ``header`` is assumed not to start or end with whitespace. (This function is designed for parsing an entire header va...
src/websockets/headers.py
def parse_list( parse_item: Callable[[str, int, str], Tuple[T, int]], header: str, pos: int, header_name: str, ) -> List[T]: """ Parse a comma-separated list from ``header`` at the given position. This is appropriate for parsing values with the following grammar: 1#item ``pars...
def parse_list( parse_item: Callable[[str, int, str], Tuple[T, int]], header: str, pos: int, header_name: str, ) -> List[T]: """ Parse a comma-separated list from ``header`` at the given position. This is appropriate for parsing values with the following grammar: 1#item ``pars...
[ "Parse", "a", "comma", "-", "separated", "list", "from", "header", "at", "the", "given", "position", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/headers.py#L110-L172
[ "def", "parse_list", "(", "parse_item", ":", "Callable", "[", "[", "str", ",", "int", ",", "str", "]", ",", "Tuple", "[", "T", ",", "int", "]", "]", ",", "header", ":", "str", ",", "pos", ":", "int", ",", "header_name", ":", "str", ",", ")", "-...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
parse_connection_option
Parse a Connection option from ``header`` at the given position. Return the protocol value and the new position. Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs.
src/websockets/headers.py
def parse_connection_option( header: str, pos: int, header_name: str ) -> Tuple[ConnectionOption, int]: """ Parse a Connection option from ``header`` at the given position. Return the protocol value and the new position. Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs. ...
def parse_connection_option( header: str, pos: int, header_name: str ) -> Tuple[ConnectionOption, int]: """ Parse a Connection option from ``header`` at the given position. Return the protocol value and the new position. Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs. ...
[ "Parse", "a", "Connection", "option", "from", "header", "at", "the", "given", "position", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/headers.py#L175-L187
[ "def", "parse_connection_option", "(", "header", ":", "str", ",", "pos", ":", "int", ",", "header_name", ":", "str", ")", "->", "Tuple", "[", "ConnectionOption", ",", "int", "]", ":", "item", ",", "pos", "=", "parse_token", "(", "header", ",", "pos", "...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
parse_upgrade_protocol
Parse an Upgrade protocol from ``header`` at the given position. Return the protocol value and the new position. Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs.
src/websockets/headers.py
def parse_upgrade_protocol( header: str, pos: int, header_name: str ) -> Tuple[UpgradeProtocol, int]: """ Parse an Upgrade protocol from ``header`` at the given position. Return the protocol value and the new position. Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs. ...
def parse_upgrade_protocol( header: str, pos: int, header_name: str ) -> Tuple[UpgradeProtocol, int]: """ Parse an Upgrade protocol from ``header`` at the given position. Return the protocol value and the new position. Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs. ...
[ "Parse", "an", "Upgrade", "protocol", "from", "header", "at", "the", "given", "position", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/headers.py#L207-L221
[ "def", "parse_upgrade_protocol", "(", "header", ":", "str", ",", "pos", ":", "int", ",", "header_name", ":", "str", ")", "->", "Tuple", "[", "UpgradeProtocol", ",", "int", "]", ":", "match", "=", "_protocol_re", ".", "match", "(", "header", ",", "pos", ...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
parse_extension_item_param
Parse a single extension parameter from ``header`` at the given position. Return a ``(name, value)`` pair and the new position. Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs.
src/websockets/headers.py
def parse_extension_item_param( header: str, pos: int, header_name: str ) -> Tuple[ExtensionParameter, int]: """ Parse a single extension parameter from ``header`` at the given position. Return a ``(name, value)`` pair and the new position. Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` o...
def parse_extension_item_param( header: str, pos: int, header_name: str ) -> Tuple[ExtensionParameter, int]: """ Parse a single extension parameter from ``header`` at the given position. Return a ``(name, value)`` pair and the new position. Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` o...
[ "Parse", "a", "single", "extension", "parameter", "from", "header", "at", "the", "given", "position", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/headers.py#L236-L267
[ "def", "parse_extension_item_param", "(", "header", ":", "str", ",", "pos", ":", "int", ",", "header_name", ":", "str", ")", "->", "Tuple", "[", "ExtensionParameter", ",", "int", "]", ":", "# Extract parameter name.", "name", ",", "pos", "=", "parse_token", ...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
parse_extension_item
Parse an extension definition from ``header`` at the given position. Return an ``(extension name, parameters)`` pair, where ``parameters`` is a list of ``(name, value)`` pairs, and the new position. Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs.
src/websockets/headers.py
def parse_extension_item( header: str, pos: int, header_name: str ) -> Tuple[ExtensionHeader, int]: """ Parse an extension definition from ``header`` at the given position. Return an ``(extension name, parameters)`` pair, where ``parameters`` is a list of ``(name, value)`` pairs, and the new positi...
def parse_extension_item( header: str, pos: int, header_name: str ) -> Tuple[ExtensionHeader, int]: """ Parse an extension definition from ``header`` at the given position. Return an ``(extension name, parameters)`` pair, where ``parameters`` is a list of ``(name, value)`` pairs, and the new positi...
[ "Parse", "an", "extension", "definition", "from", "header", "at", "the", "given", "position", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/headers.py#L270-L291
[ "def", "parse_extension_item", "(", "header", ":", "str", ",", "pos", ":", "int", ",", "header_name", ":", "str", ")", "->", "Tuple", "[", "ExtensionHeader", ",", "int", "]", ":", "# Extract extension name.", "name", ",", "pos", "=", "parse_token", "(", "h...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
build_extension_item
Build an extension definition. This is the reverse of :func:`parse_extension_item`.
src/websockets/headers.py
def build_extension_item(name: str, parameters: List[ExtensionParameter]) -> str: """ Build an extension definition. This is the reverse of :func:`parse_extension_item`. """ return "; ".join( [name] + [ # Quoted strings aren't necessary because values are always tokens....
def build_extension_item(name: str, parameters: List[ExtensionParameter]) -> str: """ Build an extension definition. This is the reverse of :func:`parse_extension_item`. """ return "; ".join( [name] + [ # Quoted strings aren't necessary because values are always tokens....
[ "Build", "an", "extension", "definition", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/headers.py#L322-L336
[ "def", "build_extension_item", "(", "name", ":", "str", ",", "parameters", ":", "List", "[", "ExtensionParameter", "]", ")", "->", "str", ":", "return", "\"; \"", ".", "join", "(", "[", "name", "]", "+", "[", "# Quoted strings aren't necessary because values are...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
build_extension
Unparse a ``Sec-WebSocket-Extensions`` header. This is the reverse of :func:`parse_extension`.
src/websockets/headers.py
def build_extension(extensions: Sequence[ExtensionHeader]) -> str: """ Unparse a ``Sec-WebSocket-Extensions`` header. This is the reverse of :func:`parse_extension`. """ return ", ".join( build_extension_item(name, parameters) for name, parameters in extensions )
def build_extension(extensions: Sequence[ExtensionHeader]) -> str: """ Unparse a ``Sec-WebSocket-Extensions`` header. This is the reverse of :func:`parse_extension`. """ return ", ".join( build_extension_item(name, parameters) for name, parameters in extensions )
[ "Unparse", "a", "Sec", "-", "WebSocket", "-", "Extensions", "header", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/headers.py#L339-L348
[ "def", "build_extension", "(", "extensions", ":", "Sequence", "[", "ExtensionHeader", "]", ")", "->", "str", ":", "return", "\", \"", ".", "join", "(", "build_extension_item", "(", "name", ",", "parameters", ")", "for", "name", ",", "parameters", "in", "exte...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
parse_subprotocol_item
Parse a subprotocol from ``header`` at the given position. Return the subprotocol value and the new position. Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs.
src/websockets/headers.py
def parse_subprotocol_item( header: str, pos: int, header_name: str ) -> Tuple[Subprotocol, int]: """ Parse a subprotocol from ``header`` at the given position. Return the subprotocol value and the new position. Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs. """ ...
def parse_subprotocol_item( header: str, pos: int, header_name: str ) -> Tuple[Subprotocol, int]: """ Parse a subprotocol from ``header`` at the given position. Return the subprotocol value and the new position. Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs. """ ...
[ "Parse", "a", "subprotocol", "from", "header", "at", "the", "given", "position", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/headers.py#L354-L366
[ "def", "parse_subprotocol_item", "(", "header", ":", "str", ",", "pos", ":", "int", ",", "header_name", ":", "str", ")", "->", "Tuple", "[", "Subprotocol", ",", "int", "]", ":", "item", ",", "pos", "=", "parse_token", "(", "header", ",", "pos", ",", ...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
build_basic_auth
Build an Authorization header for HTTP Basic Auth.
src/websockets/headers.py
def build_basic_auth(username: str, password: str) -> str: """ Build an Authorization header for HTTP Basic Auth. """ # https://tools.ietf.org/html/rfc7617#section-2 assert ":" not in username user_pass = f"{username}:{password}" basic_credentials = base64.b64encode(user_pass.encode()).deco...
def build_basic_auth(username: str, password: str) -> str: """ Build an Authorization header for HTTP Basic Auth. """ # https://tools.ietf.org/html/rfc7617#section-2 assert ":" not in username user_pass = f"{username}:{password}" basic_credentials = base64.b64encode(user_pass.encode()).deco...
[ "Build", "an", "Authorization", "header", "for", "HTTP", "Basic", "Auth", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/headers.py#L395-L404
[ "def", "build_basic_auth", "(", "username", ":", "str", ",", "password", ":", "str", ")", "->", "str", ":", "# https://tools.ietf.org/html/rfc7617#section-2", "assert", "\":\"", "not", "in", "username", "user_pass", "=", "f\"{username}:{password}\"", "basic_credentials"...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
unix_serve
Similar to :func:`serve()`, but for listening on Unix sockets. This function calls the event loop's :meth:`~asyncio.AbstractEventLoop.create_unix_server` method. It is only available on Unix. It's useful for deploying a server behind a reverse proxy such as nginx.
src/websockets/server.py
def unix_serve( ws_handler: Callable[[WebSocketServerProtocol, str], Awaitable[Any]], path: str, **kwargs: Any, ) -> Serve: """ Similar to :func:`serve()`, but for listening on Unix sockets. This function calls the event loop's :meth:`~asyncio.AbstractEventLoop.create_unix_server` method. ...
def unix_serve( ws_handler: Callable[[WebSocketServerProtocol, str], Awaitable[Any]], path: str, **kwargs: Any, ) -> Serve: """ Similar to :func:`serve()`, but for listening on Unix sockets. This function calls the event loop's :meth:`~asyncio.AbstractEventLoop.create_unix_server` method. ...
[ "Similar", "to", ":", "func", ":", "serve", "()", "but", "for", "listening", "on", "Unix", "sockets", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/server.py#L935-L951
[ "def", "unix_serve", "(", "ws_handler", ":", "Callable", "[", "[", "WebSocketServerProtocol", ",", "str", "]", ",", "Awaitable", "[", "Any", "]", "]", ",", "path", ":", "str", ",", "*", "*", "kwargs", ":", "Any", ",", ")", "->", "Serve", ":", "return...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
WebSocketServerProtocol.connection_made
Register connection and initialize a task to handle it.
src/websockets/server.py
def connection_made(self, transport: asyncio.BaseTransport) -> None: """ Register connection and initialize a task to handle it. """ super().connection_made(transport) # Register the connection with the server before creating the handler # task. Registering at the beginn...
def connection_made(self, transport: asyncio.BaseTransport) -> None: """ Register connection and initialize a task to handle it. """ super().connection_made(transport) # Register the connection with the server before creating the handler # task. Registering at the beginn...
[ "Register", "connection", "and", "initialize", "a", "task", "to", "handle", "it", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/server.py#L111-L122
[ "def", "connection_made", "(", "self", ",", "transport", ":", "asyncio", ".", "BaseTransport", ")", "->", "None", ":", "super", "(", ")", ".", "connection_made", "(", "transport", ")", "# Register the connection with the server before creating the handler", "# task. Reg...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
WebSocketServerProtocol.handler
Handle the lifecycle of a WebSocket connection. Since this method doesn't have a caller able to handle exceptions, it attemps to log relevant ones and guarantees that the TCP connection is closed before exiting.
src/websockets/server.py
async def handler(self) -> None: """ Handle the lifecycle of a WebSocket connection. Since this method doesn't have a caller able to handle exceptions, it attemps to log relevant ones and guarantees that the TCP connection is closed before exiting. """ try: ...
async def handler(self) -> None: """ Handle the lifecycle of a WebSocket connection. Since this method doesn't have a caller able to handle exceptions, it attemps to log relevant ones and guarantees that the TCP connection is closed before exiting. """ try: ...
[ "Handle", "the", "lifecycle", "of", "a", "WebSocket", "connection", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/server.py#L124-L217
[ "async", "def", "handler", "(", "self", ")", "->", "None", ":", "try", ":", "try", ":", "path", "=", "await", "self", ".", "handshake", "(", "origins", "=", "self", ".", "origins", ",", "available_extensions", "=", "self", ".", "available_extensions", ",...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
WebSocketServerProtocol.read_http_request
Read request line and headers from the HTTP request. Raise :exc:`~websockets.exceptions.InvalidMessage` if the HTTP message is malformed or isn't an HTTP/1.1 GET request. Don't attempt to read the request body because WebSocket handshake requests don't have one. If the request contains...
src/websockets/server.py
async def read_http_request(self) -> Tuple[str, Headers]: """ Read request line and headers from the HTTP request. Raise :exc:`~websockets.exceptions.InvalidMessage` if the HTTP message is malformed or isn't an HTTP/1.1 GET request. Don't attempt to read the request body becaus...
async def read_http_request(self) -> Tuple[str, Headers]: """ Read request line and headers from the HTTP request. Raise :exc:`~websockets.exceptions.InvalidMessage` if the HTTP message is malformed or isn't an HTTP/1.1 GET request. Don't attempt to read the request body becaus...
[ "Read", "request", "line", "and", "headers", "from", "the", "HTTP", "request", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/server.py#L219-L242
[ "async", "def", "read_http_request", "(", "self", ")", "->", "Tuple", "[", "str", ",", "Headers", "]", ":", "try", ":", "path", ",", "headers", "=", "await", "read_request", "(", "self", ".", "reader", ")", "except", "ValueError", "as", "exc", ":", "ra...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
WebSocketServerProtocol.write_http_response
Write status line and headers to the HTTP response. This coroutine is also able to write a response body.
src/websockets/server.py
def write_http_response( self, status: http.HTTPStatus, headers: Headers, body: Optional[bytes] = None ) -> None: """ Write status line and headers to the HTTP response. This coroutine is also able to write a response body. """ self.response_headers = headers ...
def write_http_response( self, status: http.HTTPStatus, headers: Headers, body: Optional[bytes] = None ) -> None: """ Write status line and headers to the HTTP response. This coroutine is also able to write a response body. """ self.response_headers = headers ...
[ "Write", "status", "line", "and", "headers", "to", "the", "HTTP", "response", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/server.py#L244-L267
[ "def", "write_http_response", "(", "self", ",", "status", ":", "http", ".", "HTTPStatus", ",", "headers", ":", "Headers", ",", "body", ":", "Optional", "[", "bytes", "]", "=", "None", ")", "->", "None", ":", "self", ".", "response_headers", "=", "headers...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
WebSocketServerProtocol.process_request
Intercept the HTTP request and return an HTTP response if needed. ``request_headers`` is a :class:`~websockets.http.Headers` instance. If this method returns ``None``, the WebSocket handshake continues. If it returns a status code, headers and a response body, that HTTP response is sen...
src/websockets/server.py
def process_request( self, path: str, request_headers: Headers ) -> Union[Optional[HTTPResponse], Awaitable[Optional[HTTPResponse]]]: """ Intercept the HTTP request and return an HTTP response if needed. ``request_headers`` is a :class:`~websockets.http.Headers` instance. I...
def process_request( self, path: str, request_headers: Headers ) -> Union[Optional[HTTPResponse], Awaitable[Optional[HTTPResponse]]]: """ Intercept the HTTP request and return an HTTP response if needed. ``request_headers`` is a :class:`~websockets.http.Headers` instance. I...
[ "Intercept", "the", "HTTP", "request", "and", "return", "an", "HTTP", "response", "if", "needed", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/server.py#L269-L303
[ "def", "process_request", "(", "self", ",", "path", ":", "str", ",", "request_headers", ":", "Headers", ")", "->", "Union", "[", "Optional", "[", "HTTPResponse", "]", ",", "Awaitable", "[", "Optional", "[", "HTTPResponse", "]", "]", "]", ":", "if", "self...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
WebSocketServerProtocol.process_origin
Handle the Origin HTTP request header. Raise :exc:`~websockets.exceptions.InvalidOrigin` if the origin isn't acceptable.
src/websockets/server.py
def process_origin( headers: Headers, origins: Optional[Sequence[Optional[Origin]]] = None ) -> Optional[Origin]: """ Handle the Origin HTTP request header. Raise :exc:`~websockets.exceptions.InvalidOrigin` if the origin isn't acceptable. """ # "The user age...
def process_origin( headers: Headers, origins: Optional[Sequence[Optional[Origin]]] = None ) -> Optional[Origin]: """ Handle the Origin HTTP request header. Raise :exc:`~websockets.exceptions.InvalidOrigin` if the origin isn't acceptable. """ # "The user age...
[ "Handle", "the", "Origin", "HTTP", "request", "header", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/server.py#L306-L325
[ "def", "process_origin", "(", "headers", ":", "Headers", ",", "origins", ":", "Optional", "[", "Sequence", "[", "Optional", "[", "Origin", "]", "]", "]", "=", "None", ")", "->", "Optional", "[", "Origin", "]", ":", "# \"The user agent MUST NOT include more tha...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
WebSocketServerProtocol.process_extensions
Handle the Sec-WebSocket-Extensions HTTP request header. Accept or reject each extension proposed in the client request. Negotiate parameters for accepted extensions. Return the Sec-WebSocket-Extensions HTTP response header and the list of accepted extensions. Raise :exc:`~web...
src/websockets/server.py
def process_extensions( headers: Headers, available_extensions: Optional[Sequence[ServerExtensionFactory]], ) -> Tuple[Optional[str], List[Extension]]: """ Handle the Sec-WebSocket-Extensions HTTP request header. Accept or reject each extension proposed in the client request...
def process_extensions( headers: Headers, available_extensions: Optional[Sequence[ServerExtensionFactory]], ) -> Tuple[Optional[str], List[Extension]]: """ Handle the Sec-WebSocket-Extensions HTTP request header. Accept or reject each extension proposed in the client request...
[ "Handle", "the", "Sec", "-", "WebSocket", "-", "Extensions", "HTTP", "request", "header", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/server.py#L328-L407
[ "def", "process_extensions", "(", "headers", ":", "Headers", ",", "available_extensions", ":", "Optional", "[", "Sequence", "[", "ServerExtensionFactory", "]", "]", ",", ")", "->", "Tuple", "[", "Optional", "[", "str", "]", ",", "List", "[", "Extension", "]"...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
WebSocketServerProtocol.process_subprotocol
Handle the Sec-WebSocket-Protocol HTTP request header. Return Sec-WebSocket-Protocol HTTP response header, which is the same as the selected subprotocol.
src/websockets/server.py
def process_subprotocol( self, headers: Headers, available_subprotocols: Optional[Sequence[Subprotocol]] ) -> Optional[Subprotocol]: """ Handle the Sec-WebSocket-Protocol HTTP request header. Return Sec-WebSocket-Protocol HTTP response header, which is the same as the select...
def process_subprotocol( self, headers: Headers, available_subprotocols: Optional[Sequence[Subprotocol]] ) -> Optional[Subprotocol]: """ Handle the Sec-WebSocket-Protocol HTTP request header. Return Sec-WebSocket-Protocol HTTP response header, which is the same as the select...
[ "Handle", "the", "Sec", "-", "WebSocket", "-", "Protocol", "HTTP", "request", "header", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/server.py#L410-L434
[ "def", "process_subprotocol", "(", "self", ",", "headers", ":", "Headers", ",", "available_subprotocols", ":", "Optional", "[", "Sequence", "[", "Subprotocol", "]", "]", ")", "->", "Optional", "[", "Subprotocol", "]", ":", "subprotocol", ":", "Optional", "[", ...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
WebSocketServerProtocol.select_subprotocol
Pick a subprotocol among those offered by the client. If several subprotocols are supported by the client and the server, the default implementation selects the preferred subprotocols by giving equal value to the priorities of the client and the server. If no subprotocols are supported...
src/websockets/server.py
def select_subprotocol( self, client_subprotocols: Sequence[Subprotocol], server_subprotocols: Sequence[Subprotocol], ) -> Optional[Subprotocol]: """ Pick a subprotocol among those offered by the client. If several subprotocols are supported by the client and the ser...
def select_subprotocol( self, client_subprotocols: Sequence[Subprotocol], server_subprotocols: Sequence[Subprotocol], ) -> Optional[Subprotocol]: """ Pick a subprotocol among those offered by the client. If several subprotocols are supported by the client and the ser...
[ "Pick", "a", "subprotocol", "among", "those", "offered", "by", "the", "client", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/server.py#L436-L469
[ "def", "select_subprotocol", "(", "self", ",", "client_subprotocols", ":", "Sequence", "[", "Subprotocol", "]", ",", "server_subprotocols", ":", "Sequence", "[", "Subprotocol", "]", ",", ")", "->", "Optional", "[", "Subprotocol", "]", ":", "if", "self", ".", ...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
WebSocketServerProtocol.handshake
Perform the server side of the opening handshake. If provided, ``origins`` is a list of acceptable HTTP Origin values. Include ``None`` if the lack of an origin is acceptable. If provided, ``available_extensions`` is a list of supported extensions in the order in which they should be u...
src/websockets/server.py
async def handshake( self, origins: Optional[Sequence[Optional[Origin]]] = None, available_extensions: Optional[Sequence[ServerExtensionFactory]] = None, available_subprotocols: Optional[Sequence[Subprotocol]] = None, extra_headers: Optional[HeadersLikeOrCallable] = None, ) -...
async def handshake( self, origins: Optional[Sequence[Optional[Origin]]] = None, available_extensions: Optional[Sequence[ServerExtensionFactory]] = None, available_subprotocols: Optional[Sequence[Subprotocol]] = None, extra_headers: Optional[HeadersLikeOrCallable] = None, ) -...
[ "Perform", "the", "server", "side", "of", "the", "opening", "handshake", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/server.py#L471-L560
[ "async", "def", "handshake", "(", "self", ",", "origins", ":", "Optional", "[", "Sequence", "[", "Optional", "[", "Origin", "]", "]", "]", "=", "None", ",", "available_extensions", ":", "Optional", "[", "Sequence", "[", "ServerExtensionFactory", "]", "]", ...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
WebSocketServer.is_serving
Tell whether the server is accepting new connections or shutting down.
src/websockets/server.py
def is_serving(self) -> bool: """ Tell whether the server is accepting new connections or shutting down. """ try: # Python ≥ 3.7 return self.server.is_serving() # type: ignore except AttributeError: # pragma: no cover # Python < 3.7 ...
def is_serving(self) -> bool: """ Tell whether the server is accepting new connections or shutting down. """ try: # Python ≥ 3.7 return self.server.is_serving() # type: ignore except AttributeError: # pragma: no cover # Python < 3.7 ...
[ "Tell", "whether", "the", "server", "is", "accepting", "new", "connections", "or", "shutting", "down", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/server.py#L627-L637
[ "def", "is_serving", "(", "self", ")", "->", "bool", ":", "try", ":", "# Python ≥ 3.7", "return", "self", ".", "server", ".", "is_serving", "(", ")", "# type: ignore", "except", "AttributeError", ":", "# pragma: no cover", "# Python < 3.7", "return", "self", "."...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
WebSocketServer.close
Close the server and terminate connections with close code 1001. This method is idempotent.
src/websockets/server.py
def close(self) -> None: """ Close the server and terminate connections with close code 1001. This method is idempotent. """ if self.close_task is None: self.close_task = self.loop.create_task(self._close())
def close(self) -> None: """ Close the server and terminate connections with close code 1001. This method is idempotent. """ if self.close_task is None: self.close_task = self.loop.create_task(self._close())
[ "Close", "the", "server", "and", "terminate", "connections", "with", "close", "code", "1001", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/server.py#L639-L647
[ "def", "close", "(", "self", ")", "->", "None", ":", "if", "self", ".", "close_task", "is", "None", ":", "self", ".", "close_task", "=", "self", ".", "loop", ".", "create_task", "(", "self", ".", "_close", "(", ")", ")" ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
WebSocketServer._close
Implementation of :meth:`close`. This calls :meth:`~asyncio.Server.close` on the underlying :class:`~asyncio.Server` object to stop accepting new connections and then closes open connections with close code 1001.
src/websockets/server.py
async def _close(self) -> None: """ Implementation of :meth:`close`. This calls :meth:`~asyncio.Server.close` on the underlying :class:`~asyncio.Server` object to stop accepting new connections and then closes open connections with close code 1001. """ # Stop ac...
async def _close(self) -> None: """ Implementation of :meth:`close`. This calls :meth:`~asyncio.Server.close` on the underlying :class:`~asyncio.Server` object to stop accepting new connections and then closes open connections with close code 1001. """ # Stop ac...
[ "Implementation", "of", ":", "meth", ":", "close", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/server.py#L649-L692
[ "async", "def", "_close", "(", "self", ")", "->", "None", ":", "# Stop accepting new connections.", "self", ".", "server", ".", "close", "(", ")", "# Wait until self.server.close() completes.", "await", "self", ".", "server", ".", "wait_closed", "(", ")", "# Wait ...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
WebSocketClientProtocol.write_http_request
Write request line and headers to the HTTP request.
src/websockets/client.py
def write_http_request(self, path: str, headers: Headers) -> None: """ Write request line and headers to the HTTP request. """ self.path = path self.request_headers = headers logger.debug("%s > GET %s HTTP/1.1", self.side, path) logger.debug("%s > %r", self.side...
def write_http_request(self, path: str, headers: Headers) -> None: """ Write request line and headers to the HTTP request. """ self.path = path self.request_headers = headers logger.debug("%s > GET %s HTTP/1.1", self.side, path) logger.debug("%s > %r", self.side...
[ "Write", "request", "line", "and", "headers", "to", "the", "HTTP", "request", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/client.py#L69-L85
[ "def", "write_http_request", "(", "self", ",", "path", ":", "str", ",", "headers", ":", "Headers", ")", "->", "None", ":", "self", ".", "path", "=", "path", "self", ".", "request_headers", "=", "headers", "logger", ".", "debug", "(", "\"%s > GET %s HTTP/1....
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
WebSocketClientProtocol.read_http_response
Read status line and headers from the HTTP response. Raise :exc:`~websockets.exceptions.InvalidMessage` if the HTTP message is malformed or isn't an HTTP/1.1 GET request. Don't attempt to read the response body because WebSocket handshake responses don't have one. If the response conta...
src/websockets/client.py
async def read_http_response(self) -> Tuple[int, Headers]: """ Read status line and headers from the HTTP response. Raise :exc:`~websockets.exceptions.InvalidMessage` if the HTTP message is malformed or isn't an HTTP/1.1 GET request. Don't attempt to read the response body beca...
async def read_http_response(self) -> Tuple[int, Headers]: """ Read status line and headers from the HTTP response. Raise :exc:`~websockets.exceptions.InvalidMessage` if the HTTP message is malformed or isn't an HTTP/1.1 GET request. Don't attempt to read the response body beca...
[ "Read", "status", "line", "and", "headers", "from", "the", "HTTP", "response", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/client.py#L87-L109
[ "async", "def", "read_http_response", "(", "self", ")", "->", "Tuple", "[", "int", ",", "Headers", "]", ":", "try", ":", "status_code", ",", "reason", ",", "headers", "=", "await", "read_response", "(", "self", ".", "reader", ")", "except", "ValueError", ...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
WebSocketClientProtocol.process_extensions
Handle the Sec-WebSocket-Extensions HTTP response header. Check that each extension is supported, as well as its parameters. Return the list of accepted extensions. Raise :exc:`~websockets.exceptions.InvalidHandshake` to abort the connection. :rfc:`6455` leaves the rules up t...
src/websockets/client.py
def process_extensions( headers: Headers, available_extensions: Optional[Sequence[ClientExtensionFactory]], ) -> List[Extension]: """ Handle the Sec-WebSocket-Extensions HTTP response header. Check that each extension is supported, as well as its parameters. Return ...
def process_extensions( headers: Headers, available_extensions: Optional[Sequence[ClientExtensionFactory]], ) -> List[Extension]: """ Handle the Sec-WebSocket-Extensions HTTP response header. Check that each extension is supported, as well as its parameters. Return ...
[ "Handle", "the", "Sec", "-", "WebSocket", "-", "Extensions", "HTTP", "response", "header", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/client.py#L112-L185
[ "def", "process_extensions", "(", "headers", ":", "Headers", ",", "available_extensions", ":", "Optional", "[", "Sequence", "[", "ClientExtensionFactory", "]", "]", ",", ")", "->", "List", "[", "Extension", "]", ":", "accepted_extensions", ":", "List", "[", "E...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
WebSocketClientProtocol.process_subprotocol
Handle the Sec-WebSocket-Protocol HTTP response header. Check that it contains exactly one supported subprotocol. Return the selected subprotocol.
src/websockets/client.py
def process_subprotocol( headers: Headers, available_subprotocols: Optional[Sequence[Subprotocol]] ) -> Optional[Subprotocol]: """ Handle the Sec-WebSocket-Protocol HTTP response header. Check that it contains exactly one supported subprotocol. Return the selected subprotoc...
def process_subprotocol( headers: Headers, available_subprotocols: Optional[Sequence[Subprotocol]] ) -> Optional[Subprotocol]: """ Handle the Sec-WebSocket-Protocol HTTP response header. Check that it contains exactly one supported subprotocol. Return the selected subprotoc...
[ "Handle", "the", "Sec", "-", "WebSocket", "-", "Protocol", "HTTP", "response", "header", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/client.py#L188-L221
[ "def", "process_subprotocol", "(", "headers", ":", "Headers", ",", "available_subprotocols", ":", "Optional", "[", "Sequence", "[", "Subprotocol", "]", "]", ")", "->", "Optional", "[", "Subprotocol", "]", ":", "subprotocol", ":", "Optional", "[", "Subprotocol", ...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
WebSocketClientProtocol.handshake
Perform the client side of the opening handshake. If provided, ``origin`` sets the Origin HTTP header. If provided, ``available_extensions`` is a list of supported extensions in the order in which they should be used. If provided, ``available_subprotocols`` is a list of supported ...
src/websockets/client.py
async def handshake( self, wsuri: WebSocketURI, origin: Optional[Origin] = None, available_extensions: Optional[Sequence[ClientExtensionFactory]] = None, available_subprotocols: Optional[Sequence[Subprotocol]] = None, extra_headers: Optional[HeadersLike] = None, ) -> ...
async def handshake( self, wsuri: WebSocketURI, origin: Optional[Origin] = None, available_extensions: Optional[Sequence[ClientExtensionFactory]] = None, available_subprotocols: Optional[Sequence[Subprotocol]] = None, extra_headers: Optional[HeadersLike] = None, ) -> ...
[ "Perform", "the", "client", "side", "of", "the", "opening", "handshake", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/client.py#L223-L309
[ "async", "def", "handshake", "(", "self", ",", "wsuri", ":", "WebSocketURI", ",", "origin", ":", "Optional", "[", "Origin", "]", "=", "None", ",", "available_extensions", ":", "Optional", "[", "Sequence", "[", "ClientExtensionFactory", "]", "]", "=", "None",...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
WebSocketCommonProtocol.client_connected
Callback when the TCP connection is established. Record references to the stream reader and the stream writer to avoid using private attributes ``_stream_reader`` and ``_stream_writer`` of :class:`~asyncio.StreamReaderProtocol`.
src/websockets/protocol.py
def client_connected( self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter ) -> None: """ Callback when the TCP connection is established. Record references to the stream reader and the stream writer to avoid using private attributes ``_stream_reader`` and ``_str...
def client_connected( self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter ) -> None: """ Callback when the TCP connection is established. Record references to the stream reader and the stream writer to avoid using private attributes ``_stream_reader`` and ``_str...
[ "Callback", "when", "the", "TCP", "connection", "is", "established", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L276-L288
[ "def", "client_connected", "(", "self", ",", "reader", ":", "asyncio", ".", "StreamReader", ",", "writer", ":", "asyncio", ".", "StreamWriter", ")", "->", "None", ":", "self", ".", "reader", "=", "reader", "self", ".", "writer", "=", "writer" ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
WebSocketCommonProtocol.connection_open
Callback when the WebSocket opening handshake completes. Enter the OPEN state and start the data transfer phase.
src/websockets/protocol.py
def connection_open(self) -> None: """ Callback when the WebSocket opening handshake completes. Enter the OPEN state and start the data transfer phase. """ # 4.1. The WebSocket Connection is Established. assert self.state is State.CONNECTING self.state = State.O...
def connection_open(self) -> None: """ Callback when the WebSocket opening handshake completes. Enter the OPEN state and start the data transfer phase. """ # 4.1. The WebSocket Connection is Established. assert self.state is State.CONNECTING self.state = State.O...
[ "Callback", "when", "the", "WebSocket", "opening", "handshake", "completes", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L290-L306
[ "def", "connection_open", "(", "self", ")", "->", "None", ":", "# 4.1. The WebSocket Connection is Established.", "assert", "self", ".", "state", "is", "State", ".", "CONNECTING", "self", ".", "state", "=", "State", ".", "OPEN", "logger", ".", "debug", "(", "\...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
WebSocketCommonProtocol.open
This property is ``True`` when the connection is usable. It may be used to detect disconnections but this is discouraged per the EAFP_ principle. When ``open`` is ``False``, using the connection raises a :exc:`~websockets.exceptions.ConnectionClosed` exception. .. _EAFP: https://docs.p...
src/websockets/protocol.py
def open(self) -> bool: """ This property is ``True`` when the connection is usable. It may be used to detect disconnections but this is discouraged per the EAFP_ principle. When ``open`` is ``False``, using the connection raises a :exc:`~websockets.exceptions.ConnectionClosed` ...
def open(self) -> bool: """ This property is ``True`` when the connection is usable. It may be used to detect disconnections but this is discouraged per the EAFP_ principle. When ``open`` is ``False``, using the connection raises a :exc:`~websockets.exceptions.ConnectionClosed` ...
[ "This", "property", "is", "True", "when", "the", "connection", "is", "usable", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L337-L348
[ "def", "open", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "state", "is", "State", ".", "OPEN", "and", "not", "self", ".", "transfer_data_task", ".", "done", "(", ")" ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
WebSocketCommonProtocol.recv
This coroutine receives the next message. It returns a :class:`str` for a text frame and :class:`bytes` for a binary frame. When the end of the message stream is reached, :meth:`recv` raises :exc:`~websockets.exceptions.ConnectionClosed`. This can happen after a normal connecti...
src/websockets/protocol.py
async def recv(self) -> Data: """ This coroutine receives the next message. It returns a :class:`str` for a text frame and :class:`bytes` for a binary frame. When the end of the message stream is reached, :meth:`recv` raises :exc:`~websockets.exceptions.ConnectionClosed...
async def recv(self) -> Data: """ This coroutine receives the next message. It returns a :class:`str` for a text frame and :class:`bytes` for a binary frame. When the end of the message stream is reached, :meth:`recv` raises :exc:`~websockets.exceptions.ConnectionClosed...
[ "This", "coroutine", "receives", "the", "next", "message", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L391-L465
[ "async", "def", "recv", "(", "self", ")", "->", "Data", ":", "if", "self", ".", "_pop_message_waiter", "is", "not", "None", ":", "raise", "RuntimeError", "(", "\"cannot call recv() while another coroutine \"", "\"is already waiting for the next message\"", ")", "# Don't...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
WebSocketCommonProtocol.send
This coroutine sends a message. It sends a string (:class:`str`) as a text frame and a bytes-like object (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) as a binary frame. It also accepts an iterable or an asynchronous iterator of strings or bytes-like objects. Eac...
src/websockets/protocol.py
async def send( self, message: Union[Data, Iterable[Data], AsyncIterable[Data]] ) -> None: """ This coroutine sends a message. It sends a string (:class:`str`) as a text frame and a bytes-like object (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) as a b...
async def send( self, message: Union[Data, Iterable[Data], AsyncIterable[Data]] ) -> None: """ This coroutine sends a message. It sends a string (:class:`str`) as a text frame and a bytes-like object (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) as a b...
[ "This", "coroutine", "sends", "a", "message", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L467-L554
[ "async", "def", "send", "(", "self", ",", "message", ":", "Union", "[", "Data", ",", "Iterable", "[", "Data", "]", ",", "AsyncIterable", "[", "Data", "]", "]", ")", "->", "None", ":", "await", "self", ".", "ensure_open", "(", ")", "# Unfragmented messa...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
WebSocketCommonProtocol.close
This coroutine performs the closing handshake. It waits for the other end to complete the handshake and for the TCP connection to terminate. As a consequence, there's no need to await :meth:`wait_closed`; :meth:`close` already does it. :meth:`close` is idempotent: it doesn't do anythin...
src/websockets/protocol.py
async def close(self, code: int = 1000, reason: str = "") -> None: """ This coroutine performs the closing handshake. It waits for the other end to complete the handshake and for the TCP connection to terminate. As a consequence, there's no need to await :meth:`wait_closed`; :me...
async def close(self, code: int = 1000, reason: str = "") -> None: """ This coroutine performs the closing handshake. It waits for the other end to complete the handshake and for the TCP connection to terminate. As a consequence, there's no need to await :meth:`wait_closed`; :me...
[ "This", "coroutine", "performs", "the", "closing", "handshake", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L556-L603
[ "async", "def", "close", "(", "self", ",", "code", ":", "int", "=", "1000", ",", "reason", ":", "str", "=", "\"\"", ")", "->", "None", ":", "try", ":", "await", "asyncio", ".", "wait_for", "(", "self", ".", "write_close_frame", "(", "serialize_close", ...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
WebSocketCommonProtocol.ping
This coroutine sends a ping. It returns a :class:`~asyncio.Future` which will be completed when the corresponding pong is received and which you may ignore if you don't want to wait. A ping may serve as a keepalive or as a check that the remote endpoint received all messages up...
src/websockets/protocol.py
async def ping(self, data: Optional[bytes] = None) -> Awaitable[None]: """ This coroutine sends a ping. It returns a :class:`~asyncio.Future` which will be completed when the corresponding pong is received and which you may ignore if you don't want to wait. A ping may s...
async def ping(self, data: Optional[bytes] = None) -> Awaitable[None]: """ This coroutine sends a ping. It returns a :class:`~asyncio.Future` which will be completed when the corresponding pong is received and which you may ignore if you don't want to wait. A ping may s...
[ "This", "coroutine", "sends", "a", "ping", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L605-L641
[ "async", "def", "ping", "(", "self", ",", "data", ":", "Optional", "[", "bytes", "]", "=", "None", ")", "->", "Awaitable", "[", "None", "]", ":", "await", "self", ".", "ensure_open", "(", ")", "if", "data", "is", "not", "None", ":", "data", "=", ...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
WebSocketCommonProtocol.pong
This coroutine sends a pong. An unsolicited pong may serve as a unidirectional heartbeat. The content may be overridden with the optional ``data`` argument which must be a string (which will be encoded to UTF-8) or a bytes-like object.
src/websockets/protocol.py
async def pong(self, data: bytes = b"") -> None: """ This coroutine sends a pong. An unsolicited pong may serve as a unidirectional heartbeat. The content may be overridden with the optional ``data`` argument which must be a string (which will be encoded to UTF-8) or a ...
async def pong(self, data: bytes = b"") -> None: """ This coroutine sends a pong. An unsolicited pong may serve as a unidirectional heartbeat. The content may be overridden with the optional ``data`` argument which must be a string (which will be encoded to UTF-8) or a ...
[ "This", "coroutine", "sends", "a", "pong", "." ]
aaugustin/websockets
python
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L643-L658
[ "async", "def", "pong", "(", "self", ",", "data", ":", "bytes", "=", "b\"\"", ")", "->", "None", ":", "await", "self", ".", "ensure_open", "(", ")", "data", "=", "encode_data", "(", "data", ")", "await", "self", ".", "write_frame", "(", "True", ",", ...
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
train
write_map_file
Given a list of mapping items (in the form described by the parse_mapping_file method) and a header line, write each row to the given input file with fields separated by tabs. :type mapFNH: file or str :param mapFNH: Either the full path to the map file or an open file handle :type items: list :pa...
phylotoast/util.py
def write_map_file(mapFNH, items, header): """ Given a list of mapping items (in the form described by the parse_mapping_file method) and a header line, write each row to the given input file with fields separated by tabs. :type mapFNH: file or str :param mapFNH: Either the full path to the map fil...
def write_map_file(mapFNH, items, header): """ Given a list of mapping items (in the form described by the parse_mapping_file method) and a header line, write each row to the given input file with fields separated by tabs. :type mapFNH: file or str :param mapFNH: Either the full path to the map fil...
[ "Given", "a", "list", "of", "mapping", "items", "(", "in", "the", "form", "described", "by", "the", "parse_mapping_file", "method", ")", "and", "a", "header", "line", "write", "each", "row", "to", "the", "given", "input", "file", "with", "fields", "separat...
smdabdoub/phylotoast
python
https://github.com/smdabdoub/phylotoast/blob/0b74ef171e6a84761710548501dfac71285a58a3/phylotoast/util.py#L111-L134
[ "def", "write_map_file", "(", "mapFNH", ",", "items", ",", "header", ")", ":", "if", "isinstance", "(", "header", ",", "list", ")", ":", "header", "=", "\"\\t\"", ".", "join", "(", "header", ")", "+", "\"\\n\"", "with", "file_handle", "(", "mapFNH", ",...
0b74ef171e6a84761710548501dfac71285a58a3
train
parse_taxonomy_table
Greengenes provides a file each OTU a full taxonomic designation. This method parses that file into a map with (key,val) = (OTU, taxonomy). :type idtaxFNH: file or str :param idtaxFNH: Either the full path to the map file or an open file handle :rtype: dict :return: A map associating each OTU ID w...
phylotoast/util.py
def parse_taxonomy_table(idtaxFNH): """ Greengenes provides a file each OTU a full taxonomic designation. This method parses that file into a map with (key,val) = (OTU, taxonomy). :type idtaxFNH: file or str :param idtaxFNH: Either the full path to the map file or an open file handle :rtype: d...
def parse_taxonomy_table(idtaxFNH): """ Greengenes provides a file each OTU a full taxonomic designation. This method parses that file into a map with (key,val) = (OTU, taxonomy). :type idtaxFNH: file or str :param idtaxFNH: Either the full path to the map file or an open file handle :rtype: d...
[ "Greengenes", "provides", "a", "file", "each", "OTU", "a", "full", "taxonomic", "designation", ".", "This", "method", "parses", "that", "file", "into", "a", "map", "with", "(", "key", "val", ")", "=", "(", "OTU", "taxonomy", ")", "." ]
smdabdoub/phylotoast
python
https://github.com/smdabdoub/phylotoast/blob/0b74ef171e6a84761710548501dfac71285a58a3/phylotoast/util.py#L137-L156
[ "def", "parse_taxonomy_table", "(", "idtaxFNH", ")", ":", "idtax", "=", "OrderedDict", "(", ")", "with", "file_handle", "(", "idtaxFNH", ")", "as", "idtxF", ":", "for", "line", "in", "idtxF", ":", "ID", ",", "tax", "=", "line", ".", "strip", "(", ")", ...
0b74ef171e6a84761710548501dfac71285a58a3
train
split_phylogeny
Return either the full or truncated version of a QIIME-formatted taxonomy string. :type p: str :param p: A QIIME-formatted taxonomy string: k__Foo; p__Bar; ... :type level: str :param level: The different level of identification are kingdom (k), phylum (p), class (c),order (o), famil...
phylotoast/util.py
def split_phylogeny(p, level="s"): """ Return either the full or truncated version of a QIIME-formatted taxonomy string. :type p: str :param p: A QIIME-formatted taxonomy string: k__Foo; p__Bar; ... :type level: str :param level: The different level of identification are kingdom (k), phylum (p...
def split_phylogeny(p, level="s"): """ Return either the full or truncated version of a QIIME-formatted taxonomy string. :type p: str :param p: A QIIME-formatted taxonomy string: k__Foo; p__Bar; ... :type level: str :param level: The different level of identification are kingdom (k), phylum (p...
[ "Return", "either", "the", "full", "or", "truncated", "version", "of", "a", "QIIME", "-", "formatted", "taxonomy", "string", "." ]
smdabdoub/phylotoast
python
https://github.com/smdabdoub/phylotoast/blob/0b74ef171e6a84761710548501dfac71285a58a3/phylotoast/util.py#L159-L177
[ "def", "split_phylogeny", "(", "p", ",", "level", "=", "\"s\"", ")", ":", "level", "=", "level", "+", "\"__\"", "result", "=", "p", ".", "split", "(", "level", ")", "return", "result", "[", "0", "]", "+", "level", "+", "result", "[", "1", "]", "....
0b74ef171e6a84761710548501dfac71285a58a3
train
ensure_dir
Check to make sure the supplied directory path does not exist, if so, create it. The method catches OSError exceptions and returns a descriptive message instead of re-raising the error. :type d: str :param d: It is the full path to a directory. :return: Does not return anything, but creates a dire...
phylotoast/util.py
def ensure_dir(d): """ Check to make sure the supplied directory path does not exist, if so, create it. The method catches OSError exceptions and returns a descriptive message instead of re-raising the error. :type d: str :param d: It is the full path to a directory. :return: Does not retu...
def ensure_dir(d): """ Check to make sure the supplied directory path does not exist, if so, create it. The method catches OSError exceptions and returns a descriptive message instead of re-raising the error. :type d: str :param d: It is the full path to a directory. :return: Does not retu...
[ "Check", "to", "make", "sure", "the", "supplied", "directory", "path", "does", "not", "exist", "if", "so", "create", "it", ".", "The", "method", "catches", "OSError", "exceptions", "and", "returns", "a", "descriptive", "message", "instead", "of", "re", "-", ...
smdabdoub/phylotoast
python
https://github.com/smdabdoub/phylotoast/blob/0b74ef171e6a84761710548501dfac71285a58a3/phylotoast/util.py#L180-L206
[ "def", "ensure_dir", "(", "d", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "d", ")", ":", "try", ":", "os", ".", "makedirs", "(", "d", ")", "except", "OSError", "as", "oe", ":", "# should not happen with os.makedirs", "# ENOENT: No such...
0b74ef171e6a84761710548501dfac71285a58a3
train
file_handle
Takes either a file path or an open file handle, checks validity and returns an open file handle or raises an appropriate Exception. :type fnh: str :param fnh: It is the full path to a file, or open file handle :type mode: str :param mode: The way in which this file will be used, for example to re...
phylotoast/util.py
def file_handle(fnh, mode="rU"): """ Takes either a file path or an open file handle, checks validity and returns an open file handle or raises an appropriate Exception. :type fnh: str :param fnh: It is the full path to a file, or open file handle :type mode: str :param mode: The way in wh...
def file_handle(fnh, mode="rU"): """ Takes either a file path or an open file handle, checks validity and returns an open file handle or raises an appropriate Exception. :type fnh: str :param fnh: It is the full path to a file, or open file handle :type mode: str :param mode: The way in wh...
[ "Takes", "either", "a", "file", "path", "or", "an", "open", "file", "handle", "checks", "validity", "and", "returns", "an", "open", "file", "handle", "or", "raises", "an", "appropriate", "Exception", "." ]
smdabdoub/phylotoast
python
https://github.com/smdabdoub/phylotoast/blob/0b74ef171e6a84761710548501dfac71285a58a3/phylotoast/util.py#L209-L231
[ "def", "file_handle", "(", "fnh", ",", "mode", "=", "\"rU\"", ")", ":", "handle", "=", "None", "if", "isinstance", "(", "fnh", ",", "file", ")", ":", "if", "fnh", ".", "closed", ":", "raise", "ValueError", "(", "\"Input file is closed.\"", ")", "handle",...
0b74ef171e6a84761710548501dfac71285a58a3
train
gather_categories
Find the user specified categories in the map and create a dictionary to contain the relevant data for each type within the categories. Multiple categories will have their types combined such that each possible combination will have its own entry in the dictionary. :type imap: dict :param imap: The...
phylotoast/util.py
def gather_categories(imap, header, categories=None): """ Find the user specified categories in the map and create a dictionary to contain the relevant data for each type within the categories. Multiple categories will have their types combined such that each possible combination will have its own entry...
def gather_categories(imap, header, categories=None): """ Find the user specified categories in the map and create a dictionary to contain the relevant data for each type within the categories. Multiple categories will have their types combined such that each possible combination will have its own entry...
[ "Find", "the", "user", "specified", "categories", "in", "the", "map", "and", "create", "a", "dictionary", "to", "contain", "the", "relevant", "data", "for", "each", "type", "within", "the", "categories", ".", "Multiple", "categories", "will", "have", "their", ...
smdabdoub/phylotoast
python
https://github.com/smdabdoub/phylotoast/blob/0b74ef171e6a84761710548501dfac71285a58a3/phylotoast/util.py#L238-L309
[ "def", "gather_categories", "(", "imap", ",", "header", ",", "categories", "=", "None", ")", ":", "# If no categories provided, return all SampleIDs", "if", "categories", "is", "None", ":", "return", "{", "\"default\"", ":", "DataCategory", "(", "set", "(", "imap"...
0b74ef171e6a84761710548501dfac71285a58a3
train
parse_unifrac
Parses the unifrac results file into a dictionary :type unifracFN: str :param unifracFN: The path to the unifrac results file :rtype: dict :return: A dictionary with keys: 'pcd' (principle coordinates data) which is a dictionary of the data keyed by sample ID, 'eigvals' (eigenvalues), and...
phylotoast/util.py
def parse_unifrac(unifracFN): """ Parses the unifrac results file into a dictionary :type unifracFN: str :param unifracFN: The path to the unifrac results file :rtype: dict :return: A dictionary with keys: 'pcd' (principle coordinates data) which is a dictionary of the data keyed ...
def parse_unifrac(unifracFN): """ Parses the unifrac results file into a dictionary :type unifracFN: str :param unifracFN: The path to the unifrac results file :rtype: dict :return: A dictionary with keys: 'pcd' (principle coordinates data) which is a dictionary of the data keyed ...
[ "Parses", "the", "unifrac", "results", "file", "into", "a", "dictionary" ]
smdabdoub/phylotoast
python
https://github.com/smdabdoub/phylotoast/blob/0b74ef171e6a84761710548501dfac71285a58a3/phylotoast/util.py#L311-L334
[ "def", "parse_unifrac", "(", "unifracFN", ")", ":", "with", "open", "(", "unifracFN", ",", "\"rU\"", ")", "as", "uF", ":", "first", "=", "uF", ".", "next", "(", ")", ".", "split", "(", "\"\\t\"", ")", "lines", "=", "[", "line", ".", "strip", "(", ...
0b74ef171e6a84761710548501dfac71285a58a3
train
parse_unifrac_v1_8
Function to parse data from older version of unifrac file obtained from Qiime version 1.8 and earlier. :type unifrac: dict :param unifracFN: The path to the unifrac results file :type file_data: list :param file_data: Unifrac data lines after stripping whitespace characters.
phylotoast/util.py
def parse_unifrac_v1_8(unifrac, file_data): """ Function to parse data from older version of unifrac file obtained from Qiime version 1.8 and earlier. :type unifrac: dict :param unifracFN: The path to the unifrac results file :type file_data: list :param file_data: Unifrac data lines after...
def parse_unifrac_v1_8(unifrac, file_data): """ Function to parse data from older version of unifrac file obtained from Qiime version 1.8 and earlier. :type unifrac: dict :param unifracFN: The path to the unifrac results file :type file_data: list :param file_data: Unifrac data lines after...
[ "Function", "to", "parse", "data", "from", "older", "version", "of", "unifrac", "file", "obtained", "from", "Qiime", "version", "1", ".", "8", "and", "earlier", "." ]
smdabdoub/phylotoast
python
https://github.com/smdabdoub/phylotoast/blob/0b74ef171e6a84761710548501dfac71285a58a3/phylotoast/util.py#L337-L356
[ "def", "parse_unifrac_v1_8", "(", "unifrac", ",", "file_data", ")", ":", "for", "line", "in", "file_data", ":", "if", "line", "==", "\"\"", ":", "break", "line", "=", "line", ".", "split", "(", "\"\\t\"", ")", "unifrac", "[", "\"pcd\"", "]", "[", "line...
0b74ef171e6a84761710548501dfac71285a58a3
train
parse_unifrac_v1_9
Function to parse data from newer version of unifrac file obtained from Qiime version 1.9 and later. :type unifracFN: str :param unifracFN: The path to the unifrac results file :type file_data: list :param file_data: Unifrac data lines after stripping whitespace characters.
phylotoast/util.py
def parse_unifrac_v1_9(unifrac, file_data): """ Function to parse data from newer version of unifrac file obtained from Qiime version 1.9 and later. :type unifracFN: str :param unifracFN: The path to the unifrac results file :type file_data: list :param file_data: Unifrac data lines after ...
def parse_unifrac_v1_9(unifrac, file_data): """ Function to parse data from newer version of unifrac file obtained from Qiime version 1.9 and later. :type unifracFN: str :param unifracFN: The path to the unifrac results file :type file_data: list :param file_data: Unifrac data lines after ...
[ "Function", "to", "parse", "data", "from", "newer", "version", "of", "unifrac", "file", "obtained", "from", "Qiime", "version", "1", ".", "9", "and", "later", "." ]
smdabdoub/phylotoast
python
https://github.com/smdabdoub/phylotoast/blob/0b74ef171e6a84761710548501dfac71285a58a3/phylotoast/util.py#L359-L378
[ "def", "parse_unifrac_v1_9", "(", "unifrac", ",", "file_data", ")", ":", "unifrac", "[", "\"eigvals\"", "]", "=", "[", "float", "(", "entry", ")", "for", "entry", "in", "file_data", "[", "0", "]", ".", "split", "(", "\"\\t\"", ")", "]", "unifrac", "[",...
0b74ef171e6a84761710548501dfac71285a58a3
train
color_mapping
Determine color-category mapping. If color_column was specified, then map the category names to color values. Otherwise, use the palettable colors to automatically generate a set of colors for the group values. :type sample_map: dict :param unifracFN: Map associating each line of the mapping file with ...
phylotoast/util.py
def color_mapping(sample_map, header, group_column, color_column=None): """ Determine color-category mapping. If color_column was specified, then map the category names to color values. Otherwise, use the palettable colors to automatically generate a set of colors for the group values. :type sample...
def color_mapping(sample_map, header, group_column, color_column=None): """ Determine color-category mapping. If color_column was specified, then map the category names to color values. Otherwise, use the palettable colors to automatically generate a set of colors for the group values. :type sample...
[ "Determine", "color", "-", "category", "mapping", ".", "If", "color_column", "was", "specified", "then", "map", "the", "category", "names", "to", "color", "values", ".", "Otherwise", "use", "the", "palettable", "colors", "to", "automatically", "generate", "a", ...
smdabdoub/phylotoast
python
https://github.com/smdabdoub/phylotoast/blob/0b74ef171e6a84761710548501dfac71285a58a3/phylotoast/util.py#L380-L419
[ "def", "color_mapping", "(", "sample_map", ",", "header", ",", "group_column", ",", "color_column", "=", "None", ")", ":", "group_colors", "=", "OrderedDict", "(", ")", "group_gather", "=", "gather_categories", "(", "sample_map", ",", "header", ",", "[", "grou...
0b74ef171e6a84761710548501dfac71285a58a3
train
ConsistentHashingRouter._route
The first argument is assumed to be the ``key`` for routing.
nydus/db/routers/keyvalue.py
def _route(self, attr, args, kwargs, **fkwargs): """ The first argument is assumed to be the ``key`` for routing. """ key = get_key(args, kwargs) found = self._hash.get_node(key) if not found and len(self._down_connections) > 0: raise self.HostListExhausted...
def _route(self, attr, args, kwargs, **fkwargs): """ The first argument is assumed to be the ``key`` for routing. """ key = get_key(args, kwargs) found = self._hash.get_node(key) if not found and len(self._down_connections) > 0: raise self.HostListExhausted...
[ "The", "first", "argument", "is", "assumed", "to", "be", "the", "key", "for", "routing", "." ]
disqus/nydus
python
https://github.com/disqus/nydus/blob/9b505840da47a34f758a830c3992fa5dcb7bb7ad/nydus/db/routers/keyvalue.py#L66-L79
[ "def", "_route", "(", "self", ",", "attr", ",", "args", ",", "kwargs", ",", "*", "*", "fkwargs", ")", ":", "key", "=", "get_key", "(", "args", ",", "kwargs", ")", "found", "=", "self", ".", "_hash", ".", "get_node", "(", "key", ")", "if", "not", ...
9b505840da47a34f758a830c3992fa5dcb7bb7ad
train
PartitionRouter._route
The first argument is assumed to be the ``key`` for routing.
nydus/db/routers/keyvalue.py
def _route(self, attr, args, kwargs, **fkwargs): """ The first argument is assumed to be the ``key`` for routing. """ key = get_key(args, kwargs) return [crc32(str(key)) % len(self.cluster)]
def _route(self, attr, args, kwargs, **fkwargs): """ The first argument is assumed to be the ``key`` for routing. """ key = get_key(args, kwargs) return [crc32(str(key)) % len(self.cluster)]
[ "The", "first", "argument", "is", "assumed", "to", "be", "the", "key", "for", "routing", "." ]
disqus/nydus
python
https://github.com/disqus/nydus/blob/9b505840da47a34f758a830c3992fa5dcb7bb7ad/nydus/db/routers/keyvalue.py#L84-L90
[ "def", "_route", "(", "self", ",", "attr", ",", "args", ",", "kwargs", ",", "*", "*", "fkwargs", ")", ":", "key", "=", "get_key", "(", "args", ",", "kwargs", ")", "return", "[", "crc32", "(", "str", "(", "key", ")", ")", "%", "len", "(", "self"...
9b505840da47a34f758a830c3992fa5dcb7bb7ad
train
plot_dist_normal
plot distribution
ctbBio/shuffle_genome.py
def plot_dist_normal(s, mu, sigma): """ plot distribution """ import matplotlib.pyplot as plt count, bins, ignored = plt.hist(s, 30, normed=True) plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) \ * np.exp( - (bins - mu)**2 / (2 * sigma**2) ), \ linewidth = 2, color = 'r') ...
def plot_dist_normal(s, mu, sigma): """ plot distribution """ import matplotlib.pyplot as plt count, bins, ignored = plt.hist(s, 30, normed=True) plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) \ * np.exp( - (bins - mu)**2 / (2 * sigma**2) ), \ linewidth = 2, color = 'r') ...
[ "plot", "distribution" ]
christophertbrown/bioscripts
python
https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/shuffle_genome.py#L16-L25
[ "def", "plot_dist_normal", "(", "s", ",", "mu", ",", "sigma", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "count", ",", "bins", ",", "ignored", "=", "plt", ".", "hist", "(", "s", ",", "30", ",", "normed", "=", "True", ")", "plt", ...
83b2566b3a5745437ec651cd6cafddd056846240
train
rev_c
return reverse completment of read
ctbBio/shuffle_genome.py
def rev_c(read): """ return reverse completment of read """ rc = [] rc_nucs = {'A':'T', 'T':'A', 'G':'C', 'C':'G', 'N':'N'} for base in read: rc.extend(rc_nucs[base.upper()]) return rc[::-1]
def rev_c(read): """ return reverse completment of read """ rc = [] rc_nucs = {'A':'T', 'T':'A', 'G':'C', 'C':'G', 'N':'N'} for base in read: rc.extend(rc_nucs[base.upper()]) return rc[::-1]
[ "return", "reverse", "completment", "of", "read" ]
christophertbrown/bioscripts
python
https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/shuffle_genome.py#L27-L35
[ "def", "rev_c", "(", "read", ")", ":", "rc", "=", "[", "]", "rc_nucs", "=", "{", "'A'", ":", "'T'", ",", "'T'", ":", "'A'", ",", "'G'", ":", "'C'", ",", "'C'", ":", "'G'", ",", "'N'", ":", "'N'", "}", "for", "base", "in", "read", ":", "rc",...
83b2566b3a5745437ec651cd6cafddd056846240
train
shuffle_genome
randomly shuffle genome
ctbBio/shuffle_genome.py
def shuffle_genome(genome, cat, fraction = float(100), plot = True, \ alpha = 0.1, beta = 100000, \ min_length = 1000, max_length = 200000): """ randomly shuffle genome """ header = '>randomized_%s' % (genome.name) sequence = list(''.join([i[1] for i in parse_fasta(genome)])) len...
def shuffle_genome(genome, cat, fraction = float(100), plot = True, \ alpha = 0.1, beta = 100000, \ min_length = 1000, max_length = 200000): """ randomly shuffle genome """ header = '>randomized_%s' % (genome.name) sequence = list(''.join([i[1] for i in parse_fasta(genome)])) len...
[ "randomly", "shuffle", "genome" ]
christophertbrown/bioscripts
python
https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/shuffle_genome.py#L37-L87
[ "def", "shuffle_genome", "(", "genome", ",", "cat", ",", "fraction", "=", "float", "(", "100", ")", ",", "plot", "=", "True", ",", "alpha", "=", "0.1", ",", "beta", "=", "100000", ",", "min_length", "=", "1000", ",", "max_length", "=", "200000", ")",...
83b2566b3a5745437ec651cd6cafddd056846240
train
MultiVarLinReg._do_analysis_no_cross_validation
Find the best model (fit) and create self.list_of_fits and self.fit
opengrid/library/regression.py
def _do_analysis_no_cross_validation(self): """ Find the best model (fit) and create self.list_of_fits and self.fit """ # first model is just the mean response_term = [Term([LookupFactor(self.y)])] model_terms = [Term([])] # empty term is the intercept all_model_...
def _do_analysis_no_cross_validation(self): """ Find the best model (fit) and create self.list_of_fits and self.fit """ # first model is just the mean response_term = [Term([LookupFactor(self.y)])] model_terms = [Term([])] # empty term is the intercept all_model_...
[ "Find", "the", "best", "model", "(", "fit", ")", "and", "create", "self", ".", "list_of_fits", "and", "self", ".", "fit" ]
opengridcc/opengrid
python
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/library/regression.py#L116-L155
[ "def", "_do_analysis_no_cross_validation", "(", "self", ")", ":", "# first model is just the mean", "response_term", "=", "[", "Term", "(", "[", "LookupFactor", "(", "self", ".", "y", ")", "]", ")", "]", "model_terms", "=", "[", "Term", "(", "[", "]", ")", ...
69b8da3c8fcea9300226c45ef0628cd6d4307651
train
MultiVarLinReg._do_analysis_cross_validation
Find the best model (fit) based on cross-valiation (leave one out)
opengrid/library/regression.py
def _do_analysis_cross_validation(self): """ Find the best model (fit) based on cross-valiation (leave one out) """ assert len(self.df) < 15, "Cross-validation is not implemented if your sample contains more than 15 datapoints" # initialization: first model is the mean, but com...
def _do_analysis_cross_validation(self): """ Find the best model (fit) based on cross-valiation (leave one out) """ assert len(self.df) < 15, "Cross-validation is not implemented if your sample contains more than 15 datapoints" # initialization: first model is the mean, but com...
[ "Find", "the", "best", "model", "(", "fit", ")", "based", "on", "cross", "-", "valiation", "(", "leave", "one", "out", ")" ]
opengridcc/opengrid
python
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/library/regression.py#L157-L219
[ "def", "_do_analysis_cross_validation", "(", "self", ")", ":", "assert", "len", "(", "self", ".", "df", ")", "<", "15", ",", "\"Cross-validation is not implemented if your sample contains more than 15 datapoints\"", "# initialization: first model is the mean, but compute cv correct...
69b8da3c8fcea9300226c45ef0628cd6d4307651
train
MultiVarLinReg._prune
If the fit contains statistically insignificant parameters, remove them. Returns a pruned fit where all parameters have p-values of the t-statistic below p_max Parameters ---------- fit: fm.ols fit object Can contain insignificant parameters p_max : float ...
opengrid/library/regression.py
def _prune(self, fit, p_max): """ If the fit contains statistically insignificant parameters, remove them. Returns a pruned fit where all parameters have p-values of the t-statistic below p_max Parameters ---------- fit: fm.ols fit object Can contain insignif...
def _prune(self, fit, p_max): """ If the fit contains statistically insignificant parameters, remove them. Returns a pruned fit where all parameters have p-values of the t-statistic below p_max Parameters ---------- fit: fm.ols fit object Can contain insignif...
[ "If", "the", "fit", "contains", "statistically", "insignificant", "parameters", "remove", "them", ".", "Returns", "a", "pruned", "fit", "where", "all", "parameters", "have", "p", "-", "values", "of", "the", "t", "-", "statistic", "below", "p_max" ]
opengridcc/opengrid
python
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/library/regression.py#L222-L272
[ "def", "_prune", "(", "self", ",", "fit", ",", "p_max", ")", ":", "def", "remove_from_model_desc", "(", "x", ",", "model_desc", ")", ":", "\"\"\"\n Return a model_desc without x\n \"\"\"", "rhs_termlist", "=", "[", "]", "for", "t", "in", "mod...
69b8da3c8fcea9300226c45ef0628cd6d4307651
train
MultiVarLinReg.find_best_rsquared
Return the best fit, based on rsquared
opengrid/library/regression.py
def find_best_rsquared(list_of_fits): """Return the best fit, based on rsquared""" res = sorted(list_of_fits, key=lambda x: x.rsquared) return res[-1]
def find_best_rsquared(list_of_fits): """Return the best fit, based on rsquared""" res = sorted(list_of_fits, key=lambda x: x.rsquared) return res[-1]
[ "Return", "the", "best", "fit", "based", "on", "rsquared" ]
opengridcc/opengrid
python
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/library/regression.py#L275-L278
[ "def", "find_best_rsquared", "(", "list_of_fits", ")", ":", "res", "=", "sorted", "(", "list_of_fits", ",", "key", "=", "lambda", "x", ":", "x", ".", "rsquared", ")", "return", "res", "[", "-", "1", "]" ]
69b8da3c8fcea9300226c45ef0628cd6d4307651
train
MultiVarLinReg.find_best_akaike
Return the best fit, based on Akaike information criterion
opengrid/library/regression.py
def find_best_akaike(list_of_fits): """Return the best fit, based on Akaike information criterion""" res = sorted(list_of_fits, key=lambda x: x.aic) return res[0]
def find_best_akaike(list_of_fits): """Return the best fit, based on Akaike information criterion""" res = sorted(list_of_fits, key=lambda x: x.aic) return res[0]
[ "Return", "the", "best", "fit", "based", "on", "Akaike", "information", "criterion" ]
opengridcc/opengrid
python
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/library/regression.py#L281-L284
[ "def", "find_best_akaike", "(", "list_of_fits", ")", ":", "res", "=", "sorted", "(", "list_of_fits", ",", "key", "=", "lambda", "x", ":", "x", ".", "aic", ")", "return", "res", "[", "0", "]" ]
69b8da3c8fcea9300226c45ef0628cd6d4307651
train
MultiVarLinReg.find_best_bic
Return the best fit, based on Akaike information criterion
opengrid/library/regression.py
def find_best_bic(list_of_fits): """Return the best fit, based on Akaike information criterion""" res = sorted(list_of_fits, key=lambda x: x.bic) return res[0]
def find_best_bic(list_of_fits): """Return the best fit, based on Akaike information criterion""" res = sorted(list_of_fits, key=lambda x: x.bic) return res[0]
[ "Return", "the", "best", "fit", "based", "on", "Akaike", "information", "criterion" ]
opengridcc/opengrid
python
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/library/regression.py#L287-L290
[ "def", "find_best_bic", "(", "list_of_fits", ")", ":", "res", "=", "sorted", "(", "list_of_fits", ",", "key", "=", "lambda", "x", ":", "x", ".", "bic", ")", "return", "res", "[", "0", "]" ]
69b8da3c8fcea9300226c45ef0628cd6d4307651
train
MultiVarLinReg._predict
Return a df with predictions and confidence interval Notes ----- The df will contain the following columns: - 'predicted': the model output - 'interval_u', 'interval_l': upper and lower confidence bounds. The result will depend on the following attributes of self: ...
opengrid/library/regression.py
def _predict(self, fit, df): """ Return a df with predictions and confidence interval Notes ----- The df will contain the following columns: - 'predicted': the model output - 'interval_u', 'interval_l': upper and lower confidence bounds. The result will ...
def _predict(self, fit, df): """ Return a df with predictions and confidence interval Notes ----- The df will contain the following columns: - 'predicted': the model output - 'interval_u', 'interval_l': upper and lower confidence bounds. The result will ...
[ "Return", "a", "df", "with", "predictions", "and", "confidence", "interval" ]
opengridcc/opengrid
python
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/library/regression.py#L292-L338
[ "def", "_predict", "(", "self", ",", "fit", ",", "df", ")", ":", "# Add model results to data as column 'predictions'", "df_res", "=", "df", ".", "copy", "(", ")", "if", "'Intercept'", "in", "fit", ".", "model", ".", "exog_names", ":", "df_res", "[", "'Inter...
69b8da3c8fcea9300226c45ef0628cd6d4307651
train
MultiVarLinReg.add_prediction
Add predictions and confidence interval to self.df self.df will contain the following columns: - 'predicted': the model output - 'interval_u', 'interval_l': upper and lower confidence bounds. Parameters ---------- None, but the result depends on the following attributes ...
opengrid/library/regression.py
def add_prediction(self): """ Add predictions and confidence interval to self.df self.df will contain the following columns: - 'predicted': the model output - 'interval_u', 'interval_l': upper and lower confidence bounds. Parameters ---------- None, but t...
def add_prediction(self): """ Add predictions and confidence interval to self.df self.df will contain the following columns: - 'predicted': the model output - 'interval_u', 'interval_l': upper and lower confidence bounds. Parameters ---------- None, but t...
[ "Add", "predictions", "and", "confidence", "interval", "to", "self", ".", "df", "self", ".", "df", "will", "contain", "the", "following", "columns", ":", "-", "predicted", ":", "the", "model", "output", "-", "interval_u", "interval_l", ":", "upper", "and", ...
opengridcc/opengrid
python
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/library/regression.py#L340-L359
[ "def", "add_prediction", "(", "self", ")", ":", "self", ".", "df", "=", "self", ".", "_predict", "(", "fit", "=", "self", ".", "fit", ",", "df", "=", "self", ".", "df", ")" ]
69b8da3c8fcea9300226c45ef0628cd6d4307651
train
MultiVarLinReg.plot
Plot measurements and predictions. By default, use self._fit and self.df, but both can be overruled by the arguments df and fit This function will detect if the data has been used for the modelling or not and will visualize them differently. Parameters ---------- model ...
opengrid/library/regression.py
def plot(self, model=True, bar_chart=True, **kwargs): """ Plot measurements and predictions. By default, use self._fit and self.df, but both can be overruled by the arguments df and fit This function will detect if the data has been used for the modelling or not and will visuali...
def plot(self, model=True, bar_chart=True, **kwargs): """ Plot measurements and predictions. By default, use self._fit and self.df, but both can be overruled by the arguments df and fit This function will detect if the data has been used for the modelling or not and will visuali...
[ "Plot", "measurements", "and", "predictions", "." ]
opengridcc/opengrid
python
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/library/regression.py#L361-L457
[ "def", "plot", "(", "self", ",", "model", "=", "True", ",", "bar_chart", "=", "True", ",", "*", "*", "kwargs", ")", ":", "plot_style", "(", ")", "figures", "=", "[", "]", "fit", "=", "kwargs", ".", "get", "(", "'fit'", ",", "self", ".", "fit", ...
69b8da3c8fcea9300226c45ef0628cd6d4307651