id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
5,600
tBuLi/symfit
symfit/core/minimizers.py
BaseMinimizer._baseobjective_from_callable
def _baseobjective_from_callable(self, func, objective_type=MinimizeModel): """ symfit works with BaseObjective subclasses internally. If a custom objective is provided, we wrap it into a BaseObjective, MinimizeModel by default. :param func: Callable. If already an instance of B...
python
def _baseobjective_from_callable(self, func, objective_type=MinimizeModel): """ symfit works with BaseObjective subclasses internally. If a custom objective is provided, we wrap it into a BaseObjective, MinimizeModel by default. :param func: Callable. If already an instance of B...
[ "def", "_baseobjective_from_callable", "(", "self", ",", "func", ",", "objective_type", "=", "MinimizeModel", ")", ":", "if", "isinstance", "(", "func", ",", "BaseObjective", ")", "or", "(", "hasattr", "(", "func", ",", "'__self__'", ")", "and", "isinstance", ...
symfit works with BaseObjective subclasses internally. If a custom objective is provided, we wrap it into a BaseObjective, MinimizeModel by default. :param func: Callable. If already an instance of BaseObjective, it is returned immediately. If not, it is turned into a BaseObjective ...
[ "symfit", "works", "with", "BaseObjective", "subclasses", "internally", ".", "If", "a", "custom", "objective", "is", "provided", "we", "wrap", "it", "into", "a", "BaseObjective", "MinimizeModel", "by", "default", "." ]
759dd3d1d4270510d651f40b23dd26b1b10eee83
https://github.com/tBuLi/symfit/blob/759dd3d1d4270510d651f40b23dd26b1b10eee83/symfit/core/minimizers.py#L44-L74
5,601
tBuLi/symfit
symfit/core/minimizers.py
GradientMinimizer.resize_jac
def resize_jac(self, func): """ Removes values with identical indices to fixed parameters from the output of func. func has to return the jacobian of a scalar function. :param func: Jacobian function to be wrapped. Is assumed to be the jacobian of a scalar function. ...
python
def resize_jac(self, func): """ Removes values with identical indices to fixed parameters from the output of func. func has to return the jacobian of a scalar function. :param func: Jacobian function to be wrapped. Is assumed to be the jacobian of a scalar function. ...
[ "def", "resize_jac", "(", "self", ",", "func", ")", ":", "if", "func", "is", "None", ":", "return", "None", "@", "wraps", "(", "func", ")", "def", "resized", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "out", "=", "func", "(", "*", "ar...
Removes values with identical indices to fixed parameters from the output of func. func has to return the jacobian of a scalar function. :param func: Jacobian function to be wrapped. Is assumed to be the jacobian of a scalar function. :return: Jacobian corresponding to non-fixed par...
[ "Removes", "values", "with", "identical", "indices", "to", "fixed", "parameters", "from", "the", "output", "of", "func", ".", "func", "has", "to", "return", "the", "jacobian", "of", "a", "scalar", "function", "." ]
759dd3d1d4270510d651f40b23dd26b1b10eee83
https://github.com/tBuLi/symfit/blob/759dd3d1d4270510d651f40b23dd26b1b10eee83/symfit/core/minimizers.py#L143-L161
5,602
tBuLi/symfit
symfit/core/minimizers.py
HessianMinimizer.resize_hess
def resize_hess(self, func): """ Removes values with identical indices to fixed parameters from the output of func. func has to return the Hessian of a scalar function. :param func: Hessian function to be wrapped. Is assumed to be the Hessian of a scalar function. :r...
python
def resize_hess(self, func): """ Removes values with identical indices to fixed parameters from the output of func. func has to return the Hessian of a scalar function. :param func: Hessian function to be wrapped. Is assumed to be the Hessian of a scalar function. :r...
[ "def", "resize_hess", "(", "self", ",", "func", ")", ":", "if", "func", "is", "None", ":", "return", "None", "@", "wraps", "(", "func", ")", "def", "resized", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "out", "=", "func", "(", "*", "a...
Removes values with identical indices to fixed parameters from the output of func. func has to return the Hessian of a scalar function. :param func: Hessian function to be wrapped. Is assumed to be the Hessian of a scalar function. :return: Hessian corresponding to free parameters o...
[ "Removes", "values", "with", "identical", "indices", "to", "fixed", "parameters", "from", "the", "output", "of", "func", ".", "func", "has", "to", "return", "the", "Hessian", "of", "a", "scalar", "function", "." ]
759dd3d1d4270510d651f40b23dd26b1b10eee83
https://github.com/tBuLi/symfit/blob/759dd3d1d4270510d651f40b23dd26b1b10eee83/symfit/core/minimizers.py#L179-L197
5,603
tBuLi/symfit
symfit/core/minimizers.py
ScipyMinimize.execute
def execute(self, bounds=None, jacobian=None, hessian=None, constraints=None, **minimize_options): """ Calls the wrapped algorithm. :param bounds: The bounds for the parameters. Usually filled by :class:`~symfit.core.minimizers.BoundedMinimizer`. :param jacobian: The Jacobia...
python
def execute(self, bounds=None, jacobian=None, hessian=None, constraints=None, **minimize_options): """ Calls the wrapped algorithm. :param bounds: The bounds for the parameters. Usually filled by :class:`~symfit.core.minimizers.BoundedMinimizer`. :param jacobian: The Jacobia...
[ "def", "execute", "(", "self", ",", "bounds", "=", "None", ",", "jacobian", "=", "None", ",", "hessian", "=", "None", ",", "constraints", "=", "None", ",", "*", "*", "minimize_options", ")", ":", "ans", "=", "minimize", "(", "self", ".", "objective", ...
Calls the wrapped algorithm. :param bounds: The bounds for the parameters. Usually filled by :class:`~symfit.core.minimizers.BoundedMinimizer`. :param jacobian: The Jacobian. Usually filled by :class:`~symfit.core.minimizers.ScipyGradientMinimize`. :param \*\*minimize_op...
[ "Calls", "the", "wrapped", "algorithm", "." ]
759dd3d1d4270510d651f40b23dd26b1b10eee83
https://github.com/tBuLi/symfit/blob/759dd3d1d4270510d651f40b23dd26b1b10eee83/symfit/core/minimizers.py#L331-L353
5,604
tBuLi/symfit
symfit/core/minimizers.py
ScipyConstrainedMinimize.scipy_constraints
def scipy_constraints(self, constraints): """ Returns all constraints in a scipy compatible format. :param constraints: List of either MinimizeModel instances (this is what is provided by :class:`~symfit.core.fit.Fit`), :class:`~symfit.core.fit.BaseModel`, or :clas...
python
def scipy_constraints(self, constraints): """ Returns all constraints in a scipy compatible format. :param constraints: List of either MinimizeModel instances (this is what is provided by :class:`~symfit.core.fit.Fit`), :class:`~symfit.core.fit.BaseModel`, or :clas...
[ "def", "scipy_constraints", "(", "self", ",", "constraints", ")", ":", "cons", "=", "[", "]", "types", "=", "{", "# scipy only distinguishes two types of constraint.", "sympy", ".", "Eq", ":", "'eq'", ",", "sympy", ".", "Ge", ":", "'ineq'", ",", "}", "for", ...
Returns all constraints in a scipy compatible format. :param constraints: List of either MinimizeModel instances (this is what is provided by :class:`~symfit.core.fit.Fit`), :class:`~symfit.core.fit.BaseModel`, or :class:`sympy.core.relational.Relational`. :return: dict of...
[ "Returns", "all", "constraints", "in", "a", "scipy", "compatible", "format", "." ]
759dd3d1d4270510d651f40b23dd26b1b10eee83
https://github.com/tBuLi/symfit/blob/759dd3d1d4270510d651f40b23dd26b1b10eee83/symfit/core/minimizers.py#L477-L517
5,605
tBuLi/symfit
symfit/core/minimizers.py
TrustConstr._get_jacobian_hessian_strategy
def _get_jacobian_hessian_strategy(self): """ Figure out how to calculate the jacobian and hessian. Will return a tuple describing how best to calculate the jacobian and hessian, repectively. If None, it should be calculated using the available analytical method. :return...
python
def _get_jacobian_hessian_strategy(self): """ Figure out how to calculate the jacobian and hessian. Will return a tuple describing how best to calculate the jacobian and hessian, repectively. If None, it should be calculated using the available analytical method. :return...
[ "def", "_get_jacobian_hessian_strategy", "(", "self", ")", ":", "if", "self", ".", "jacobian", "is", "not", "None", "and", "self", ".", "hessian", "is", "None", ":", "jacobian", "=", "None", "hessian", "=", "'cs'", "elif", "self", ".", "jacobian", "is", ...
Figure out how to calculate the jacobian and hessian. Will return a tuple describing how best to calculate the jacobian and hessian, repectively. If None, it should be calculated using the available analytical method. :return: tuple of jacobian_method, hessian_method
[ "Figure", "out", "how", "to", "calculate", "the", "jacobian", "and", "hessian", ".", "Will", "return", "a", "tuple", "describing", "how", "best", "to", "calculate", "the", "jacobian", "and", "hessian", "repectively", ".", "If", "None", "it", "should", "be", ...
759dd3d1d4270510d651f40b23dd26b1b10eee83
https://github.com/tBuLi/symfit/blob/759dd3d1d4270510d651f40b23dd26b1b10eee83/symfit/core/minimizers.py#L566-L584
5,606
tBuLi/symfit
symfit/core/minimizers.py
BasinHopping.execute
def execute(self, **minimize_options): """ Execute the basin-hopping minimization. :param minimize_options: options to be passed on to :func:`scipy.optimize.basinhopping`. :return: :class:`symfit.core.fit_results.FitResults` """ if 'minimizer_kwargs' not in m...
python
def execute(self, **minimize_options): """ Execute the basin-hopping minimization. :param minimize_options: options to be passed on to :func:`scipy.optimize.basinhopping`. :return: :class:`symfit.core.fit_results.FitResults` """ if 'minimizer_kwargs' not in m...
[ "def", "execute", "(", "self", ",", "*", "*", "minimize_options", ")", ":", "if", "'minimizer_kwargs'", "not", "in", "minimize_options", ":", "minimize_options", "[", "'minimizer_kwargs'", "]", "=", "{", "}", "if", "'method'", "not", "in", "minimize_options", ...
Execute the basin-hopping minimization. :param minimize_options: options to be passed on to :func:`scipy.optimize.basinhopping`. :return: :class:`symfit.core.fit_results.FitResults`
[ "Execute", "the", "basin", "-", "hopping", "minimization", "." ]
759dd3d1d4270510d651f40b23dd26b1b10eee83
https://github.com/tBuLi/symfit/blob/759dd3d1d4270510d651f40b23dd26b1b10eee83/symfit/core/minimizers.py#L719-L748
5,607
tBuLi/symfit
symfit/core/printing.py
SymfitNumPyPrinter._print_MatMul
def _print_MatMul(self, expr): """ Matrix multiplication printer. The sympy one turns everything into a dot product without type-checking. """ from sympy import MatrixExpr links = [] for i, j in zip(expr.args[1:], expr.args[:-1]): if isinstance(i, Matr...
python
def _print_MatMul(self, expr): """ Matrix multiplication printer. The sympy one turns everything into a dot product without type-checking. """ from sympy import MatrixExpr links = [] for i, j in zip(expr.args[1:], expr.args[:-1]): if isinstance(i, Matr...
[ "def", "_print_MatMul", "(", "self", ",", "expr", ")", ":", "from", "sympy", "import", "MatrixExpr", "links", "=", "[", "]", "for", "i", ",", "j", "in", "zip", "(", "expr", ".", "args", "[", "1", ":", "]", ",", "expr", ".", "args", "[", ":", "-...
Matrix multiplication printer. The sympy one turns everything into a dot product without type-checking.
[ "Matrix", "multiplication", "printer", ".", "The", "sympy", "one", "turns", "everything", "into", "a", "dot", "product", "without", "type", "-", "checking", "." ]
759dd3d1d4270510d651f40b23dd26b1b10eee83
https://github.com/tBuLi/symfit/blob/759dd3d1d4270510d651f40b23dd26b1b10eee83/symfit/core/printing.py#L34-L50
5,608
tBuLi/symfit
symfit/contrib/interactive_guess/interactive_guess.py
InteractiveGuess.execute
def execute(self, **kwargs): """ Execute the interactive guessing procedure. :param show: Whether or not to show the figure. Useful for testing. :type show: bool :param block: Blocking call to matplotlib :type show: bool Any additional keyword arguments are pass...
python
def execute(self, **kwargs): """ Execute the interactive guessing procedure. :param show: Whether or not to show the figure. Useful for testing. :type show: bool :param block: Blocking call to matplotlib :type show: bool Any additional keyword arguments are pass...
[ "def", "execute", "(", "self", ",", "*", "*", "kwargs", ")", ":", "show", "=", "kwargs", ".", "pop", "(", "'show'", ")", "if", "show", ":", "# self.fig.show() # Apparently this does something else,", "# see https://github.com/matplotlib/matplotlib/issues/6138", "plt", ...
Execute the interactive guessing procedure. :param show: Whether or not to show the figure. Useful for testing. :type show: bool :param block: Blocking call to matplotlib :type show: bool Any additional keyword arguments are passed to matplotlib.pyplot.show().
[ "Execute", "the", "interactive", "guessing", "procedure", "." ]
759dd3d1d4270510d651f40b23dd26b1b10eee83
https://github.com/tBuLi/symfit/blob/759dd3d1d4270510d651f40b23dd26b1b10eee83/symfit/contrib/interactive_guess/interactive_guess.py#L99-L115
5,609
tBuLi/symfit
symfit/contrib/interactive_guess/interactive_guess.py
InteractiveGuess._set_up_sliders
def _set_up_sliders(self): """ Creates an slider for every parameter. """ i = 0.05 self._sliders = {} for param in self.model.params: if not param.fixed: axbg = 'lightgoldenrodyellow' else: axbg = 'red' #...
python
def _set_up_sliders(self): """ Creates an slider for every parameter. """ i = 0.05 self._sliders = {} for param in self.model.params: if not param.fixed: axbg = 'lightgoldenrodyellow' else: axbg = 'red' #...
[ "def", "_set_up_sliders", "(", "self", ")", ":", "i", "=", "0.05", "self", ".", "_sliders", "=", "{", "}", "for", "param", "in", "self", ".", "model", ".", "params", ":", "if", "not", "param", ".", "fixed", ":", "axbg", "=", "'lightgoldenrodyellow'", ...
Creates an slider for every parameter.
[ "Creates", "an", "slider", "for", "every", "parameter", "." ]
759dd3d1d4270510d651f40b23dd26b1b10eee83
https://github.com/tBuLi/symfit/blob/759dd3d1d4270510d651f40b23dd26b1b10eee83/symfit/contrib/interactive_guess/interactive_guess.py#L158-L186
5,610
tBuLi/symfit
symfit/contrib/interactive_guess/interactive_guess.py
InteractiveGuess._update_plot
def _update_plot(self, _): """Callback to redraw the plot to reflect the new parameter values.""" # Since all sliders call this same callback without saying who they are # I need to update the values for all parameters. This can be # circumvented by creating a seperate callback function ...
python
def _update_plot(self, _): """Callback to redraw the plot to reflect the new parameter values.""" # Since all sliders call this same callback without saying who they are # I need to update the values for all parameters. This can be # circumvented by creating a seperate callback function ...
[ "def", "_update_plot", "(", "self", ",", "_", ")", ":", "# Since all sliders call this same callback without saying who they are", "# I need to update the values for all parameters. This can be", "# circumvented by creating a seperate callback function for each", "# parameter.", "for", "pa...
Callback to redraw the plot to reflect the new parameter values.
[ "Callback", "to", "redraw", "the", "plot", "to", "reflect", "the", "new", "parameter", "values", "." ]
759dd3d1d4270510d651f40b23dd26b1b10eee83
https://github.com/tBuLi/symfit/blob/759dd3d1d4270510d651f40b23dd26b1b10eee83/symfit/contrib/interactive_guess/interactive_guess.py#L200-L209
5,611
tBuLi/symfit
symfit/contrib/interactive_guess/interactive_guess.py
InteractiveGuess._eval_model
def _eval_model(self): """ Convenience method for evaluating the model with the current parameters :return: named tuple with results """ arguments = self._x_grid.copy() arguments.update({param: param.value for param in self.model.params}) return self.model(**key2...
python
def _eval_model(self): """ Convenience method for evaluating the model with the current parameters :return: named tuple with results """ arguments = self._x_grid.copy() arguments.update({param: param.value for param in self.model.params}) return self.model(**key2...
[ "def", "_eval_model", "(", "self", ")", ":", "arguments", "=", "self", ".", "_x_grid", ".", "copy", "(", ")", "arguments", ".", "update", "(", "{", "param", ":", "param", ".", "value", "for", "param", "in", "self", ".", "model", ".", "params", "}", ...
Convenience method for evaluating the model with the current parameters :return: named tuple with results
[ "Convenience", "method", "for", "evaluating", "the", "model", "with", "the", "current", "parameters" ]
759dd3d1d4270510d651f40b23dd26b1b10eee83
https://github.com/tBuLi/symfit/blob/759dd3d1d4270510d651f40b23dd26b1b10eee83/symfit/contrib/interactive_guess/interactive_guess.py#L211-L219
5,612
tBuLi/symfit
symfit/contrib/interactive_guess/interactive_guess.py
Strategy2D.plot_data
def plot_data(self, proj, ax): """ Creates and plots a scatter plot of the original data. """ x, y = proj ax.scatter(self.ig.independent_data[x], self.ig.dependent_data[y], c='b')
python
def plot_data(self, proj, ax): """ Creates and plots a scatter plot of the original data. """ x, y = proj ax.scatter(self.ig.independent_data[x], self.ig.dependent_data[y], c='b')
[ "def", "plot_data", "(", "self", ",", "proj", ",", "ax", ")", ":", "x", ",", "y", "=", "proj", "ax", ".", "scatter", "(", "self", ".", "ig", ".", "independent_data", "[", "x", "]", ",", "self", ".", "ig", ".", "dependent_data", "[", "y", "]", "...
Creates and plots a scatter plot of the original data.
[ "Creates", "and", "plots", "a", "scatter", "plot", "of", "the", "original", "data", "." ]
759dd3d1d4270510d651f40b23dd26b1b10eee83
https://github.com/tBuLi/symfit/blob/759dd3d1d4270510d651f40b23dd26b1b10eee83/symfit/contrib/interactive_guess/interactive_guess.py#L241-L247
5,613
tBuLi/symfit
symfit/contrib/interactive_guess/interactive_guess.py
StrategynD.plot_data
def plot_data(self, proj, ax): """ Creates and plots the contourplot of the original data. This is done by evaluating the density of projected datapoints on a grid. """ x, y = proj x_data = self.ig.independent_data[x] y_data = self.ig.dependent_data[y] pro...
python
def plot_data(self, proj, ax): """ Creates and plots the contourplot of the original data. This is done by evaluating the density of projected datapoints on a grid. """ x, y = proj x_data = self.ig.independent_data[x] y_data = self.ig.dependent_data[y] pro...
[ "def", "plot_data", "(", "self", ",", "proj", ",", "ax", ")", ":", "x", ",", "y", "=", "proj", "x_data", "=", "self", ".", "ig", ".", "independent_data", "[", "x", "]", "y_data", "=", "self", ".", "ig", ".", "dependent_data", "[", "y", "]", "proj...
Creates and plots the contourplot of the original data. This is done by evaluating the density of projected datapoints on a grid.
[ "Creates", "and", "plots", "the", "contourplot", "of", "the", "original", "data", ".", "This", "is", "done", "by", "evaluating", "the", "density", "of", "projected", "datapoints", "on", "a", "grid", "." ]
759dd3d1d4270510d651f40b23dd26b1b10eee83
https://github.com/tBuLi/symfit/blob/759dd3d1d4270510d651f40b23dd26b1b10eee83/symfit/contrib/interactive_guess/interactive_guess.py#L278-L302
5,614
tBuLi/symfit
symfit/distributions.py
BivariateGaussian
def BivariateGaussian(x, y, mu_x, mu_y, sig_x, sig_y, rho): """ Bivariate Gaussian pdf. :param x: :class:`symfit.core.argument.Variable` :param y: :class:`symfit.core.argument.Variable` :param mu_x: :class:`symfit.core.argument.Parameter` for the mean of `x` :param mu_y: :class:`symfit.core.arg...
python
def BivariateGaussian(x, y, mu_x, mu_y, sig_x, sig_y, rho): """ Bivariate Gaussian pdf. :param x: :class:`symfit.core.argument.Variable` :param y: :class:`symfit.core.argument.Variable` :param mu_x: :class:`symfit.core.argument.Parameter` for the mean of `x` :param mu_y: :class:`symfit.core.arg...
[ "def", "BivariateGaussian", "(", "x", ",", "y", ",", "mu_x", ",", "mu_y", ",", "sig_x", ",", "sig_y", ",", "rho", ")", ":", "exponent", "=", "-", "1", "/", "(", "2", "*", "(", "1", "-", "rho", "**", "2", ")", ")", "exponent", "*=", "(", "x", ...
Bivariate Gaussian pdf. :param x: :class:`symfit.core.argument.Variable` :param y: :class:`symfit.core.argument.Variable` :param mu_x: :class:`symfit.core.argument.Parameter` for the mean of `x` :param mu_y: :class:`symfit.core.argument.Parameter` for the mean of `y` :param sig_x: :class:`symfit.co...
[ "Bivariate", "Gaussian", "pdf", "." ]
759dd3d1d4270510d651f40b23dd26b1b10eee83
https://github.com/tBuLi/symfit/blob/759dd3d1d4270510d651f40b23dd26b1b10eee83/symfit/distributions.py#L21-L40
5,615
tBuLi/symfit
symfit/core/fit.py
r_squared
def r_squared(model, fit_result, data): """ Calculates the coefficient of determination, R^2, for the fit. (Is not defined properly for vector valued functions.) :param model: Model instance :param fit_result: FitResults instance :param data: data with which the fit was performed. """ ...
python
def r_squared(model, fit_result, data): """ Calculates the coefficient of determination, R^2, for the fit. (Is not defined properly for vector valued functions.) :param model: Model instance :param fit_result: FitResults instance :param data: data with which the fit was performed. """ ...
[ "def", "r_squared", "(", "model", ",", "fit_result", ",", "data", ")", ":", "# First filter out the dependent vars", "y_is", "=", "[", "data", "[", "var", "]", "for", "var", "in", "model", "if", "var", "in", "data", "]", "x_is", "=", "[", "value", "for",...
Calculates the coefficient of determination, R^2, for the fit. (Is not defined properly for vector valued functions.) :param model: Model instance :param fit_result: FitResults instance :param data: data with which the fit was performed.
[ "Calculates", "the", "coefficient", "of", "determination", "R^2", "for", "the", "fit", "." ]
759dd3d1d4270510d651f40b23dd26b1b10eee83
https://github.com/tBuLi/symfit/blob/759dd3d1d4270510d651f40b23dd26b1b10eee83/symfit/core/fit.py#L1431-L1448
5,616
tBuLi/symfit
symfit/core/fit.py
_partial_subs
def _partial_subs(func, func2vars): """ Partial-bug proof substitution. Works by making the substitutions on the expression inside the derivative first, and then rebuilding the derivative safely without evaluating it using `_partial_diff`. """ if isinstance(func, sympy.Derivative): new_f...
python
def _partial_subs(func, func2vars): """ Partial-bug proof substitution. Works by making the substitutions on the expression inside the derivative first, and then rebuilding the derivative safely without evaluating it using `_partial_diff`. """ if isinstance(func, sympy.Derivative): new_f...
[ "def", "_partial_subs", "(", "func", ",", "func2vars", ")", ":", "if", "isinstance", "(", "func", ",", "sympy", ".", "Derivative", ")", ":", "new_func", "=", "func", ".", "expr", ".", "xreplace", "(", "func2vars", ")", "new_variables", "=", "tuple", "(",...
Partial-bug proof substitution. Works by making the substitutions on the expression inside the derivative first, and then rebuilding the derivative safely without evaluating it using `_partial_diff`.
[ "Partial", "-", "bug", "proof", "substitution", ".", "Works", "by", "making", "the", "substitutions", "on", "the", "expression", "inside", "the", "derivative", "first", "and", "then", "rebuilding", "the", "derivative", "safely", "without", "evaluating", "it", "u...
759dd3d1d4270510d651f40b23dd26b1b10eee83
https://github.com/tBuLi/symfit/blob/759dd3d1d4270510d651f40b23dd26b1b10eee83/symfit/core/fit.py#L1693-L1705
5,617
tBuLi/symfit
symfit/core/fit.py
BaseModel._init_from_dict
def _init_from_dict(self, model_dict): """ Initiate self from a model_dict to make sure attributes such as vars, params are available. Creates lists of alphabetically sorted independent vars, dependent vars, sigma vars, and parameters. Finally it creates a signature for this model so it...
python
def _init_from_dict(self, model_dict): """ Initiate self from a model_dict to make sure attributes such as vars, params are available. Creates lists of alphabetically sorted independent vars, dependent vars, sigma vars, and parameters. Finally it creates a signature for this model so it...
[ "def", "_init_from_dict", "(", "self", ",", "model_dict", ")", ":", "sort_func", "=", "lambda", "symbol", ":", "symbol", ".", "name", "self", ".", "model_dict", "=", "OrderedDict", "(", "sorted", "(", "model_dict", ".", "items", "(", ")", ",", "key", "="...
Initiate self from a model_dict to make sure attributes such as vars, params are available. Creates lists of alphabetically sorted independent vars, dependent vars, sigma vars, and parameters. Finally it creates a signature for this model so it can be called nicely. This signature only contains ...
[ "Initiate", "self", "from", "a", "model_dict", "to", "make", "sure", "attributes", "such", "as", "vars", "params", "are", "available", "." ]
759dd3d1d4270510d651f40b23dd26b1b10eee83
https://github.com/tBuLi/symfit/blob/759dd3d1d4270510d651f40b23dd26b1b10eee83/symfit/core/fit.py#L273-L310
5,618
tBuLi/symfit
symfit/core/fit.py
BaseModel.function_dict
def function_dict(self): """ Equivalent to ``self.model_dict``, but with all variables replaced by functions if applicable. Sorted by the evaluation order according to ``self.ordered_symbols``, not alphabetical like ``self.model_dict``! """ func_dict = OrderedDict() ...
python
def function_dict(self): """ Equivalent to ``self.model_dict``, but with all variables replaced by functions if applicable. Sorted by the evaluation order according to ``self.ordered_symbols``, not alphabetical like ``self.model_dict``! """ func_dict = OrderedDict() ...
[ "def", "function_dict", "(", "self", ")", ":", "func_dict", "=", "OrderedDict", "(", ")", "for", "var", ",", "func", "in", "self", ".", "vars_as_functions", ".", "items", "(", ")", ":", "expr", "=", "self", ".", "model_dict", "[", "var", "]", ".", "x...
Equivalent to ``self.model_dict``, but with all variables replaced by functions if applicable. Sorted by the evaluation order according to ``self.ordered_symbols``, not alphabetical like ``self.model_dict``!
[ "Equivalent", "to", "self", ".", "model_dict", "but", "with", "all", "variables", "replaced", "by", "functions", "if", "applicable", ".", "Sorted", "by", "the", "evaluation", "order", "according", "to", "self", ".", "ordered_symbols", "not", "alphabetical", "lik...
759dd3d1d4270510d651f40b23dd26b1b10eee83
https://github.com/tBuLi/symfit/blob/759dd3d1d4270510d651f40b23dd26b1b10eee83/symfit/core/fit.py#L340-L350
5,619
tBuLi/symfit
symfit/core/fit.py
TakesData._model_sanity
def _model_sanity(model): """ Perform some basic sanity checking on the model to warn users when they might be trying something ill advised. :param model: model instance. """ if not isinstance(model, ODEModel) and not isinstance(model, BaseNumericalModel): # ...
python
def _model_sanity(model): """ Perform some basic sanity checking on the model to warn users when they might be trying something ill advised. :param model: model instance. """ if not isinstance(model, ODEModel) and not isinstance(model, BaseNumericalModel): # ...
[ "def", "_model_sanity", "(", "model", ")", ":", "if", "not", "isinstance", "(", "model", ",", "ODEModel", ")", "and", "not", "isinstance", "(", "model", ",", "BaseNumericalModel", ")", ":", "# Such a model should probably not contain derivatives", "for", "var", ",...
Perform some basic sanity checking on the model to warn users when they might be trying something ill advised. :param model: model instance.
[ "Perform", "some", "basic", "sanity", "checking", "on", "the", "model", "to", "warn", "users", "when", "they", "might", "be", "trying", "something", "ill", "advised", "." ]
759dd3d1d4270510d651f40b23dd26b1b10eee83
https://github.com/tBuLi/symfit/blob/759dd3d1d4270510d651f40b23dd26b1b10eee83/symfit/core/fit.py#L1014-L1028
5,620
tBuLi/symfit
symfit/core/fit.py
TakesData.data_shapes
def data_shapes(self): """ Returns the shape of the data. In most cases this will be the same for all variables of the same type, if not this raises an Exception. Ignores variables which are set to None by design so we know that those None variables can be assumed to have the sa...
python
def data_shapes(self): """ Returns the shape of the data. In most cases this will be the same for all variables of the same type, if not this raises an Exception. Ignores variables which are set to None by design so we know that those None variables can be assumed to have the sa...
[ "def", "data_shapes", "(", "self", ")", ":", "independent_shapes", "=", "[", "]", "for", "var", ",", "data", "in", "self", ".", "independent_data", ".", "items", "(", ")", ":", "if", "data", "is", "not", "None", ":", "independent_shapes", ".", "append", ...
Returns the shape of the data. In most cases this will be the same for all variables of the same type, if not this raises an Exception. Ignores variables which are set to None by design so we know that those None variables can be assumed to have the same shape as the other in calculatio...
[ "Returns", "the", "shape", "of", "the", "data", ".", "In", "most", "cases", "this", "will", "be", "the", "same", "for", "all", "variables", "of", "the", "same", "type", "if", "not", "this", "raises", "an", "Exception", "." ]
759dd3d1d4270510d651f40b23dd26b1b10eee83
https://github.com/tBuLi/symfit/blob/759dd3d1d4270510d651f40b23dd26b1b10eee83/symfit/core/fit.py#L1067-L1088
5,621
tBuLi/symfit
symfit/core/fit.py
Fit.execute
def execute(self, **minimize_options): """ Execute the fit. :param minimize_options: keyword arguments to be passed to the specified minimizer. :return: FitResults instance """ minimizer_ans = self.minimizer.execute(**minimize_options) try: # to build...
python
def execute(self, **minimize_options): """ Execute the fit. :param minimize_options: keyword arguments to be passed to the specified minimizer. :return: FitResults instance """ minimizer_ans = self.minimizer.execute(**minimize_options) try: # to build...
[ "def", "execute", "(", "self", ",", "*", "*", "minimize_options", ")", ":", "minimizer_ans", "=", "self", ".", "minimizer", ".", "execute", "(", "*", "*", "minimize_options", ")", "try", ":", "# to build covariance matrix", "cov_matrix", "=", "minimizer_ans", ...
Execute the fit. :param minimize_options: keyword arguments to be passed to the specified minimizer. :return: FitResults instance
[ "Execute", "the", "fit", "." ]
759dd3d1d4270510d651f40b23dd26b1b10eee83
https://github.com/tBuLi/symfit/blob/759dd3d1d4270510d651f40b23dd26b1b10eee83/symfit/core/fit.py#L1407-L1428
5,622
tBuLi/symfit
symfit/core/fit.py
ODEModel.eval_components
def eval_components(self, *args, **kwargs): """ Numerically integrate the system of ODEs. :param args: Ordered arguments for the parameters and independent variables :param kwargs: Keyword arguments for the parameters and independent variables :return: ...
python
def eval_components(self, *args, **kwargs): """ Numerically integrate the system of ODEs. :param args: Ordered arguments for the parameters and independent variables :param kwargs: Keyword arguments for the parameters and independent variables :return: ...
[ "def", "eval_components", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "bound_arguments", "=", "self", ".", "__signature__", ".", "bind", "(", "*", "args", ",", "*", "*", "kwargs", ")", "t_like", "=", "bound_arguments", ".", "argum...
Numerically integrate the system of ODEs. :param args: Ordered arguments for the parameters and independent variables :param kwargs: Keyword arguments for the parameters and independent variables :return:
[ "Numerically", "integrate", "the", "system", "of", "ODEs", "." ]
759dd3d1d4270510d651f40b23dd26b1b10eee83
https://github.com/tBuLi/symfit/blob/759dd3d1d4270510d651f40b23dd26b1b10eee83/symfit/core/fit.py#L1590-L1660
5,623
tBuLi/symfit
symfit/core/operators.py
call
def call(self, *values, **named_values): """ Call an expression to evaluate it at the given point. Future improvements: I would like if func and signature could be buffered after the first call so they don't have to be recalculated for every call. However, nothing can be stored on self as sympy use...
python
def call(self, *values, **named_values): """ Call an expression to evaluate it at the given point. Future improvements: I would like if func and signature could be buffered after the first call so they don't have to be recalculated for every call. However, nothing can be stored on self as sympy use...
[ "def", "call", "(", "self", ",", "*", "values", ",", "*", "*", "named_values", ")", ":", "independent_vars", ",", "params", "=", "seperate_symbols", "(", "self", ")", "# Convert to a pythonic function", "func", "=", "sympy_to_py", "(", "self", ",", "independen...
Call an expression to evaluate it at the given point. Future improvements: I would like if func and signature could be buffered after the first call so they don't have to be recalculated for every call. However, nothing can be stored on self as sympy uses __slots__ for efficiency. This means there is no ...
[ "Call", "an", "expression", "to", "evaluate", "it", "at", "the", "given", "point", "." ]
759dd3d1d4270510d651f40b23dd26b1b10eee83
https://github.com/tBuLi/symfit/blob/759dd3d1d4270510d651f40b23dd26b1b10eee83/symfit/core/operators.py#L48-L92
5,624
tBuLi/symfit
symfit/core/fit_results.py
FitResults.variance
def variance(self, param): """ Return the variance in a given parameter as found by the fit. :param param: ``Parameter`` Instance. :return: Variance of ``param``. """ param_number = self.model.params.index(param) try: return self.covariance_matrix[par...
python
def variance(self, param): """ Return the variance in a given parameter as found by the fit. :param param: ``Parameter`` Instance. :return: Variance of ``param``. """ param_number = self.model.params.index(param) try: return self.covariance_matrix[par...
[ "def", "variance", "(", "self", ",", "param", ")", ":", "param_number", "=", "self", ".", "model", ".", "params", ".", "index", "(", "param", ")", "try", ":", "return", "self", ".", "covariance_matrix", "[", "param_number", ",", "param_number", "]", "exc...
Return the variance in a given parameter as found by the fit. :param param: ``Parameter`` Instance. :return: Variance of ``param``.
[ "Return", "the", "variance", "in", "a", "given", "parameter", "as", "found", "by", "the", "fit", "." ]
759dd3d1d4270510d651f40b23dd26b1b10eee83
https://github.com/tBuLi/symfit/blob/759dd3d1d4270510d651f40b23dd26b1b10eee83/symfit/core/fit_results.py#L99-L111
5,625
tBuLi/symfit
symfit/core/fit_results.py
FitResults.covariance
def covariance(self, param_1, param_2): """ Return the covariance between param_1 and param_2. :param param_1: ``Parameter`` Instance. :param param_2: ``Parameter`` Instance. :return: Covariance of the two params. """ param_1_number = self.model.params.index(para...
python
def covariance(self, param_1, param_2): """ Return the covariance between param_1 and param_2. :param param_1: ``Parameter`` Instance. :param param_2: ``Parameter`` Instance. :return: Covariance of the two params. """ param_1_number = self.model.params.index(para...
[ "def", "covariance", "(", "self", ",", "param_1", ",", "param_2", ")", ":", "param_1_number", "=", "self", ".", "model", ".", "params", ".", "index", "(", "param_1", ")", "param_2_number", "=", "self", ".", "model", ".", "params", ".", "index", "(", "p...
Return the covariance between param_1 and param_2. :param param_1: ``Parameter`` Instance. :param param_2: ``Parameter`` Instance. :return: Covariance of the two params.
[ "Return", "the", "covariance", "between", "param_1", "and", "param_2", "." ]
759dd3d1d4270510d651f40b23dd26b1b10eee83
https://github.com/tBuLi/symfit/blob/759dd3d1d4270510d651f40b23dd26b1b10eee83/symfit/core/fit_results.py#L113-L123
5,626
tBuLi/symfit
symfit/core/fit_results.py
FitResults._array_safe_dict_eq
def _array_safe_dict_eq(one_dict, other_dict): """ Dicts containing arrays are hard to compare. This function uses numpy.allclose to compare arrays, and does normal comparison for all other types. :param one_dict: :param other_dict: :return: bool """ ...
python
def _array_safe_dict_eq(one_dict, other_dict): """ Dicts containing arrays are hard to compare. This function uses numpy.allclose to compare arrays, and does normal comparison for all other types. :param one_dict: :param other_dict: :return: bool """ ...
[ "def", "_array_safe_dict_eq", "(", "one_dict", ",", "other_dict", ")", ":", "for", "key", "in", "one_dict", ":", "try", ":", "assert", "one_dict", "[", "key", "]", "==", "other_dict", "[", "key", "]", "except", "ValueError", "as", "err", ":", "# When deali...
Dicts containing arrays are hard to compare. This function uses numpy.allclose to compare arrays, and does normal comparison for all other types. :param one_dict: :param other_dict: :return: bool
[ "Dicts", "containing", "arrays", "are", "hard", "to", "compare", ".", "This", "function", "uses", "numpy", ".", "allclose", "to", "compare", "arrays", "and", "does", "normal", "comparison", "for", "all", "other", "types", "." ]
759dd3d1d4270510d651f40b23dd26b1b10eee83
https://github.com/tBuLi/symfit/blob/759dd3d1d4270510d651f40b23dd26b1b10eee83/symfit/core/fit_results.py#L126-L147
5,627
tBuLi/symfit
examples/callable_numerical_model.py
nonanalytical_func
def nonanalytical_func(x, a, b): """ This can be any pythonic function which should be fitted, typically one which is not easily written or supported as an analytical expression. """ # Do your non-trivial magic here. In this case a Piecewise, although this # could also be done symbolically. ...
python
def nonanalytical_func(x, a, b): """ This can be any pythonic function which should be fitted, typically one which is not easily written or supported as an analytical expression. """ # Do your non-trivial magic here. In this case a Piecewise, although this # could also be done symbolically. ...
[ "def", "nonanalytical_func", "(", "x", ",", "a", ",", "b", ")", ":", "# Do your non-trivial magic here. In this case a Piecewise, although this", "# could also be done symbolically.", "y", "=", "np", ".", "zeros_like", "(", "x", ")", "y", "[", "x", ">", "b", "]", ...
This can be any pythonic function which should be fitted, typically one which is not easily written or supported as an analytical expression.
[ "This", "can", "be", "any", "pythonic", "function", "which", "should", "be", "fitted", "typically", "one", "which", "is", "not", "easily", "written", "or", "supported", "as", "an", "analytical", "expression", "." ]
759dd3d1d4270510d651f40b23dd26b1b10eee83
https://github.com/tBuLi/symfit/blob/759dd3d1d4270510d651f40b23dd26b1b10eee83/examples/callable_numerical_model.py#L5-L15
5,628
mixcloud/django-experiments
experiments/admin.py
ExperimentAdmin.get_form
def get_form(self, request, obj=None, **kwargs): """ Add the default alternative dropdown with appropriate choices """ if obj: if obj.alternatives: choices = [(alternative, alternative) for alternative in obj.alternatives.keys()] else: ...
python
def get_form(self, request, obj=None, **kwargs): """ Add the default alternative dropdown with appropriate choices """ if obj: if obj.alternatives: choices = [(alternative, alternative) for alternative in obj.alternatives.keys()] else: ...
[ "def", "get_form", "(", "self", ",", "request", ",", "obj", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "obj", ":", "if", "obj", ".", "alternatives", ":", "choices", "=", "[", "(", "alternative", ",", "alternative", ")", "for", "alternative...
Add the default alternative dropdown with appropriate choices
[ "Add", "the", "default", "alternative", "dropdown", "with", "appropriate", "choices" ]
1f45e9f8a108b51e44918daa647269b2b8d43f1d
https://github.com/mixcloud/django-experiments/blob/1f45e9f8a108b51e44918daa647269b2b8d43f1d/experiments/admin.py#L46-L61
5,629
mixcloud/django-experiments
experiments/admin.py
ExperimentAdmin.set_alternative_view
def set_alternative_view(self, request): """ Allows the admin user to change their assigned alternative """ if not request.user.has_perm('experiments.change_experiment'): return HttpResponseForbidden() experiment_name = request.POST.get("experiment") alternat...
python
def set_alternative_view(self, request): """ Allows the admin user to change their assigned alternative """ if not request.user.has_perm('experiments.change_experiment'): return HttpResponseForbidden() experiment_name = request.POST.get("experiment") alternat...
[ "def", "set_alternative_view", "(", "self", ",", "request", ")", ":", "if", "not", "request", ".", "user", ".", "has_perm", "(", "'experiments.change_experiment'", ")", ":", "return", "HttpResponseForbidden", "(", ")", "experiment_name", "=", "request", ".", "PO...
Allows the admin user to change their assigned alternative
[ "Allows", "the", "admin", "user", "to", "change", "their", "assigned", "alternative" ]
1f45e9f8a108b51e44918daa647269b2b8d43f1d
https://github.com/mixcloud/django-experiments/blob/1f45e9f8a108b51e44918daa647269b2b8d43f1d/experiments/admin.py#L112-L128
5,630
mixcloud/django-experiments
experiments/admin.py
ExperimentAdmin.set_state_view
def set_state_view(self, request): """ Changes the experiment state """ if not request.user.has_perm('experiments.change_experiment'): return HttpResponseForbidden() try: state = int(request.POST.get("state", "")) except ValueError: re...
python
def set_state_view(self, request): """ Changes the experiment state """ if not request.user.has_perm('experiments.change_experiment'): return HttpResponseForbidden() try: state = int(request.POST.get("state", "")) except ValueError: re...
[ "def", "set_state_view", "(", "self", ",", "request", ")", ":", "if", "not", "request", ".", "user", ".", "has_perm", "(", "'experiments.change_experiment'", ")", ":", "return", "HttpResponseForbidden", "(", ")", "try", ":", "state", "=", "int", "(", "reques...
Changes the experiment state
[ "Changes", "the", "experiment", "state" ]
1f45e9f8a108b51e44918daa647269b2b8d43f1d
https://github.com/mixcloud/django-experiments/blob/1f45e9f8a108b51e44918daa647269b2b8d43f1d/experiments/admin.py#L130-L156
5,631
mixcloud/django-experiments
experiments/utils.py
WebUser.get_alternative
def get_alternative(self, experiment_name): """ Get the alternative this user is enrolled in. """ experiment = None try: # catching the KeyError instead of using .get so that the experiment is auto created if desired experiment = experiment_manager[experim...
python
def get_alternative(self, experiment_name): """ Get the alternative this user is enrolled in. """ experiment = None try: # catching the KeyError instead of using .get so that the experiment is auto created if desired experiment = experiment_manager[experim...
[ "def", "get_alternative", "(", "self", ",", "experiment_name", ")", ":", "experiment", "=", "None", "try", ":", "# catching the KeyError instead of using .get so that the experiment is auto created if desired", "experiment", "=", "experiment_manager", "[", "experiment_name", "]...
Get the alternative this user is enrolled in.
[ "Get", "the", "alternative", "this", "user", "is", "enrolled", "in", "." ]
1f45e9f8a108b51e44918daa647269b2b8d43f1d
https://github.com/mixcloud/django-experiments/blob/1f45e9f8a108b51e44918daa647269b2b8d43f1d/experiments/utils.py#L102-L119
5,632
mixcloud/django-experiments
experiments/utils.py
WebUser.set_alternative
def set_alternative(self, experiment_name, alternative): """Explicitly set the alternative the user is enrolled in for the specified experiment. This allows you to change a user between alternatives. The user and goal counts for the new alternative will be increment, but those for the old one w...
python
def set_alternative(self, experiment_name, alternative): """Explicitly set the alternative the user is enrolled in for the specified experiment. This allows you to change a user between alternatives. The user and goal counts for the new alternative will be increment, but those for the old one w...
[ "def", "set_alternative", "(", "self", ",", "experiment_name", ",", "alternative", ")", ":", "experiment", "=", "experiment_manager", ".", "get_experiment", "(", "experiment_name", ")", "if", "experiment", ":", "self", ".", "_set_enrollment", "(", "experiment", ",...
Explicitly set the alternative the user is enrolled in for the specified experiment. This allows you to change a user between alternatives. The user and goal counts for the new alternative will be increment, but those for the old one will not be decremented. The user will be enrolled in the exp...
[ "Explicitly", "set", "the", "alternative", "the", "user", "is", "enrolled", "in", "for", "the", "specified", "experiment", "." ]
1f45e9f8a108b51e44918daa647269b2b8d43f1d
https://github.com/mixcloud/django-experiments/blob/1f45e9f8a108b51e44918daa647269b2b8d43f1d/experiments/utils.py#L121-L129
5,633
mixcloud/django-experiments
experiments/utils.py
WebUser.goal
def goal(self, goal_name, count=1): """Record that this user has performed a particular goal This will update the goal stats for all experiments the user is enrolled in.""" for enrollment in self._get_all_enrollments(): if enrollment.experiment.is_displaying_alternatives(): ...
python
def goal(self, goal_name, count=1): """Record that this user has performed a particular goal This will update the goal stats for all experiments the user is enrolled in.""" for enrollment in self._get_all_enrollments(): if enrollment.experiment.is_displaying_alternatives(): ...
[ "def", "goal", "(", "self", ",", "goal_name", ",", "count", "=", "1", ")", ":", "for", "enrollment", "in", "self", ".", "_get_all_enrollments", "(", ")", ":", "if", "enrollment", ".", "experiment", ".", "is_displaying_alternatives", "(", ")", ":", "self", ...
Record that this user has performed a particular goal This will update the goal stats for all experiments the user is enrolled in.
[ "Record", "that", "this", "user", "has", "performed", "a", "particular", "goal" ]
1f45e9f8a108b51e44918daa647269b2b8d43f1d
https://github.com/mixcloud/django-experiments/blob/1f45e9f8a108b51e44918daa647269b2b8d43f1d/experiments/utils.py#L131-L137
5,634
mixcloud/django-experiments
experiments/utils.py
WebUser.incorporate
def incorporate(self, other_user): """Incorporate all enrollments and goals performed by the other user If this user is not enrolled in a given experiment, the results for the other user are incorporated. For experiments this user is already enrolled in the results of the other user are...
python
def incorporate(self, other_user): """Incorporate all enrollments and goals performed by the other user If this user is not enrolled in a given experiment, the results for the other user are incorporated. For experiments this user is already enrolled in the results of the other user are...
[ "def", "incorporate", "(", "self", ",", "other_user", ")", ":", "for", "enrollment", "in", "other_user", ".", "_get_all_enrollments", "(", ")", ":", "if", "not", "self", ".", "_get_enrollment", "(", "enrollment", ".", "experiment", ")", ":", "self", ".", "...
Incorporate all enrollments and goals performed by the other user If this user is not enrolled in a given experiment, the results for the other user are incorporated. For experiments this user is already enrolled in the results of the other user are discarded. This takes a relatively l...
[ "Incorporate", "all", "enrollments", "and", "goals", "performed", "by", "the", "other", "user" ]
1f45e9f8a108b51e44918daa647269b2b8d43f1d
https://github.com/mixcloud/django-experiments/blob/1f45e9f8a108b51e44918daa647269b2b8d43f1d/experiments/utils.py#L143-L158
5,635
mixcloud/django-experiments
experiments/utils.py
WebUser.visit
def visit(self): """Record that the user has visited the site for the purposes of retention tracking""" for enrollment in self._get_all_enrollments(): if enrollment.experiment.is_displaying_alternatives(): # We have two different goals, VISIT_NOT_PRESENT_COUNT_GOAL and VISIT_...
python
def visit(self): """Record that the user has visited the site for the purposes of retention tracking""" for enrollment in self._get_all_enrollments(): if enrollment.experiment.is_displaying_alternatives(): # We have two different goals, VISIT_NOT_PRESENT_COUNT_GOAL and VISIT_...
[ "def", "visit", "(", "self", ")", ":", "for", "enrollment", "in", "self", ".", "_get_all_enrollments", "(", ")", ":", "if", "enrollment", ".", "experiment", ".", "is_displaying_alternatives", "(", ")", ":", "# We have two different goals, VISIT_NOT_PRESENT_COUNT_GOAL ...
Record that the user has visited the site for the purposes of retention tracking
[ "Record", "that", "the", "user", "has", "visited", "the", "site", "for", "the", "purposes", "of", "retention", "tracking" ]
1f45e9f8a108b51e44918daa647269b2b8d43f1d
https://github.com/mixcloud/django-experiments/blob/1f45e9f8a108b51e44918daa647269b2b8d43f1d/experiments/utils.py#L160-L177
5,636
jgrassler/mkdocs-pandoc
mkdocs_pandoc/pandoc_converter.py
PandocConverter.flatten_pages
def flatten_pages(self, pages, level=1): """Recursively flattens pages data structure into a one-dimensional data structure""" flattened = [] for page in pages: if type(page) is list: flattened.append( { 'f...
python
def flatten_pages(self, pages, level=1): """Recursively flattens pages data structure into a one-dimensional data structure""" flattened = [] for page in pages: if type(page) is list: flattened.append( { 'f...
[ "def", "flatten_pages", "(", "self", ",", "pages", ",", "level", "=", "1", ")", ":", "flattened", "=", "[", "]", "for", "page", "in", "pages", ":", "if", "type", "(", "page", ")", "is", "list", ":", "flattened", ".", "append", "(", "{", "'file'", ...
Recursively flattens pages data structure into a one-dimensional data structure
[ "Recursively", "flattens", "pages", "data", "structure", "into", "a", "one", "-", "dimensional", "data", "structure" ]
11edfb90830325dca85bd0369bb8e2da8d6815b3
https://github.com/jgrassler/mkdocs-pandoc/blob/11edfb90830325dca85bd0369bb8e2da8d6815b3/mkdocs_pandoc/pandoc_converter.py#L68-L96
5,637
jgrassler/mkdocs-pandoc
mkdocs_pandoc/pandoc_converter.py
PandocConverter.convert
def convert(self): """User-facing conversion method. Returns pandoc document as a list of lines.""" lines = [] pages = self.flatten_pages(self.config['pages']) f_exclude = mkdocs_pandoc.filters.exclude.ExcludeFilter( exclude=self.exclude) f_include = mk...
python
def convert(self): """User-facing conversion method. Returns pandoc document as a list of lines.""" lines = [] pages = self.flatten_pages(self.config['pages']) f_exclude = mkdocs_pandoc.filters.exclude.ExcludeFilter( exclude=self.exclude) f_include = mk...
[ "def", "convert", "(", "self", ")", ":", "lines", "=", "[", "]", "pages", "=", "self", ".", "flatten_pages", "(", "self", ".", "config", "[", "'pages'", "]", ")", "f_exclude", "=", "mkdocs_pandoc", ".", "filters", ".", "exclude", ".", "ExcludeFilter", ...
User-facing conversion method. Returns pandoc document as a list of lines.
[ "User", "-", "facing", "conversion", "method", ".", "Returns", "pandoc", "document", "as", "a", "list", "of", "lines", "." ]
11edfb90830325dca85bd0369bb8e2da8d6815b3
https://github.com/jgrassler/mkdocs-pandoc/blob/11edfb90830325dca85bd0369bb8e2da8d6815b3/mkdocs_pandoc/pandoc_converter.py#L98-L167
5,638
jgrassler/mkdocs-pandoc
mkdocs_pandoc/filters/tables.py
TableFilter.blocks
def blocks(self, lines): """Groups lines into markdown blocks""" state = markdown.blockparser.State() blocks = [] # We use three states: start, ``` and '\n' state.set('start') # index of current block currblock = 0 for line in lines: line +=...
python
def blocks(self, lines): """Groups lines into markdown blocks""" state = markdown.blockparser.State() blocks = [] # We use three states: start, ``` and '\n' state.set('start') # index of current block currblock = 0 for line in lines: line +=...
[ "def", "blocks", "(", "self", ",", "lines", ")", ":", "state", "=", "markdown", ".", "blockparser", ".", "State", "(", ")", "blocks", "=", "[", "]", "# We use three states: start, ``` and '\\n'", "state", ".", "set", "(", "'start'", ")", "# index of current bl...
Groups lines into markdown blocks
[ "Groups", "lines", "into", "markdown", "blocks" ]
11edfb90830325dca85bd0369bb8e2da8d6815b3
https://github.com/jgrassler/mkdocs-pandoc/blob/11edfb90830325dca85bd0369bb8e2da8d6815b3/mkdocs_pandoc/filters/tables.py#L31-L57
5,639
jgrassler/mkdocs-pandoc
mkdocs_pandoc/filters/tables.py
TableFilter.ruler_line
def ruler_line(self, widths, linetype='-'): """Generates a ruler line for separating rows from each other""" cells = [] for w in widths: cells.append(linetype * (w+2)) return '+' + '+'.join(cells) + '+'
python
def ruler_line(self, widths, linetype='-'): """Generates a ruler line for separating rows from each other""" cells = [] for w in widths: cells.append(linetype * (w+2)) return '+' + '+'.join(cells) + '+'
[ "def", "ruler_line", "(", "self", ",", "widths", ",", "linetype", "=", "'-'", ")", ":", "cells", "=", "[", "]", "for", "w", "in", "widths", ":", "cells", ".", "append", "(", "linetype", "*", "(", "w", "+", "2", ")", ")", "return", "'+'", "+", "...
Generates a ruler line for separating rows from each other
[ "Generates", "a", "ruler", "line", "for", "separating", "rows", "from", "each", "other" ]
11edfb90830325dca85bd0369bb8e2da8d6815b3
https://github.com/jgrassler/mkdocs-pandoc/blob/11edfb90830325dca85bd0369bb8e2da8d6815b3/mkdocs_pandoc/filters/tables.py#L182-L187
5,640
jgrassler/mkdocs-pandoc
mkdocs_pandoc/filters/tables.py
TableFilter.wrap_row
def wrap_row(self, widths, row, width_default=None): """Wraps a single line table row into a fixed width, multi-line table.""" lines = [] longest = 0 # longest wrapped column in row if not width_default: width_default = self.width_default # Wrap column contents ...
python
def wrap_row(self, widths, row, width_default=None): """Wraps a single line table row into a fixed width, multi-line table.""" lines = [] longest = 0 # longest wrapped column in row if not width_default: width_default = self.width_default # Wrap column contents ...
[ "def", "wrap_row", "(", "self", ",", "widths", ",", "row", ",", "width_default", "=", "None", ")", ":", "lines", "=", "[", "]", "longest", "=", "0", "# longest wrapped column in row", "if", "not", "width_default", ":", "width_default", "=", "self", ".", "w...
Wraps a single line table row into a fixed width, multi-line table.
[ "Wraps", "a", "single", "line", "table", "row", "into", "a", "fixed", "width", "multi", "-", "line", "table", "." ]
11edfb90830325dca85bd0369bb8e2da8d6815b3
https://github.com/jgrassler/mkdocs-pandoc/blob/11edfb90830325dca85bd0369bb8e2da8d6815b3/mkdocs_pandoc/filters/tables.py#L190-L234
5,641
mishbahr/djangocms-forms
djangocms_forms/admin.py
FormSubmissionAdmin.render_export_form
def render_export_form(self, request, context, form_url=''): """ Render the from submission export form. """ context.update({ 'has_change_permission': self.has_change_permission(request), 'form_url': mark_safe(form_url), 'opts': self.opts, ...
python
def render_export_form(self, request, context, form_url=''): """ Render the from submission export form. """ context.update({ 'has_change_permission': self.has_change_permission(request), 'form_url': mark_safe(form_url), 'opts': self.opts, ...
[ "def", "render_export_form", "(", "self", ",", "request", ",", "context", ",", "form_url", "=", "''", ")", ":", "context", ".", "update", "(", "{", "'has_change_permission'", ":", "self", ".", "has_change_permission", "(", "request", ")", ",", "'form_url'", ...
Render the from submission export form.
[ "Render", "the", "from", "submission", "export", "form", "." ]
9d7a4ef9769fd5e1526921c084d6da7b8070a2c1
https://github.com/mishbahr/djangocms-forms/blob/9d7a4ef9769fd5e1526921c084d6da7b8070a2c1/djangocms_forms/admin.py#L260-L272
5,642
mishbahr/djangocms-forms
djangocms_forms/forms.py
FormDefinitionAdminForm.clean_form_template
def clean_form_template(self): """ Check if template exists """ form_template = self.cleaned_data.get('form_template', '') if form_template: try: get_template(form_template) except TemplateDoesNotExist: msg = _('Selected Form Template does ...
python
def clean_form_template(self): """ Check if template exists """ form_template = self.cleaned_data.get('form_template', '') if form_template: try: get_template(form_template) except TemplateDoesNotExist: msg = _('Selected Form Template does ...
[ "def", "clean_form_template", "(", "self", ")", ":", "form_template", "=", "self", ".", "cleaned_data", ".", "get", "(", "'form_template'", ",", "''", ")", "if", "form_template", ":", "try", ":", "get_template", "(", "form_template", ")", "except", "TemplateDo...
Check if template exists
[ "Check", "if", "template", "exists" ]
9d7a4ef9769fd5e1526921c084d6da7b8070a2c1
https://github.com/mishbahr/djangocms-forms/blob/9d7a4ef9769fd5e1526921c084d6da7b8070a2c1/djangocms_forms/forms.py#L75-L84
5,643
nikdon/pyEntropy
pyentrp/entropy.py
_embed
def _embed(x, order=3, delay=1): """Time-delay embedding. Parameters ---------- x : 1d-array, shape (n_times) Time series order : int Embedding dimension (order) delay : int Delay. Returns ------- embedded : ndarray, shape (n_times - (order - 1) * delay, ord...
python
def _embed(x, order=3, delay=1): """Time-delay embedding. Parameters ---------- x : 1d-array, shape (n_times) Time series order : int Embedding dimension (order) delay : int Delay. Returns ------- embedded : ndarray, shape (n_times - (order - 1) * delay, ord...
[ "def", "_embed", "(", "x", ",", "order", "=", "3", ",", "delay", "=", "1", ")", ":", "N", "=", "len", "(", "x", ")", "Y", "=", "np", ".", "empty", "(", "(", "order", ",", "N", "-", "(", "order", "-", "1", ")", "*", "delay", ")", ")", "f...
Time-delay embedding. Parameters ---------- x : 1d-array, shape (n_times) Time series order : int Embedding dimension (order) delay : int Delay. Returns ------- embedded : ndarray, shape (n_times - (order - 1) * delay, order) Embedded time-series.
[ "Time", "-", "delay", "embedding", "." ]
ae2bf71c2e5b6edb2e468ff52183b30acf7073e6
https://github.com/nikdon/pyEntropy/blob/ae2bf71c2e5b6edb2e468ff52183b30acf7073e6/pyentrp/entropy.py#L10-L31
5,644
nikdon/pyEntropy
pyentrp/entropy.py
util_pattern_space
def util_pattern_space(time_series, lag, dim): """Create a set of sequences with given lag and dimension Args: time_series: Vector or string of the sample data lag: Lag between beginning of sequences dim: Dimension (number of patterns) Returns: 2D array of vectors """ ...
python
def util_pattern_space(time_series, lag, dim): """Create a set of sequences with given lag and dimension Args: time_series: Vector or string of the sample data lag: Lag between beginning of sequences dim: Dimension (number of patterns) Returns: 2D array of vectors """ ...
[ "def", "util_pattern_space", "(", "time_series", ",", "lag", ",", "dim", ")", ":", "n", "=", "len", "(", "time_series", ")", "if", "lag", "*", "dim", ">", "n", ":", "raise", "Exception", "(", "'Result matrix exceeded size limit, try to change lag or dim.'", ")",...
Create a set of sequences with given lag and dimension Args: time_series: Vector or string of the sample data lag: Lag between beginning of sequences dim: Dimension (number of patterns) Returns: 2D array of vectors
[ "Create", "a", "set", "of", "sequences", "with", "given", "lag", "and", "dimension" ]
ae2bf71c2e5b6edb2e468ff52183b30acf7073e6
https://github.com/nikdon/pyEntropy/blob/ae2bf71c2e5b6edb2e468ff52183b30acf7073e6/pyentrp/entropy.py#L34-L57
5,645
nikdon/pyEntropy
pyentrp/entropy.py
util_granulate_time_series
def util_granulate_time_series(time_series, scale): """Extract coarse-grained time series Args: time_series: Time series scale: Scale factor Returns: Vector of coarse-grained time series with given scale factor """ n = len(time_series) b = int(np.fix(n / scale)) tem...
python
def util_granulate_time_series(time_series, scale): """Extract coarse-grained time series Args: time_series: Time series scale: Scale factor Returns: Vector of coarse-grained time series with given scale factor """ n = len(time_series) b = int(np.fix(n / scale)) tem...
[ "def", "util_granulate_time_series", "(", "time_series", ",", "scale", ")", ":", "n", "=", "len", "(", "time_series", ")", "b", "=", "int", "(", "np", ".", "fix", "(", "n", "/", "scale", ")", ")", "temp", "=", "np", ".", "reshape", "(", "time_series"...
Extract coarse-grained time series Args: time_series: Time series scale: Scale factor Returns: Vector of coarse-grained time series with given scale factor
[ "Extract", "coarse", "-", "grained", "time", "series" ]
ae2bf71c2e5b6edb2e468ff52183b30acf7073e6
https://github.com/nikdon/pyEntropy/blob/ae2bf71c2e5b6edb2e468ff52183b30acf7073e6/pyentrp/entropy.py#L64-L78
5,646
nikdon/pyEntropy
pyentrp/entropy.py
shannon_entropy
def shannon_entropy(time_series): """Return the Shannon Entropy of the sample data. Args: time_series: Vector or string of the sample data Returns: The Shannon Entropy as float value """ # Check if string if not isinstance(time_series, str): time_series = list(time_ser...
python
def shannon_entropy(time_series): """Return the Shannon Entropy of the sample data. Args: time_series: Vector or string of the sample data Returns: The Shannon Entropy as float value """ # Check if string if not isinstance(time_series, str): time_series = list(time_ser...
[ "def", "shannon_entropy", "(", "time_series", ")", ":", "# Check if string", "if", "not", "isinstance", "(", "time_series", ",", "str", ")", ":", "time_series", "=", "list", "(", "time_series", ")", "# Create a frequency data", "data_set", "=", "list", "(", "set...
Return the Shannon Entropy of the sample data. Args: time_series: Vector or string of the sample data Returns: The Shannon Entropy as float value
[ "Return", "the", "Shannon", "Entropy", "of", "the", "sample", "data", "." ]
ae2bf71c2e5b6edb2e468ff52183b30acf7073e6
https://github.com/nikdon/pyEntropy/blob/ae2bf71c2e5b6edb2e468ff52183b30acf7073e6/pyentrp/entropy.py#L81-L110
5,647
nikdon/pyEntropy
pyentrp/entropy.py
sample_entropy
def sample_entropy(time_series, sample_length, tolerance = None): """Calculates the sample entropy of degree m of a time_series. This method uses chebychev norm. It is quite fast for random data, but can be slower is there is structure in the input time series. Args: time_series: numpy arr...
python
def sample_entropy(time_series, sample_length, tolerance = None): """Calculates the sample entropy of degree m of a time_series. This method uses chebychev norm. It is quite fast for random data, but can be slower is there is structure in the input time series. Args: time_series: numpy arr...
[ "def", "sample_entropy", "(", "time_series", ",", "sample_length", ",", "tolerance", "=", "None", ")", ":", "#The code below follows the sample length convention of Ref [1] so:", "M", "=", "sample_length", "-", "1", "time_series", "=", "np", ".", "array", "(", "time_s...
Calculates the sample entropy of degree m of a time_series. This method uses chebychev norm. It is quite fast for random data, but can be slower is there is structure in the input time series. Args: time_series: numpy array of time series sample_length: length of longest template vecto...
[ "Calculates", "the", "sample", "entropy", "of", "degree", "m", "of", "a", "time_series", "." ]
ae2bf71c2e5b6edb2e468ff52183b30acf7073e6
https://github.com/nikdon/pyEntropy/blob/ae2bf71c2e5b6edb2e468ff52183b30acf7073e6/pyentrp/entropy.py#L113-L179
5,648
nikdon/pyEntropy
pyentrp/entropy.py
multiscale_entropy
def multiscale_entropy(time_series, sample_length, tolerance = None, maxscale = None): """Calculate the Multiscale Entropy of the given time series considering different time-scales of the time series. Args: time_series: Time series for analysis sample_length: Bandwidth or group of points ...
python
def multiscale_entropy(time_series, sample_length, tolerance = None, maxscale = None): """Calculate the Multiscale Entropy of the given time series considering different time-scales of the time series. Args: time_series: Time series for analysis sample_length: Bandwidth or group of points ...
[ "def", "multiscale_entropy", "(", "time_series", ",", "sample_length", ",", "tolerance", "=", "None", ",", "maxscale", "=", "None", ")", ":", "if", "tolerance", "is", "None", ":", "#we need to fix the tolerance at this level. If it remains 'None' it will be changed in call ...
Calculate the Multiscale Entropy of the given time series considering different time-scales of the time series. Args: time_series: Time series for analysis sample_length: Bandwidth or group of points tolerance: Tolerance (default = 0.1*std(time_series)) Returns: Vector cont...
[ "Calculate", "the", "Multiscale", "Entropy", "of", "the", "given", "time", "series", "considering", "different", "time", "-", "scales", "of", "the", "time", "series", "." ]
ae2bf71c2e5b6edb2e468ff52183b30acf7073e6
https://github.com/nikdon/pyEntropy/blob/ae2bf71c2e5b6edb2e468ff52183b30acf7073e6/pyentrp/entropy.py#L182-L209
5,649
nikdon/pyEntropy
pyentrp/entropy.py
permutation_entropy
def permutation_entropy(time_series, order=3, delay=1, normalize=False): """Permutation Entropy. Parameters ---------- time_series : list or np.array Time series order : int Order of permutation entropy delay : int Time delay normalize : bool If True, divide ...
python
def permutation_entropy(time_series, order=3, delay=1, normalize=False): """Permutation Entropy. Parameters ---------- time_series : list or np.array Time series order : int Order of permutation entropy delay : int Time delay normalize : bool If True, divide ...
[ "def", "permutation_entropy", "(", "time_series", ",", "order", "=", "3", ",", "delay", "=", "1", ",", "normalize", "=", "False", ")", ":", "x", "=", "np", ".", "array", "(", "time_series", ")", "hashmult", "=", "np", ".", "power", "(", "order", ",",...
Permutation Entropy. Parameters ---------- time_series : list or np.array Time series order : int Order of permutation entropy delay : int Time delay normalize : bool If True, divide by log2(factorial(m)) to normalize the entropy between 0 and 1. Otherwis...
[ "Permutation", "Entropy", "." ]
ae2bf71c2e5b6edb2e468ff52183b30acf7073e6
https://github.com/nikdon/pyEntropy/blob/ae2bf71c2e5b6edb2e468ff52183b30acf7073e6/pyentrp/entropy.py#L212-L278
5,650
nikdon/pyEntropy
pyentrp/entropy.py
multiscale_permutation_entropy
def multiscale_permutation_entropy(time_series, m, delay, scale): """Calculate the Multiscale Permutation Entropy Args: time_series: Time series for analysis m: Order of permutation entropy delay: Time delay scale: Scale factor Returns: Vector containing Multiscale ...
python
def multiscale_permutation_entropy(time_series, m, delay, scale): """Calculate the Multiscale Permutation Entropy Args: time_series: Time series for analysis m: Order of permutation entropy delay: Time delay scale: Scale factor Returns: Vector containing Multiscale ...
[ "def", "multiscale_permutation_entropy", "(", "time_series", ",", "m", ",", "delay", ",", "scale", ")", ":", "mspe", "=", "[", "]", "for", "i", "in", "range", "(", "scale", ")", ":", "coarse_time_series", "=", "util_granulate_time_series", "(", "time_series", ...
Calculate the Multiscale Permutation Entropy Args: time_series: Time series for analysis m: Order of permutation entropy delay: Time delay scale: Scale factor Returns: Vector containing Multiscale Permutation Entropy Reference: [1] Francesco Carlo Morabito ...
[ "Calculate", "the", "Multiscale", "Permutation", "Entropy" ]
ae2bf71c2e5b6edb2e468ff52183b30acf7073e6
https://github.com/nikdon/pyEntropy/blob/ae2bf71c2e5b6edb2e468ff52183b30acf7073e6/pyentrp/entropy.py#L281-L303
5,651
nikdon/pyEntropy
pyentrp/entropy.py
composite_multiscale_entropy
def composite_multiscale_entropy(time_series, sample_length, scale, tolerance=None): """Calculate the Composite Multiscale Entropy of the given time series. Args: time_series: Time series for analysis sample_length: Number of sequential points of the time series scale: Scale factor ...
python
def composite_multiscale_entropy(time_series, sample_length, scale, tolerance=None): """Calculate the Composite Multiscale Entropy of the given time series. Args: time_series: Time series for analysis sample_length: Number of sequential points of the time series scale: Scale factor ...
[ "def", "composite_multiscale_entropy", "(", "time_series", ",", "sample_length", ",", "scale", ",", "tolerance", "=", "None", ")", ":", "cmse", "=", "np", ".", "zeros", "(", "(", "1", ",", "scale", ")", ")", "for", "i", "in", "range", "(", "scale", ")"...
Calculate the Composite Multiscale Entropy of the given time series. Args: time_series: Time series for analysis sample_length: Number of sequential points of the time series scale: Scale factor tolerance: Tolerance (default = 0.1...0.2 * std(time_series)) Returns: Vect...
[ "Calculate", "the", "Composite", "Multiscale", "Entropy", "of", "the", "given", "time", "series", "." ]
ae2bf71c2e5b6edb2e468ff52183b30acf7073e6
https://github.com/nikdon/pyEntropy/blob/ae2bf71c2e5b6edb2e468ff52183b30acf7073e6/pyentrp/entropy.py#L307-L329
5,652
kyan001/ping3
ping3.py
ones_comp_sum16
def ones_comp_sum16(num1: int, num2: int) -> int: """Calculates the 1's complement sum for 16-bit numbers. Args: num1: 16-bit number. num2: 16-bit number. Returns: The calculated result. """ carry = 1 << 16 result = num1 + num2 return result if result < carry else ...
python
def ones_comp_sum16(num1: int, num2: int) -> int: """Calculates the 1's complement sum for 16-bit numbers. Args: num1: 16-bit number. num2: 16-bit number. Returns: The calculated result. """ carry = 1 << 16 result = num1 + num2 return result if result < carry else ...
[ "def", "ones_comp_sum16", "(", "num1", ":", "int", ",", "num2", ":", "int", ")", "->", "int", ":", "carry", "=", "1", "<<", "16", "result", "=", "num1", "+", "num2", "return", "result", "if", "result", "<", "carry", "else", "result", "+", "1", "-",...
Calculates the 1's complement sum for 16-bit numbers. Args: num1: 16-bit number. num2: 16-bit number. Returns: The calculated result.
[ "Calculates", "the", "1", "s", "complement", "sum", "for", "16", "-", "bit", "numbers", "." ]
fc9e8a4b828965a800036dfbd019e97114ad80b3
https://github.com/kyan001/ping3/blob/fc9e8a4b828965a800036dfbd019e97114ad80b3/ping3.py#L34-L47
5,653
kyan001/ping3
ping3.py
checksum
def checksum(source: bytes) -> int: """Calculates the checksum of the input bytes. RFC1071: https://tools.ietf.org/html/rfc1071 RFC792: https://tools.ietf.org/html/rfc792 Args: source: The input to be calculated. Returns: Calculated checksum. """ if len(source) % 2: # if ...
python
def checksum(source: bytes) -> int: """Calculates the checksum of the input bytes. RFC1071: https://tools.ietf.org/html/rfc1071 RFC792: https://tools.ietf.org/html/rfc792 Args: source: The input to be calculated. Returns: Calculated checksum. """ if len(source) % 2: # if ...
[ "def", "checksum", "(", "source", ":", "bytes", ")", "->", "int", ":", "if", "len", "(", "source", ")", "%", "2", ":", "# if the total length is odd, padding with one octet of zeros for computing the checksum", "source", "+=", "b'\\x00'", "sum", "=", "0", "for", "...
Calculates the checksum of the input bytes. RFC1071: https://tools.ietf.org/html/rfc1071 RFC792: https://tools.ietf.org/html/rfc792 Args: source: The input to be calculated. Returns: Calculated checksum.
[ "Calculates", "the", "checksum", "of", "the", "input", "bytes", "." ]
fc9e8a4b828965a800036dfbd019e97114ad80b3
https://github.com/kyan001/ping3/blob/fc9e8a4b828965a800036dfbd019e97114ad80b3/ping3.py#L50-L67
5,654
kyan001/ping3
ping3.py
send_one_ping
def send_one_ping(sock: socket, dest_addr: str, icmp_id: int, seq: int, size: int): """Sends one ping to the given destination. ICMP Header (bits): type (8), code (8), checksum (16), id (16), sequence (16) ICMP Payload: time (double), data ICMP Wikipedia: https://en.wikipedia.org/wiki/Internet_Control_...
python
def send_one_ping(sock: socket, dest_addr: str, icmp_id: int, seq: int, size: int): """Sends one ping to the given destination. ICMP Header (bits): type (8), code (8), checksum (16), id (16), sequence (16) ICMP Payload: time (double), data ICMP Wikipedia: https://en.wikipedia.org/wiki/Internet_Control_...
[ "def", "send_one_ping", "(", "sock", ":", "socket", ",", "dest_addr", ":", "str", ",", "icmp_id", ":", "int", ",", "seq", ":", "int", ",", "size", ":", "int", ")", ":", "try", ":", "dest_addr", "=", "socket", ".", "gethostbyname", "(", "dest_addr", "...
Sends one ping to the given destination. ICMP Header (bits): type (8), code (8), checksum (16), id (16), sequence (16) ICMP Payload: time (double), data ICMP Wikipedia: https://en.wikipedia.org/wiki/Internet_Control_Message_Protocol Args: sock: Socket. dest_addr: The destination addres...
[ "Sends", "one", "ping", "to", "the", "given", "destination", "." ]
fc9e8a4b828965a800036dfbd019e97114ad80b3
https://github.com/kyan001/ping3/blob/fc9e8a4b828965a800036dfbd019e97114ad80b3/ping3.py#L70-L100
5,655
kyan001/ping3
ping3.py
receive_one_ping
def receive_one_ping(sock: socket, icmp_id: int, seq: int, timeout: int) -> float or None: """Receives the ping from the socket. IP Header (bits): version (8), type of service (8), length (16), id (16), flags (16), time to live (8), protocol (8), checksum (16), source ip (32), destination ip (32). ICMP Pac...
python
def receive_one_ping(sock: socket, icmp_id: int, seq: int, timeout: int) -> float or None: """Receives the ping from the socket. IP Header (bits): version (8), type of service (8), length (16), id (16), flags (16), time to live (8), protocol (8), checksum (16), source ip (32), destination ip (32). ICMP Pac...
[ "def", "receive_one_ping", "(", "sock", ":", "socket", ",", "icmp_id", ":", "int", ",", "seq", ":", "int", ",", "timeout", ":", "int", ")", "->", "float", "or", "None", ":", "ip_header_slice", "=", "slice", "(", "0", ",", "struct", ".", "calcsize", "...
Receives the ping from the socket. IP Header (bits): version (8), type of service (8), length (16), id (16), flags (16), time to live (8), protocol (8), checksum (16), source ip (32), destination ip (32). ICMP Packet (bytes): IP Header (20), ICMP Header (8), ICMP Payload (*). Ping Wikipedia: https://en.wik...
[ "Receives", "the", "ping", "from", "the", "socket", "." ]
fc9e8a4b828965a800036dfbd019e97114ad80b3
https://github.com/kyan001/ping3/blob/fc9e8a4b828965a800036dfbd019e97114ad80b3/ping3.py#L103-L149
5,656
kyan001/ping3
ping3.py
ping
def ping(dest_addr: str, timeout: int = 4, unit: str = "s", src_addr: str = None, ttl: int = 64, seq: int = 0, size: int = 56) -> float or None: """ Send one ping to destination address with the given timeout. Args: dest_addr: The destination address, can be an IP address or a domain name. Ex. "192...
python
def ping(dest_addr: str, timeout: int = 4, unit: str = "s", src_addr: str = None, ttl: int = 64, seq: int = 0, size: int = 56) -> float or None: """ Send one ping to destination address with the given timeout. Args: dest_addr: The destination address, can be an IP address or a domain name. Ex. "192...
[ "def", "ping", "(", "dest_addr", ":", "str", ",", "timeout", ":", "int", "=", "4", ",", "unit", ":", "str", "=", "\"s\"", ",", "src_addr", ":", "str", "=", "None", ",", "ttl", ":", "int", "=", "64", ",", "seq", ":", "int", "=", "0", ",", "siz...
Send one ping to destination address with the given timeout. Args: dest_addr: The destination address, can be an IP address or a domain name. Ex. "192.168.1.1"/"example.com" timeout: Timeout in seconds. Default is 4s, same as Windows CMD. (default 4) unit: The unit of returned value. "s" fo...
[ "Send", "one", "ping", "to", "destination", "address", "with", "the", "given", "timeout", "." ]
fc9e8a4b828965a800036dfbd019e97114ad80b3
https://github.com/kyan001/ping3/blob/fc9e8a4b828965a800036dfbd019e97114ad80b3/ping3.py#L152-L188
5,657
kyan001/ping3
ping3.py
verbose_ping
def verbose_ping(dest_addr: str, count: int = 4, *args, **kwargs): """ Send pings to destination address with the given timeout and display the result. Args: dest_addr: The destination address. Ex. "192.168.1.1"/"example.com" count: How many pings should be sent. Default is 4, same as Windo...
python
def verbose_ping(dest_addr: str, count: int = 4, *args, **kwargs): """ Send pings to destination address with the given timeout and display the result. Args: dest_addr: The destination address. Ex. "192.168.1.1"/"example.com" count: How many pings should be sent. Default is 4, same as Windo...
[ "def", "verbose_ping", "(", "dest_addr", ":", "str", ",", "count", ":", "int", "=", "4", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "timeout", "=", "kwargs", ".", "get", "(", "\"timeout\"", ")", "src", "=", "kwargs", ".", "get", "(", "\...
Send pings to destination address with the given timeout and display the result. Args: dest_addr: The destination address. Ex. "192.168.1.1"/"example.com" count: How many pings should be sent. Default is 4, same as Windows CMD. (default 4) *args and **kwargs: And all the other arguments ava...
[ "Send", "pings", "to", "destination", "address", "with", "the", "given", "timeout", "and", "display", "the", "result", "." ]
fc9e8a4b828965a800036dfbd019e97114ad80b3
https://github.com/kyan001/ping3/blob/fc9e8a4b828965a800036dfbd019e97114ad80b3/ping3.py#L191-L215
5,658
barrust/pyspellchecker
spellchecker/spellchecker.py
SpellChecker.distance
def distance(self, val): """ set the distance parameter """ tmp = 2 try: int(val) if val > 0 and val <= 2: tmp = val except (ValueError, TypeError): pass self._distance = tmp
python
def distance(self, val): """ set the distance parameter """ tmp = 2 try: int(val) if val > 0 and val <= 2: tmp = val except (ValueError, TypeError): pass self._distance = tmp
[ "def", "distance", "(", "self", ",", "val", ")", ":", "tmp", "=", "2", "try", ":", "int", "(", "val", ")", "if", "val", ">", "0", "and", "val", "<=", "2", ":", "tmp", "=", "val", "except", "(", "ValueError", ",", "TypeError", ")", ":", "pass", ...
set the distance parameter
[ "set", "the", "distance", "parameter" ]
fa96024c0cdeba99e10e11060d5fd7aba796b271
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L79-L88
5,659
barrust/pyspellchecker
spellchecker/spellchecker.py
SpellChecker.export
def export(self, filepath, encoding="utf-8", gzipped=True): """ Export the word frequency list for import in the future Args: filepath (str): The filepath to the exported dictionary encoding (str): The encoding of the resulting output gzipped (bool):...
python
def export(self, filepath, encoding="utf-8", gzipped=True): """ Export the word frequency list for import in the future Args: filepath (str): The filepath to the exported dictionary encoding (str): The encoding of the resulting output gzipped (bool):...
[ "def", "export", "(", "self", ",", "filepath", ",", "encoding", "=", "\"utf-8\"", ",", "gzipped", "=", "True", ")", ":", "data", "=", "json", ".", "dumps", "(", "self", ".", "word_frequency", ".", "dictionary", ",", "sort_keys", "=", "True", ")", "writ...
Export the word frequency list for import in the future Args: filepath (str): The filepath to the exported dictionary encoding (str): The encoding of the resulting output gzipped (bool): Whether to gzip the dictionary or not
[ "Export", "the", "word", "frequency", "list", "for", "import", "in", "the", "future" ]
fa96024c0cdeba99e10e11060d5fd7aba796b271
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L100-L108
5,660
barrust/pyspellchecker
spellchecker/spellchecker.py
SpellChecker.word_probability
def word_probability(self, word, total_words=None): """ Calculate the probability of the `word` being the desired, correct word Args: word (str): The word for which the word probability is \ calculated total_words (int): The total number o...
python
def word_probability(self, word, total_words=None): """ Calculate the probability of the `word` being the desired, correct word Args: word (str): The word for which the word probability is \ calculated total_words (int): The total number o...
[ "def", "word_probability", "(", "self", ",", "word", ",", "total_words", "=", "None", ")", ":", "if", "total_words", "is", "None", ":", "total_words", "=", "self", ".", "_word_frequency", ".", "total_words", "return", "self", ".", "_word_frequency", ".", "di...
Calculate the probability of the `word` being the desired, correct word Args: word (str): The word for which the word probability is \ calculated total_words (int): The total number of words to use in the \ calculation; use the def...
[ "Calculate", "the", "probability", "of", "the", "word", "being", "the", "desired", "correct", "word" ]
fa96024c0cdeba99e10e11060d5fd7aba796b271
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L110-L124
5,661
barrust/pyspellchecker
spellchecker/spellchecker.py
SpellChecker.correction
def correction(self, word): """ The most probable correct spelling for the word Args: word (str): The word to correct Returns: str: The most likely candidate """ return max(self.candidates(word), key=self.word_probability)
python
def correction(self, word): """ The most probable correct spelling for the word Args: word (str): The word to correct Returns: str: The most likely candidate """ return max(self.candidates(word), key=self.word_probability)
[ "def", "correction", "(", "self", ",", "word", ")", ":", "return", "max", "(", "self", ".", "candidates", "(", "word", ")", ",", "key", "=", "self", ".", "word_probability", ")" ]
The most probable correct spelling for the word Args: word (str): The word to correct Returns: str: The most likely candidate
[ "The", "most", "probable", "correct", "spelling", "for", "the", "word" ]
fa96024c0cdeba99e10e11060d5fd7aba796b271
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L126-L133
5,662
barrust/pyspellchecker
spellchecker/spellchecker.py
SpellChecker.candidates
def candidates(self, word): """ Generate possible spelling corrections for the provided word up to an edit distance of two, if and only when needed Args: word (str): The word for which to calculate candidate spellings Returns: set: The set of ...
python
def candidates(self, word): """ Generate possible spelling corrections for the provided word up to an edit distance of two, if and only when needed Args: word (str): The word for which to calculate candidate spellings Returns: set: The set of ...
[ "def", "candidates", "(", "self", ",", "word", ")", ":", "if", "self", ".", "known", "(", "[", "word", "]", ")", ":", "# short-cut if word is correct already", "return", "{", "word", "}", "# get edit distance 1...", "res", "=", "[", "x", "for", "x", "in", ...
Generate possible spelling corrections for the provided word up to an edit distance of two, if and only when needed Args: word (str): The word for which to calculate candidate spellings Returns: set: The set of words that are possible candidates
[ "Generate", "possible", "spelling", "corrections", "for", "the", "provided", "word", "up", "to", "an", "edit", "distance", "of", "two", "if", "and", "only", "when", "needed" ]
fa96024c0cdeba99e10e11060d5fd7aba796b271
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L135-L155
5,663
barrust/pyspellchecker
spellchecker/spellchecker.py
SpellChecker.known
def known(self, words): """ The subset of `words` that appear in the dictionary of words Args: words (list): List of words to determine which are in the \ corpus Returns: set: The set of those words from the input that are in the \ ...
python
def known(self, words): """ The subset of `words` that appear in the dictionary of words Args: words (list): List of words to determine which are in the \ corpus Returns: set: The set of those words from the input that are in the \ ...
[ "def", "known", "(", "self", ",", "words", ")", ":", "tmp", "=", "[", "w", ".", "lower", "(", ")", "for", "w", "in", "words", "]", "return", "set", "(", "w", "for", "w", "in", "tmp", "if", "w", "in", "self", ".", "_word_frequency", ".", "dictio...
The subset of `words` that appear in the dictionary of words Args: words (list): List of words to determine which are in the \ corpus Returns: set: The set of those words from the input that are in the \ corpus
[ "The", "subset", "of", "words", "that", "appear", "in", "the", "dictionary", "of", "words" ]
fa96024c0cdeba99e10e11060d5fd7aba796b271
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L157-L172
5,664
barrust/pyspellchecker
spellchecker/spellchecker.py
SpellChecker.edit_distance_1
def edit_distance_1(self, word): """ Compute all strings that are one edit away from `word` using only the letters in the corpus Args: word (str): The word for which to calculate the edit distance Returns: set: The set of strings that are edit...
python
def edit_distance_1(self, word): """ Compute all strings that are one edit away from `word` using only the letters in the corpus Args: word (str): The word for which to calculate the edit distance Returns: set: The set of strings that are edit...
[ "def", "edit_distance_1", "(", "self", ",", "word", ")", ":", "word", "=", "word", ".", "lower", "(", ")", "if", "self", ".", "_check_if_should_check", "(", "word", ")", "is", "False", ":", "return", "{", "word", "}", "letters", "=", "self", ".", "_w...
Compute all strings that are one edit away from `word` using only the letters in the corpus Args: word (str): The word for which to calculate the edit distance Returns: set: The set of strings that are edit distance one from the \ prov...
[ "Compute", "all", "strings", "that", "are", "one", "edit", "away", "from", "word", "using", "only", "the", "letters", "in", "the", "corpus" ]
fa96024c0cdeba99e10e11060d5fd7aba796b271
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L186-L204
5,665
barrust/pyspellchecker
spellchecker/spellchecker.py
SpellChecker.edit_distance_2
def edit_distance_2(self, word): """ Compute all strings that are two edits away from `word` using only the letters in the corpus Args: word (str): The word for which to calculate the edit distance Returns: set: The set of strings that are edi...
python
def edit_distance_2(self, word): """ Compute all strings that are two edits away from `word` using only the letters in the corpus Args: word (str): The word for which to calculate the edit distance Returns: set: The set of strings that are edi...
[ "def", "edit_distance_2", "(", "self", ",", "word", ")", ":", "word", "=", "word", ".", "lower", "(", ")", "return", "[", "e2", "for", "e1", "in", "self", ".", "edit_distance_1", "(", "word", ")", "for", "e2", "in", "self", ".", "edit_distance_1", "(...
Compute all strings that are two edits away from `word` using only the letters in the corpus Args: word (str): The word for which to calculate the edit distance Returns: set: The set of strings that are edit distance two from the \ pro...
[ "Compute", "all", "strings", "that", "are", "two", "edits", "away", "from", "word", "using", "only", "the", "letters", "in", "the", "corpus" ]
fa96024c0cdeba99e10e11060d5fd7aba796b271
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L206-L218
5,666
barrust/pyspellchecker
spellchecker/spellchecker.py
SpellChecker.__edit_distance_alt
def __edit_distance_alt(self, words): """ Compute all strings that are 1 edits away from all the words using only the letters in the corpus Args: words (list): The words for which to calculate the edit distance Returns: set: The set of strings...
python
def __edit_distance_alt(self, words): """ Compute all strings that are 1 edits away from all the words using only the letters in the corpus Args: words (list): The words for which to calculate the edit distance Returns: set: The set of strings...
[ "def", "__edit_distance_alt", "(", "self", ",", "words", ")", ":", "words", "=", "[", "x", ".", "lower", "(", ")", "for", "x", "in", "words", "]", "return", "[", "e2", "for", "e1", "in", "words", "for", "e2", "in", "self", ".", "edit_distance_1", "...
Compute all strings that are 1 edits away from all the words using only the letters in the corpus Args: words (list): The words for which to calculate the edit distance Returns: set: The set of strings that are edit distance two from the \ ...
[ "Compute", "all", "strings", "that", "are", "1", "edits", "away", "from", "all", "the", "words", "using", "only", "the", "letters", "in", "the", "corpus" ]
fa96024c0cdeba99e10e11060d5fd7aba796b271
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L220-L230
5,667
barrust/pyspellchecker
spellchecker/spellchecker.py
WordFrequency.pop
def pop(self, key, default=None): """ Remove the key and return the associated value or default if not found Args: key (str): The key to remove default (obj): The value to return if key is not present """ return self._dictionary.pop(key.lower(), d...
python
def pop(self, key, default=None): """ Remove the key and return the associated value or default if not found Args: key (str): The key to remove default (obj): The value to return if key is not present """ return self._dictionary.pop(key.lower(), d...
[ "def", "pop", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "return", "self", ".", "_dictionary", ".", "pop", "(", "key", ".", "lower", "(", ")", ",", "default", ")" ]
Remove the key and return the associated value or default if not found Args: key (str): The key to remove default (obj): The value to return if key is not present
[ "Remove", "the", "key", "and", "return", "the", "associated", "value", "or", "default", "if", "not", "found" ]
fa96024c0cdeba99e10e11060d5fd7aba796b271
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L275-L282
5,668
barrust/pyspellchecker
spellchecker/spellchecker.py
WordFrequency.items
def items(self): """ Iterator over the words in the dictionary Yields: str: The next word in the dictionary int: The number of instances in the dictionary Note: This is the same as `dict.items()` """ for word in self._dictionary.ke...
python
def items(self): """ Iterator over the words in the dictionary Yields: str: The next word in the dictionary int: The number of instances in the dictionary Note: This is the same as `dict.items()` """ for word in self._dictionary.ke...
[ "def", "items", "(", "self", ")", ":", "for", "word", "in", "self", ".", "_dictionary", ".", "keys", "(", ")", ":", "yield", "word", ",", "self", ".", "_dictionary", "[", "word", "]" ]
Iterator over the words in the dictionary Yields: str: The next word in the dictionary int: The number of instances in the dictionary Note: This is the same as `dict.items()`
[ "Iterator", "over", "the", "words", "in", "the", "dictionary" ]
fa96024c0cdeba99e10e11060d5fd7aba796b271
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L350-L359
5,669
barrust/pyspellchecker
spellchecker/spellchecker.py
WordFrequency.load_dictionary
def load_dictionary(self, filename, encoding="utf-8"): """ Load in a pre-built word frequency list Args: filename (str): The filepath to the json (optionally gzipped) \ file to be loaded encoding (str): The encoding of the dictionary """ with ...
python
def load_dictionary(self, filename, encoding="utf-8"): """ Load in a pre-built word frequency list Args: filename (str): The filepath to the json (optionally gzipped) \ file to be loaded encoding (str): The encoding of the dictionary """ with ...
[ "def", "load_dictionary", "(", "self", ",", "filename", ",", "encoding", "=", "\"utf-8\"", ")", ":", "with", "load_file", "(", "filename", ",", "encoding", ")", "as", "data", ":", "self", ".", "_dictionary", ".", "update", "(", "json", ".", "loads", "(",...
Load in a pre-built word frequency list Args: filename (str): The filepath to the json (optionally gzipped) \ file to be loaded encoding (str): The encoding of the dictionary
[ "Load", "in", "a", "pre", "-", "built", "word", "frequency", "list" ]
fa96024c0cdeba99e10e11060d5fd7aba796b271
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L361-L370
5,670
barrust/pyspellchecker
spellchecker/spellchecker.py
WordFrequency.load_text_file
def load_text_file(self, filename, encoding="utf-8", tokenizer=None): """ Load in a text file from which to generate a word frequency list Args: filename (str): The filepath to the text file to be loaded encoding (str): The encoding of the text file t...
python
def load_text_file(self, filename, encoding="utf-8", tokenizer=None): """ Load in a text file from which to generate a word frequency list Args: filename (str): The filepath to the text file to be loaded encoding (str): The encoding of the text file t...
[ "def", "load_text_file", "(", "self", ",", "filename", ",", "encoding", "=", "\"utf-8\"", ",", "tokenizer", "=", "None", ")", ":", "with", "load_file", "(", "filename", ",", "encoding", "=", "encoding", ")", "as", "data", ":", "self", ".", "load_text", "...
Load in a text file from which to generate a word frequency list Args: filename (str): The filepath to the text file to be loaded encoding (str): The encoding of the text file tokenizer (function): The function to use to tokenize a string
[ "Load", "in", "a", "text", "file", "from", "which", "to", "generate", "a", "word", "frequency", "list" ]
fa96024c0cdeba99e10e11060d5fd7aba796b271
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L372-L381
5,671
barrust/pyspellchecker
spellchecker/spellchecker.py
WordFrequency.load_text
def load_text(self, text, tokenizer=None): """ Load text from which to generate a word frequency list Args: text (str): The text to be loaded tokenizer (function): The function to use to tokenize a string """ if tokenizer: words = [x.lower...
python
def load_text(self, text, tokenizer=None): """ Load text from which to generate a word frequency list Args: text (str): The text to be loaded tokenizer (function): The function to use to tokenize a string """ if tokenizer: words = [x.lower...
[ "def", "load_text", "(", "self", ",", "text", ",", "tokenizer", "=", "None", ")", ":", "if", "tokenizer", ":", "words", "=", "[", "x", ".", "lower", "(", ")", "for", "x", "in", "tokenizer", "(", "text", ")", "]", "else", ":", "words", "=", "self"...
Load text from which to generate a word frequency list Args: text (str): The text to be loaded tokenizer (function): The function to use to tokenize a string
[ "Load", "text", "from", "which", "to", "generate", "a", "word", "frequency", "list" ]
fa96024c0cdeba99e10e11060d5fd7aba796b271
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L383-L396
5,672
barrust/pyspellchecker
spellchecker/spellchecker.py
WordFrequency.load_words
def load_words(self, words): """ Load a list of words from which to generate a word frequency list Args: words (list): The list of words to be loaded """ self._dictionary.update([word.lower() for word in words]) self._update_dictionary()
python
def load_words(self, words): """ Load a list of words from which to generate a word frequency list Args: words (list): The list of words to be loaded """ self._dictionary.update([word.lower() for word in words]) self._update_dictionary()
[ "def", "load_words", "(", "self", ",", "words", ")", ":", "self", ".", "_dictionary", ".", "update", "(", "[", "word", ".", "lower", "(", ")", "for", "word", "in", "words", "]", ")", "self", ".", "_update_dictionary", "(", ")" ]
Load a list of words from which to generate a word frequency list Args: words (list): The list of words to be loaded
[ "Load", "a", "list", "of", "words", "from", "which", "to", "generate", "a", "word", "frequency", "list" ]
fa96024c0cdeba99e10e11060d5fd7aba796b271
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L398-L404
5,673
barrust/pyspellchecker
spellchecker/spellchecker.py
WordFrequency.remove_words
def remove_words(self, words): """ Remove a list of words from the word frequency list Args: words (list): The list of words to remove """ for word in words: self._dictionary.pop(word.lower()) self._update_dictionary()
python
def remove_words(self, words): """ Remove a list of words from the word frequency list Args: words (list): The list of words to remove """ for word in words: self._dictionary.pop(word.lower()) self._update_dictionary()
[ "def", "remove_words", "(", "self", ",", "words", ")", ":", "for", "word", "in", "words", ":", "self", ".", "_dictionary", ".", "pop", "(", "word", ".", "lower", "(", ")", ")", "self", ".", "_update_dictionary", "(", ")" ]
Remove a list of words from the word frequency list Args: words (list): The list of words to remove
[ "Remove", "a", "list", "of", "words", "from", "the", "word", "frequency", "list" ]
fa96024c0cdeba99e10e11060d5fd7aba796b271
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L413-L420
5,674
barrust/pyspellchecker
spellchecker/spellchecker.py
WordFrequency.remove
def remove(self, word): """ Remove a word from the word frequency list Args: word (str): The word to remove """ self._dictionary.pop(word.lower()) self._update_dictionary()
python
def remove(self, word): """ Remove a word from the word frequency list Args: word (str): The word to remove """ self._dictionary.pop(word.lower()) self._update_dictionary()
[ "def", "remove", "(", "self", ",", "word", ")", ":", "self", ".", "_dictionary", ".", "pop", "(", "word", ".", "lower", "(", ")", ")", "self", ".", "_update_dictionary", "(", ")" ]
Remove a word from the word frequency list Args: word (str): The word to remove
[ "Remove", "a", "word", "from", "the", "word", "frequency", "list" ]
fa96024c0cdeba99e10e11060d5fd7aba796b271
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L422-L428
5,675
barrust/pyspellchecker
spellchecker/spellchecker.py
WordFrequency.remove_by_threshold
def remove_by_threshold(self, threshold=5): """ Remove all words at, or below, the provided threshold Args: threshold (int): The threshold at which a word is to be \ removed """ keys = [x for x in self._dictionary.keys()] for key in keys: ...
python
def remove_by_threshold(self, threshold=5): """ Remove all words at, or below, the provided threshold Args: threshold (int): The threshold at which a word is to be \ removed """ keys = [x for x in self._dictionary.keys()] for key in keys: ...
[ "def", "remove_by_threshold", "(", "self", ",", "threshold", "=", "5", ")", ":", "keys", "=", "[", "x", "for", "x", "in", "self", ".", "_dictionary", ".", "keys", "(", ")", "]", "for", "key", "in", "keys", ":", "if", "self", ".", "_dictionary", "["...
Remove all words at, or below, the provided threshold Args: threshold (int): The threshold at which a word is to be \ removed
[ "Remove", "all", "words", "at", "or", "below", "the", "provided", "threshold" ]
fa96024c0cdeba99e10e11060d5fd7aba796b271
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L430-L440
5,676
barrust/pyspellchecker
spellchecker/spellchecker.py
WordFrequency._update_dictionary
def _update_dictionary(self): """ Update the word frequency object """ self._total_words = sum(self._dictionary.values()) self._unique_words = len(self._dictionary.keys()) self._letters = set() for key in self._dictionary: self._letters.update(key)
python
def _update_dictionary(self): """ Update the word frequency object """ self._total_words = sum(self._dictionary.values()) self._unique_words = len(self._dictionary.keys()) self._letters = set() for key in self._dictionary: self._letters.update(key)
[ "def", "_update_dictionary", "(", "self", ")", ":", "self", ".", "_total_words", "=", "sum", "(", "self", ".", "_dictionary", ".", "values", "(", ")", ")", "self", ".", "_unique_words", "=", "len", "(", "self", ".", "_dictionary", ".", "keys", "(", ")"...
Update the word frequency object
[ "Update", "the", "word", "frequency", "object" ]
fa96024c0cdeba99e10e11060d5fd7aba796b271
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L442-L448
5,677
barrust/pyspellchecker
spellchecker/utils.py
load_file
def load_file(filename, encoding): """ Context manager to handle opening a gzip or text file correctly and reading all the data Args: filename (str): The filename to open encoding (str): The file encoding to use Yields: str: The string data from the file ...
python
def load_file(filename, encoding): """ Context manager to handle opening a gzip or text file correctly and reading all the data Args: filename (str): The filename to open encoding (str): The file encoding to use Yields: str: The string data from the file ...
[ "def", "load_file", "(", "filename", ",", "encoding", ")", ":", "try", ":", "with", "gzip", ".", "open", "(", "filename", ",", "mode", "=", "\"rt\"", ")", "as", "fobj", ":", "yield", "fobj", ".", "read", "(", ")", "except", "(", "OSError", ",", "IO...
Context manager to handle opening a gzip or text file correctly and reading all the data Args: filename (str): The filename to open encoding (str): The file encoding to use Yields: str: The string data from the file read
[ "Context", "manager", "to", "handle", "opening", "a", "gzip", "or", "text", "file", "correctly", "and", "reading", "all", "the", "data" ]
fa96024c0cdeba99e10e11060d5fd7aba796b271
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/utils.py#L16-L31
5,678
barrust/pyspellchecker
spellchecker/utils.py
write_file
def write_file(filepath, encoding, gzipped, data): """ Write the data to file either as a gzip file or text based on the gzipped parameter Args: filepath (str): The filename to open encoding (str): The file encoding to use gzipped (bool): Whether the file should ...
python
def write_file(filepath, encoding, gzipped, data): """ Write the data to file either as a gzip file or text based on the gzipped parameter Args: filepath (str): The filename to open encoding (str): The file encoding to use gzipped (bool): Whether the file should ...
[ "def", "write_file", "(", "filepath", ",", "encoding", ",", "gzipped", ",", "data", ")", ":", "if", "gzipped", ":", "with", "gzip", ".", "open", "(", "filepath", ",", "\"wt\"", ")", "as", "fobj", ":", "fobj", ".", "write", "(", "data", ")", "else", ...
Write the data to file either as a gzip file or text based on the gzipped parameter Args: filepath (str): The filename to open encoding (str): The file encoding to use gzipped (bool): Whether the file should be gzipped or not data (str): The data to be wr...
[ "Write", "the", "data", "to", "file", "either", "as", "a", "gzip", "file", "or", "text", "based", "on", "the", "gzipped", "parameter" ]
fa96024c0cdeba99e10e11060d5fd7aba796b271
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/utils.py#L34-L51
5,679
merantix/picasso
picasso/examples/keras/model.py
KerasMNISTModel.preprocess
def preprocess(self, raw_inputs): """Convert images into the format required by our model. Our model requires that inputs be grayscale (mode 'L'), be resized to `MNIST_DIM`, and be represented as float32 numpy arrays in range [0, 1]. Args: raw_inputs (list of Images...
python
def preprocess(self, raw_inputs): """Convert images into the format required by our model. Our model requires that inputs be grayscale (mode 'L'), be resized to `MNIST_DIM`, and be represented as float32 numpy arrays in range [0, 1]. Args: raw_inputs (list of Images...
[ "def", "preprocess", "(", "self", ",", "raw_inputs", ")", ":", "image_arrays", "=", "[", "]", "for", "raw_im", "in", "raw_inputs", ":", "im", "=", "raw_im", ".", "convert", "(", "'L'", ")", "im", "=", "im", ".", "resize", "(", "MNIST_DIM", ",", "Imag...
Convert images into the format required by our model. Our model requires that inputs be grayscale (mode 'L'), be resized to `MNIST_DIM`, and be represented as float32 numpy arrays in range [0, 1]. Args: raw_inputs (list of Images): a list of PIL Image objects Retur...
[ "Convert", "images", "into", "the", "format", "required", "by", "our", "model", "." ]
d276b9b7408dd1032fe0ccb84ea9b6604a32915e
https://github.com/merantix/picasso/blob/d276b9b7408dd1032fe0ccb84ea9b6604a32915e/picasso/examples/keras/model.py#L23-L47
5,680
merantix/picasso
picasso/interfaces/rest.py
initialize_new_session
def initialize_new_session(): """Check session and initialize if necessary Before every request, check the user session. If no session exists, add one and provide temporary locations for images """ if 'image_uid_counter' in session and 'image_list' in session: logger.debug('images are alr...
python
def initialize_new_session(): """Check session and initialize if necessary Before every request, check the user session. If no session exists, add one and provide temporary locations for images """ if 'image_uid_counter' in session and 'image_list' in session: logger.debug('images are alr...
[ "def", "initialize_new_session", "(", ")", ":", "if", "'image_uid_counter'", "in", "session", "and", "'image_list'", "in", "session", ":", "logger", ".", "debug", "(", "'images are already being tracked'", ")", "else", ":", "# reset image list counter for the session", ...
Check session and initialize if necessary Before every request, check the user session. If no session exists, add one and provide temporary locations for images
[ "Check", "session", "and", "initialize", "if", "necessary" ]
d276b9b7408dd1032fe0ccb84ea9b6604a32915e
https://github.com/merantix/picasso/blob/d276b9b7408dd1032fe0ccb84ea9b6604a32915e/picasso/interfaces/rest.py#L42-L60
5,681
merantix/picasso
picasso/interfaces/rest.py
images
def images(): """Upload images via REST interface Check if file upload was successful and sanatize user input. TODO: return file URL instead of filename """ if request.method == 'POST': file_upload = request.files['file'] if file_upload: image = dict() imag...
python
def images(): """Upload images via REST interface Check if file upload was successful and sanatize user input. TODO: return file URL instead of filename """ if request.method == 'POST': file_upload = request.files['file'] if file_upload: image = dict() imag...
[ "def", "images", "(", ")", ":", "if", "request", ".", "method", "==", "'POST'", ":", "file_upload", "=", "request", ".", "files", "[", "'file'", "]", "if", "file_upload", ":", "image", "=", "dict", "(", ")", "image", "[", "'filename'", "]", "=", "sec...
Upload images via REST interface Check if file upload was successful and sanatize user input. TODO: return file URL instead of filename
[ "Upload", "images", "via", "REST", "interface" ]
d276b9b7408dd1032fe0ccb84ea9b6604a32915e
https://github.com/merantix/picasso/blob/d276b9b7408dd1032fe0ccb84ea9b6604a32915e/picasso/interfaces/rest.py#L84-L109
5,682
merantix/picasso
picasso/interfaces/rest.py
visualizers
def visualizers(): """Get a list of available visualizers Responses with a JSON list of available visualizers """ list_of_visualizers = [] for visualizer in get_visualizations(): list_of_visualizers.append({'name': visualizer}) return jsonify(visualizers=list_of_visualizers)
python
def visualizers(): """Get a list of available visualizers Responses with a JSON list of available visualizers """ list_of_visualizers = [] for visualizer in get_visualizations(): list_of_visualizers.append({'name': visualizer}) return jsonify(visualizers=list_of_visualizers)
[ "def", "visualizers", "(", ")", ":", "list_of_visualizers", "=", "[", "]", "for", "visualizer", "in", "get_visualizations", "(", ")", ":", "list_of_visualizers", ".", "append", "(", "{", "'name'", ":", "visualizer", "}", ")", "return", "jsonify", "(", "visua...
Get a list of available visualizers Responses with a JSON list of available visualizers
[ "Get", "a", "list", "of", "available", "visualizers" ]
d276b9b7408dd1032fe0ccb84ea9b6604a32915e
https://github.com/merantix/picasso/blob/d276b9b7408dd1032fe0ccb84ea9b6604a32915e/picasso/interfaces/rest.py#L113-L122
5,683
merantix/picasso
picasso/interfaces/rest.py
visualize
def visualize(): """Trigger a visualization via the REST API Takes a single image and generates the visualization data, returning the output exactly as given by the target visualization. """ session['settings'] = {} image_uid = request.args.get('image') vis_name = request.args.get('visual...
python
def visualize(): """Trigger a visualization via the REST API Takes a single image and generates the visualization data, returning the output exactly as given by the target visualization. """ session['settings'] = {} image_uid = request.args.get('image') vis_name = request.args.get('visual...
[ "def", "visualize", "(", ")", ":", "session", "[", "'settings'", "]", "=", "{", "}", "image_uid", "=", "request", ".", "args", ".", "get", "(", "'image'", ")", "vis_name", "=", "request", ".", "args", ".", "get", "(", "'visualizer'", ")", "vis", "=",...
Trigger a visualization via the REST API Takes a single image and generates the visualization data, returning the output exactly as given by the target visualization.
[ "Trigger", "a", "visualization", "via", "the", "REST", "API" ]
d276b9b7408dd1032fe0ccb84ea9b6604a32915e
https://github.com/merantix/picasso/blob/d276b9b7408dd1032fe0ccb84ea9b6604a32915e/picasso/interfaces/rest.py#L133-L166
5,684
merantix/picasso
picasso/interfaces/rest.py
reset
def reset(): """Delete the session and clear temporary directories """ shutil.rmtree(session['img_input_dir']) shutil.rmtree(session['img_output_dir']) session.clear() return jsonify(ok='true')
python
def reset(): """Delete the session and clear temporary directories """ shutil.rmtree(session['img_input_dir']) shutil.rmtree(session['img_output_dir']) session.clear() return jsonify(ok='true')
[ "def", "reset", "(", ")", ":", "shutil", ".", "rmtree", "(", "session", "[", "'img_input_dir'", "]", ")", "shutil", ".", "rmtree", "(", "session", "[", "'img_output_dir'", "]", ")", "session", ".", "clear", "(", ")", "return", "jsonify", "(", "ok", "="...
Delete the session and clear temporary directories
[ "Delete", "the", "session", "and", "clear", "temporary", "directories" ]
d276b9b7408dd1032fe0ccb84ea9b6604a32915e
https://github.com/merantix/picasso/blob/d276b9b7408dd1032fe0ccb84ea9b6604a32915e/picasso/interfaces/rest.py#L170-L177
5,685
merantix/picasso
picasso/visualizations/base.py
BaseVisualization.update_settings
def update_settings(self, settings): """Update the settings If a derived class has an ALLOWED_SETTINGS dict, we check here that incoming settings from the web app are allowed, and set the child properties as appropriate. """ def error_string(setting, setting_val): ...
python
def update_settings(self, settings): """Update the settings If a derived class has an ALLOWED_SETTINGS dict, we check here that incoming settings from the web app are allowed, and set the child properties as appropriate. """ def error_string(setting, setting_val): ...
[ "def", "update_settings", "(", "self", ",", "settings", ")", ":", "def", "error_string", "(", "setting", ",", "setting_val", ")", ":", "return", "(", "'{val} is not an acceptable value for '", "'parameter {param} for visualization'", "'{vis}.'", ")", ".", "format", "(...
Update the settings If a derived class has an ALLOWED_SETTINGS dict, we check here that incoming settings from the web app are allowed, and set the child properties as appropriate.
[ "Update", "the", "settings" ]
d276b9b7408dd1032fe0ccb84ea9b6604a32915e
https://github.com/merantix/picasso/blob/d276b9b7408dd1032fe0ccb84ea9b6604a32915e/picasso/visualizations/base.py#L60-L87
5,686
merantix/picasso
picasso/models/base.py
load_model
def load_model(model_cls_path, model_cls_name, model_load_args): """Get an instance of the described model. Args: model_cls_path: Path to the module in which the model class is defined. model_cls_name: Name of the model class. model_load_args: Dictionary of args to pass to t...
python
def load_model(model_cls_path, model_cls_name, model_load_args): """Get an instance of the described model. Args: model_cls_path: Path to the module in which the model class is defined. model_cls_name: Name of the model class. model_load_args: Dictionary of args to pass to t...
[ "def", "load_model", "(", "model_cls_path", ",", "model_cls_name", ",", "model_load_args", ")", ":", "spec", "=", "importlib", ".", "util", ".", "spec_from_file_location", "(", "'active_model'", ",", "model_cls_path", ")", "model_module", "=", "importlib", ".", "u...
Get an instance of the described model. Args: model_cls_path: Path to the module in which the model class is defined. model_cls_name: Name of the model class. model_load_args: Dictionary of args to pass to the `load` method of the model instance. Returns: ...
[ "Get", "an", "instance", "of", "the", "described", "model", "." ]
d276b9b7408dd1032fe0ccb84ea9b6604a32915e
https://github.com/merantix/picasso/blob/d276b9b7408dd1032fe0ccb84ea9b6604a32915e/picasso/models/base.py#L18-L42
5,687
merantix/picasso
picasso/models/base.py
BaseModel.decode_prob
def decode_prob(self, class_probabilities): """Given predicted class probabilites for a set of examples, annotate each logit with a class name. By default, we name each class using its index in the logits array. Args: class_probabilities (array): Class probabilities as outp...
python
def decode_prob(self, class_probabilities): """Given predicted class probabilites for a set of examples, annotate each logit with a class name. By default, we name each class using its index in the logits array. Args: class_probabilities (array): Class probabilities as outp...
[ "def", "decode_prob", "(", "self", ",", "class_probabilities", ")", ":", "results", "=", "[", "]", "for", "row", "in", "class_probabilities", ":", "entries", "=", "[", "]", "for", "i", ",", "prob", "in", "enumerate", "(", "row", ")", ":", "entries", "....
Given predicted class probabilites for a set of examples, annotate each logit with a class name. By default, we name each class using its index in the logits array. Args: class_probabilities (array): Class probabilities as output by `self.predict`, i.e., a numpy arr...
[ "Given", "predicted", "class", "probabilites", "for", "a", "set", "of", "examples", "annotate", "each", "logit", "with", "a", "class", "name", "." ]
d276b9b7408dd1032fe0ccb84ea9b6604a32915e
https://github.com/merantix/picasso/blob/d276b9b7408dd1032fe0ccb84ea9b6604a32915e/picasso/models/base.py#L174-L210
5,688
merantix/picasso
picasso/utils.py
_get_visualization_classes
def _get_visualization_classes(): """Import visualizations classes dynamically """ visualization_attr = vars(import_module('picasso.visualizations')) visualization_submodules = [ visualization_attr[x] for x in visualization_attr if isinstance(visualization_attr[x], ModuleType)] ...
python
def _get_visualization_classes(): """Import visualizations classes dynamically """ visualization_attr = vars(import_module('picasso.visualizations')) visualization_submodules = [ visualization_attr[x] for x in visualization_attr if isinstance(visualization_attr[x], ModuleType)] ...
[ "def", "_get_visualization_classes", "(", ")", ":", "visualization_attr", "=", "vars", "(", "import_module", "(", "'picasso.visualizations'", ")", ")", "visualization_submodules", "=", "[", "visualization_attr", "[", "x", "]", "for", "x", "in", "visualization_attr", ...
Import visualizations classes dynamically
[ "Import", "visualizations", "classes", "dynamically" ]
d276b9b7408dd1032fe0ccb84ea9b6604a32915e
https://github.com/merantix/picasso/blob/d276b9b7408dd1032fe0ccb84ea9b6604a32915e/picasso/utils.py#L32-L49
5,689
merantix/picasso
picasso/utils.py
get_model
def get_model(): """Get the NN model that's being analyzed from the request context. Put the model in the request context if it is not yet there. Returns: instance of :class:`.models.model.Model` or derived class """ if not hasattr(g, 'model'): g.model = load_model(current_...
python
def get_model(): """Get the NN model that's being analyzed from the request context. Put the model in the request context if it is not yet there. Returns: instance of :class:`.models.model.Model` or derived class """ if not hasattr(g, 'model'): g.model = load_model(current_...
[ "def", "get_model", "(", ")", ":", "if", "not", "hasattr", "(", "g", ",", "'model'", ")", ":", "g", ".", "model", "=", "load_model", "(", "current_app", ".", "config", "[", "'MODEL_CLS_PATH'", "]", ",", "current_app", ".", "config", "[", "'MODEL_CLS_NAME...
Get the NN model that's being analyzed from the request context. Put the model in the request context if it is not yet there. Returns: instance of :class:`.models.model.Model` or derived class
[ "Get", "the", "NN", "model", "that", "s", "being", "analyzed", "from", "the", "request", "context", ".", "Put", "the", "model", "in", "the", "request", "context", "if", "it", "is", "not", "yet", "there", "." ]
d276b9b7408dd1032fe0ccb84ea9b6604a32915e
https://github.com/merantix/picasso/blob/d276b9b7408dd1032fe0ccb84ea9b6604a32915e/picasso/utils.py#L52-L64
5,690
merantix/picasso
picasso/utils.py
get_visualizations
def get_visualizations(): """Get the available visualizations from the request context. Put the visualizations in the request context if they are not yet there. Returns: :obj:`list` of instances of :class:`.BaseVisualization` or derived class """ if not hasattr(g, 'visualizations'...
python
def get_visualizations(): """Get the available visualizations from the request context. Put the visualizations in the request context if they are not yet there. Returns: :obj:`list` of instances of :class:`.BaseVisualization` or derived class """ if not hasattr(g, 'visualizations'...
[ "def", "get_visualizations", "(", ")", ":", "if", "not", "hasattr", "(", "g", ",", "'visualizations'", ")", ":", "g", ".", "visualizations", "=", "{", "}", "for", "VisClass", "in", "_get_visualization_classes", "(", ")", ":", "vis", "=", "VisClass", "(", ...
Get the available visualizations from the request context. Put the visualizations in the request context if they are not yet there. Returns: :obj:`list` of instances of :class:`.BaseVisualization` or derived class
[ "Get", "the", "available", "visualizations", "from", "the", "request", "context", ".", "Put", "the", "visualizations", "in", "the", "request", "context", "if", "they", "are", "not", "yet", "there", "." ]
d276b9b7408dd1032fe0ccb84ea9b6604a32915e
https://github.com/merantix/picasso/blob/d276b9b7408dd1032fe0ccb84ea9b6604a32915e/picasso/utils.py#L67-L81
5,691
merantix/picasso
picasso/utils.py
get_app_state
def get_app_state(): """Get current status of application in context Returns: :obj:`dict` of application status """ if not hasattr(g, 'app_state'): model = get_model() g.app_state = { 'app_title': APP_TITLE, 'model_name': type(model).__name__, ...
python
def get_app_state(): """Get current status of application in context Returns: :obj:`dict` of application status """ if not hasattr(g, 'app_state'): model = get_model() g.app_state = { 'app_title': APP_TITLE, 'model_name': type(model).__name__, ...
[ "def", "get_app_state", "(", ")", ":", "if", "not", "hasattr", "(", "g", ",", "'app_state'", ")", ":", "model", "=", "get_model", "(", ")", "g", ".", "app_state", "=", "{", "'app_title'", ":", "APP_TITLE", ",", "'model_name'", ":", "type", "(", "model"...
Get current status of application in context Returns: :obj:`dict` of application status
[ "Get", "current", "status", "of", "application", "in", "context" ]
d276b9b7408dd1032fe0ccb84ea9b6604a32915e
https://github.com/merantix/picasso/blob/d276b9b7408dd1032fe0ccb84ea9b6604a32915e/picasso/utils.py#L84-L99
5,692
arraylabs/pymyq
pymyq/api.py
login
async def login( username: str, password: str, brand: str, websession: ClientSession = None) -> API: """Log in to the API.""" api = API(brand, websession) await api.authenticate(username, password) return api
python
async def login( username: str, password: str, brand: str, websession: ClientSession = None) -> API: """Log in to the API.""" api = API(brand, websession) await api.authenticate(username, password) return api
[ "async", "def", "login", "(", "username", ":", "str", ",", "password", ":", "str", ",", "brand", ":", "str", ",", "websession", ":", "ClientSession", "=", "None", ")", "->", "API", ":", "api", "=", "API", "(", "brand", ",", "websession", ")", "await"...
Log in to the API.
[ "Log", "in", "to", "the", "API", "." ]
413ae01ca23568f7b5f698a87e872f456072356b
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/api.py#L286-L292
5,693
arraylabs/pymyq
pymyq/api.py
API._create_websession
def _create_websession(self): """Create a web session.""" from socket import AF_INET from aiohttp import ClientTimeout, TCPConnector _LOGGER.debug('Creating web session') conn = TCPConnector( family=AF_INET, limit_per_host=5, enable_cleanup_cl...
python
def _create_websession(self): """Create a web session.""" from socket import AF_INET from aiohttp import ClientTimeout, TCPConnector _LOGGER.debug('Creating web session') conn = TCPConnector( family=AF_INET, limit_per_host=5, enable_cleanup_cl...
[ "def", "_create_websession", "(", "self", ")", ":", "from", "socket", "import", "AF_INET", "from", "aiohttp", "import", "ClientTimeout", ",", "TCPConnector", "_LOGGER", ".", "debug", "(", "'Creating web session'", ")", "conn", "=", "TCPConnector", "(", "family", ...
Create a web session.
[ "Create", "a", "web", "session", "." ]
413ae01ca23568f7b5f698a87e872f456072356b
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/api.py#L73-L89
5,694
arraylabs/pymyq
pymyq/api.py
API.close_websession
async def close_websession(self): """Close web session if not already closed and created by us.""" # We do not close the web session if it was provided. if self._supplied_websession or self._websession is None: return _LOGGER.debug('Closing connections') # Need to se...
python
async def close_websession(self): """Close web session if not already closed and created by us.""" # We do not close the web session if it was provided. if self._supplied_websession or self._websession is None: return _LOGGER.debug('Closing connections') # Need to se...
[ "async", "def", "close_websession", "(", "self", ")", ":", "# We do not close the web session if it was provided.", "if", "self", ".", "_supplied_websession", "or", "self", ".", "_websession", "is", "None", ":", "return", "_LOGGER", ".", "debug", "(", "'Closing connec...
Close web session if not already closed and created by us.
[ "Close", "web", "session", "if", "not", "already", "closed", "and", "created", "by", "us", "." ]
413ae01ca23568f7b5f698a87e872f456072356b
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/api.py#L91-L104
5,695
arraylabs/pymyq
pymyq/api.py
API.authenticate
async def authenticate(self, username: str, password: str) -> None: """Authenticate against the API.""" self._credentials = { 'username': username, 'password': password, } await self._get_security_token()
python
async def authenticate(self, username: str, password: str) -> None: """Authenticate against the API.""" self._credentials = { 'username': username, 'password': password, } await self._get_security_token()
[ "async", "def", "authenticate", "(", "self", ",", "username", ":", "str", ",", "password", ":", "str", ")", "->", "None", ":", "self", ".", "_credentials", "=", "{", "'username'", ":", "username", ",", "'password'", ":", "password", ",", "}", "await", ...
Authenticate against the API.
[ "Authenticate", "against", "the", "API", "." ]
413ae01ca23568f7b5f698a87e872f456072356b
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/api.py#L219-L226
5,696
arraylabs/pymyq
pymyq/api.py
API._get_security_token
async def _get_security_token(self) -> None: """Request a security token.""" _LOGGER.debug('Requesting security token.') if self._credentials is None: return # Make sure only 1 request can be sent at a time. async with self._security_token_lock: # Confirm...
python
async def _get_security_token(self) -> None: """Request a security token.""" _LOGGER.debug('Requesting security token.') if self._credentials is None: return # Make sure only 1 request can be sent at a time. async with self._security_token_lock: # Confirm...
[ "async", "def", "_get_security_token", "(", "self", ")", "->", "None", ":", "_LOGGER", ".", "debug", "(", "'Requesting security token.'", ")", "if", "self", ".", "_credentials", "is", "None", ":", "return", "# Make sure only 1 request can be sent at a time.", "async",...
Request a security token.
[ "Request", "a", "security", "token", "." ]
413ae01ca23568f7b5f698a87e872f456072356b
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/api.py#L228-L253
5,697
arraylabs/pymyq
pymyq/api.py
API.get_devices
async def get_devices(self, covers_only: bool = True) -> list: """Get a list of all devices associated with the account.""" from .device import MyQDevice _LOGGER.debug('Retrieving list of devices') devices_resp = await self._request('get', DEVICE_LIST_ENDPOINT) # print(json.dump...
python
async def get_devices(self, covers_only: bool = True) -> list: """Get a list of all devices associated with the account.""" from .device import MyQDevice _LOGGER.debug('Retrieving list of devices') devices_resp = await self._request('get', DEVICE_LIST_ENDPOINT) # print(json.dump...
[ "async", "def", "get_devices", "(", "self", ",", "covers_only", ":", "bool", "=", "True", ")", "->", "list", ":", "from", ".", "device", "import", "MyQDevice", "_LOGGER", ".", "debug", "(", "'Retrieving list of devices'", ")", "devices_resp", "=", "await", "...
Get a list of all devices associated with the account.
[ "Get", "a", "list", "of", "all", "devices", "associated", "with", "the", "account", "." ]
413ae01ca23568f7b5f698a87e872f456072356b
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/api.py#L255-L283
5,698
arraylabs/pymyq
pymyq/device.py
MyQDevice.name
def name(self) -> str: """Return the device name.""" return next( attr['Value'] for attr in self._device_json.get('Attributes', []) if attr.get('AttributeDisplayName') == 'desc')
python
def name(self) -> str: """Return the device name.""" return next( attr['Value'] for attr in self._device_json.get('Attributes', []) if attr.get('AttributeDisplayName') == 'desc')
[ "def", "name", "(", "self", ")", "->", "str", ":", "return", "next", "(", "attr", "[", "'Value'", "]", "for", "attr", "in", "self", ".", "_device_json", ".", "get", "(", "'Attributes'", ",", "[", "]", ")", "if", "attr", ".", "get", "(", "'Attribute...
Return the device name.
[ "Return", "the", "device", "name", "." ]
413ae01ca23568f7b5f698a87e872f456072356b
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/device.py#L64-L68
5,699
arraylabs/pymyq
pymyq/device.py
MyQDevice.available
def available(self) -> bool: """Return if device is online or not.""" # Both ability to retrieve state from MyQ cloud AND device itself has # to be online. is_available = self.api.online and \ next( attr['Value'] for attr in self._device_json.g...
python
def available(self) -> bool: """Return if device is online or not.""" # Both ability to retrieve state from MyQ cloud AND device itself has # to be online. is_available = self.api.online and \ next( attr['Value'] for attr in self._device_json.g...
[ "def", "available", "(", "self", ")", "->", "bool", ":", "# Both ability to retrieve state from MyQ cloud AND device itself has", "# to be online.", "is_available", "=", "self", ".", "api", ".", "online", "and", "next", "(", "attr", "[", "'Value'", "]", "for", "attr...
Return if device is online or not.
[ "Return", "if", "device", "is", "online", "or", "not", "." ]
413ae01ca23568f7b5f698a87e872f456072356b
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/device.py#L71-L81