INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Creates matrix of shape |sentences|×|sentences|. | def _create_matrix(self, sentences, threshold, tf_metrics, idf_metrics):
"""
Creates matrix of shape |sentences|×|sentences|.
"""
# create matrix |sentences|×|sentences| filled with zeroes
sentences_count = len(sentences)
matrix = numpy.zeros((sentences_count, sentences_c... |
We compute idf-modified-cosine(sentence1, sentence2) here.
It's cosine similarity of these two sentences (vectors) A, B computed as cos(x, y) = A . B / (|A| . |B|)
Sentences are represented as vector TF*IDF metrics.
:param sentence1:
Iterable object where every item represents word ... | def cosine_similarity(sentence1, sentence2, tf1, tf2, idf_metrics):
"""
We compute idf-modified-cosine(sentence1, sentence2) here.
It's cosine similarity of these two sentences (vectors) A, B computed as cos(x, y) = A . B / (|A| . |B|)
Sentences are represented as vector TF*IDF metrics.
... |
Decorator for unicode compatible classes. Method ``__unicode__``
has to be implemented to work decorator as expected. | def unicode_compatible(cls):
"""
Decorator for unicode compatible classes. Method ``__unicode__``
has to be implemented to work decorator as expected.
"""
if PY3:
cls.__str__ = cls.__unicode__
cls.__bytes__ = lambda self: self.__str__().encode("utf-8")
else:
cls.__str__ =... |
Summary
Args:
weld_type (TYPE): Description
dim (TYPE): Description
Returns:
TYPE: Description | def to_weld_type(weld_type, dim):
"""Summary
Args:
weld_type (TYPE): Description
dim (TYPE): Description
Returns:
TYPE: Description
"""
for i in xrange(dim):
weld_type = WeldVec(weld_type)
return weld_type |
Summary
Args:
verbose (bool, optional): Description
decode (bool, optional): Description
Returns:
TYPE: Description | def evaluate(self, verbose=True, decode=True, passes=None, num_threads=1,
apply_experimental_transforms=False):
"""Summary
Args:
verbose (bool, optional): Description
decode (bool, optional): Description
Returns:
TYPE: Description
""... |
Generating a new weldarray from a given arr for self.
@arr: weldarray or ndarray.
- weldarray: Just update the weldobject with the context from the
weldarray.
- ndarray: Add the given array to the context of the weldobject.
Sets self.name and self.weldobj. | def _gen_weldobj(self, arr):
'''
Generating a new weldarray from a given arr for self.
@arr: weldarray or ndarray.
- weldarray: Just update the weldobject with the context from the
weldarray.
- ndarray: Add the given array to the context of the weldobject.
... |
Helper function for __array_ufunc__ that deals with the input/output checks and determines
if this should be relegated to numpy's implementation or not.
@input_args: args to __array_ufunc__
@outputs: specified outputs.
@ret: Bool, If weld supports the given input/output format or not - ... | def _process_ufunc_inputs(self, input_args, outputs):
'''
Helper function for __array_ufunc__ that deals with the input/output checks and determines
if this should be relegated to numpy's implementation or not.
@input_args: args to __array_ufunc__
@outputs: specified outputs.
... |
relegate responsibility of executing ufunc to numpy. | def _handle_numpy(self, ufunc, method, input_args, outputs, kwargs):
'''
relegate responsibility of executing ufunc to numpy.
'''
# Relegating the work to numpy. If input arg is weldarray, evaluate it,
# and convert to ndarray before passing to super()
for i, arg_ in enum... |
TODO: add description | def _handle_call(self, ufunc, input_args, outputs):
'''
TODO: add description
'''
# if output is not None, choose the first one - since we don't support any ops with
# multiple outputs.
if outputs: output = outputs[0]
else: output = None
# check for suppo... |
TODO: support for multidimensional arrays. | def _reduce_op(self, op, result=None):
'''
TODO: support for multidimensional arrays.
'''
template = 'result(for({arr},merger[{type}, {op}], |b, i, e| merge(b, e)))'
self.weldobj.weld_code = template.format(arr = self.weldobj.weld_code,
... |
TODO: describe.
TODO: For multi-dimensional case, might need extra work here if the reduction is being
performed only along a certain axis.
We force evaluation at the end of the reduction - weird errors if we don't. This seems
safer anyway.
np supports reduce only for binary ops. | def _handle_reduce(self, ufunc, input_args, outputs):
'''
TODO: describe.
TODO: For multi-dimensional case, might need extra work here if the reduction is being
performed only along a certain axis.
We force evaluation at the end of the reduction - weird errors if we don't. This s... |
Creating a new result weldarray from self. If self is view into a weldarray, then evaluate
the parent first as self would not be storing the ops that have been registered to it (only
base_array would store those). | def _get_result(self):
'''
Creating a new result weldarray from self. If self is view into a weldarray, then evaluate
the parent first as self would not be storing the ops that have been registered to it (only
base_array would store those).
'''
if self._weldarray_view:
... |
@unop: str, weld IR for the given function.
@result: output array.
Create a new array, and updates weldobj.weld_code with the code for
unop. | def _unary_op(self, unop, result=None):
'''
@unop: str, weld IR for the given function.
@result: output array.
Create a new array, and updates weldobj.weld_code with the code for
unop.
'''
def _update_array_unary_op(res, unop):
'''
@res: w... |
Helper function for _binary_op.
@other, scalar values (i32, i64, f32, f64).
@result: weldarray to store results in. | def _scalar_binary_op(self, other, binop, result):
'''
Helper function for _binary_op.
@other, scalar values (i32, i64, f32, f64).
@result: weldarray to store results in.
'''
template = 'map({arr}, |z: {type}| z {binop} {other}{suffix})'
weld_type = result._weld_t... |
@result: weldarray that is being updated
@other: weldarray or scalar. (result binop other)
@binop: str, operation to perform.
FIXME: the common indexing pattern for parent/child in _update_view might be too expensive
(uses if statements (unneccessary checks when updating child) and woul... | def _update_views_binary(self, result, other, binop):
'''
@result: weldarray that is being updated
@other: weldarray or scalar. (result binop other)
@binop: str, operation to perform.
FIXME: the common indexing pattern for parent/child in _update_view might be too expensive
... |
Summary
Returns:
TYPE: Description | def _get_column_names(self):
"""Summary
Returns:
TYPE: Description
"""
column_names = set()
for column in self.df:
column_names.add(column)
for column in self.unmaterialized_cols:
column_names.add(column)
return list(column_nam... |
Summary
Args:
grouping_column_name (TYPE): Description
Returns:
TYPE: Description | def filter(self, predicates):
"""Summary
Args:
grouping_column_name (TYPE): Description
Returns:
TYPE: Description
"""
tys = []
for col_name, raw_column in self.raw_columns.items():
dtype = str(raw_column.dtype)
if dtype =... |
Summary
Returns:
TYPE: Description | def evaluate(self, verbose=True, passes=None):
"""Summary
Returns:
TYPE: Description
"""
if self.is_pivot:
index, pivot, columns = LazyOpResult(
self.expr,
self.weld_type,
0
).evaluate(verbose=verbose, p... |
Sorts the values of this series | def sort_values(self, ascending=False):
""" Sorts the values of this series
"""
if self.index_type is not None:
index_expr = grizzly_impl.get_field(self.expr, 0)
column_expr = grizzly_impl.get_field(self.expr, 1)
zip_expr = grizzly_impl.zip_columns([index_exp... |
Summary
Returns:
TYPE: Description | def unique(self):
"""Summary
Returns:
TYPE: Description
"""
return SeriesWeld(
grizzly_impl.unique(
self.expr,
self.weld_type
),
self.weld_type,
self.df,
self.column_name
) |
Summary
Returns:
TYPE: Description | def lower(self):
"""Summary
Returns:
TYPE: Description
"""
# TODO : Bug in nested map operating on strings
# TODO : Check that self.weld_type is a string type
vectype = self.weld_type
if isinstance(vectype, WeldVec):
elem_type = vectype.el... |
Summary
Returns:
TYPE: Description | def contains(self, string):
"""Summary
Returns:
TYPE: Description
"""
# Check that self.weld_type is a string type
vectype = self.weld_type
if isinstance(vectype, WeldVec):
elem_type = vectype.elemType
if isinstance(elem_type, WeldChar):
... |
Summary
Returns:
TYPE: Description | def prod(self):
"""Summary
Returns:
TYPE: Description
"""
return LazyOpResult(
grizzly_impl.aggr(
self.expr,
"*",
1,
self.weld_type
),
self.weld_type,
0
) |
Summary
Returns:
TYPE: Description | def sum(self):
"""Summary
Returns:
TYPE: Description
"""
return LazyOpResult(
grizzly_impl.aggr(
self.expr,
"+",
0,
self.weld_type
),
self.weld_type,
0
) |
Summary
Returns:
TYPE: Description | def count(self):
"""Summary
Returns:
TYPE: Description
"""
return LazyOpResult(
grizzly_impl.count(
self.expr,
self.weld_type
),
WeldInt(),
0
) |
Summary
Args:
predicates (TYPE): Description
new_value (TYPE): Description
Returns:
TYPE: Description | def mask(self, predicates, new_value):
"""Summary
Args:
predicates (TYPE): Description
new_value (TYPE): Description
Returns:
TYPE: Description
"""
if isinstance(predicates, SeriesWeld):
predicates = predicates.expr
return... |
Summary
Args:
other (TYPE): Description
Returns:
TYPE: Description | def add(self, other):
"""Summary
Args:
other (TYPE): Description
Returns:
TYPE: Description
"""
if isinstance(other, SeriesWeld):
other = other.expr
return SeriesWeld(
grizzly_impl.element_wise_op(
self.exp... |
Summary
Args:
start (TYPE): Description
size (TYPE): Description
Returns:
TYPE: Description | def slice(self, start, size):
"""Summary
Args:
start (TYPE): Description
size (TYPE): Description
Returns:
TYPE: Description
"""
return SeriesWeld(
grizzly_impl.slice(
self.expr,
start,
... |
Update this context. if value is another context,
the names from that context are added into this one.
Otherwise, a new name is assigned and returned.
TODO tys for inputs. | def update(self, value, tys=None, override=True):
"""
Update this context. if value is another context,
the names from that context are added into this one.
Otherwise, a new name is assigned and returned.
TODO tys for inputs.
"""
if isinstance(value, WeldObject):... |
Summary
Returns:
TYPE: Description | def sum(self):
"""Summary
Returns:
TYPE: Description
"""
return GroupedDataFrameWeld(
grizzly_impl.groupby_sum(
self.columns,
self.column_types,
self.grouping_columns,
self.grouping_column_types
... |
Summary
Returns:
TYPE: Description | def sort_values(self, by, ascending=True):
"""Summary
Returns:
TYPE: Description
"""
if len(self.column_types) == 1:
vec_type = [WeldVec(self.column_types[0])]
else:
vec_type = [WeldVec(WeldStruct(self.column_types))]
if len(self.colu... |
Returns the sizes of the groups as series.
Returns:
TYPE: Description | def size(self):
"""Returns the sizes of the groups as series.
Returns:
TYPE: Description
"""
if len(self.grouping_column_types) > 1:
index_type = WeldStruct([self.grouping_column_types])
# Figure out what to use for multi-key index name
# ... |
Summary
Args:
column_name (TYPE): Description
column_type (TYPE): Description
index (TYPE): Description
Returns:
TYPE: Description | def get_column(self, column_name, column_type, index, verbose=True):
"""Summary
Args:
column_name (TYPE): Description
column_type (TYPE): Description
index (TYPE): Description
Returns:
TYPE: Description
"""
return LazyOpResult(
... |
Flattens the grouped data structure.
#TODO: The parameters here are meaningless
Flattens the grouped data structure.
What is returned is a DataFrameWeld object. | def reset_index(self, inplace=True, drop=True):
""" Flattens the grouped data structure.
#TODO: The parameters here are meaningless
Flattens the grouped data structure.
What is returned is a DataFrameWeld object.
"""
if len(self.column_types) == 1:
vectype =... |
Summary
Returns:
TYPE: Description | def evaluate(self, verbose=True, passes=None):
"""Summary
Returns:
TYPE: Description
"""
i = 0
exprs = []
for column_name in self.column_names:
if len(self.column_names) > 1:
index = "1.$%d" % i
else:
in... |
Standard deviation
Note that is by default normalizd by n - 1
# TODO, what does pandas do for multiple grouping columns?
# Currently we are just going to use one grouping column | def std(self):
"""Standard deviation
Note that is by default normalizd by n - 1
# TODO, what does pandas do for multiple grouping columns?
# Currently we are just going to use one grouping column
"""
std_expr = grizzly_impl.groupby_std(
[self.column],
... |
WeldContext is currently hidden from the Python API. We create a new
context per Weld run and give ownership of it to the resulting value.
NOTE: This can leak the context if the result of the Weld run is an
error. | def run(self, conf, arg, err):
"""
WeldContext is currently hidden from the Python API. We create a new
context per Weld run and give ownership of it to the resulting value.
NOTE: This can leak the context if the result of the Weld run is an
error.
"""
weld_conte... |
Computes the aggregate of elements in the array.
Args:
array (WeldObject / Numpy.ndarray): Input array to aggregate
op (str): Op string used to aggregate the array (+ / *)
initial_value (int): Initial value for aggregation
ty (WeldType): Type of each element in the input array
... | def aggr(array, op, initial_value, ty):
"""
Computes the aggregate of elements in the array.
Args:
array (WeldObject / Numpy.ndarray): Input array to aggregate
op (str): Op string used to aggregate the array (+ / *)
initial_value (int): Initial value for aggregation
ty (Weld... |
Computes the dot product between a matrix and a vector.
Args:
matrix (WeldObject / Numpy.ndarray): 2-d input matrix
vector (WeldObject / Numpy.ndarray): 1-d input vector
ty (WeldType): Type of each element in the input matrix and vector
Returns:
A WeldObject representing this c... | def dot(matrix, vector, matrix_ty, vector_ty):
"""
Computes the dot product between a matrix and a vector.
Args:
matrix (WeldObject / Numpy.ndarray): 2-d input matrix
vector (WeldObject / Numpy.ndarray): 1-d input vector
ty (WeldType): Type of each element in the input matrix and ve... |
Computes the per-element exponenet of the passed-in array.
Args:
array (WeldObject / Numpy.ndarray): Input array
ty (WeldType): Type of each element in the input array
Returns:
A WeldObject representing this computation | def exp(array, ty):
"""
Computes the per-element exponenet of the passed-in array.
Args:
array (WeldObject / Numpy.ndarray): Input array
ty (WeldType): Type of each element in the input array
Returns:
A WeldObject representing this computation
"""
weld_obj = WeldObject(... |
Checks the base address of the given arrays to figure out if child and par
have overlapping memory regions. | def is_view_child(view, par):
'''
Checks the base address of the given arrays to figure out if child and par
have overlapping memory regions.
'''
if par.base is None:
# par is the base array.
return view.base is par
else:
# par is a view of another array as well!
... |
Returns a dictionary of the Weld supported binary ops, with values being their Weld symbol. | def get_supported_binary_ops():
'''
Returns a dictionary of the Weld supported binary ops, with values being their Weld symbol.
'''
binary_ops = {}
binary_ops[np.add.__name__] = '+'
binary_ops[np.subtract.__name__] = '-'
binary_ops[np.multiply.__name__] = '*'
binary_ops[np.divide.__name_... |
Returns a dictionary of the Weld supported unary ops, with values being their Weld symbol. | def get_supported_unary_ops():
'''
Returns a dictionary of the Weld supported unary ops, with values being their Weld symbol.
'''
unary_ops = {}
unary_ops[np.exp.__name__] = 'exp'
unary_ops[np.log.__name__] = 'log'
unary_ops[np.sqrt.__name__] = 'sqrt'
return unary_ops |
Summary
Returns:
TYPE: Description | def ctype_class(self):
"""Summary
Returns:
TYPE: Description
"""
def vec_factory(elemType):
"""Summary
Args:
elemType (TYPE): Description
Returns:
TYPE: Description
"""
class Vec(St... |
Summary
Returns:
TYPE: Description | def ctype_class(self):
"""Summary
Returns:
TYPE: Description
"""
def struct_factory(field_types):
"""Summary
Args:
field_types (TYPE): Description
Returns:
TYPE: Description
"""
cla... |
Fetch a field from a struct expr | def get_field(expr, field):
""" Fetch a field from a struct expr
"""
weld_obj = WeldObject(encoder_, decoder_)
struct_var = weld_obj.update(expr)
if isinstance(expr, WeldObject):
struct_var = expr.obj_id
weld_obj.dependencies[struct_var] = expr
weld_template = """
%(stru... |
Returns a new array, with each element in the original array satisfying the
passed-in predicate set to `new_value`
Args:
array (WeldObject / Numpy.ndarray): Input array
predicates (WeldObject / Numpy.ndarray<bool>): Predicate set
new_value (WeldObject / Numpy.ndarray / str): mask value
... | def mask(array, predicates, new_value, ty):
"""
Returns a new array, with each element in the original array satisfying the
passed-in predicate set to `new_value`
Args:
array (WeldObject / Numpy.ndarray): Input array
predicates (WeldObject / Numpy.ndarray<bool>): Predicate set
n... |
Returns a new array, with each element in the original array satisfying the
passed-in predicate set to `new_value`
Args:
array (WeldObject / Numpy.ndarray): Input array
predicates (WeldObject / Numpy.ndarray<bool>): Predicate set
ty (WeldType): Type of each element in the input array
... | def filter(array, predicates, ty=None):
"""
Returns a new array, with each element in the original array satisfying the
passed-in predicate set to `new_value`
Args:
array (WeldObject / Numpy.ndarray): Input array
predicates (WeldObject / Numpy.ndarray<bool>): Predicate set
ty (W... |
Returns a new array, with each element in the original array satisfying the
passed-in predicate set to `new_value`
Args:
array (WeldObject / Numpy.ndarray): Input array
predicates (WeldObject / Numpy.ndarray<bool>): Predicate set
ty (WeldType): Type of each element in the input array
... | def pivot_filter(pivot_array, predicates, ty=None):
"""
Returns a new array, with each element in the original array satisfying the
passed-in predicate set to `new_value`
Args:
array (WeldObject / Numpy.ndarray): Input array
predicates (WeldObject / Numpy.ndarray<bool>): Predicate set
... |
Operation of series and other, element-wise (binary operator add)
Args:
array (WeldObject / Numpy.ndarray): Input array
other (WeldObject / Numpy.ndarray): Second Input array
op (str): Op string used to compute element-wise operation (+ / *)
ty (WeldType): Type of each element in th... | def element_wise_op(array, other, op, ty):
"""
Operation of series and other, element-wise (binary operator add)
Args:
array (WeldObject / Numpy.ndarray): Input array
other (WeldObject / Numpy.ndarray): Second Input array
op (str): Op string used to compute element-wise operation (+... |
Zip together multiple columns.
Args:
columns (WeldObject / Numpy.ndarray): lust of columns
Returns:
A WeldObject representing this computation | def unzip_columns(expr, column_types):
"""
Zip together multiple columns.
Args:
columns (WeldObject / Numpy.ndarray): lust of columns
Returns:
A WeldObject representing this computation
"""
weld_obj = WeldObject(encoder_, decoder_)
column_appenders = []
struct_fields = ... |
Sorts the vector.
If the field parameter is provided then the sort
operators on a vector of structs where the sort key
is the field of the struct.
Args:
expr (WeldObject)
field (Int) | def sort(expr, field = None, keytype=None, ascending=True):
"""
Sorts the vector.
If the field parameter is provided then the sort
operators on a vector of structs where the sort key
is the field of the struct.
Args:
expr (WeldObject)
field (Int)
"""
weld_obj = WeldObject(en... |
Slices the vector.
Args:
expr (WeldObject)
start (Long)
stop (Long) | def slice_vec(expr, start, stop):
"""
Slices the vector.
Args:
expr (WeldObject)
start (Long)
stop (Long)
"""
weld_obj = WeldObject(encoder_, decoder_)
expr_var = weld_obj.update(expr)
if isinstance(expr, WeldObject):
expr_var = expr.obj_id
weld_obj.depend... |
Zip together multiple columns.
Args:
columns (WeldObject / Numpy.ndarray): lust of columns
Returns:
A WeldObject representing this computation | def zip_columns(columns):
"""
Zip together multiple columns.
Args:
columns (WeldObject / Numpy.ndarray): lust of columns
Returns:
A WeldObject representing this computation
"""
weld_obj = WeldObject(encoder_, decoder_)
column_vars = []
for column in columns:
col... |
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 (=... | 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 (... |
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
... | 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... |
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:
... | 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... |
Computes a join on two tables | 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.... |
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. | 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_)
... |
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
... | 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.
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
... | 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.
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
... | 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.
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
... | 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... |
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... | 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... |
Computes the dot product between a matrix and a vector.
TODO: Make this more generic
Args:
matrix (TYPE): Description
vector (TYPE): Description | 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 a per-element exponent of the passed-in vector.
Args:
vector (TYPE): Description | 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... |
Summary
Returns:
TYPE: Description | def sum(self):
"""Summary
Returns:
TYPE: Description
"""
return NumpyArrayWeld(
numpy_weld_impl.aggr(
self.expr,
"+",
0,
self.weld_type
),
self.weld_type,
0
... |
Wrapper around weldarray - first create np.array and then convert to
weldarray. | def array(arr, *args, **kwargs):
'''
Wrapper around weldarray - first create np.array and then convert to
weldarray.
'''
return weldarray(np.array(arr, *args, **kwargs)) |
Summary
Args:
obj (TYPE): Description
Returns:
TYPE: Description
Raises:
Exception: Description | 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'... |
Converts Python object to Weld object.
Args:
obj: Python object that needs to be converted to Weld format
Returns:
Weld formatted object | 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 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:
... | 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
... |
Tries to remove temp files by filename wildcard path. | 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 |
Returns LooseVersion object of the Tesseract version | 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 the result of a Tesseract OCR run on the provided image to string | 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 pdf/hocr | 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 string containing box boundaries, confidences,
and other information. Requires Tesseract 3.05+ | 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... |
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. | 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 ... |
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
... | 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 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... | 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... |
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.
"... |
Serialize the data for a close frame.
This is the reverse of :func:`parse_close`. | 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") |
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... | 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:`... |
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 ... | 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`... |
Check that this frame contains acceptable values.
Raise :exc:`~websockets.exceptions.WebSocketProtocolError` if this
frame contains incorrect values. | 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... |
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... | 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 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... | 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 HTTP headers from ``stream``.
``stream`` is an :class:`~asyncio.StreamReader`.
Return a :class:`Headers` instance
Non-ASCII characters are represented with surrogate escapes. | 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 a single line from ``stream``.
``stream`` is an :class:`~asyncio.StreamReader`.
Return :class:`bytes` without CRLF. | 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... |
Return the (possibly empty) list of all values for a header. | 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 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. | 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] |
Parse optional whitespace from ``header`` at the given position.
Return the new position.
The whitespace itself isn't returned because it isn't significant. | 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 a token from ``header`` at the given position.
Return the token value and the new position.
Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs. | 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 quoted string from ``header`` at the given position.
Return the unquoted value and the new position.
Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs. | 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 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... | 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 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 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 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. | 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 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. | 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... |
Build an extension definition.
This is the reverse of :func:`parse_extension_item`. | 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.... |
Unparse a ``Sec-WebSocket-Extensions`` header.
This is the reverse of :func:`parse_extension`. | 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
) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.