repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
lmjohns3/downhill
examples/mnist-sparse-factorization.py
load_mnist
def load_mnist(): '''Load the MNIST digits dataset.''' mnist = skdata.mnist.dataset.MNIST() mnist.meta # trigger download if needed. def arr(n, dtype): arr = mnist.arrays[n] return arr.reshape((len(arr), -1)).astype(dtype) train_images = arr('train_images', np.float32) / 128 - 1 train_labels = arr('train_labels', np.uint8) return ((train_images[:50000], train_labels[:50000, 0]), (train_images[50000:], train_labels[50000:, 0]))
python
def load_mnist(): '''Load the MNIST digits dataset.''' mnist = skdata.mnist.dataset.MNIST() mnist.meta # trigger download if needed. def arr(n, dtype): arr = mnist.arrays[n] return arr.reshape((len(arr), -1)).astype(dtype) train_images = arr('train_images', np.float32) / 128 - 1 train_labels = arr('train_labels', np.uint8) return ((train_images[:50000], train_labels[:50000, 0]), (train_images[50000:], train_labels[50000:, 0]))
[ "def", "load_mnist", "(", ")", ":", "mnist", "=", "skdata", ".", "mnist", ".", "dataset", ".", "MNIST", "(", ")", "mnist", ".", "meta", "# trigger download if needed.", "def", "arr", "(", "n", ",", "dtype", ")", ":", "arr", "=", "mnist", ".", "arrays", "[", "n", "]", "return", "arr", ".", "reshape", "(", "(", "len", "(", "arr", ")", ",", "-", "1", ")", ")", ".", "astype", "(", "dtype", ")", "train_images", "=", "arr", "(", "'train_images'", ",", "np", ".", "float32", ")", "/", "128", "-", "1", "train_labels", "=", "arr", "(", "'train_labels'", ",", "np", ".", "uint8", ")", "return", "(", "(", "train_images", "[", ":", "50000", "]", ",", "train_labels", "[", ":", "50000", ",", "0", "]", ")", ",", "(", "train_images", "[", "50000", ":", "]", ",", "train_labels", "[", "50000", ":", ",", "0", "]", ")", ")" ]
Load the MNIST digits dataset.
[ "Load", "the", "MNIST", "digits", "dataset", "." ]
train
https://github.com/lmjohns3/downhill/blob/42111ab03b5e6fa47b7bf7c7cb5caa402f10ce6d/examples/mnist-sparse-factorization.py#L11-L22
lmjohns3/downhill
downhill/base.py
build
def build(algo, loss, params=None, inputs=None, updates=(), monitors=(), monitor_gradients=False): '''Construct an optimizer by name. Parameters ---------- algo : str The name of the optimization algorithm to build. loss : Theano expression Loss function to minimize. This must be a scalar-valued expression. params : list of Theano variables, optional Symbolic variables to adjust to minimize the loss. If not given, these will be computed automatically by walking the computation graph. inputs : list of Theano variables, optional Symbolic variables required to compute the loss. If not given, these will be computed automatically by walking the computation graph. updates : list of update pairs, optional A list of pairs providing updates for the internal of the loss computation. Normally this is empty, but it can be provided if the loss, for example, requires an update to an internal random number generator. monitors : dict or sequence of (str, Theano expression) tuples, optional Additional values to monitor during optimization. These must be provided as either a sequence of (name, expression) tuples, or as a dictionary mapping string names to Theano expressions. monitor_gradients : bool, optional If True, add monitors to log the norms of the parameter gradients during optimization. Defaults to False. Returns ------- optimizer : :class:`Optimizer` An optimizer instance. ''' return Optimizer.build(algo, loss, params, inputs, updates=updates, monitors=monitors, monitor_gradients=monitor_gradients)
python
def build(algo, loss, params=None, inputs=None, updates=(), monitors=(), monitor_gradients=False): '''Construct an optimizer by name. Parameters ---------- algo : str The name of the optimization algorithm to build. loss : Theano expression Loss function to minimize. This must be a scalar-valued expression. params : list of Theano variables, optional Symbolic variables to adjust to minimize the loss. If not given, these will be computed automatically by walking the computation graph. inputs : list of Theano variables, optional Symbolic variables required to compute the loss. If not given, these will be computed automatically by walking the computation graph. updates : list of update pairs, optional A list of pairs providing updates for the internal of the loss computation. Normally this is empty, but it can be provided if the loss, for example, requires an update to an internal random number generator. monitors : dict or sequence of (str, Theano expression) tuples, optional Additional values to monitor during optimization. These must be provided as either a sequence of (name, expression) tuples, or as a dictionary mapping string names to Theano expressions. monitor_gradients : bool, optional If True, add monitors to log the norms of the parameter gradients during optimization. Defaults to False. Returns ------- optimizer : :class:`Optimizer` An optimizer instance. ''' return Optimizer.build(algo, loss, params, inputs, updates=updates, monitors=monitors, monitor_gradients=monitor_gradients)
[ "def", "build", "(", "algo", ",", "loss", ",", "params", "=", "None", ",", "inputs", "=", "None", ",", "updates", "=", "(", ")", ",", "monitors", "=", "(", ")", ",", "monitor_gradients", "=", "False", ")", ":", "return", "Optimizer", ".", "build", "(", "algo", ",", "loss", ",", "params", ",", "inputs", ",", "updates", "=", "updates", ",", "monitors", "=", "monitors", ",", "monitor_gradients", "=", "monitor_gradients", ")" ]
Construct an optimizer by name. Parameters ---------- algo : str The name of the optimization algorithm to build. loss : Theano expression Loss function to minimize. This must be a scalar-valued expression. params : list of Theano variables, optional Symbolic variables to adjust to minimize the loss. If not given, these will be computed automatically by walking the computation graph. inputs : list of Theano variables, optional Symbolic variables required to compute the loss. If not given, these will be computed automatically by walking the computation graph. updates : list of update pairs, optional A list of pairs providing updates for the internal of the loss computation. Normally this is empty, but it can be provided if the loss, for example, requires an update to an internal random number generator. monitors : dict or sequence of (str, Theano expression) tuples, optional Additional values to monitor during optimization. These must be provided as either a sequence of (name, expression) tuples, or as a dictionary mapping string names to Theano expressions. monitor_gradients : bool, optional If True, add monitors to log the norms of the parameter gradients during optimization. Defaults to False. Returns ------- optimizer : :class:`Optimizer` An optimizer instance.
[ "Construct", "an", "optimizer", "by", "name", "." ]
train
https://github.com/lmjohns3/downhill/blob/42111ab03b5e6fa47b7bf7c7cb5caa402f10ce6d/downhill/base.py#L15-L50
lmjohns3/downhill
downhill/base.py
Optimizer._compile
def _compile(self, **kwargs): '''Compile the Theano functions for evaluating and updating our model. ''' util.log('compiling evaluation function') self.f_eval = theano.function(self._inputs, self._monitor_exprs, updates=self._updates, name='evaluation') label = self.__class__.__name__ util.log('compiling {} optimizer'.format(click.style(label, fg='red'))) updates = list(self._updates) + list(self.get_updates(**kwargs)) self.f_step = theano.function(self._inputs, self._monitor_exprs, updates=updates, name=label)
python
def _compile(self, **kwargs): '''Compile the Theano functions for evaluating and updating our model. ''' util.log('compiling evaluation function') self.f_eval = theano.function(self._inputs, self._monitor_exprs, updates=self._updates, name='evaluation') label = self.__class__.__name__ util.log('compiling {} optimizer'.format(click.style(label, fg='red'))) updates = list(self._updates) + list(self.get_updates(**kwargs)) self.f_step = theano.function(self._inputs, self._monitor_exprs, updates=updates, name=label)
[ "def", "_compile", "(", "self", ",", "*", "*", "kwargs", ")", ":", "util", ".", "log", "(", "'compiling evaluation function'", ")", "self", ".", "f_eval", "=", "theano", ".", "function", "(", "self", ".", "_inputs", ",", "self", ".", "_monitor_exprs", ",", "updates", "=", "self", ".", "_updates", ",", "name", "=", "'evaluation'", ")", "label", "=", "self", ".", "__class__", ".", "__name__", "util", ".", "log", "(", "'compiling {} optimizer'", ".", "format", "(", "click", ".", "style", "(", "label", ",", "fg", "=", "'red'", ")", ")", ")", "updates", "=", "list", "(", "self", ".", "_updates", ")", "+", "list", "(", "self", ".", "get_updates", "(", "*", "*", "kwargs", ")", ")", "self", ".", "f_step", "=", "theano", ".", "function", "(", "self", ".", "_inputs", ",", "self", ".", "_monitor_exprs", ",", "updates", "=", "updates", ",", "name", "=", "label", ")" ]
Compile the Theano functions for evaluating and updating our model.
[ "Compile", "the", "Theano", "functions", "for", "evaluating", "and", "updating", "our", "model", "." ]
train
https://github.com/lmjohns3/downhill/blob/42111ab03b5e6fa47b7bf7c7cb5caa402f10ce6d/downhill/base.py#L153-L167
lmjohns3/downhill
downhill/base.py
Optimizer.get_updates
def get_updates(self, **kwargs): '''Get parameter update expressions for performing optimization. Keyword arguments can be applied here to set any of the global optimizer attributes. Yields ------ updates : (parameter, expression) tuples A sequence of parameter updates to be applied during optimization. ''' self._prepare(**kwargs) for param, grad in self._differentiate(): for var, update in self._get_updates_for(param, grad): # For auxiliary variables, updates are meant to replace the # existing variable value. if var != param: yield var, update continue # If momentum is disabled, just apply the parameter delta. if self.momentum == 0: yield var, param - update continue # Momentum is enabled, so we keep track of velocity here. vel_tm1 = util.shared_like(param, 'vel') vel_t = util.as_float(self.momentum) * vel_tm1 - update if self.nesterov: # see http://arxiv.org/pdf/1212.0901v2.pdf (eq 7) and # https://github.com/lisa-lab/pylearn2/pull/136#issuecomment-10381617 mom_sqr = util.as_float(self.momentum ** 2) mom_inc = util.as_float(1 + self.momentum) vel_t = mom_sqr * vel_tm1 - mom_inc * update yield vel_tm1, vel_t yield param, param + vel_t
python
def get_updates(self, **kwargs): '''Get parameter update expressions for performing optimization. Keyword arguments can be applied here to set any of the global optimizer attributes. Yields ------ updates : (parameter, expression) tuples A sequence of parameter updates to be applied during optimization. ''' self._prepare(**kwargs) for param, grad in self._differentiate(): for var, update in self._get_updates_for(param, grad): # For auxiliary variables, updates are meant to replace the # existing variable value. if var != param: yield var, update continue # If momentum is disabled, just apply the parameter delta. if self.momentum == 0: yield var, param - update continue # Momentum is enabled, so we keep track of velocity here. vel_tm1 = util.shared_like(param, 'vel') vel_t = util.as_float(self.momentum) * vel_tm1 - update if self.nesterov: # see http://arxiv.org/pdf/1212.0901v2.pdf (eq 7) and # https://github.com/lisa-lab/pylearn2/pull/136#issuecomment-10381617 mom_sqr = util.as_float(self.momentum ** 2) mom_inc = util.as_float(1 + self.momentum) vel_t = mom_sqr * vel_tm1 - mom_inc * update yield vel_tm1, vel_t yield param, param + vel_t
[ "def", "get_updates", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_prepare", "(", "*", "*", "kwargs", ")", "for", "param", ",", "grad", "in", "self", ".", "_differentiate", "(", ")", ":", "for", "var", ",", "update", "in", "self", ".", "_get_updates_for", "(", "param", ",", "grad", ")", ":", "# For auxiliary variables, updates are meant to replace the", "# existing variable value.", "if", "var", "!=", "param", ":", "yield", "var", ",", "update", "continue", "# If momentum is disabled, just apply the parameter delta.", "if", "self", ".", "momentum", "==", "0", ":", "yield", "var", ",", "param", "-", "update", "continue", "# Momentum is enabled, so we keep track of velocity here.", "vel_tm1", "=", "util", ".", "shared_like", "(", "param", ",", "'vel'", ")", "vel_t", "=", "util", ".", "as_float", "(", "self", ".", "momentum", ")", "*", "vel_tm1", "-", "update", "if", "self", ".", "nesterov", ":", "# see http://arxiv.org/pdf/1212.0901v2.pdf (eq 7) and", "# https://github.com/lisa-lab/pylearn2/pull/136#issuecomment-10381617", "mom_sqr", "=", "util", ".", "as_float", "(", "self", ".", "momentum", "**", "2", ")", "mom_inc", "=", "util", ".", "as_float", "(", "1", "+", "self", ".", "momentum", ")", "vel_t", "=", "mom_sqr", "*", "vel_tm1", "-", "mom_inc", "*", "update", "yield", "vel_tm1", ",", "vel_t", "yield", "param", ",", "param", "+", "vel_t" ]
Get parameter update expressions for performing optimization. Keyword arguments can be applied here to set any of the global optimizer attributes. Yields ------ updates : (parameter, expression) tuples A sequence of parameter updates to be applied during optimization.
[ "Get", "parameter", "update", "expressions", "for", "performing", "optimization", "." ]
train
https://github.com/lmjohns3/downhill/blob/42111ab03b5e6fa47b7bf7c7cb5caa402f10ce6d/downhill/base.py#L169-L202
lmjohns3/downhill
downhill/base.py
Optimizer._differentiate
def _differentiate(self, params=None): '''Return a sequence of gradients for our parameters. If this optimizer has been configured with a gradient norm limit, or with elementwise gradient clipping, this method applies the appropriate rescaling and clipping operations before returning the gradient. Parameters ---------- params : list of Theano variables, optional Return the gradient with respect to these parameters. Defaults to all parameters that the optimizer knows about. Yields ------ pairs : (param, grad) tuples Generates a sequence of tuples representing each of the parameters requested and the corresponding Theano gradient expressions. ''' if params is None: params = self._params for param, grad in zip(params, TT.grad(self._loss, params)): if self.max_gradient_elem > 0: limit = util.as_float(self.max_gradient_elem) yield param, TT.clip(grad, -limit, limit) elif self.max_gradient_norm > 0: norm = TT.sqrt((grad * grad).sum()) limit = util.as_float(self.max_gradient_norm) yield param, grad * TT.minimum(1, limit / norm) else: yield param, grad
python
def _differentiate(self, params=None): '''Return a sequence of gradients for our parameters. If this optimizer has been configured with a gradient norm limit, or with elementwise gradient clipping, this method applies the appropriate rescaling and clipping operations before returning the gradient. Parameters ---------- params : list of Theano variables, optional Return the gradient with respect to these parameters. Defaults to all parameters that the optimizer knows about. Yields ------ pairs : (param, grad) tuples Generates a sequence of tuples representing each of the parameters requested and the corresponding Theano gradient expressions. ''' if params is None: params = self._params for param, grad in zip(params, TT.grad(self._loss, params)): if self.max_gradient_elem > 0: limit = util.as_float(self.max_gradient_elem) yield param, TT.clip(grad, -limit, limit) elif self.max_gradient_norm > 0: norm = TT.sqrt((grad * grad).sum()) limit = util.as_float(self.max_gradient_norm) yield param, grad * TT.minimum(1, limit / norm) else: yield param, grad
[ "def", "_differentiate", "(", "self", ",", "params", "=", "None", ")", ":", "if", "params", "is", "None", ":", "params", "=", "self", ".", "_params", "for", "param", ",", "grad", "in", "zip", "(", "params", ",", "TT", ".", "grad", "(", "self", ".", "_loss", ",", "params", ")", ")", ":", "if", "self", ".", "max_gradient_elem", ">", "0", ":", "limit", "=", "util", ".", "as_float", "(", "self", ".", "max_gradient_elem", ")", "yield", "param", ",", "TT", ".", "clip", "(", "grad", ",", "-", "limit", ",", "limit", ")", "elif", "self", ".", "max_gradient_norm", ">", "0", ":", "norm", "=", "TT", ".", "sqrt", "(", "(", "grad", "*", "grad", ")", ".", "sum", "(", ")", ")", "limit", "=", "util", ".", "as_float", "(", "self", ".", "max_gradient_norm", ")", "yield", "param", ",", "grad", "*", "TT", ".", "minimum", "(", "1", ",", "limit", "/", "norm", ")", "else", ":", "yield", "param", ",", "grad" ]
Return a sequence of gradients for our parameters. If this optimizer has been configured with a gradient norm limit, or with elementwise gradient clipping, this method applies the appropriate rescaling and clipping operations before returning the gradient. Parameters ---------- params : list of Theano variables, optional Return the gradient with respect to these parameters. Defaults to all parameters that the optimizer knows about. Yields ------ pairs : (param, grad) tuples Generates a sequence of tuples representing each of the parameters requested and the corresponding Theano gradient expressions.
[ "Return", "a", "sequence", "of", "gradients", "for", "our", "parameters", "." ]
train
https://github.com/lmjohns3/downhill/blob/42111ab03b5e6fa47b7bf7c7cb5caa402f10ce6d/downhill/base.py#L214-L244
lmjohns3/downhill
downhill/base.py
Optimizer.set_params
def set_params(self, targets=None): '''Set the values of the parameters to the given target values. Parameters ---------- targets : sequence of ndarray, optional Arrays for setting the parameters of our model. If this is not provided, the current best parameters for this optimizer will be used. ''' if not isinstance(targets, (list, tuple)): targets = self._best_params for param, target in zip(self._params, targets): param.set_value(target)
python
def set_params(self, targets=None): '''Set the values of the parameters to the given target values. Parameters ---------- targets : sequence of ndarray, optional Arrays for setting the parameters of our model. If this is not provided, the current best parameters for this optimizer will be used. ''' if not isinstance(targets, (list, tuple)): targets = self._best_params for param, target in zip(self._params, targets): param.set_value(target)
[ "def", "set_params", "(", "self", ",", "targets", "=", "None", ")", ":", "if", "not", "isinstance", "(", "targets", ",", "(", "list", ",", "tuple", ")", ")", ":", "targets", "=", "self", ".", "_best_params", "for", "param", ",", "target", "in", "zip", "(", "self", ".", "_params", ",", "targets", ")", ":", "param", ".", "set_value", "(", "target", ")" ]
Set the values of the parameters to the given target values. Parameters ---------- targets : sequence of ndarray, optional Arrays for setting the parameters of our model. If this is not provided, the current best parameters for this optimizer will be used.
[ "Set", "the", "values", "of", "the", "parameters", "to", "the", "given", "target", "values", "." ]
train
https://github.com/lmjohns3/downhill/blob/42111ab03b5e6fa47b7bf7c7cb5caa402f10ce6d/downhill/base.py#L246-L259
lmjohns3/downhill
downhill/base.py
Optimizer._log
def _log(self, monitors, iteration, label='', suffix=''): '''Log the state of the optimizer on the console. Parameters ---------- monitors : OrderedDict A dictionary of monitor names mapped to values. These names and values are what is being logged. iteration : int Optimization iteration that we are logging. label : str, optional A label for the name of the optimizer creating the log line. Defaults to the name of the current class. suffix : str, optional A suffix to add to the end of the log line, if any. ''' label = label or self.__class__.__name__ fields = (('{}={:.6f}').format(k, v) for k, v in monitors.items()) util.log('{} {} {}{}'.format(label, iteration, ' '.join(fields), suffix))
python
def _log(self, monitors, iteration, label='', suffix=''): '''Log the state of the optimizer on the console. Parameters ---------- monitors : OrderedDict A dictionary of monitor names mapped to values. These names and values are what is being logged. iteration : int Optimization iteration that we are logging. label : str, optional A label for the name of the optimizer creating the log line. Defaults to the name of the current class. suffix : str, optional A suffix to add to the end of the log line, if any. ''' label = label or self.__class__.__name__ fields = (('{}={:.6f}').format(k, v) for k, v in monitors.items()) util.log('{} {} {}{}'.format(label, iteration, ' '.join(fields), suffix))
[ "def", "_log", "(", "self", ",", "monitors", ",", "iteration", ",", "label", "=", "''", ",", "suffix", "=", "''", ")", ":", "label", "=", "label", "or", "self", ".", "__class__", ".", "__name__", "fields", "=", "(", "(", "'{}={:.6f}'", ")", ".", "format", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "monitors", ".", "items", "(", ")", ")", "util", ".", "log", "(", "'{} {} {}{}'", ".", "format", "(", "label", ",", "iteration", ",", "' '", ".", "join", "(", "fields", ")", ",", "suffix", ")", ")" ]
Log the state of the optimizer on the console. Parameters ---------- monitors : OrderedDict A dictionary of monitor names mapped to values. These names and values are what is being logged. iteration : int Optimization iteration that we are logging. label : str, optional A label for the name of the optimizer creating the log line. Defaults to the name of the current class. suffix : str, optional A suffix to add to the end of the log line, if any.
[ "Log", "the", "state", "of", "the", "optimizer", "on", "the", "console", "." ]
train
https://github.com/lmjohns3/downhill/blob/42111ab03b5e6fa47b7bf7c7cb5caa402f10ce6d/downhill/base.py#L261-L279
lmjohns3/downhill
downhill/base.py
Optimizer.evaluate
def evaluate(self, dataset): '''Evaluate the current model parameters on a dataset. Parameters ---------- dataset : :class:`Dataset <downhill.dataset.Dataset>` A set of data to use for evaluating the model. Returns ------- monitors : OrderedDict A dictionary mapping monitor names to values. Monitors are quantities of interest during optimization---for example, loss function, accuracy, or whatever the optimization task requires. ''' if dataset is None: values = [self.f_eval()] else: values = [self.f_eval(*x) for x in dataset] monitors = zip(self._monitor_names, np.mean(values, axis=0)) return collections.OrderedDict(monitors)
python
def evaluate(self, dataset): '''Evaluate the current model parameters on a dataset. Parameters ---------- dataset : :class:`Dataset <downhill.dataset.Dataset>` A set of data to use for evaluating the model. Returns ------- monitors : OrderedDict A dictionary mapping monitor names to values. Monitors are quantities of interest during optimization---for example, loss function, accuracy, or whatever the optimization task requires. ''' if dataset is None: values = [self.f_eval()] else: values = [self.f_eval(*x) for x in dataset] monitors = zip(self._monitor_names, np.mean(values, axis=0)) return collections.OrderedDict(monitors)
[ "def", "evaluate", "(", "self", ",", "dataset", ")", ":", "if", "dataset", "is", "None", ":", "values", "=", "[", "self", ".", "f_eval", "(", ")", "]", "else", ":", "values", "=", "[", "self", ".", "f_eval", "(", "*", "x", ")", "for", "x", "in", "dataset", "]", "monitors", "=", "zip", "(", "self", ".", "_monitor_names", ",", "np", ".", "mean", "(", "values", ",", "axis", "=", "0", ")", ")", "return", "collections", ".", "OrderedDict", "(", "monitors", ")" ]
Evaluate the current model parameters on a dataset. Parameters ---------- dataset : :class:`Dataset <downhill.dataset.Dataset>` A set of data to use for evaluating the model. Returns ------- monitors : OrderedDict A dictionary mapping monitor names to values. Monitors are quantities of interest during optimization---for example, loss function, accuracy, or whatever the optimization task requires.
[ "Evaluate", "the", "current", "model", "parameters", "on", "a", "dataset", "." ]
train
https://github.com/lmjohns3/downhill/blob/42111ab03b5e6fa47b7bf7c7cb5caa402f10ce6d/downhill/base.py#L281-L301
lmjohns3/downhill
downhill/base.py
Optimizer._prepare
def _prepare(self, **kwargs): '''Set up properties for optimization. This method can be overridden by base classes to provide parameters that are specific to a particular optimization technique (e.g., setting up a learning rate value). ''' self.learning_rate = util.as_float(kwargs.pop('learning_rate', 1e-4)) self.momentum = kwargs.pop('momentum', 0) self.nesterov = kwargs.pop('nesterov', False) self.patience = kwargs.get('patience', 5) self.validate_every = kwargs.pop('validate_every', 10) self.min_improvement = kwargs.pop('min_improvement', 0) self.max_gradient_norm = kwargs.pop('max_gradient_norm', 0) self.max_gradient_elem = kwargs.pop('max_gradient_elem', 0) util.log_param('patience', self.patience) util.log_param('validate_every', self.validate_every) util.log_param('min_improvement', self.min_improvement) util.log_param('max_gradient_norm', self.max_gradient_norm) util.log_param('max_gradient_elem', self.max_gradient_elem) util.log_param('learning_rate', self.learning_rate) util.log_param('momentum', self.momentum) util.log_param('nesterov', self.nesterov)
python
def _prepare(self, **kwargs): '''Set up properties for optimization. This method can be overridden by base classes to provide parameters that are specific to a particular optimization technique (e.g., setting up a learning rate value). ''' self.learning_rate = util.as_float(kwargs.pop('learning_rate', 1e-4)) self.momentum = kwargs.pop('momentum', 0) self.nesterov = kwargs.pop('nesterov', False) self.patience = kwargs.get('patience', 5) self.validate_every = kwargs.pop('validate_every', 10) self.min_improvement = kwargs.pop('min_improvement', 0) self.max_gradient_norm = kwargs.pop('max_gradient_norm', 0) self.max_gradient_elem = kwargs.pop('max_gradient_elem', 0) util.log_param('patience', self.patience) util.log_param('validate_every', self.validate_every) util.log_param('min_improvement', self.min_improvement) util.log_param('max_gradient_norm', self.max_gradient_norm) util.log_param('max_gradient_elem', self.max_gradient_elem) util.log_param('learning_rate', self.learning_rate) util.log_param('momentum', self.momentum) util.log_param('nesterov', self.nesterov)
[ "def", "_prepare", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "learning_rate", "=", "util", ".", "as_float", "(", "kwargs", ".", "pop", "(", "'learning_rate'", ",", "1e-4", ")", ")", "self", ".", "momentum", "=", "kwargs", ".", "pop", "(", "'momentum'", ",", "0", ")", "self", ".", "nesterov", "=", "kwargs", ".", "pop", "(", "'nesterov'", ",", "False", ")", "self", ".", "patience", "=", "kwargs", ".", "get", "(", "'patience'", ",", "5", ")", "self", ".", "validate_every", "=", "kwargs", ".", "pop", "(", "'validate_every'", ",", "10", ")", "self", ".", "min_improvement", "=", "kwargs", ".", "pop", "(", "'min_improvement'", ",", "0", ")", "self", ".", "max_gradient_norm", "=", "kwargs", ".", "pop", "(", "'max_gradient_norm'", ",", "0", ")", "self", ".", "max_gradient_elem", "=", "kwargs", ".", "pop", "(", "'max_gradient_elem'", ",", "0", ")", "util", ".", "log_param", "(", "'patience'", ",", "self", ".", "patience", ")", "util", ".", "log_param", "(", "'validate_every'", ",", "self", ".", "validate_every", ")", "util", ".", "log_param", "(", "'min_improvement'", ",", "self", ".", "min_improvement", ")", "util", ".", "log_param", "(", "'max_gradient_norm'", ",", "self", ".", "max_gradient_norm", ")", "util", ".", "log_param", "(", "'max_gradient_elem'", ",", "self", ".", "max_gradient_elem", ")", "util", ".", "log_param", "(", "'learning_rate'", ",", "self", ".", "learning_rate", ")", "util", ".", "log_param", "(", "'momentum'", ",", "self", ".", "momentum", ")", "util", ".", "log_param", "(", "'nesterov'", ",", "self", ".", "nesterov", ")" ]
Set up properties for optimization. This method can be overridden by base classes to provide parameters that are specific to a particular optimization technique (e.g., setting up a learning rate value).
[ "Set", "up", "properties", "for", "optimization", "." ]
train
https://github.com/lmjohns3/downhill/blob/42111ab03b5e6fa47b7bf7c7cb5caa402f10ce6d/downhill/base.py#L329-L352
lmjohns3/downhill
downhill/base.py
Optimizer.iterate
def iterate(self, train=None, valid=None, max_updates=None, **kwargs): r'''Optimize a loss iteratively using a training and validation dataset. This method yields a series of monitor values to the caller. After every optimization epoch, a pair of monitor dictionaries is generated: one evaluated on the training dataset during the epoch, and another evaluated on the validation dataset at the most recent validation epoch. The validation monitors might not be updated during every optimization iteration; in this case, the most recent validation monitors will be yielded along with the training monitors. Additional keyword arguments supplied here will set the global optimizer attributes. Parameters ---------- train : sequence or :class:`Dataset <downhill.dataset.Dataset>` A set of training data for computing updates to model parameters. valid : sequence or :class:`Dataset <downhill.dataset.Dataset>` A set of validation data for computing monitor values and determining when the loss has stopped improving. Defaults to the training data. max_updates : int, optional If specified, halt optimization after this many gradient updates have been processed. If not provided, uses early stopping to decide when to halt. Yields ------ train_monitors : dict A dictionary mapping monitor names to values, evaluated on the training dataset. valid_monitors : dict A dictionary containing monitor values evaluated on the validation dataset. ''' self._compile(**kwargs) if valid is None: valid = train iteration = 0 training = validation = None while max_updates is None or iteration < max_updates: if not iteration % self.validate_every: try: validation = self.evaluate(valid) except KeyboardInterrupt: util.log('interrupted!') break if self._test_patience(validation): util.log('patience elapsed!') break try: training = self._step(train) except KeyboardInterrupt: util.log('interrupted!') break iteration += 1 self._log(training, iteration) yield training, validation self.set_params('best')
python
def iterate(self, train=None, valid=None, max_updates=None, **kwargs): r'''Optimize a loss iteratively using a training and validation dataset. This method yields a series of monitor values to the caller. After every optimization epoch, a pair of monitor dictionaries is generated: one evaluated on the training dataset during the epoch, and another evaluated on the validation dataset at the most recent validation epoch. The validation monitors might not be updated during every optimization iteration; in this case, the most recent validation monitors will be yielded along with the training monitors. Additional keyword arguments supplied here will set the global optimizer attributes. Parameters ---------- train : sequence or :class:`Dataset <downhill.dataset.Dataset>` A set of training data for computing updates to model parameters. valid : sequence or :class:`Dataset <downhill.dataset.Dataset>` A set of validation data for computing monitor values and determining when the loss has stopped improving. Defaults to the training data. max_updates : int, optional If specified, halt optimization after this many gradient updates have been processed. If not provided, uses early stopping to decide when to halt. Yields ------ train_monitors : dict A dictionary mapping monitor names to values, evaluated on the training dataset. valid_monitors : dict A dictionary containing monitor values evaluated on the validation dataset. ''' self._compile(**kwargs) if valid is None: valid = train iteration = 0 training = validation = None while max_updates is None or iteration < max_updates: if not iteration % self.validate_every: try: validation = self.evaluate(valid) except KeyboardInterrupt: util.log('interrupted!') break if self._test_patience(validation): util.log('patience elapsed!') break try: training = self._step(train) except KeyboardInterrupt: util.log('interrupted!') break iteration += 1 self._log(training, iteration) yield training, validation self.set_params('best')
[ "def", "iterate", "(", "self", ",", "train", "=", "None", ",", "valid", "=", "None", ",", "max_updates", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_compile", "(", "*", "*", "kwargs", ")", "if", "valid", "is", "None", ":", "valid", "=", "train", "iteration", "=", "0", "training", "=", "validation", "=", "None", "while", "max_updates", "is", "None", "or", "iteration", "<", "max_updates", ":", "if", "not", "iteration", "%", "self", ".", "validate_every", ":", "try", ":", "validation", "=", "self", ".", "evaluate", "(", "valid", ")", "except", "KeyboardInterrupt", ":", "util", ".", "log", "(", "'interrupted!'", ")", "break", "if", "self", ".", "_test_patience", "(", "validation", ")", ":", "util", ".", "log", "(", "'patience elapsed!'", ")", "break", "try", ":", "training", "=", "self", ".", "_step", "(", "train", ")", "except", "KeyboardInterrupt", ":", "util", ".", "log", "(", "'interrupted!'", ")", "break", "iteration", "+=", "1", "self", ".", "_log", "(", "training", ",", "iteration", ")", "yield", "training", ",", "validation", "self", ".", "set_params", "(", "'best'", ")" ]
r'''Optimize a loss iteratively using a training and validation dataset. This method yields a series of monitor values to the caller. After every optimization epoch, a pair of monitor dictionaries is generated: one evaluated on the training dataset during the epoch, and another evaluated on the validation dataset at the most recent validation epoch. The validation monitors might not be updated during every optimization iteration; in this case, the most recent validation monitors will be yielded along with the training monitors. Additional keyword arguments supplied here will set the global optimizer attributes. Parameters ---------- train : sequence or :class:`Dataset <downhill.dataset.Dataset>` A set of training data for computing updates to model parameters. valid : sequence or :class:`Dataset <downhill.dataset.Dataset>` A set of validation data for computing monitor values and determining when the loss has stopped improving. Defaults to the training data. max_updates : int, optional If specified, halt optimization after this many gradient updates have been processed. If not provided, uses early stopping to decide when to halt. Yields ------ train_monitors : dict A dictionary mapping monitor names to values, evaluated on the training dataset. valid_monitors : dict A dictionary containing monitor values evaluated on the validation dataset.
[ "r", "Optimize", "a", "loss", "iteratively", "using", "a", "training", "and", "validation", "dataset", "." ]
train
https://github.com/lmjohns3/downhill/blob/42111ab03b5e6fa47b7bf7c7cb5caa402f10ce6d/downhill/base.py#L354-L415
lmjohns3/downhill
downhill/base.py
Optimizer.minimize
def minimize(self, *args, **kwargs): '''Optimize our loss exhaustively. This method is a thin wrapper over the :func:`iterate` method. It simply exhausts the iterative optimization process and returns the final monitor values. Returns ------- train_monitors : dict A dictionary mapping monitor names to values, evaluated on the training dataset. valid_monitors : dict A dictionary containing monitor values evaluated on the validation dataset. ''' monitors = None for monitors in self.iterate(*args, **kwargs): pass return monitors
python
def minimize(self, *args, **kwargs): '''Optimize our loss exhaustively. This method is a thin wrapper over the :func:`iterate` method. It simply exhausts the iterative optimization process and returns the final monitor values. Returns ------- train_monitors : dict A dictionary mapping monitor names to values, evaluated on the training dataset. valid_monitors : dict A dictionary containing monitor values evaluated on the validation dataset. ''' monitors = None for monitors in self.iterate(*args, **kwargs): pass return monitors
[ "def", "minimize", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "monitors", "=", "None", "for", "monitors", "in", "self", ".", "iterate", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "pass", "return", "monitors" ]
Optimize our loss exhaustively. This method is a thin wrapper over the :func:`iterate` method. It simply exhausts the iterative optimization process and returns the final monitor values. Returns ------- train_monitors : dict A dictionary mapping monitor names to values, evaluated on the training dataset. valid_monitors : dict A dictionary containing monitor values evaluated on the validation dataset.
[ "Optimize", "our", "loss", "exhaustively", "." ]
train
https://github.com/lmjohns3/downhill/blob/42111ab03b5e6fa47b7bf7c7cb5caa402f10ce6d/downhill/base.py#L417-L436
lmjohns3/downhill
downhill/base.py
Optimizer._step
def _step(self, dataset): '''Advance the state of the optimizer by one step. Parameters ---------- dataset : :class:`Dataset <downhill.dataset.Dataset>` A dataset for optimizing the model. Returns ------- train_monitors : dict A dictionary mapping monitor names to values. ''' if dataset is None: values = [self.f_step()] else: values = [self.f_step(*x) for x in dataset] return collections.OrderedDict( zip(self._monitor_names, np.mean(values, axis=0)))
python
def _step(self, dataset): '''Advance the state of the optimizer by one step. Parameters ---------- dataset : :class:`Dataset <downhill.dataset.Dataset>` A dataset for optimizing the model. Returns ------- train_monitors : dict A dictionary mapping monitor names to values. ''' if dataset is None: values = [self.f_step()] else: values = [self.f_step(*x) for x in dataset] return collections.OrderedDict( zip(self._monitor_names, np.mean(values, axis=0)))
[ "def", "_step", "(", "self", ",", "dataset", ")", ":", "if", "dataset", "is", "None", ":", "values", "=", "[", "self", ".", "f_step", "(", ")", "]", "else", ":", "values", "=", "[", "self", ".", "f_step", "(", "*", "x", ")", "for", "x", "in", "dataset", "]", "return", "collections", ".", "OrderedDict", "(", "zip", "(", "self", ".", "_monitor_names", ",", "np", ".", "mean", "(", "values", ",", "axis", "=", "0", ")", ")", ")" ]
Advance the state of the optimizer by one step. Parameters ---------- dataset : :class:`Dataset <downhill.dataset.Dataset>` A dataset for optimizing the model. Returns ------- train_monitors : dict A dictionary mapping monitor names to values.
[ "Advance", "the", "state", "of", "the", "optimizer", "by", "one", "step", "." ]
train
https://github.com/lmjohns3/downhill/blob/42111ab03b5e6fa47b7bf7c7cb5caa402f10ce6d/downhill/base.py#L438-L456
timothycrosley/connectable
connectable/base.py
accept_arguments
def accept_arguments(method, number_of_arguments=1): """Returns True if the given method will accept the given number of arguments method: the method to perform introspection on number_of_arguments: the number_of_arguments """ if 'method' in method.__class__.__name__: number_of_arguments += 1 func = getattr(method, 'im_func', getattr(method, '__func__')) func_defaults = getattr(func, 'func_defaults', getattr(func, '__defaults__')) number_of_defaults = func_defaults and len(func_defaults) or 0 elif method.__class__.__name__ == 'function': func_defaults = getattr(method, 'func_defaults', getattr(method, '__defaults__')) number_of_defaults = func_defaults and len(func_defaults) or 0 coArgCount = getattr(method, 'func_code', getattr(method, '__code__')).co_argcount if(coArgCount >= number_of_arguments and coArgCount - number_of_defaults <= number_of_arguments): return True return False
python
def accept_arguments(method, number_of_arguments=1): """Returns True if the given method will accept the given number of arguments method: the method to perform introspection on number_of_arguments: the number_of_arguments """ if 'method' in method.__class__.__name__: number_of_arguments += 1 func = getattr(method, 'im_func', getattr(method, '__func__')) func_defaults = getattr(func, 'func_defaults', getattr(func, '__defaults__')) number_of_defaults = func_defaults and len(func_defaults) or 0 elif method.__class__.__name__ == 'function': func_defaults = getattr(method, 'func_defaults', getattr(method, '__defaults__')) number_of_defaults = func_defaults and len(func_defaults) or 0 coArgCount = getattr(method, 'func_code', getattr(method, '__code__')).co_argcount if(coArgCount >= number_of_arguments and coArgCount - number_of_defaults <= number_of_arguments): return True return False
[ "def", "accept_arguments", "(", "method", ",", "number_of_arguments", "=", "1", ")", ":", "if", "'method'", "in", "method", ".", "__class__", ".", "__name__", ":", "number_of_arguments", "+=", "1", "func", "=", "getattr", "(", "method", ",", "'im_func'", ",", "getattr", "(", "method", ",", "'__func__'", ")", ")", "func_defaults", "=", "getattr", "(", "func", ",", "'func_defaults'", ",", "getattr", "(", "func", ",", "'__defaults__'", ")", ")", "number_of_defaults", "=", "func_defaults", "and", "len", "(", "func_defaults", ")", "or", "0", "elif", "method", ".", "__class__", ".", "__name__", "==", "'function'", ":", "func_defaults", "=", "getattr", "(", "method", ",", "'func_defaults'", ",", "getattr", "(", "method", ",", "'__defaults__'", ")", ")", "number_of_defaults", "=", "func_defaults", "and", "len", "(", "func_defaults", ")", "or", "0", "coArgCount", "=", "getattr", "(", "method", ",", "'func_code'", ",", "getattr", "(", "method", ",", "'__code__'", ")", ")", ".", "co_argcount", "if", "(", "coArgCount", ">=", "number_of_arguments", "and", "coArgCount", "-", "number_of_defaults", "<=", "number_of_arguments", ")", ":", "return", "True", "return", "False" ]
Returns True if the given method will accept the given number of arguments method: the method to perform introspection on number_of_arguments: the number_of_arguments
[ "Returns", "True", "if", "the", "given", "method", "will", "accept", "the", "given", "number", "of", "arguments" ]
train
https://github.com/timothycrosley/connectable/blob/d5958d974c04b16f410c602786809d0e2a6665d2/connectable/base.py#L98-L117
timothycrosley/connectable
connectable/base.py
Connectable.emit
def emit(self, signal, value=None, gather=False): """Emits a signal, causing all slot methods connected with the signal to be called (optionally w/ related value) signal: the name of the signal to emit, must be defined in the classes 'signals' list. value: the value to pass to all connected slot methods. gather: if set, causes emit to return a list of all slot results """ results = [] if gather else True if hasattr(self, 'connections') and signal in self.connections: for condition, values in self.connections[signal].items(): if condition is None or condition == value or (callable(condition) and condition(value)): for slot, transform in values.items(): if transform is not None: if callable(transform): used_value = transform(value) elif isinstance(transform, str): used_value = transform.format(value=value) else: used_value = transform else: used_value = value if used_value is not None: if(accept_arguments(slot, 1)): result = slot(used_value) elif(accept_arguments(slot, 0)): result = slot() else: result = '' else: result = slot() if gather: results.append(result) return results
python
def emit(self, signal, value=None, gather=False): """Emits a signal, causing all slot methods connected with the signal to be called (optionally w/ related value) signal: the name of the signal to emit, must be defined in the classes 'signals' list. value: the value to pass to all connected slot methods. gather: if set, causes emit to return a list of all slot results """ results = [] if gather else True if hasattr(self, 'connections') and signal in self.connections: for condition, values in self.connections[signal].items(): if condition is None or condition == value or (callable(condition) and condition(value)): for slot, transform in values.items(): if transform is not None: if callable(transform): used_value = transform(value) elif isinstance(transform, str): used_value = transform.format(value=value) else: used_value = transform else: used_value = value if used_value is not None: if(accept_arguments(slot, 1)): result = slot(used_value) elif(accept_arguments(slot, 0)): result = slot() else: result = '' else: result = slot() if gather: results.append(result) return results
[ "def", "emit", "(", "self", ",", "signal", ",", "value", "=", "None", ",", "gather", "=", "False", ")", ":", "results", "=", "[", "]", "if", "gather", "else", "True", "if", "hasattr", "(", "self", ",", "'connections'", ")", "and", "signal", "in", "self", ".", "connections", ":", "for", "condition", ",", "values", "in", "self", ".", "connections", "[", "signal", "]", ".", "items", "(", ")", ":", "if", "condition", "is", "None", "or", "condition", "==", "value", "or", "(", "callable", "(", "condition", ")", "and", "condition", "(", "value", ")", ")", ":", "for", "slot", ",", "transform", "in", "values", ".", "items", "(", ")", ":", "if", "transform", "is", "not", "None", ":", "if", "callable", "(", "transform", ")", ":", "used_value", "=", "transform", "(", "value", ")", "elif", "isinstance", "(", "transform", ",", "str", ")", ":", "used_value", "=", "transform", ".", "format", "(", "value", "=", "value", ")", "else", ":", "used_value", "=", "transform", "else", ":", "used_value", "=", "value", "if", "used_value", "is", "not", "None", ":", "if", "(", "accept_arguments", "(", "slot", ",", "1", ")", ")", ":", "result", "=", "slot", "(", "used_value", ")", "elif", "(", "accept_arguments", "(", "slot", ",", "0", ")", ")", ":", "result", "=", "slot", "(", ")", "else", ":", "result", "=", "''", "else", ":", "result", "=", "slot", "(", ")", "if", "gather", ":", "results", ".", "append", "(", "result", ")", "return", "results" ]
Emits a signal, causing all slot methods connected with the signal to be called (optionally w/ related value) signal: the name of the signal to emit, must be defined in the classes 'signals' list. value: the value to pass to all connected slot methods. gather: if set, causes emit to return a list of all slot results
[ "Emits", "a", "signal", "causing", "all", "slot", "methods", "connected", "with", "the", "signal", "to", "be", "called", "(", "optionally", "w", "/", "related", "value", ")" ]
train
https://github.com/timothycrosley/connectable/blob/d5958d974c04b16f410c602786809d0e2a6665d2/connectable/base.py#L22-L57
timothycrosley/connectable
connectable/base.py
Connectable.connect
def connect(self, signal, slot, transform=None, condition=None): """Defines a connection between this objects signal and another objects slot signal: the signal this class will emit, to cause the slot method to be called receiver: the object containing the slot method to be called slot: the slot method to call transform: an optional value override to pass into the slot method as the first variable condition: only call the slot if the value emitted matches the required value or calling required returns True """ if not signal in self.signals: print("WARNING: {0} is trying to connect a slot to an undefined signal: {1}".format(self.__class__.__name__, str(signal))) return if not hasattr(self, 'connections'): self.connections = {} connection = self.connections.setdefault(signal, {}) connection = connection.setdefault(condition, {}) connection[slot] = transform
python
def connect(self, signal, slot, transform=None, condition=None): """Defines a connection between this objects signal and another objects slot signal: the signal this class will emit, to cause the slot method to be called receiver: the object containing the slot method to be called slot: the slot method to call transform: an optional value override to pass into the slot method as the first variable condition: only call the slot if the value emitted matches the required value or calling required returns True """ if not signal in self.signals: print("WARNING: {0} is trying to connect a slot to an undefined signal: {1}".format(self.__class__.__name__, str(signal))) return if not hasattr(self, 'connections'): self.connections = {} connection = self.connections.setdefault(signal, {}) connection = connection.setdefault(condition, {}) connection[slot] = transform
[ "def", "connect", "(", "self", ",", "signal", ",", "slot", ",", "transform", "=", "None", ",", "condition", "=", "None", ")", ":", "if", "not", "signal", "in", "self", ".", "signals", ":", "print", "(", "\"WARNING: {0} is trying to connect a slot to an undefined signal: {1}\"", ".", "format", "(", "self", ".", "__class__", ".", "__name__", ",", "str", "(", "signal", ")", ")", ")", "return", "if", "not", "hasattr", "(", "self", ",", "'connections'", ")", ":", "self", ".", "connections", "=", "{", "}", "connection", "=", "self", ".", "connections", ".", "setdefault", "(", "signal", ",", "{", "}", ")", "connection", "=", "connection", ".", "setdefault", "(", "condition", ",", "{", "}", ")", "connection", "[", "slot", "]", "=", "transform" ]
Defines a connection between this objects signal and another objects slot signal: the signal this class will emit, to cause the slot method to be called receiver: the object containing the slot method to be called slot: the slot method to call transform: an optional value override to pass into the slot method as the first variable condition: only call the slot if the value emitted matches the required value or calling required returns True
[ "Defines", "a", "connection", "between", "this", "objects", "signal", "and", "another", "objects", "slot" ]
train
https://github.com/timothycrosley/connectable/blob/d5958d974c04b16f410c602786809d0e2a6665d2/connectable/base.py#L59-L77
timothycrosley/connectable
connectable/base.py
Connectable.disconnect
def disconnect(self, signal=None, slot=None, transform=None, condition=None): """Removes connection(s) between this objects signal and connected slot(s) signal: the signal this class will emit, to cause the slot method to be called receiver: the object containing the slot method to be called slot: the slot method or function to call transform: an optional value override to pass into the slot method as the first variable condition: only call the slot method if the value emitted matches this condition """ if slot: self.connections[signal][condition].pop(slot, None) elif condition is not None: self.connections[signal].pop(condition, None) elif signal: self.connections.pop(signal, None) else: delattr(self, 'connections')
python
def disconnect(self, signal=None, slot=None, transform=None, condition=None): """Removes connection(s) between this objects signal and connected slot(s) signal: the signal this class will emit, to cause the slot method to be called receiver: the object containing the slot method to be called slot: the slot method or function to call transform: an optional value override to pass into the slot method as the first variable condition: only call the slot method if the value emitted matches this condition """ if slot: self.connections[signal][condition].pop(slot, None) elif condition is not None: self.connections[signal].pop(condition, None) elif signal: self.connections.pop(signal, None) else: delattr(self, 'connections')
[ "def", "disconnect", "(", "self", ",", "signal", "=", "None", ",", "slot", "=", "None", ",", "transform", "=", "None", ",", "condition", "=", "None", ")", ":", "if", "slot", ":", "self", ".", "connections", "[", "signal", "]", "[", "condition", "]", ".", "pop", "(", "slot", ",", "None", ")", "elif", "condition", "is", "not", "None", ":", "self", ".", "connections", "[", "signal", "]", ".", "pop", "(", "condition", ",", "None", ")", "elif", "signal", ":", "self", ".", "connections", ".", "pop", "(", "signal", ",", "None", ")", "else", ":", "delattr", "(", "self", ",", "'connections'", ")" ]
Removes connection(s) between this objects signal and connected slot(s) signal: the signal this class will emit, to cause the slot method to be called receiver: the object containing the slot method to be called slot: the slot method or function to call transform: an optional value override to pass into the slot method as the first variable condition: only call the slot method if the value emitted matches this condition
[ "Removes", "connection", "(", "s", ")", "between", "this", "objects", "signal", "and", "connected", "slot", "(", "s", ")" ]
train
https://github.com/timothycrosley/connectable/blob/d5958d974c04b16f410c602786809d0e2a6665d2/connectable/base.py#L79-L95
Lagg/steamodd
steam/sim.py
inventory_context.get
def get(self, key): """ Returns context data for a given app, can be an ID or a case insensitive name """ keystr = str(key) res = None try: res = self.ctx[keystr] except KeyError: for k, v in self.ctx.items(): if "name" in v and v["name"].lower() == keystr.lower(): res = v break return res
python
def get(self, key): """ Returns context data for a given app, can be an ID or a case insensitive name """ keystr = str(key) res = None try: res = self.ctx[keystr] except KeyError: for k, v in self.ctx.items(): if "name" in v and v["name"].lower() == keystr.lower(): res = v break return res
[ "def", "get", "(", "self", ",", "key", ")", ":", "keystr", "=", "str", "(", "key", ")", "res", "=", "None", "try", ":", "res", "=", "self", ".", "ctx", "[", "keystr", "]", "except", "KeyError", ":", "for", "k", ",", "v", "in", "self", ".", "ctx", ".", "items", "(", ")", ":", "if", "\"name\"", "in", "v", "and", "v", "[", "\"name\"", "]", ".", "lower", "(", ")", "==", "keystr", ".", "lower", "(", ")", ":", "res", "=", "v", "break", "return", "res" ]
Returns context data for a given app, can be an ID or a case insensitive name
[ "Returns", "context", "data", "for", "a", "given", "app", "can", "be", "an", "ID", "or", "a", "case", "insensitive", "name" ]
train
https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/sim.py#L35-L48
Lagg/steamodd
steam/sim.py
item.hash_name
def hash_name(self): """ The URL-friendly identifier for the item. Generates its own approximation if one isn't available """ name = self._item.get("market_hash_name") if not name: name = "{0.appid}-{0.name}".format(self) return name
python
def hash_name(self): """ The URL-friendly identifier for the item. Generates its own approximation if one isn't available """ name = self._item.get("market_hash_name") if not name: name = "{0.appid}-{0.name}".format(self) return name
[ "def", "hash_name", "(", "self", ")", ":", "name", "=", "self", ".", "_item", ".", "get", "(", "\"market_hash_name\"", ")", "if", "not", "name", ":", "name", "=", "\"{0.appid}-{0.name}\"", ".", "format", "(", "self", ")", "return", "name" ]
The URL-friendly identifier for the item. Generates its own approximation if one isn't available
[ "The", "URL", "-", "friendly", "identifier", "for", "the", "item", ".", "Generates", "its", "own", "approximation", "if", "one", "isn", "t", "available" ]
train
https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/sim.py#L260-L267
Lagg/steamodd
steam/sim.py
item.quality
def quality(self): """ Can't really trust presence of a schema here, but there is an ID sometimes """ try: qid = int((self.tool_metadata or {}).get("quality", 0)) except: qid = 0 # We might be able to get the quality strings from the item's tags internal_name, name = "normal", "Normal" if self.tags: tags = {x.get('category'): x for x in self.tags} if 'Quality' in tags: internal_name, name = tags['Quality'].get('internal_name'), tags['Quality'].get('name') return qid, internal_name, name
python
def quality(self): """ Can't really trust presence of a schema here, but there is an ID sometimes """ try: qid = int((self.tool_metadata or {}).get("quality", 0)) except: qid = 0 # We might be able to get the quality strings from the item's tags internal_name, name = "normal", "Normal" if self.tags: tags = {x.get('category'): x for x in self.tags} if 'Quality' in tags: internal_name, name = tags['Quality'].get('internal_name'), tags['Quality'].get('name') return qid, internal_name, name
[ "def", "quality", "(", "self", ")", ":", "try", ":", "qid", "=", "int", "(", "(", "self", ".", "tool_metadata", "or", "{", "}", ")", ".", "get", "(", "\"quality\"", ",", "0", ")", ")", "except", ":", "qid", "=", "0", "# We might be able to get the quality strings from the item's tags", "internal_name", ",", "name", "=", "\"normal\"", ",", "\"Normal\"", "if", "self", ".", "tags", ":", "tags", "=", "{", "x", ".", "get", "(", "'category'", ")", ":", "x", "for", "x", "in", "self", ".", "tags", "}", "if", "'Quality'", "in", "tags", ":", "internal_name", ",", "name", "=", "tags", "[", "'Quality'", "]", ".", "get", "(", "'internal_name'", ")", ",", "tags", "[", "'Quality'", "]", ".", "get", "(", "'name'", ")", "return", "qid", ",", "internal_name", ",", "name" ]
Can't really trust presence of a schema here, but there is an ID sometimes
[ "Can", "t", "really", "trust", "presence", "of", "a", "schema", "here", "but", "there", "is", "an", "ID", "sometimes" ]
train
https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/sim.py#L292-L306
Lagg/steamodd
steam/api.py
key.get
def get(cls): """Get the current API key. if one has not been given via 'set' the env var STEAMODD_API_KEY will be checked instead. """ apikey = cls.__api_key or cls.__api_key_env_var if apikey: return apikey else: raise APIKeyMissingError("API key not set")
python
def get(cls): """Get the current API key. if one has not been given via 'set' the env var STEAMODD_API_KEY will be checked instead. """ apikey = cls.__api_key or cls.__api_key_env_var if apikey: return apikey else: raise APIKeyMissingError("API key not set")
[ "def", "get", "(", "cls", ")", ":", "apikey", "=", "cls", ".", "__api_key", "or", "cls", ".", "__api_key_env_var", "if", "apikey", ":", "return", "apikey", "else", ":", "raise", "APIKeyMissingError", "(", "\"API key not set\"", ")" ]
Get the current API key. if one has not been given via 'set' the env var STEAMODD_API_KEY will be checked instead.
[ "Get", "the", "current", "API", "key", ".", "if", "one", "has", "not", "been", "given", "via", "set", "the", "env", "var", "STEAMODD_API_KEY", "will", "be", "checked", "instead", "." ]
train
https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/api.py#L77-L87
Lagg/steamodd
steam/api.py
method_result.call
def call(self): """ Make the API call again and fetch fresh data. """ data = self._downloader.download() # Only try to pass errors arg if supported if sys.version >= "2.7": data = data.decode("utf-8", errors="ignore") else: data = data.decode("utf-8") self.update(json.loads(data)) self._fetched = True
python
def call(self): """ Make the API call again and fetch fresh data. """ data = self._downloader.download() # Only try to pass errors arg if supported if sys.version >= "2.7": data = data.decode("utf-8", errors="ignore") else: data = data.decode("utf-8") self.update(json.loads(data)) self._fetched = True
[ "def", "call", "(", "self", ")", ":", "data", "=", "self", ".", "_downloader", ".", "download", "(", ")", "# Only try to pass errors arg if supported", "if", "sys", ".", "version", ">=", "\"2.7\"", ":", "data", "=", "data", ".", "decode", "(", "\"utf-8\"", ",", "errors", "=", "\"ignore\"", ")", "else", ":", "data", "=", "data", ".", "decode", "(", "\"utf-8\"", ")", "self", ".", "update", "(", "json", ".", "loads", "(", "data", ")", ")", "self", ".", "_fetched", "=", "True" ]
Make the API call again and fetch fresh data.
[ "Make", "the", "API", "call", "again", "and", "fetch", "fresh", "data", "." ]
train
https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/api.py#L248-L259
Lagg/steamodd
steam/items.py
schema._attribute_definition
def _attribute_definition(self, attrid): """ Returns the attribute definition dict of a given attribute ID, can be the name or the integer ID """ attrs = self._schema["attributes"] try: # Make a new dict to avoid side effects return dict(attrs[attrid]) except KeyError: attr_names = self._schema["attribute_names"] attrdef = attrs.get(attr_names.get(str(attrid).lower())) if not attrdef: return None else: return dict(attrdef)
python
def _attribute_definition(self, attrid): """ Returns the attribute definition dict of a given attribute ID, can be the name or the integer ID """ attrs = self._schema["attributes"] try: # Make a new dict to avoid side effects return dict(attrs[attrid]) except KeyError: attr_names = self._schema["attribute_names"] attrdef = attrs.get(attr_names.get(str(attrid).lower())) if not attrdef: return None else: return dict(attrdef)
[ "def", "_attribute_definition", "(", "self", ",", "attrid", ")", ":", "attrs", "=", "self", ".", "_schema", "[", "\"attributes\"", "]", "try", ":", "# Make a new dict to avoid side effects", "return", "dict", "(", "attrs", "[", "attrid", "]", ")", "except", "KeyError", ":", "attr_names", "=", "self", ".", "_schema", "[", "\"attribute_names\"", "]", "attrdef", "=", "attrs", ".", "get", "(", "attr_names", ".", "get", "(", "str", "(", "attrid", ")", ".", "lower", "(", ")", ")", ")", "if", "not", "attrdef", ":", "return", "None", "else", ":", "return", "dict", "(", "attrdef", ")" ]
Returns the attribute definition dict of a given attribute ID, can be the name or the integer ID
[ "Returns", "the", "attribute", "definition", "dict", "of", "a", "given", "attribute", "ID", "can", "be", "the", "name", "or", "the", "integer", "ID" ]
train
https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/items.py#L130-L145
Lagg/steamodd
steam/items.py
schema._quality_definition
def _quality_definition(self, qid): """ Returns the ID and localized name of the given quality, can be either ID type """ qualities = self._schema["qualities"] try: return qualities[qid] except KeyError: qid = self._schema["quality_names"].get(str(qid).lower(), 0) return qualities.get(qid, (qid, "normal", "Normal"))
python
def _quality_definition(self, qid): """ Returns the ID and localized name of the given quality, can be either ID type """ qualities = self._schema["qualities"] try: return qualities[qid] except KeyError: qid = self._schema["quality_names"].get(str(qid).lower(), 0) return qualities.get(qid, (qid, "normal", "Normal"))
[ "def", "_quality_definition", "(", "self", ",", "qid", ")", ":", "qualities", "=", "self", ".", "_schema", "[", "\"qualities\"", "]", "try", ":", "return", "qualities", "[", "qid", "]", "except", "KeyError", ":", "qid", "=", "self", ".", "_schema", "[", "\"quality_names\"", "]", ".", "get", "(", "str", "(", "qid", ")", ".", "lower", "(", ")", ",", "0", ")", "return", "qualities", ".", "get", "(", "qid", ",", "(", "qid", ",", "\"normal\"", ",", "\"Normal\"", ")", ")" ]
Returns the ID and localized name of the given quality, can be either ID type
[ "Returns", "the", "ID", "and", "localized", "name", "of", "the", "given", "quality", "can", "be", "either", "ID", "type" ]
train
https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/items.py#L147-L155
Lagg/steamodd
steam/items.py
schema.attributes
def attributes(self): """ Returns all attributes in the schema """ attrs = self._schema["attributes"] return [item_attribute(attr) for attr in sorted(attrs.values(), key=operator.itemgetter("defindex"))]
python
def attributes(self): """ Returns all attributes in the schema """ attrs = self._schema["attributes"] return [item_attribute(attr) for attr in sorted(attrs.values(), key=operator.itemgetter("defindex"))]
[ "def", "attributes", "(", "self", ")", ":", "attrs", "=", "self", ".", "_schema", "[", "\"attributes\"", "]", "return", "[", "item_attribute", "(", "attr", ")", "for", "attr", "in", "sorted", "(", "attrs", ".", "values", "(", ")", ",", "key", "=", "operator", ".", "itemgetter", "(", "\"defindex\"", ")", ")", "]" ]
Returns all attributes in the schema
[ "Returns", "all", "attributes", "in", "the", "schema" ]
train
https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/items.py#L158-L162
Lagg/steamodd
steam/items.py
schema.origin_id_to_name
def origin_id_to_name(self, origin): """ Returns a localized origin name for a given ID """ try: oid = int(origin) except (ValueError, TypeError): return None return self.origins.get(oid)
python
def origin_id_to_name(self, origin): """ Returns a localized origin name for a given ID """ try: oid = int(origin) except (ValueError, TypeError): return None return self.origins.get(oid)
[ "def", "origin_id_to_name", "(", "self", ",", "origin", ")", ":", "try", ":", "oid", "=", "int", "(", "origin", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "return", "None", "return", "self", ".", "origins", ".", "get", "(", "oid", ")" ]
Returns a localized origin name for a given ID
[ "Returns", "a", "localized", "origin", "name", "for", "a", "given", "ID" ]
train
https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/items.py#L195-L202
Lagg/steamodd
steam/items.py
item.attributes
def attributes(self): """ Returns a list of attributes """ overridden_attrs = self._attributes sortmap = {"neutral": 1, "positive": 2, "negative": 3} sortedattrs = list(overridden_attrs.values()) sortedattrs.sort(key=operator.itemgetter("defindex")) sortedattrs.sort(key=lambda t: sortmap.get(t.get("effect_type", "neutral"), 99)) return [item_attribute(theattr) for theattr in sortedattrs]
python
def attributes(self): """ Returns a list of attributes """ overridden_attrs = self._attributes sortmap = {"neutral": 1, "positive": 2, "negative": 3} sortedattrs = list(overridden_attrs.values()) sortedattrs.sort(key=operator.itemgetter("defindex")) sortedattrs.sort(key=lambda t: sortmap.get(t.get("effect_type", "neutral"), 99)) return [item_attribute(theattr) for theattr in sortedattrs]
[ "def", "attributes", "(", "self", ")", ":", "overridden_attrs", "=", "self", ".", "_attributes", "sortmap", "=", "{", "\"neutral\"", ":", "1", ",", "\"positive\"", ":", "2", ",", "\"negative\"", ":", "3", "}", "sortedattrs", "=", "list", "(", "overridden_attrs", ".", "values", "(", ")", ")", "sortedattrs", ".", "sort", "(", "key", "=", "operator", ".", "itemgetter", "(", "\"defindex\"", ")", ")", "sortedattrs", ".", "sort", "(", "key", "=", "lambda", "t", ":", "sortmap", ".", "get", "(", "t", ".", "get", "(", "\"effect_type\"", ",", "\"neutral\"", ")", ",", "99", ")", ")", "return", "[", "item_attribute", "(", "theattr", ")", "for", "theattr", "in", "sortedattrs", "]" ]
Returns a list of attributes
[ "Returns", "a", "list", "of", "attributes" ]
train
https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/items.py#L269-L280
Lagg/steamodd
steam/items.py
item.equipped
def equipped(self): """ Returns a dict of classes that have the item equipped and in what slot """ equipped = self._item.get("equipped", []) # WORKAROUND: 0 is probably an off-by-one error # WORKAROUND: 65535 actually serves a purpose (according to Valve) return dict([(eq["class"], eq["slot"]) for eq in equipped if eq["class"] != 0 and eq["slot"] != 65535])
python
def equipped(self): """ Returns a dict of classes that have the item equipped and in what slot """ equipped = self._item.get("equipped", []) # WORKAROUND: 0 is probably an off-by-one error # WORKAROUND: 65535 actually serves a purpose (according to Valve) return dict([(eq["class"], eq["slot"]) for eq in equipped if eq["class"] != 0 and eq["slot"] != 65535])
[ "def", "equipped", "(", "self", ")", ":", "equipped", "=", "self", ".", "_item", ".", "get", "(", "\"equipped\"", ",", "[", "]", ")", "# WORKAROUND: 0 is probably an off-by-one error", "# WORKAROUND: 65535 actually serves a purpose (according to Valve)", "return", "dict", "(", "[", "(", "eq", "[", "\"class\"", "]", ",", "eq", "[", "\"slot\"", "]", ")", "for", "eq", "in", "equipped", "if", "eq", "[", "\"class\"", "]", "!=", "0", "and", "eq", "[", "\"slot\"", "]", "!=", "65535", "]", ")" ]
Returns a dict of classes that have the item equipped and in what slot
[ "Returns", "a", "dict", "of", "classes", "that", "have", "the", "item", "equipped", "and", "in", "what", "slot" ]
train
https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/items.py#L306-L312
Lagg/steamodd
steam/items.py
item.equipable_classes
def equipable_classes(self): """ Returns a list of classes that _can_ use the item. """ sitem = self._schema_item return [c for c in sitem.get("used_by_classes", self.equipped.keys()) if c]
python
def equipable_classes(self): """ Returns a list of classes that _can_ use the item. """ sitem = self._schema_item return [c for c in sitem.get("used_by_classes", self.equipped.keys()) if c]
[ "def", "equipable_classes", "(", "self", ")", ":", "sitem", "=", "self", ".", "_schema_item", "return", "[", "c", "for", "c", "in", "sitem", ".", "get", "(", "\"used_by_classes\"", ",", "self", ".", "equipped", ".", "keys", "(", ")", ")", "if", "c", "]" ]
Returns a list of classes that _can_ use the item.
[ "Returns", "a", "list", "of", "classes", "that", "_can_", "use", "the", "item", "." ]
train
https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/items.py#L315-L319
Lagg/steamodd
steam/items.py
item.contents
def contents(self): """ Returns the item in the container, if there is one. This will be a standard item object. """ rawitem = self._item.get("contained_item") if rawitem: return self.__class__(rawitem, self._schema)
python
def contents(self): """ Returns the item in the container, if there is one. This will be a standard item object. """ rawitem = self._item.get("contained_item") if rawitem: return self.__class__(rawitem, self._schema)
[ "def", "contents", "(", "self", ")", ":", "rawitem", "=", "self", ".", "_item", ".", "get", "(", "\"contained_item\"", ")", "if", "rawitem", ":", "return", "self", ".", "__class__", "(", "rawitem", ",", "self", ".", "_schema", ")" ]
Returns the item in the container, if there is one. This will be a standard item object.
[ "Returns", "the", "item", "in", "the", "container", "if", "there", "is", "one", ".", "This", "will", "be", "a", "standard", "item", "object", "." ]
train
https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/items.py#L422-L427
Lagg/steamodd
steam/items.py
item.full_name
def full_name(self): """ The full name of the item, generated depending on things such as its quality, rank, the schema language, and so on. """ qid, quality_str, pretty_quality_str = self.quality custom_name = self.custom_name item_name = self.name english = (self._language == "en_US") rank = self.rank prefixed = self._schema_item.get("proper_name", False) prefix = '' suffix = '' pfinal = '' if item_name.startswith("The ") and prefixed: item_name = item_name[4:] if quality_str != "unique" and quality_str != "normal": pfinal = pretty_quality_str if english: if prefixed: if quality_str == "unique": pfinal = "The" elif quality_str == "unique": pfinal = '' if rank and quality_str == "strange": pfinal = rank["name"] if english: prefix = pfinal elif pfinal: suffix = '(' + pfinal + ') ' + suffix return (prefix + " " + item_name + " " + suffix).strip()
python
def full_name(self): """ The full name of the item, generated depending on things such as its quality, rank, the schema language, and so on. """ qid, quality_str, pretty_quality_str = self.quality custom_name = self.custom_name item_name = self.name english = (self._language == "en_US") rank = self.rank prefixed = self._schema_item.get("proper_name", False) prefix = '' suffix = '' pfinal = '' if item_name.startswith("The ") and prefixed: item_name = item_name[4:] if quality_str != "unique" and quality_str != "normal": pfinal = pretty_quality_str if english: if prefixed: if quality_str == "unique": pfinal = "The" elif quality_str == "unique": pfinal = '' if rank and quality_str == "strange": pfinal = rank["name"] if english: prefix = pfinal elif pfinal: suffix = '(' + pfinal + ') ' + suffix return (prefix + " " + item_name + " " + suffix).strip()
[ "def", "full_name", "(", "self", ")", ":", "qid", ",", "quality_str", ",", "pretty_quality_str", "=", "self", ".", "quality", "custom_name", "=", "self", ".", "custom_name", "item_name", "=", "self", ".", "name", "english", "=", "(", "self", ".", "_language", "==", "\"en_US\"", ")", "rank", "=", "self", ".", "rank", "prefixed", "=", "self", ".", "_schema_item", ".", "get", "(", "\"proper_name\"", ",", "False", ")", "prefix", "=", "''", "suffix", "=", "''", "pfinal", "=", "''", "if", "item_name", ".", "startswith", "(", "\"The \"", ")", "and", "prefixed", ":", "item_name", "=", "item_name", "[", "4", ":", "]", "if", "quality_str", "!=", "\"unique\"", "and", "quality_str", "!=", "\"normal\"", ":", "pfinal", "=", "pretty_quality_str", "if", "english", ":", "if", "prefixed", ":", "if", "quality_str", "==", "\"unique\"", ":", "pfinal", "=", "\"The\"", "elif", "quality_str", "==", "\"unique\"", ":", "pfinal", "=", "''", "if", "rank", "and", "quality_str", "==", "\"strange\"", ":", "pfinal", "=", "rank", "[", "\"name\"", "]", "if", "english", ":", "prefix", "=", "pfinal", "elif", "pfinal", ":", "suffix", "=", "'('", "+", "pfinal", "+", "') '", "+", "suffix", "return", "(", "prefix", "+", "\" \"", "+", "item_name", "+", "\" \"", "+", "suffix", ")", ".", "strip", "(", ")" ]
The full name of the item, generated depending on things such as its quality, rank, the schema language, and so on.
[ "The", "full", "name", "of", "the", "item", "generated", "depending", "on", "things", "such", "as", "its", "quality", "rank", "the", "schema", "language", "and", "so", "on", "." ]
train
https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/items.py#L444-L481
Lagg/steamodd
steam/items.py
item.kill_eaters
def kill_eaters(self): """ Returns a list of tuples containing the proper localized kill eater type strings and their values according to set/type/value "order" """ eaters = {} ranktypes = self._kill_types for attr in self: aname = attr.name.strip() aid = attr.id if aname.startswith("kill eater"): try: # Get the name prefix (matches up type and score and # determines the primary type for ranking) eateri = list(filter(None, aname.split(' ')))[-1] if eateri.isdigit(): eateri = int(eateri) else: # Probably the primary type/score which has no number eateri = 0 except IndexError: # Fallback to attr ID (will completely fail to make # anything legible but better than nothing) eateri = aid if aname.find("user") != -1: # User score types have lower sorting priority eateri += 100 eaters.setdefault(eateri, [None, None]) if aname.find("score type") != -1 or aname.find("kill type") != -1: # Score type attribute if eaters[eateri][0] is None: eaters[eateri][0] = attr.value else: # Value attribute eaters[eateri][1] = attr.value eaterlist = [] defaultleveldata = "KillEaterRank" for key, eater in sorted(eaters.items()): etype, count = eater # Eater type can be null (it still is in some older items), null # count means we're looking at either an uninitialized item or # schema item if count is not None: rank = ranktypes.get(etype or 0, {"level_data": defaultleveldata, "type_name": "Count"}) eaterlist.append((rank.get("level_data", defaultleveldata), rank["type_name"], count)) return eaterlist
python
def kill_eaters(self): """ Returns a list of tuples containing the proper localized kill eater type strings and their values according to set/type/value "order" """ eaters = {} ranktypes = self._kill_types for attr in self: aname = attr.name.strip() aid = attr.id if aname.startswith("kill eater"): try: # Get the name prefix (matches up type and score and # determines the primary type for ranking) eateri = list(filter(None, aname.split(' ')))[-1] if eateri.isdigit(): eateri = int(eateri) else: # Probably the primary type/score which has no number eateri = 0 except IndexError: # Fallback to attr ID (will completely fail to make # anything legible but better than nothing) eateri = aid if aname.find("user") != -1: # User score types have lower sorting priority eateri += 100 eaters.setdefault(eateri, [None, None]) if aname.find("score type") != -1 or aname.find("kill type") != -1: # Score type attribute if eaters[eateri][0] is None: eaters[eateri][0] = attr.value else: # Value attribute eaters[eateri][1] = attr.value eaterlist = [] defaultleveldata = "KillEaterRank" for key, eater in sorted(eaters.items()): etype, count = eater # Eater type can be null (it still is in some older items), null # count means we're looking at either an uninitialized item or # schema item if count is not None: rank = ranktypes.get(etype or 0, {"level_data": defaultleveldata, "type_name": "Count"}) eaterlist.append((rank.get("level_data", defaultleveldata), rank["type_name"], count)) return eaterlist
[ "def", "kill_eaters", "(", "self", ")", ":", "eaters", "=", "{", "}", "ranktypes", "=", "self", ".", "_kill_types", "for", "attr", "in", "self", ":", "aname", "=", "attr", ".", "name", ".", "strip", "(", ")", "aid", "=", "attr", ".", "id", "if", "aname", ".", "startswith", "(", "\"kill eater\"", ")", ":", "try", ":", "# Get the name prefix (matches up type and score and", "# determines the primary type for ranking)", "eateri", "=", "list", "(", "filter", "(", "None", ",", "aname", ".", "split", "(", "' '", ")", ")", ")", "[", "-", "1", "]", "if", "eateri", ".", "isdigit", "(", ")", ":", "eateri", "=", "int", "(", "eateri", ")", "else", ":", "# Probably the primary type/score which has no number", "eateri", "=", "0", "except", "IndexError", ":", "# Fallback to attr ID (will completely fail to make", "# anything legible but better than nothing)", "eateri", "=", "aid", "if", "aname", ".", "find", "(", "\"user\"", ")", "!=", "-", "1", ":", "# User score types have lower sorting priority", "eateri", "+=", "100", "eaters", ".", "setdefault", "(", "eateri", ",", "[", "None", ",", "None", "]", ")", "if", "aname", ".", "find", "(", "\"score type\"", ")", "!=", "-", "1", "or", "aname", ".", "find", "(", "\"kill type\"", ")", "!=", "-", "1", ":", "# Score type attribute", "if", "eaters", "[", "eateri", "]", "[", "0", "]", "is", "None", ":", "eaters", "[", "eateri", "]", "[", "0", "]", "=", "attr", ".", "value", "else", ":", "# Value attribute", "eaters", "[", "eateri", "]", "[", "1", "]", "=", "attr", ".", "value", "eaterlist", "=", "[", "]", "defaultleveldata", "=", "\"KillEaterRank\"", "for", "key", ",", "eater", "in", "sorted", "(", "eaters", ".", "items", "(", ")", ")", ":", "etype", ",", "count", "=", "eater", "# Eater type can be null (it still is in some older items), null", "# count means we're looking at either an uninitialized item or", "# schema item", "if", "count", "is", "not", "None", ":", "rank", "=", "ranktypes", ".", "get", "(", "etype", "or", "0", ",", "{", "\"level_data\"", ":", "defaultleveldata", ",", "\"type_name\"", ":", "\"Count\"", "}", ")", "eaterlist", ".", "append", "(", "(", "rank", ".", "get", "(", "\"level_data\"", ",", "defaultleveldata", ")", ",", "rank", "[", "\"type_name\"", "]", ",", "count", ")", ")", "return", "eaterlist" ]
Returns a list of tuples containing the proper localized kill eater type strings and their values according to set/type/value "order"
[ "Returns", "a", "list", "of", "tuples", "containing", "the", "proper", "localized", "kill", "eater", "type", "strings", "and", "their", "values", "according", "to", "set", "/", "type", "/", "value", "order" ]
train
https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/items.py#L484-L540
Lagg/steamodd
steam/items.py
item.rank
def rank(self): """ Returns the item's rank (if it has one) as a dict that includes required score, name, and level. """ if self._rank != {}: # Don't bother doing attribute lookups again return self._rank try: # The eater determining the rank levelkey, typename, count = self.kill_eaters[0] except IndexError: # Apparently no eater available self._rank = None return None rankset = self._ranks.get(levelkey, [{"level": 0, "required_score": 0, "name": "Strange"}]) for rank in rankset: self._rank = rank if count < rank["required_score"]: break return self._rank
python
def rank(self): """ Returns the item's rank (if it has one) as a dict that includes required score, name, and level. """ if self._rank != {}: # Don't bother doing attribute lookups again return self._rank try: # The eater determining the rank levelkey, typename, count = self.kill_eaters[0] except IndexError: # Apparently no eater available self._rank = None return None rankset = self._ranks.get(levelkey, [{"level": 0, "required_score": 0, "name": "Strange"}]) for rank in rankset: self._rank = rank if count < rank["required_score"]: break return self._rank
[ "def", "rank", "(", "self", ")", ":", "if", "self", ".", "_rank", "!=", "{", "}", ":", "# Don't bother doing attribute lookups again", "return", "self", ".", "_rank", "try", ":", "# The eater determining the rank", "levelkey", ",", "typename", ",", "count", "=", "self", ".", "kill_eaters", "[", "0", "]", "except", "IndexError", ":", "# Apparently no eater available", "self", ".", "_rank", "=", "None", "return", "None", "rankset", "=", "self", ".", "_ranks", ".", "get", "(", "levelkey", ",", "[", "{", "\"level\"", ":", "0", ",", "\"required_score\"", ":", "0", ",", "\"name\"", ":", "\"Strange\"", "}", "]", ")", "for", "rank", "in", "rankset", ":", "self", ".", "_rank", "=", "rank", "if", "count", "<", "rank", "[", "\"required_score\"", "]", ":", "break", "return", "self", ".", "_rank" ]
Returns the item's rank (if it has one) as a dict that includes required score, name, and level.
[ "Returns", "the", "item", "s", "rank", "(", "if", "it", "has", "one", ")", "as", "a", "dict", "that", "includes", "required", "score", "name", "and", "level", "." ]
train
https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/items.py#L543-L571
Lagg/steamodd
steam/items.py
item.available_styles
def available_styles(self): """ Returns a list of all styles defined for the item """ styles = self._schema_item.get("styles", []) return list(map(operator.itemgetter("name"), styles))
python
def available_styles(self): """ Returns a list of all styles defined for the item """ styles = self._schema_item.get("styles", []) return list(map(operator.itemgetter("name"), styles))
[ "def", "available_styles", "(", "self", ")", ":", "styles", "=", "self", ".", "_schema_item", ".", "get", "(", "\"styles\"", ",", "[", "]", ")", "return", "list", "(", "map", "(", "operator", ".", "itemgetter", "(", "\"name\"", ")", ",", "styles", ")", ")" ]
Returns a list of all styles defined for the item
[ "Returns", "a", "list", "of", "all", "styles", "defined", "for", "the", "item" ]
train
https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/items.py#L574-L578
Lagg/steamodd
steam/items.py
item_attribute.formatted_value
def formatted_value(self): """ Returns a formatted value as a string""" # TODO: Cleanup all of this, it's just weird and unnatural maths val = self.value pval = val ftype = self.value_type if ftype == "percentage": pval = int(round(val * 100)) if self.type == "negative": pval = 0 - (100 - pval) else: pval -= 100 elif ftype == "additive_percentage": pval = int(round(val * 100)) elif ftype == "inverted_percentage": pval = 100 - int(round(val * 100)) # Can't remember what workaround this was, is it needed? if self.type == "negative": if self.value > 1: pval = 0 - pval elif ftype == "additive" or ftype == "particle_index" or ftype == "account_id": if int(val) == val: pval = int(val) elif ftype == "date": d = time.gmtime(int(val)) pval = time.strftime("%Y-%m-%d %H:%M:%S", d) return u"{0}".format(pval)
python
def formatted_value(self): """ Returns a formatted value as a string""" # TODO: Cleanup all of this, it's just weird and unnatural maths val = self.value pval = val ftype = self.value_type if ftype == "percentage": pval = int(round(val * 100)) if self.type == "negative": pval = 0 - (100 - pval) else: pval -= 100 elif ftype == "additive_percentage": pval = int(round(val * 100)) elif ftype == "inverted_percentage": pval = 100 - int(round(val * 100)) # Can't remember what workaround this was, is it needed? if self.type == "negative": if self.value > 1: pval = 0 - pval elif ftype == "additive" or ftype == "particle_index" or ftype == "account_id": if int(val) == val: pval = int(val) elif ftype == "date": d = time.gmtime(int(val)) pval = time.strftime("%Y-%m-%d %H:%M:%S", d) return u"{0}".format(pval)
[ "def", "formatted_value", "(", "self", ")", ":", "# TODO: Cleanup all of this, it's just weird and unnatural maths", "val", "=", "self", ".", "value", "pval", "=", "val", "ftype", "=", "self", ".", "value_type", "if", "ftype", "==", "\"percentage\"", ":", "pval", "=", "int", "(", "round", "(", "val", "*", "100", ")", ")", "if", "self", ".", "type", "==", "\"negative\"", ":", "pval", "=", "0", "-", "(", "100", "-", "pval", ")", "else", ":", "pval", "-=", "100", "elif", "ftype", "==", "\"additive_percentage\"", ":", "pval", "=", "int", "(", "round", "(", "val", "*", "100", ")", ")", "elif", "ftype", "==", "\"inverted_percentage\"", ":", "pval", "=", "100", "-", "int", "(", "round", "(", "val", "*", "100", ")", ")", "# Can't remember what workaround this was, is it needed?", "if", "self", ".", "type", "==", "\"negative\"", ":", "if", "self", ".", "value", ">", "1", ":", "pval", "=", "0", "-", "pval", "elif", "ftype", "==", "\"additive\"", "or", "ftype", "==", "\"particle_index\"", "or", "ftype", "==", "\"account_id\"", ":", "if", "int", "(", "val", ")", "==", "val", ":", "pval", "=", "int", "(", "val", ")", "elif", "ftype", "==", "\"date\"", ":", "d", "=", "time", ".", "gmtime", "(", "int", "(", "val", ")", ")", "pval", "=", "time", ".", "strftime", "(", "\"%Y-%m-%d %H:%M:%S\"", ",", "d", ")", "return", "u\"{0}\"", ".", "format", "(", "pval", ")" ]
Returns a formatted value as a string
[ "Returns", "a", "formatted", "value", "as", "a", "string" ]
train
https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/items.py#L711-L741
Lagg/steamodd
steam/items.py
item_attribute.formatted_description
def formatted_description(self): """ Returns a formatted description string (%s* tokens replaced) or None if unavailable """ desc = self.description if desc: return desc.replace("%s1", self.formatted_value) else: return None
python
def formatted_description(self): """ Returns a formatted description string (%s* tokens replaced) or None if unavailable """ desc = self.description if desc: return desc.replace("%s1", self.formatted_value) else: return None
[ "def", "formatted_description", "(", "self", ")", ":", "desc", "=", "self", ".", "description", "if", "desc", ":", "return", "desc", ".", "replace", "(", "\"%s1\"", ",", "self", ".", "formatted_value", ")", "else", ":", "return", "None" ]
Returns a formatted description string (%s* tokens replaced) or None if unavailable
[ "Returns", "a", "formatted", "description", "string", "(", "%s", "*", "tokens", "replaced", ")", "or", "None", "if", "unavailable" ]
train
https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/items.py#L744-L751
Lagg/steamodd
steam/items.py
item_attribute.value_type
def value_type(self): """ The attribute's type, note that this is the type of the attribute's value and not its affect on the item (i.e. negative or positive). See 'type' for that. """ redundantprefix = "value_is_" vtype = self._attribute.get("description_format") if vtype and vtype.startswith(redundantprefix): return vtype[len(redundantprefix):] else: return vtype
python
def value_type(self): """ The attribute's type, note that this is the type of the attribute's value and not its affect on the item (i.e. negative or positive). See 'type' for that. """ redundantprefix = "value_is_" vtype = self._attribute.get("description_format") if vtype and vtype.startswith(redundantprefix): return vtype[len(redundantprefix):] else: return vtype
[ "def", "value_type", "(", "self", ")", ":", "redundantprefix", "=", "\"value_is_\"", "vtype", "=", "self", ".", "_attribute", ".", "get", "(", "\"description_format\"", ")", "if", "vtype", "and", "vtype", ".", "startswith", "(", "redundantprefix", ")", ":", "return", "vtype", "[", "len", "(", "redundantprefix", ")", ":", "]", "else", ":", "return", "vtype" ]
The attribute's type, note that this is the type of the attribute's value and not its affect on the item (i.e. negative or positive). See 'type' for that.
[ "The", "attribute", "s", "type", "note", "that", "this", "is", "the", "type", "of", "the", "attribute", "s", "value", "and", "not", "its", "affect", "on", "the", "item", "(", "i", ".", "e", ".", "negative", "or", "positive", ")", ".", "See", "type", "for", "that", "." ]
train
https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/items.py#L819-L829
Lagg/steamodd
steam/items.py
item_attribute.account_info
def account_info(self): """ Certain attributes have a user's account information associated with it such as a gifted or crafted item. A dict with two keys: 'persona' and 'id64'. None if the attribute has no account information attached to it. """ account_info = self._attribute.get("account_info") if account_info: return {"persona": account_info.get("personaname", ""), "id64": account_info["steamid"]} else: return None
python
def account_info(self): """ Certain attributes have a user's account information associated with it such as a gifted or crafted item. A dict with two keys: 'persona' and 'id64'. None if the attribute has no account information attached to it. """ account_info = self._attribute.get("account_info") if account_info: return {"persona": account_info.get("personaname", ""), "id64": account_info["steamid"]} else: return None
[ "def", "account_info", "(", "self", ")", ":", "account_info", "=", "self", ".", "_attribute", ".", "get", "(", "\"account_info\"", ")", "if", "account_info", ":", "return", "{", "\"persona\"", ":", "account_info", ".", "get", "(", "\"personaname\"", ",", "\"\"", ")", ",", "\"id64\"", ":", "account_info", "[", "\"steamid\"", "]", "}", "else", ":", "return", "None" ]
Certain attributes have a user's account information associated with it such as a gifted or crafted item. A dict with two keys: 'persona' and 'id64'. None if the attribute has no account information attached to it.
[ "Certain", "attributes", "have", "a", "user", "s", "account", "information", "associated", "with", "it", "such", "as", "a", "gifted", "or", "crafted", "item", "." ]
train
https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/items.py#L839-L850
Lagg/steamodd
steam/items.py
asset_item.tags
def tags(self): """ Returns a dict containing tags and their localized labels as values """ return dict([(t, self._catalog.tags.get(t, t)) for t in self._asset.get("tags", [])])
python
def tags(self): """ Returns a dict containing tags and their localized labels as values """ return dict([(t, self._catalog.tags.get(t, t)) for t in self._asset.get("tags", [])])
[ "def", "tags", "(", "self", ")", ":", "return", "dict", "(", "[", "(", "t", ",", "self", ".", "_catalog", ".", "tags", ".", "get", "(", "t", ",", "t", ")", ")", "for", "t", "in", "self", ".", "_asset", ".", "get", "(", "\"tags\"", ",", "[", "]", ")", "]", ")" ]
Returns a dict containing tags and their localized labels as values
[ "Returns", "a", "dict", "containing", "tags", "and", "their", "localized", "labels", "as", "values" ]
train
https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/items.py#L965-L967
Lagg/steamodd
steam/user.py
profile.vanity
def vanity(self): """ Returns the user's vanity url if it exists, None otherwise """ purl = self.profile_url.strip('/') if purl.find("/id/") != -1: return os.path.basename(purl)
python
def vanity(self): """ Returns the user's vanity url if it exists, None otherwise """ purl = self.profile_url.strip('/') if purl.find("/id/") != -1: return os.path.basename(purl)
[ "def", "vanity", "(", "self", ")", ":", "purl", "=", "self", ".", "profile_url", ".", "strip", "(", "'/'", ")", "if", "purl", ".", "find", "(", "\"/id/\"", ")", "!=", "-", "1", ":", "return", "os", ".", "path", ".", "basename", "(", "purl", ")" ]
Returns the user's vanity url if it exists, None otherwise
[ "Returns", "the", "user", "s", "vanity", "url", "if", "it", "exists", "None", "otherwise" ]
train
https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/user.py#L90-L94
Lagg/steamodd
steam/user.py
profile.creation_date
def creation_date(self): """ Returns the account creation date as a localtime time.struct_time struct if public""" timestamp = self._prof.get("timecreated") if timestamp: return time.localtime(timestamp)
python
def creation_date(self): """ Returns the account creation date as a localtime time.struct_time struct if public""" timestamp = self._prof.get("timecreated") if timestamp: return time.localtime(timestamp)
[ "def", "creation_date", "(", "self", ")", ":", "timestamp", "=", "self", ".", "_prof", ".", "get", "(", "\"timecreated\"", ")", "if", "timestamp", ":", "return", "time", ".", "localtime", "(", "timestamp", ")" ]
Returns the account creation date as a localtime time.struct_time struct if public
[ "Returns", "the", "account", "creation", "date", "as", "a", "localtime", "time", ".", "struct_time", "struct", "if", "public" ]
train
https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/user.py#L158-L163
Lagg/steamodd
steam/user.py
profile.current_game
def current_game(self): """ Returns a tuple of 3 elements (each of which may be None if not available): Current game app ID, server ip:port, misc. extra info (eg. game title) """ obj = self._prof gameid = obj.get("gameid") gameserverip = obj.get("gameserverip") gameextrainfo = obj.get("gameextrainfo") return (int(gameid) if gameid else None, gameserverip, gameextrainfo)
python
def current_game(self): """ Returns a tuple of 3 elements (each of which may be None if not available): Current game app ID, server ip:port, misc. extra info (eg. game title) """ obj = self._prof gameid = obj.get("gameid") gameserverip = obj.get("gameserverip") gameextrainfo = obj.get("gameextrainfo") return (int(gameid) if gameid else None, gameserverip, gameextrainfo)
[ "def", "current_game", "(", "self", ")", ":", "obj", "=", "self", ".", "_prof", "gameid", "=", "obj", ".", "get", "(", "\"gameid\"", ")", "gameserverip", "=", "obj", ".", "get", "(", "\"gameserverip\"", ")", "gameextrainfo", "=", "obj", ".", "get", "(", "\"gameextrainfo\"", ")", "return", "(", "int", "(", "gameid", ")", "if", "gameid", "else", "None", ",", "gameserverip", ",", "gameextrainfo", ")" ]
Returns a tuple of 3 elements (each of which may be None if not available): Current game app ID, server ip:port, misc. extra info (eg. game title)
[ "Returns", "a", "tuple", "of", "3", "elements", "(", "each", "of", "which", "may", "be", "None", "if", "not", "available", ")", ":", "Current", "game", "app", "ID", "server", "ip", ":", "port", "misc", ".", "extra", "info", "(", "eg", ".", "game", "title", ")" ]
train
https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/user.py#L166-L175
Lagg/steamodd
steam/user.py
profile.level
def level(self): """ Returns the the user's profile level, note that this runs a separate request because the profile level data isn't in the standard player summary output even though it should be. Which is also why it's not implemented as a separate class. You won't need this output and not the profile output """ level_key = "player_level" if level_key in self._api["response"]: return self._api["response"][level_key] try: lvl = api.interface("IPlayerService").GetSteamLevel(steamid=self.id64)["response"][level_key] self._api["response"][level_key] = lvl return lvl except: return -1
python
def level(self): """ Returns the the user's profile level, note that this runs a separate request because the profile level data isn't in the standard player summary output even though it should be. Which is also why it's not implemented as a separate class. You won't need this output and not the profile output """ level_key = "player_level" if level_key in self._api["response"]: return self._api["response"][level_key] try: lvl = api.interface("IPlayerService").GetSteamLevel(steamid=self.id64)["response"][level_key] self._api["response"][level_key] = lvl return lvl except: return -1
[ "def", "level", "(", "self", ")", ":", "level_key", "=", "\"player_level\"", "if", "level_key", "in", "self", ".", "_api", "[", "\"response\"", "]", ":", "return", "self", ".", "_api", "[", "\"response\"", "]", "[", "level_key", "]", "try", ":", "lvl", "=", "api", ".", "interface", "(", "\"IPlayerService\"", ")", ".", "GetSteamLevel", "(", "steamid", "=", "self", ".", "id64", ")", "[", "\"response\"", "]", "[", "level_key", "]", "self", ".", "_api", "[", "\"response\"", "]", "[", "level_key", "]", "=", "lvl", "return", "lvl", "except", ":", "return", "-", "1" ]
Returns the the user's profile level, note that this runs a separate request because the profile level data isn't in the standard player summary output even though it should be. Which is also why it's not implemented as a separate class. You won't need this output and not the profile output
[ "Returns", "the", "the", "user", "s", "profile", "level", "note", "that", "this", "runs", "a", "separate", "request", "because", "the", "profile", "level", "data", "isn", "t", "in", "the", "standard", "player", "summary", "output", "even", "though", "it", "should", "be", ".", "Which", "is", "also", "why", "it", "s", "not", "implemented", "as", "a", "separate", "class", ".", "You", "won", "t", "need", "this", "output", "and", "not", "the", "profile", "output" ]
train
https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/user.py#L208-L226
Lagg/steamodd
steam/user.py
profile.from_def
def from_def(cls, obj): """ Builds a profile object from a raw player summary object """ prof = cls(obj["steamid"]) prof._cache = obj return prof
python
def from_def(cls, obj): """ Builds a profile object from a raw player summary object """ prof = cls(obj["steamid"]) prof._cache = obj return prof
[ "def", "from_def", "(", "cls", ",", "obj", ")", ":", "prof", "=", "cls", "(", "obj", "[", "\"steamid\"", "]", ")", "prof", ".", "_cache", "=", "obj", "return", "prof" ]
Builds a profile object from a raw player summary object
[ "Builds", "a", "profile", "object", "from", "a", "raw", "player", "summary", "object" ]
train
https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/user.py#L229-L234
michaelbrooks/twitter-monitor
twitter_monitor/listener.py
JsonStreamListener.on_status_withheld
def on_status_withheld(self, status_id, user_id, countries): """Called when a status is withheld""" logger.info('Status %s withheld for user %s', status_id, user_id) return True
python
def on_status_withheld(self, status_id, user_id, countries): """Called when a status is withheld""" logger.info('Status %s withheld for user %s', status_id, user_id) return True
[ "def", "on_status_withheld", "(", "self", ",", "status_id", ",", "user_id", ",", "countries", ")", ":", "logger", ".", "info", "(", "'Status %s withheld for user %s'", ",", "status_id", ",", "user_id", ")", "return", "True" ]
Called when a status is withheld
[ "Called", "when", "a", "status", "is", "withheld" ]
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/listener.py#L91-L94
michaelbrooks/twitter-monitor
twitter_monitor/listener.py
JsonStreamListener.on_disconnect
def on_disconnect(self, code, stream_name, reason): """Called when a disconnect is received""" logger.error('Disconnect message: %s %s %s', code, stream_name, reason) return True
python
def on_disconnect(self, code, stream_name, reason): """Called when a disconnect is received""" logger.error('Disconnect message: %s %s %s', code, stream_name, reason) return True
[ "def", "on_disconnect", "(", "self", ",", "code", ",", "stream_name", ",", "reason", ")", ":", "logger", ".", "error", "(", "'Disconnect message: %s %s %s'", ",", "code", ",", "stream_name", ",", "reason", ")", "return", "True" ]
Called when a disconnect is received
[ "Called", "when", "a", "disconnect", "is", "received" ]
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/listener.py#L101-L104
michaelbrooks/twitter-monitor
twitter_monitor/listener.py
JsonStreamListener.on_error
def on_error(self, status_code): """Called when a non-200 status code is returned""" logger.error('Twitter returned error code %s', status_code) self.error = status_code return False
python
def on_error(self, status_code): """Called when a non-200 status code is returned""" logger.error('Twitter returned error code %s', status_code) self.error = status_code return False
[ "def", "on_error", "(", "self", ",", "status_code", ")", ":", "logger", ".", "error", "(", "'Twitter returned error code %s'", ",", "status_code", ")", "self", ".", "error", "=", "status_code", "return", "False" ]
Called when a non-200 status code is returned
[ "Called", "when", "a", "non", "-", "200", "status", "code", "is", "returned" ]
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/listener.py#L110-L114
michaelbrooks/twitter-monitor
twitter_monitor/listener.py
JsonStreamListener.on_exception
def on_exception(self, exception): """An exception occurred in the streaming thread""" logger.error('Exception from stream!', exc_info=True) self.streaming_exception = exception
python
def on_exception(self, exception): """An exception occurred in the streaming thread""" logger.error('Exception from stream!', exc_info=True) self.streaming_exception = exception
[ "def", "on_exception", "(", "self", ",", "exception", ")", ":", "logger", ".", "error", "(", "'Exception from stream!'", ",", "exc_info", "=", "True", ")", "self", ".", "streaming_exception", "=", "exception" ]
An exception occurred in the streaming thread
[ "An", "exception", "occurred", "in", "the", "streaming", "thread" ]
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/listener.py#L121-L124
michaelbrooks/twitter-monitor
twitter_monitor/checker.py
TermChecker.check
def check(self): """ Checks if the list of tracked terms has changed. Returns True if changed, otherwise False. """ new_tracking_terms = self.update_tracking_terms() terms_changed = False # any deleted terms? if self._tracking_terms_set > new_tracking_terms: logging.debug("Some tracking terms removed") terms_changed = True # any added terms? elif self._tracking_terms_set < new_tracking_terms: logging.debug("Some tracking terms added") terms_changed = True # Go ahead and store for later self._tracking_terms_set = new_tracking_terms # If the terms changed, we need to restart the stream return terms_changed
python
def check(self): """ Checks if the list of tracked terms has changed. Returns True if changed, otherwise False. """ new_tracking_terms = self.update_tracking_terms() terms_changed = False # any deleted terms? if self._tracking_terms_set > new_tracking_terms: logging.debug("Some tracking terms removed") terms_changed = True # any added terms? elif self._tracking_terms_set < new_tracking_terms: logging.debug("Some tracking terms added") terms_changed = True # Go ahead and store for later self._tracking_terms_set = new_tracking_terms # If the terms changed, we need to restart the stream return terms_changed
[ "def", "check", "(", "self", ")", ":", "new_tracking_terms", "=", "self", ".", "update_tracking_terms", "(", ")", "terms_changed", "=", "False", "# any deleted terms?", "if", "self", ".", "_tracking_terms_set", ">", "new_tracking_terms", ":", "logging", ".", "debug", "(", "\"Some tracking terms removed\"", ")", "terms_changed", "=", "True", "# any added terms?", "elif", "self", ".", "_tracking_terms_set", "<", "new_tracking_terms", ":", "logging", ".", "debug", "(", "\"Some tracking terms added\"", ")", "terms_changed", "=", "True", "# Go ahead and store for later", "self", ".", "_tracking_terms_set", "=", "new_tracking_terms", "# If the terms changed, we need to restart the stream", "return", "terms_changed" ]
Checks if the list of tracked terms has changed. Returns True if changed, otherwise False.
[ "Checks", "if", "the", "list", "of", "tracked", "terms", "has", "changed", ".", "Returns", "True", "if", "changed", "otherwise", "False", "." ]
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/checker.py#L33-L57
michaelbrooks/twitter-monitor
twitter_monitor/checker.py
FileTermChecker.update_tracking_terms
def update_tracking_terms(self): """ Terms must be one-per-line. Blank lines will be skipped. """ import codecs with codecs.open(self.filename,"r", encoding='utf8') as input: # read all the lines lines = input.readlines() # build a set of terms new_terms = set() for line in lines: line = line.strip() if len(line): new_terms.add(line) return set(new_terms)
python
def update_tracking_terms(self): """ Terms must be one-per-line. Blank lines will be skipped. """ import codecs with codecs.open(self.filename,"r", encoding='utf8') as input: # read all the lines lines = input.readlines() # build a set of terms new_terms = set() for line in lines: line = line.strip() if len(line): new_terms.add(line) return set(new_terms)
[ "def", "update_tracking_terms", "(", "self", ")", ":", "import", "codecs", "with", "codecs", ".", "open", "(", "self", ".", "filename", ",", "\"r\"", ",", "encoding", "=", "'utf8'", ")", "as", "input", ":", "# read all the lines", "lines", "=", "input", ".", "readlines", "(", ")", "# build a set of terms", "new_terms", "=", "set", "(", ")", "for", "line", "in", "lines", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "len", "(", "line", ")", ":", "new_terms", ".", "add", "(", "line", ")", "return", "set", "(", "new_terms", ")" ]
Terms must be one-per-line. Blank lines will be skipped.
[ "Terms", "must", "be", "one", "-", "per", "-", "line", ".", "Blank", "lines", "will", "be", "skipped", "." ]
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/checker.py#L75-L92
michaelbrooks/twitter-monitor
twitter_monitor/basic_stream.py
launch_debugger
def launch_debugger(frame, stream=None): """ Interrupt running process, and provide a python prompt for interactive debugging. """ d = {'_frame': frame} # Allow access to frame object. d.update(frame.f_globals) # Unless shadowed by global d.update(frame.f_locals) import code, traceback i = code.InteractiveConsole(d) message = "Signal received : entering python shell.\nTraceback:\n" message += ''.join(traceback.format_stack(frame)) i.interact(message)
python
def launch_debugger(frame, stream=None): """ Interrupt running process, and provide a python prompt for interactive debugging. """ d = {'_frame': frame} # Allow access to frame object. d.update(frame.f_globals) # Unless shadowed by global d.update(frame.f_locals) import code, traceback i = code.InteractiveConsole(d) message = "Signal received : entering python shell.\nTraceback:\n" message += ''.join(traceback.format_stack(frame)) i.interact(message)
[ "def", "launch_debugger", "(", "frame", ",", "stream", "=", "None", ")", ":", "d", "=", "{", "'_frame'", ":", "frame", "}", "# Allow access to frame object.", "d", ".", "update", "(", "frame", ".", "f_globals", ")", "# Unless shadowed by global", "d", ".", "update", "(", "frame", ".", "f_locals", ")", "import", "code", ",", "traceback", "i", "=", "code", ".", "InteractiveConsole", "(", "d", ")", "message", "=", "\"Signal received : entering python shell.\\nTraceback:\\n\"", "message", "+=", "''", ".", "join", "(", "traceback", ".", "format_stack", "(", "frame", ")", ")", "i", ".", "interact", "(", "message", ")" ]
Interrupt running process, and provide a python prompt for interactive debugging.
[ "Interrupt", "running", "process", "and", "provide", "a", "python", "prompt", "for", "interactive", "debugging", "." ]
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L75-L90
michaelbrooks/twitter-monitor
twitter_monitor/basic_stream.py
set_debug_listener
def set_debug_listener(stream): """Break into a debugger if receives the SIGUSR1 signal""" def debugger(sig, frame): launch_debugger(frame, stream) if hasattr(signal, 'SIGUSR1'): signal.signal(signal.SIGUSR1, debugger) else: logger.warn("Cannot set SIGUSR1 signal for debug mode.")
python
def set_debug_listener(stream): """Break into a debugger if receives the SIGUSR1 signal""" def debugger(sig, frame): launch_debugger(frame, stream) if hasattr(signal, 'SIGUSR1'): signal.signal(signal.SIGUSR1, debugger) else: logger.warn("Cannot set SIGUSR1 signal for debug mode.")
[ "def", "set_debug_listener", "(", "stream", ")", ":", "def", "debugger", "(", "sig", ",", "frame", ")", ":", "launch_debugger", "(", "frame", ",", "stream", ")", "if", "hasattr", "(", "signal", ",", "'SIGUSR1'", ")", ":", "signal", ".", "signal", "(", "signal", ".", "SIGUSR1", ",", "debugger", ")", "else", ":", "logger", ".", "warn", "(", "\"Cannot set SIGUSR1 signal for debug mode.\"", ")" ]
Break into a debugger if receives the SIGUSR1 signal
[ "Break", "into", "a", "debugger", "if", "receives", "the", "SIGUSR1", "signal" ]
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L93-L102
michaelbrooks/twitter-monitor
twitter_monitor/basic_stream.py
set_terminate_listeners
def set_terminate_listeners(stream): """Die on SIGTERM or SIGINT""" def stop(signum, frame): terminate(stream.listener) # Installs signal handlers for handling SIGINT and SIGTERM # gracefully. signal.signal(signal.SIGINT, stop) signal.signal(signal.SIGTERM, stop)
python
def set_terminate_listeners(stream): """Die on SIGTERM or SIGINT""" def stop(signum, frame): terminate(stream.listener) # Installs signal handlers for handling SIGINT and SIGTERM # gracefully. signal.signal(signal.SIGINT, stop) signal.signal(signal.SIGTERM, stop)
[ "def", "set_terminate_listeners", "(", "stream", ")", ":", "def", "stop", "(", "signum", ",", "frame", ")", ":", "terminate", "(", "stream", ".", "listener", ")", "# Installs signal handlers for handling SIGINT and SIGTERM", "# gracefully.", "signal", ".", "signal", "(", "signal", ".", "SIGINT", ",", "stop", ")", "signal", ".", "signal", "(", "signal", ".", "SIGTERM", ",", "stop", ")" ]
Die on SIGTERM or SIGINT
[ "Die", "on", "SIGTERM", "or", "SIGINT" ]
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L115-L124
michaelbrooks/twitter-monitor
twitter_monitor/basic_stream.py
get_tweepy_auth
def get_tweepy_auth(twitter_api_key, twitter_api_secret, twitter_access_token, twitter_access_token_secret): """Make a tweepy auth object""" auth = tweepy.OAuthHandler(twitter_api_key, twitter_api_secret) auth.set_access_token(twitter_access_token, twitter_access_token_secret) return auth
python
def get_tweepy_auth(twitter_api_key, twitter_api_secret, twitter_access_token, twitter_access_token_secret): """Make a tweepy auth object""" auth = tweepy.OAuthHandler(twitter_api_key, twitter_api_secret) auth.set_access_token(twitter_access_token, twitter_access_token_secret) return auth
[ "def", "get_tweepy_auth", "(", "twitter_api_key", ",", "twitter_api_secret", ",", "twitter_access_token", ",", "twitter_access_token_secret", ")", ":", "auth", "=", "tweepy", ".", "OAuthHandler", "(", "twitter_api_key", ",", "twitter_api_secret", ")", "auth", ".", "set_access_token", "(", "twitter_access_token", ",", "twitter_access_token_secret", ")", "return", "auth" ]
Make a tweepy auth object
[ "Make", "a", "tweepy", "auth", "object" ]
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L127-L134
michaelbrooks/twitter-monitor
twitter_monitor/basic_stream.py
construct_listener
def construct_listener(outfile=None): """Create the listener that prints tweets""" if outfile is not None: if os.path.exists(outfile): raise IOError("File %s already exists" % outfile) outfile = open(outfile, 'wb') return PrintingListener(out=outfile)
python
def construct_listener(outfile=None): """Create the listener that prints tweets""" if outfile is not None: if os.path.exists(outfile): raise IOError("File %s already exists" % outfile) outfile = open(outfile, 'wb') return PrintingListener(out=outfile)
[ "def", "construct_listener", "(", "outfile", "=", "None", ")", ":", "if", "outfile", "is", "not", "None", ":", "if", "os", ".", "path", ".", "exists", "(", "outfile", ")", ":", "raise", "IOError", "(", "\"File %s already exists\"", "%", "outfile", ")", "outfile", "=", "open", "(", "outfile", ",", "'wb'", ")", "return", "PrintingListener", "(", "out", "=", "outfile", ")" ]
Create the listener that prints tweets
[ "Create", "the", "listener", "that", "prints", "tweets" ]
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L137-L145
michaelbrooks/twitter-monitor
twitter_monitor/basic_stream.py
begin_stream_loop
def begin_stream_loop(stream, poll_interval): """Start and maintain the streaming connection...""" while should_continue(): try: stream.start_polling(poll_interval) except Exception as e: # Infinite restart logger.error("Exception while polling. Restarting in 1 second.", exc_info=True) time.sleep(1)
python
def begin_stream_loop(stream, poll_interval): """Start and maintain the streaming connection...""" while should_continue(): try: stream.start_polling(poll_interval) except Exception as e: # Infinite restart logger.error("Exception while polling. Restarting in 1 second.", exc_info=True) time.sleep(1)
[ "def", "begin_stream_loop", "(", "stream", ",", "poll_interval", ")", ":", "while", "should_continue", "(", ")", ":", "try", ":", "stream", ".", "start_polling", "(", "poll_interval", ")", "except", "Exception", "as", "e", ":", "# Infinite restart", "logger", ".", "error", "(", "\"Exception while polling. Restarting in 1 second.\"", ",", "exc_info", "=", "True", ")", "time", ".", "sleep", "(", "1", ")" ]
Start and maintain the streaming connection...
[ "Start", "and", "maintain", "the", "streaming", "connection", "..." ]
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L150-L158
michaelbrooks/twitter-monitor
twitter_monitor/basic_stream.py
start
def start(track_file, twitter_api_key, twitter_api_secret, twitter_access_token, twitter_access_token_secret, poll_interval=15, unfiltered=False, languages=None, debug=False, outfile=None): """Start the stream.""" listener = construct_listener(outfile) checker = BasicFileTermChecker(track_file, listener) auth = get_tweepy_auth(twitter_api_key, twitter_api_secret, twitter_access_token, twitter_access_token_secret) stream = DynamicTwitterStream(auth, listener, checker, unfiltered=unfiltered, languages=languages) set_terminate_listeners(stream) if debug: set_debug_listener(stream) begin_stream_loop(stream, poll_interval)
python
def start(track_file, twitter_api_key, twitter_api_secret, twitter_access_token, twitter_access_token_secret, poll_interval=15, unfiltered=False, languages=None, debug=False, outfile=None): """Start the stream.""" listener = construct_listener(outfile) checker = BasicFileTermChecker(track_file, listener) auth = get_tweepy_auth(twitter_api_key, twitter_api_secret, twitter_access_token, twitter_access_token_secret) stream = DynamicTwitterStream(auth, listener, checker, unfiltered=unfiltered, languages=languages) set_terminate_listeners(stream) if debug: set_debug_listener(stream) begin_stream_loop(stream, poll_interval)
[ "def", "start", "(", "track_file", ",", "twitter_api_key", ",", "twitter_api_secret", ",", "twitter_access_token", ",", "twitter_access_token_secret", ",", "poll_interval", "=", "15", ",", "unfiltered", "=", "False", ",", "languages", "=", "None", ",", "debug", "=", "False", ",", "outfile", "=", "None", ")", ":", "listener", "=", "construct_listener", "(", "outfile", ")", "checker", "=", "BasicFileTermChecker", "(", "track_file", ",", "listener", ")", "auth", "=", "get_tweepy_auth", "(", "twitter_api_key", ",", "twitter_api_secret", ",", "twitter_access_token", ",", "twitter_access_token_secret", ")", "stream", "=", "DynamicTwitterStream", "(", "auth", ",", "listener", ",", "checker", ",", "unfiltered", "=", "unfiltered", ",", "languages", "=", "languages", ")", "set_terminate_listeners", "(", "stream", ")", "if", "debug", ":", "set_debug_listener", "(", "stream", ")", "begin_stream_loop", "(", "stream", ",", "poll_interval", ")" ]
Start the stream.
[ "Start", "the", "stream", "." ]
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L161-L186
michaelbrooks/twitter-monitor
twitter_monitor/basic_stream.py
PrintingListener.on_status
def on_status(self, status): """Print out some tweets""" self.out.write(json.dumps(status)) self.out.write(os.linesep) self.received += 1 return not self.terminate
python
def on_status(self, status): """Print out some tweets""" self.out.write(json.dumps(status)) self.out.write(os.linesep) self.received += 1 return not self.terminate
[ "def", "on_status", "(", "self", ",", "status", ")", ":", "self", ".", "out", ".", "write", "(", "json", ".", "dumps", "(", "status", ")", ")", "self", ".", "out", ".", "write", "(", "os", ".", "linesep", ")", "self", ".", "received", "+=", "1", "return", "not", "self", ".", "terminate" ]
Print out some tweets
[ "Print", "out", "some", "tweets" ]
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L38-L44
michaelbrooks/twitter-monitor
twitter_monitor/basic_stream.py
PrintingListener.print_status
def print_status(self): """Print out the current tweet rate and reset the counter""" tweets = self.received now = time.time() diff = now - self.since self.since = now self.received = 0 if diff > 0: logger.info("Receiving tweets at %s tps", tweets / diff)
python
def print_status(self): """Print out the current tweet rate and reset the counter""" tweets = self.received now = time.time() diff = now - self.since self.since = now self.received = 0 if diff > 0: logger.info("Receiving tweets at %s tps", tweets / diff)
[ "def", "print_status", "(", "self", ")", ":", "tweets", "=", "self", ".", "received", "now", "=", "time", ".", "time", "(", ")", "diff", "=", "now", "-", "self", ".", "since", "self", ".", "since", "=", "now", "self", ".", "received", "=", "0", "if", "diff", ">", "0", ":", "logger", ".", "info", "(", "\"Receiving tweets at %s tps\"", ",", "tweets", "/", "diff", ")" ]
Print out the current tweet rate and reset the counter
[ "Print", "out", "the", "current", "tweet", "rate", "and", "reset", "the", "counter" ]
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L50-L58
michaelbrooks/twitter-monitor
twitter_monitor/stream.py
DynamicTwitterStream.start_polling
def start_polling(self, interval): """ Start polling for term updates and streaming. """ interval = float(interval) self.polling = True # clear the stored list of terms - we aren't tracking any self.term_checker.reset() logger.info("Starting polling for changes to the track list") while self.polling: loop_start = time() self.update_stream() self.handle_exceptions() # wait for the interval unless interrupted, compensating for time elapsed in the loop elapsed = time() - loop_start sleep(max(0.1, interval - elapsed)) logger.warning("Term poll ceased!")
python
def start_polling(self, interval): """ Start polling for term updates and streaming. """ interval = float(interval) self.polling = True # clear the stored list of terms - we aren't tracking any self.term_checker.reset() logger.info("Starting polling for changes to the track list") while self.polling: loop_start = time() self.update_stream() self.handle_exceptions() # wait for the interval unless interrupted, compensating for time elapsed in the loop elapsed = time() - loop_start sleep(max(0.1, interval - elapsed)) logger.warning("Term poll ceased!")
[ "def", "start_polling", "(", "self", ",", "interval", ")", ":", "interval", "=", "float", "(", "interval", ")", "self", ".", "polling", "=", "True", "# clear the stored list of terms - we aren't tracking any", "self", ".", "term_checker", ".", "reset", "(", ")", "logger", ".", "info", "(", "\"Starting polling for changes to the track list\"", ")", "while", "self", ".", "polling", ":", "loop_start", "=", "time", "(", ")", "self", ".", "update_stream", "(", ")", "self", ".", "handle_exceptions", "(", ")", "# wait for the interval unless interrupted, compensating for time elapsed in the loop", "elapsed", "=", "time", "(", ")", "-", "loop_start", "sleep", "(", "max", "(", "0.1", ",", "interval", "-", "elapsed", ")", ")", "logger", ".", "warning", "(", "\"Term poll ceased!\"", ")" ]
Start polling for term updates and streaming.
[ "Start", "polling", "for", "term", "updates", "and", "streaming", "." ]
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/stream.py#L33-L56
michaelbrooks/twitter-monitor
twitter_monitor/stream.py
DynamicTwitterStream.update_stream
def update_stream(self): """ Restarts the stream with the current list of tracking terms. """ need_to_restart = False # If we think we are running, but something has gone wrong in the streaming thread # Restart it. if self.stream is not None and not self.stream.running: logger.warning("Stream exists but isn't running") self.listener.error = False self.listener.streaming_exception = None need_to_restart = True # Check if the tracking list has changed if self.term_checker.check(): logger.info("Terms have changed") need_to_restart = True # If we aren't running and we are allowing unfiltered streams if self.stream is None and self.unfiltered: need_to_restart = True if not need_to_restart: return logger.info("Restarting stream...") # Stop any old stream self.stop_stream() # Start a new stream self.start_stream()
python
def update_stream(self): """ Restarts the stream with the current list of tracking terms. """ need_to_restart = False # If we think we are running, but something has gone wrong in the streaming thread # Restart it. if self.stream is not None and not self.stream.running: logger.warning("Stream exists but isn't running") self.listener.error = False self.listener.streaming_exception = None need_to_restart = True # Check if the tracking list has changed if self.term_checker.check(): logger.info("Terms have changed") need_to_restart = True # If we aren't running and we are allowing unfiltered streams if self.stream is None and self.unfiltered: need_to_restart = True if not need_to_restart: return logger.info("Restarting stream...") # Stop any old stream self.stop_stream() # Start a new stream self.start_stream()
[ "def", "update_stream", "(", "self", ")", ":", "need_to_restart", "=", "False", "# If we think we are running, but something has gone wrong in the streaming thread", "# Restart it.", "if", "self", ".", "stream", "is", "not", "None", "and", "not", "self", ".", "stream", ".", "running", ":", "logger", ".", "warning", "(", "\"Stream exists but isn't running\"", ")", "self", ".", "listener", ".", "error", "=", "False", "self", ".", "listener", ".", "streaming_exception", "=", "None", "need_to_restart", "=", "True", "# Check if the tracking list has changed", "if", "self", ".", "term_checker", ".", "check", "(", ")", ":", "logger", ".", "info", "(", "\"Terms have changed\"", ")", "need_to_restart", "=", "True", "# If we aren't running and we are allowing unfiltered streams", "if", "self", ".", "stream", "is", "None", "and", "self", ".", "unfiltered", ":", "need_to_restart", "=", "True", "if", "not", "need_to_restart", ":", "return", "logger", ".", "info", "(", "\"Restarting stream...\"", ")", "# Stop any old stream", "self", ".", "stop_stream", "(", ")", "# Start a new stream", "self", ".", "start_stream", "(", ")" ]
Restarts the stream with the current list of tracking terms.
[ "Restarts", "the", "stream", "with", "the", "current", "list", "of", "tracking", "terms", "." ]
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/stream.py#L65-L98
michaelbrooks/twitter-monitor
twitter_monitor/stream.py
DynamicTwitterStream.start_stream
def start_stream(self): """Starts a stream with teh current tracking terms""" tracking_terms = self.term_checker.tracking_terms() if len(tracking_terms) > 0 or self.unfiltered: # we have terms to track, so build a new stream self.stream = tweepy.Stream(self.auth, self.listener, stall_warnings=True, timeout=90, retry_count=self.retry_count) if len(tracking_terms) > 0: logger.info("Starting new twitter stream with %s terms:", len(tracking_terms)) logger.info(" %s", repr(tracking_terms)) # Launch it in a new thread self.stream.filter(track=tracking_terms, async=True, languages=self.languages) else: logger.info("Starting new unfiltered stream") self.stream.sample(async=True, languages=self.languages)
python
def start_stream(self): """Starts a stream with teh current tracking terms""" tracking_terms = self.term_checker.tracking_terms() if len(tracking_terms) > 0 or self.unfiltered: # we have terms to track, so build a new stream self.stream = tweepy.Stream(self.auth, self.listener, stall_warnings=True, timeout=90, retry_count=self.retry_count) if len(tracking_terms) > 0: logger.info("Starting new twitter stream with %s terms:", len(tracking_terms)) logger.info(" %s", repr(tracking_terms)) # Launch it in a new thread self.stream.filter(track=tracking_terms, async=True, languages=self.languages) else: logger.info("Starting new unfiltered stream") self.stream.sample(async=True, languages=self.languages)
[ "def", "start_stream", "(", "self", ")", ":", "tracking_terms", "=", "self", ".", "term_checker", ".", "tracking_terms", "(", ")", "if", "len", "(", "tracking_terms", ")", ">", "0", "or", "self", ".", "unfiltered", ":", "# we have terms to track, so build a new stream", "self", ".", "stream", "=", "tweepy", ".", "Stream", "(", "self", ".", "auth", ",", "self", ".", "listener", ",", "stall_warnings", "=", "True", ",", "timeout", "=", "90", ",", "retry_count", "=", "self", ".", "retry_count", ")", "if", "len", "(", "tracking_terms", ")", ">", "0", ":", "logger", ".", "info", "(", "\"Starting new twitter stream with %s terms:\"", ",", "len", "(", "tracking_terms", ")", ")", "logger", ".", "info", "(", "\" %s\"", ",", "repr", "(", "tracking_terms", ")", ")", "# Launch it in a new thread", "self", ".", "stream", ".", "filter", "(", "track", "=", "tracking_terms", ",", "async", "=", "True", ",", "languages", "=", "self", ".", "languages", ")", "else", ":", "logger", ".", "info", "(", "\"Starting new unfiltered stream\"", ")", "self", ".", "stream", ".", "sample", "(", "async", "=", "True", ",", "languages", "=", "self", ".", "languages", ")" ]
Starts a stream with teh current tracking terms
[ "Starts", "a", "stream", "with", "teh", "current", "tracking", "terms" ]
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/stream.py#L100-L120
michaelbrooks/twitter-monitor
twitter_monitor/stream.py
DynamicTwitterStream.stop_stream
def stop_stream(self): """ Stops the current stream. Blocks until this is done. """ if self.stream is not None: # There is a streaming thread logger.warning("Stopping twitter stream...") self.stream.disconnect() self.stream = None # wait a few seconds to allow the streaming to actually stop sleep(self.STOP_TIMEOUT)
python
def stop_stream(self): """ Stops the current stream. Blocks until this is done. """ if self.stream is not None: # There is a streaming thread logger.warning("Stopping twitter stream...") self.stream.disconnect() self.stream = None # wait a few seconds to allow the streaming to actually stop sleep(self.STOP_TIMEOUT)
[ "def", "stop_stream", "(", "self", ")", ":", "if", "self", ".", "stream", "is", "not", "None", ":", "# There is a streaming thread", "logger", ".", "warning", "(", "\"Stopping twitter stream...\"", ")", "self", ".", "stream", ".", "disconnect", "(", ")", "self", ".", "stream", "=", "None", "# wait a few seconds to allow the streaming to actually stop", "sleep", "(", "self", ".", "STOP_TIMEOUT", ")" ]
Stops the current stream. Blocks until this is done.
[ "Stops", "the", "current", "stream", ".", "Blocks", "until", "this", "is", "done", "." ]
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/stream.py#L122-L136
coagulant/django-twitter-tag
twitter_tag/templatetags/twitter_tag.py
BaseTwitterTag.enrich
def enrich(self, tweet): """ Apply the local presentation logic to the fetched data.""" tweet = urlize_tweet(expand_tweet_urls(tweet)) # parses created_at "Wed Aug 27 13:08:45 +0000 2008" if settings.USE_TZ: tweet['datetime'] = datetime.strptime(tweet['created_at'], '%a %b %d %H:%M:%S +0000 %Y').replace(tzinfo=timezone.utc) else: tweet['datetime'] = datetime.strptime(tweet['created_at'], '%a %b %d %H:%M:%S +0000 %Y') return tweet
python
def enrich(self, tweet): """ Apply the local presentation logic to the fetched data.""" tweet = urlize_tweet(expand_tweet_urls(tweet)) # parses created_at "Wed Aug 27 13:08:45 +0000 2008" if settings.USE_TZ: tweet['datetime'] = datetime.strptime(tweet['created_at'], '%a %b %d %H:%M:%S +0000 %Y').replace(tzinfo=timezone.utc) else: tweet['datetime'] = datetime.strptime(tweet['created_at'], '%a %b %d %H:%M:%S +0000 %Y') return tweet
[ "def", "enrich", "(", "self", ",", "tweet", ")", ":", "tweet", "=", "urlize_tweet", "(", "expand_tweet_urls", "(", "tweet", ")", ")", "# parses created_at \"Wed Aug 27 13:08:45 +0000 2008\"", "if", "settings", ".", "USE_TZ", ":", "tweet", "[", "'datetime'", "]", "=", "datetime", ".", "strptime", "(", "tweet", "[", "'created_at'", "]", ",", "'%a %b %d %H:%M:%S +0000 %Y'", ")", ".", "replace", "(", "tzinfo", "=", "timezone", ".", "utc", ")", "else", ":", "tweet", "[", "'datetime'", "]", "=", "datetime", ".", "strptime", "(", "tweet", "[", "'created_at'", "]", ",", "'%a %b %d %H:%M:%S +0000 %Y'", ")", "return", "tweet" ]
Apply the local presentation logic to the fetched data.
[ "Apply", "the", "local", "presentation", "logic", "to", "the", "fetched", "data", "." ]
train
https://github.com/coagulant/django-twitter-tag/blob/2cb0f46837279e12b1ac250794a71611bac1acdc/twitter_tag/templatetags/twitter_tag.py#L37-L47
coagulant/django-twitter-tag
twitter_tag/utils.py
get_user_cache_key
def get_user_cache_key(**kwargs): """ Generate suitable key to cache twitter tag context """ key = 'get_tweets_%s' % ('_'.join([str(kwargs[key]) for key in sorted(kwargs) if kwargs[key]])) not_allowed = re.compile('[^%s]' % ''.join([chr(i) for i in range(33, 128)])) key = not_allowed.sub('', key) return key
python
def get_user_cache_key(**kwargs): """ Generate suitable key to cache twitter tag context """ key = 'get_tweets_%s' % ('_'.join([str(kwargs[key]) for key in sorted(kwargs) if kwargs[key]])) not_allowed = re.compile('[^%s]' % ''.join([chr(i) for i in range(33, 128)])) key = not_allowed.sub('', key) return key
[ "def", "get_user_cache_key", "(", "*", "*", "kwargs", ")", ":", "key", "=", "'get_tweets_%s'", "%", "(", "'_'", ".", "join", "(", "[", "str", "(", "kwargs", "[", "key", "]", ")", "for", "key", "in", "sorted", "(", "kwargs", ")", "if", "kwargs", "[", "key", "]", "]", ")", ")", "not_allowed", "=", "re", ".", "compile", "(", "'[^%s]'", "%", "''", ".", "join", "(", "[", "chr", "(", "i", ")", "for", "i", "in", "range", "(", "33", ",", "128", ")", "]", ")", ")", "key", "=", "not_allowed", ".", "sub", "(", "''", ",", "key", ")", "return", "key" ]
Generate suitable key to cache twitter tag context
[ "Generate", "suitable", "key", "to", "cache", "twitter", "tag", "context" ]
train
https://github.com/coagulant/django-twitter-tag/blob/2cb0f46837279e12b1ac250794a71611bac1acdc/twitter_tag/utils.py#L9-L15
coagulant/django-twitter-tag
twitter_tag/utils.py
get_search_cache_key
def get_search_cache_key(prefix, *args): """ Generate suitable key to cache twitter tag context """ key = '%s_%s' % (prefix, '_'.join([str(arg) for arg in args if arg])) not_allowed = re.compile('[^%s]' % ''.join([chr(i) for i in range(33, 128)])) key = not_allowed.sub('', key) return key
python
def get_search_cache_key(prefix, *args): """ Generate suitable key to cache twitter tag context """ key = '%s_%s' % (prefix, '_'.join([str(arg) for arg in args if arg])) not_allowed = re.compile('[^%s]' % ''.join([chr(i) for i in range(33, 128)])) key = not_allowed.sub('', key) return key
[ "def", "get_search_cache_key", "(", "prefix", ",", "*", "args", ")", ":", "key", "=", "'%s_%s'", "%", "(", "prefix", ",", "'_'", ".", "join", "(", "[", "str", "(", "arg", ")", "for", "arg", "in", "args", "if", "arg", "]", ")", ")", "not_allowed", "=", "re", ".", "compile", "(", "'[^%s]'", "%", "''", ".", "join", "(", "[", "chr", "(", "i", ")", "for", "i", "in", "range", "(", "33", ",", "128", ")", "]", ")", ")", "key", "=", "not_allowed", ".", "sub", "(", "''", ",", "key", ")", "return", "key" ]
Generate suitable key to cache twitter tag context
[ "Generate", "suitable", "key", "to", "cache", "twitter", "tag", "context" ]
train
https://github.com/coagulant/django-twitter-tag/blob/2cb0f46837279e12b1ac250794a71611bac1acdc/twitter_tag/utils.py#L18-L24
coagulant/django-twitter-tag
twitter_tag/utils.py
urlize_tweet
def urlize_tweet(tweet): """ Turn #hashtag and @username in a text to Twitter hyperlinks, similar to the ``urlize()`` function in Django. """ text = tweet.get('html', tweet['text']) for hash in tweet['entities']['hashtags']: text = text.replace('#%s' % hash['text'], TWITTER_HASHTAG_URL % (quote(hash['text'].encode("utf-8")), hash['text'])) for mention in tweet['entities']['user_mentions']: text = text.replace('@%s' % mention['screen_name'], TWITTER_USERNAME_URL % (quote(mention['screen_name']), mention['screen_name'])) tweet['html'] = text return tweet
python
def urlize_tweet(tweet): """ Turn #hashtag and @username in a text to Twitter hyperlinks, similar to the ``urlize()`` function in Django. """ text = tweet.get('html', tweet['text']) for hash in tweet['entities']['hashtags']: text = text.replace('#%s' % hash['text'], TWITTER_HASHTAG_URL % (quote(hash['text'].encode("utf-8")), hash['text'])) for mention in tweet['entities']['user_mentions']: text = text.replace('@%s' % mention['screen_name'], TWITTER_USERNAME_URL % (quote(mention['screen_name']), mention['screen_name'])) tweet['html'] = text return tweet
[ "def", "urlize_tweet", "(", "tweet", ")", ":", "text", "=", "tweet", ".", "get", "(", "'html'", ",", "tweet", "[", "'text'", "]", ")", "for", "hash", "in", "tweet", "[", "'entities'", "]", "[", "'hashtags'", "]", ":", "text", "=", "text", ".", "replace", "(", "'#%s'", "%", "hash", "[", "'text'", "]", ",", "TWITTER_HASHTAG_URL", "%", "(", "quote", "(", "hash", "[", "'text'", "]", ".", "encode", "(", "\"utf-8\"", ")", ")", ",", "hash", "[", "'text'", "]", ")", ")", "for", "mention", "in", "tweet", "[", "'entities'", "]", "[", "'user_mentions'", "]", ":", "text", "=", "text", ".", "replace", "(", "'@%s'", "%", "mention", "[", "'screen_name'", "]", ",", "TWITTER_USERNAME_URL", "%", "(", "quote", "(", "mention", "[", "'screen_name'", "]", ")", ",", "mention", "[", "'screen_name'", "]", ")", ")", "tweet", "[", "'html'", "]", "=", "text", "return", "tweet" ]
Turn #hashtag and @username in a text to Twitter hyperlinks, similar to the ``urlize()`` function in Django.
[ "Turn", "#hashtag", "and" ]
train
https://github.com/coagulant/django-twitter-tag/blob/2cb0f46837279e12b1ac250794a71611bac1acdc/twitter_tag/utils.py#L31-L41
coagulant/django-twitter-tag
twitter_tag/utils.py
expand_tweet_urls
def expand_tweet_urls(tweet): """ Replace shortened URLs with long URLs in the twitter status, and add the "RT" flag. Should be used before urlize_tweet """ if 'retweeted_status' in tweet: text = 'RT @{user}: {text}'.format(user=tweet['retweeted_status']['user']['screen_name'], text=tweet['retweeted_status']['text']) urls = tweet['retweeted_status']['entities']['urls'] else: text = tweet['text'] urls = tweet['entities']['urls'] for url in urls: text = text.replace(url['url'], '<a href="%s">%s</a>' % (url['expanded_url'], url['display_url'])) tweet['html'] = text return tweet
python
def expand_tweet_urls(tweet): """ Replace shortened URLs with long URLs in the twitter status, and add the "RT" flag. Should be used before urlize_tweet """ if 'retweeted_status' in tweet: text = 'RT @{user}: {text}'.format(user=tweet['retweeted_status']['user']['screen_name'], text=tweet['retweeted_status']['text']) urls = tweet['retweeted_status']['entities']['urls'] else: text = tweet['text'] urls = tweet['entities']['urls'] for url in urls: text = text.replace(url['url'], '<a href="%s">%s</a>' % (url['expanded_url'], url['display_url'])) tweet['html'] = text return tweet
[ "def", "expand_tweet_urls", "(", "tweet", ")", ":", "if", "'retweeted_status'", "in", "tweet", ":", "text", "=", "'RT @{user}: {text}'", ".", "format", "(", "user", "=", "tweet", "[", "'retweeted_status'", "]", "[", "'user'", "]", "[", "'screen_name'", "]", ",", "text", "=", "tweet", "[", "'retweeted_status'", "]", "[", "'text'", "]", ")", "urls", "=", "tweet", "[", "'retweeted_status'", "]", "[", "'entities'", "]", "[", "'urls'", "]", "else", ":", "text", "=", "tweet", "[", "'text'", "]", "urls", "=", "tweet", "[", "'entities'", "]", "[", "'urls'", "]", "for", "url", "in", "urls", ":", "text", "=", "text", ".", "replace", "(", "url", "[", "'url'", "]", ",", "'<a href=\"%s\">%s</a>'", "%", "(", "url", "[", "'expanded_url'", "]", ",", "url", "[", "'display_url'", "]", ")", ")", "tweet", "[", "'html'", "]", "=", "text", "return", "tweet" ]
Replace shortened URLs with long URLs in the twitter status, and add the "RT" flag. Should be used before urlize_tweet
[ "Replace", "shortened", "URLs", "with", "long", "URLs", "in", "the", "twitter", "status", "and", "add", "the", "RT", "flag", ".", "Should", "be", "used", "before", "urlize_tweet" ]
train
https://github.com/coagulant/django-twitter-tag/blob/2cb0f46837279e12b1ac250794a71611bac1acdc/twitter_tag/utils.py#L44-L59
ThePlasmaRailgun/py-rolldice
rolldice/rolldice.py
safe_power
def safe_power(a, b): """ Same power of a ^ b :param a: Number a :param b: Number b :return: a ^ b """ if abs(a) > MAX_POWER or abs(b) > MAX_POWER: raise ValueError('Number too high!') return a ** b
python
def safe_power(a, b): """ Same power of a ^ b :param a: Number a :param b: Number b :return: a ^ b """ if abs(a) > MAX_POWER or abs(b) > MAX_POWER: raise ValueError('Number too high!') return a ** b
[ "def", "safe_power", "(", "a", ",", "b", ")", ":", "if", "abs", "(", "a", ")", ">", "MAX_POWER", "or", "abs", "(", "b", ")", ">", "MAX_POWER", ":", "raise", "ValueError", "(", "'Number too high!'", ")", "return", "a", "**", "b" ]
Same power of a ^ b :param a: Number a :param b: Number b :return: a ^ b
[ "Same", "power", "of", "a", "^", "b", ":", "param", "a", ":", "Number", "a", ":", "param", "b", ":", "Number", "b", ":", "return", ":", "a", "^", "b" ]
train
https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L55-L64
ThePlasmaRailgun/py-rolldice
rolldice/rolldice.py
rabin_miller
def rabin_miller(p): """ Performs a rabin-miller primality test :param p: Number to test :return: Bool of whether num is prime """ # From this stackoverflow answer: https://codegolf.stackexchange.com/questions/26739/super-speedy-totient-function if p < 2: return False if p != 2 and p & 1 == 0: return False s = p - 1 while s & 1 == 0: s >>= 1 for x in range(10): a = random.randrange(p - 1) + 1 temp = s mod = pow(a, temp, p) while temp != p - 1 and mod != 1 and mod != p - 1: mod = (mod * mod) % p temp = temp * 2 if mod != p - 1 and temp % 2 == 0: return False return True
python
def rabin_miller(p): """ Performs a rabin-miller primality test :param p: Number to test :return: Bool of whether num is prime """ # From this stackoverflow answer: https://codegolf.stackexchange.com/questions/26739/super-speedy-totient-function if p < 2: return False if p != 2 and p & 1 == 0: return False s = p - 1 while s & 1 == 0: s >>= 1 for x in range(10): a = random.randrange(p - 1) + 1 temp = s mod = pow(a, temp, p) while temp != p - 1 and mod != 1 and mod != p - 1: mod = (mod * mod) % p temp = temp * 2 if mod != p - 1 and temp % 2 == 0: return False return True
[ "def", "rabin_miller", "(", "p", ")", ":", "# From this stackoverflow answer: https://codegolf.stackexchange.com/questions/26739/super-speedy-totient-function", "if", "p", "<", "2", ":", "return", "False", "if", "p", "!=", "2", "and", "p", "&", "1", "==", "0", ":", "return", "False", "s", "=", "p", "-", "1", "while", "s", "&", "1", "==", "0", ":", "s", ">>=", "1", "for", "x", "in", "range", "(", "10", ")", ":", "a", "=", "random", ".", "randrange", "(", "p", "-", "1", ")", "+", "1", "temp", "=", "s", "mod", "=", "pow", "(", "a", ",", "temp", ",", "p", ")", "while", "temp", "!=", "p", "-", "1", "and", "mod", "!=", "1", "and", "mod", "!=", "p", "-", "1", ":", "mod", "=", "(", "mod", "*", "mod", ")", "%", "p", "temp", "=", "temp", "*", "2", "if", "mod", "!=", "p", "-", "1", "and", "temp", "%", "2", "==", "0", ":", "return", "False", "return", "True" ]
Performs a rabin-miller primality test :param p: Number to test :return: Bool of whether num is prime
[ "Performs", "a", "rabin", "-", "miller", "primality", "test" ]
train
https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L67-L91
ThePlasmaRailgun/py-rolldice
rolldice/rolldice.py
zero_width_split
def zero_width_split(pattern, string): """ Split a string on a regex that only matches zero-width strings :param pattern: Regex pattern that matches zero-width strings :param string: String to split on. :return: Split array """ splits = list((m.start(), m.end()) for m in regex.finditer(pattern, string, regex.VERBOSE)) starts = [0] + [i[1] for i in splits] ends = [i[0] for i in splits] + [len(string)] return [string[start:end] for start, end in zip(starts, ends)]
python
def zero_width_split(pattern, string): """ Split a string on a regex that only matches zero-width strings :param pattern: Regex pattern that matches zero-width strings :param string: String to split on. :return: Split array """ splits = list((m.start(), m.end()) for m in regex.finditer(pattern, string, regex.VERBOSE)) starts = [0] + [i[1] for i in splits] ends = [i[0] for i in splits] + [len(string)] return [string[start:end] for start, end in zip(starts, ends)]
[ "def", "zero_width_split", "(", "pattern", ",", "string", ")", ":", "splits", "=", "list", "(", "(", "m", ".", "start", "(", ")", ",", "m", ".", "end", "(", ")", ")", "for", "m", "in", "regex", ".", "finditer", "(", "pattern", ",", "string", ",", "regex", ".", "VERBOSE", ")", ")", "starts", "=", "[", "0", "]", "+", "[", "i", "[", "1", "]", "for", "i", "in", "splits", "]", "ends", "=", "[", "i", "[", "0", "]", "for", "i", "in", "splits", "]", "+", "[", "len", "(", "string", ")", "]", "return", "[", "string", "[", "start", ":", "end", "]", "for", "start", ",", "end", "in", "zip", "(", "starts", ",", "ends", ")", "]" ]
Split a string on a regex that only matches zero-width strings :param pattern: Regex pattern that matches zero-width strings :param string: String to split on. :return: Split array
[ "Split", "a", "string", "on", "a", "regex", "that", "only", "matches", "zero", "-", "width", "strings" ]
train
https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L308-L319
ThePlasmaRailgun/py-rolldice
rolldice/rolldice.py
roll_group
def roll_group(group): """ Rolls a group of dice in 2d6, 3d10, d12, etc. format :param group: String of dice group :return: Array of results """ group = regex.match(r'^(\d*)d(\d+)$', group, regex.IGNORECASE) num_of_dice = int(group[1]) if group[1] != '' else 1 type_of_dice = int(group[2]) assert num_of_dice > 0 result = [] for i in range(num_of_dice): result.append(random.randint(1, type_of_dice)) return result
python
def roll_group(group): """ Rolls a group of dice in 2d6, 3d10, d12, etc. format :param group: String of dice group :return: Array of results """ group = regex.match(r'^(\d*)d(\d+)$', group, regex.IGNORECASE) num_of_dice = int(group[1]) if group[1] != '' else 1 type_of_dice = int(group[2]) assert num_of_dice > 0 result = [] for i in range(num_of_dice): result.append(random.randint(1, type_of_dice)) return result
[ "def", "roll_group", "(", "group", ")", ":", "group", "=", "regex", ".", "match", "(", "r'^(\\d*)d(\\d+)$'", ",", "group", ",", "regex", ".", "IGNORECASE", ")", "num_of_dice", "=", "int", "(", "group", "[", "1", "]", ")", "if", "group", "[", "1", "]", "!=", "''", "else", "1", "type_of_dice", "=", "int", "(", "group", "[", "2", "]", ")", "assert", "num_of_dice", ">", "0", "result", "=", "[", "]", "for", "i", "in", "range", "(", "num_of_dice", ")", ":", "result", ".", "append", "(", "random", ".", "randint", "(", "1", ",", "type_of_dice", ")", ")", "return", "result" ]
Rolls a group of dice in 2d6, 3d10, d12, etc. format :param group: String of dice group :return: Array of results
[ "Rolls", "a", "group", "of", "dice", "in", "2d6", "3d10", "d12", "etc", ".", "format" ]
train
https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L322-L337
ThePlasmaRailgun/py-rolldice
rolldice/rolldice.py
num_equal
def num_equal(result, operator, comparator): """ Returns the number of elements in a list that pass a comparison :param result: The list of results of a dice roll :param operator: Operator in string to perform comparison on: Either '+', '-', or '*' :param comparator: The value to compare :return: """ if operator == '<': return len([x for x in result if x < comparator]) elif operator == '>': return len([x for x in result if x > comparator]) elif operator == '=': return len([x for x in result if x == comparator]) else: raise ValueError
python
def num_equal(result, operator, comparator): """ Returns the number of elements in a list that pass a comparison :param result: The list of results of a dice roll :param operator: Operator in string to perform comparison on: Either '+', '-', or '*' :param comparator: The value to compare :return: """ if operator == '<': return len([x for x in result if x < comparator]) elif operator == '>': return len([x for x in result if x > comparator]) elif operator == '=': return len([x for x in result if x == comparator]) else: raise ValueError
[ "def", "num_equal", "(", "result", ",", "operator", ",", "comparator", ")", ":", "if", "operator", "==", "'<'", ":", "return", "len", "(", "[", "x", "for", "x", "in", "result", "if", "x", "<", "comparator", "]", ")", "elif", "operator", "==", "'>'", ":", "return", "len", "(", "[", "x", "for", "x", "in", "result", "if", "x", ">", "comparator", "]", ")", "elif", "operator", "==", "'='", ":", "return", "len", "(", "[", "x", "for", "x", "in", "result", "if", "x", "==", "comparator", "]", ")", "else", ":", "raise", "ValueError" ]
Returns the number of elements in a list that pass a comparison :param result: The list of results of a dice roll :param operator: Operator in string to perform comparison on: Either '+', '-', or '*' :param comparator: The value to compare :return:
[ "Returns", "the", "number", "of", "elements", "in", "a", "list", "that", "pass", "a", "comparison" ]
train
https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L340-L357
ThePlasmaRailgun/py-rolldice
rolldice/rolldice.py
roll_dice
def roll_dice(roll, *, functions=True, floats=True): """ Rolls dice in dice notation with advanced syntax used according to tinyurl.com/pydice :param roll: Roll in dice notation :return: Result of roll, and an explanation string """ roll = ''.join(roll.split()) roll = regex.sub(r'(?<=d)%', '100', roll, regex.IGNORECASE) roll = roll.replace('^', '**') roll = zero_width_split(r'((?<=[\(\),%^\/+*-])(?=.))|((?<=.)(?=[\(\),%^\/+*-]))', roll) # Split the string on the boundary between operators and other chars string = [] results = [] for group in roll: if group in '()/=<>,%^+*-' or group in DEFAULT_FUNCTIONS: #Append operators without modification results.append(group) string.append(group) continue try: explode = regex.match(r'^((\d*)d(\d+))!$', group, regex.IGNORECASE) # Regex for exploding dice, ie. 2d10!, 4d100!, d12!, etc. specific_explode = regex.match(r'^((\d*)d(\d+))!(\d+)$', group) # Regex for exploding dice on specific number, ie. d20!10 or d12!4 comparison_explode = regex.match(r'^((\d*)d(\d+))!([<>])(\d+)$', group, regex.IGNORECASE) # Regex for exploding dice with a comparison, ie. d20!>10, d6!<2 penetrate = regex.match(r'^((\d*)d(\d+))!p$', group, regex.IGNORECASE) # Penetrating dice are the same as exploding except any dice after the initial number are added with a -1 penalty specific_penetrate = regex.match(r'^((\d*)d(\d+))!p(\d+)$', group, regex.IGNORECASE) # See above comparison_penetrate = regex.match(r'^((\d*)d(\d+))!p([<>])(\d+)$', group, regex.IGNORECASE) # See above reroll = regex.match(r'^((\d*)d(\d+))([Rr])$', group, regex.IGNORECASE) # Reroll on a one, matches 1d6R, 4d12r, etc. specific_reroll = regex.match(r'^((\d*)d(\d+))([Rr])(\d+)$', group, regex.IGNORECASE) # Reroll on a specific number comparison_reroll = regex.match(r'^((\d*)d(\d+))([Rr])([<>])(\d+)$', group, regex.IGNORECASE) # Reroll on a comparison success_comparison = regex.match(r'^((?:\d*)d(\d+))([<>])(\d+)$', group, regex.IGNORECASE) # Regex for dice with comparison, ie. 2d10>4, 5d3<2, etc. success_fail_comparison = regex.match(r'^((?:\d*)d(\d+))(?|((<)(\d+)f(>)(\d+))|((>)(\d+)f(<)(\d+)))$', group, regex.IGNORECASE) # Regex for dice with success comparison and failure comparison. keep = regex.match(r'^((?:\d*)d\d+)([Kk])(\d*)$', group, regex.IGNORECASE) # Regex for keeping a number of dice, ie. 2d10K, 2d10k3, etc. drop = regex.match(r'^((?:\d*)d\d+)([Xx])(\d*)$', group, regex.IGNORECASE) # As above but with dropping dice and X individual = regex.match(r'^((\d*)d(\d+))([asm])(\d+)$', group, regex.IGNORECASE) #Regex for rolling dice with a modifier attached to each roll normal = regex.match(r'^((\d*)d(\d+))$', group, regex.IGNORECASE) # Regex for normal dice rolls literal = regex.match(r'^(\d+)(?!\.)$', group, regex.IGNORECASE) # Regex for number literals. float_literal = regex.match(r'^(\.\d+)|(\d+.\d+)$', group, regex.IGNORECASE) # Regex for floats if explode is not None: # Handle exploding dice without a comparison modifier. type_of_dice = int(explode[3]) result = [] last_result = roll_group(explode[1]) result.extend(last_result) number_to_roll = num_equal(last_result, '=', type_of_dice) while number_to_roll != 0: last_result = roll_group(str(number_to_roll) + 'd' + str(type_of_dice)) # Reroll dice result.extend(last_result) number_to_roll = num_equal(last_result, '=', type_of_dice) # Check how many dice we have to reroll again results.append(sum(result)) roll = ','.join([('!' + str(i) if i == type_of_dice else str(i)) for i in result]) # Build a string of the dice rolls, adding an exclamation mark before every roll that resulted in an explosion. string.append('[%s]' % roll) elif specific_explode is not None: # Handle exploding dice without a comparison modifier. type_of_dice = int(specific_explode[3]) comparator = int(specific_explode[4]) assert 0 < comparator <= type_of_dice result = [] last_result = roll_group(specific_explode[1]) result.extend(last_result) number_to_roll = num_equal(last_result, '=', comparator) while number_to_roll != 0: last_result = roll_group(str(number_to_roll) + 'd' + str(type_of_dice)) result.extend(last_result) number_to_roll = num_equal(last_result, '=', comparator) results.append(sum(result)) roll = ','.join([('!' + str(i) if i == comparator else str(i)) for i in result]) # Build a string of the dice rolls, adding an exclamation mark before every roll that resulted in an explosion. string.append('[%s]' % roll) elif comparison_explode is not None: # Handle exploding dice with a comparison modifier type_of_dice = int(comparison_explode[3]) comparator = int(comparison_explode[5]) if comparison_explode[4] == '>': # Ensure comparison is within bounds assert 0 < comparator < type_of_dice else: assert 1 < comparator <= type_of_dice result = [] last_result = roll_group(comparison_explode[1]) result.extend(last_result) if comparison_explode[4] == '>': number_to_roll = num_equal(last_result, '>', comparator) while number_to_roll != 0: last_result = roll_group(str(number_to_roll) + 'd' + str(type_of_dice)) result.extend(last_result) number_to_roll = num_equal(last_result, '>', comparator) roll = ','.join([('!' + str(i) if i > comparator else str(i)) for i in result]) # Same as on other explodes except with a > or < comparison else: number_to_roll = num_equal(last_result, '<', comparator) while number_to_roll != 0: last_result = roll_group(str(number_to_roll) + 'd' + str(type_of_dice)) result.extend(last_result) number_to_roll = num_equal(last_result, '<', comparator) roll = ','.join([('!' + str(i) if i < comparator else str(i)) for i in result]) # Same as on other explodes except with a > or < comparison results.append(sum(result)) string.append('[%s]' % roll) elif penetrate is not None: # Handle penetrating dice without a comparison modifier. type_of_dice = int(penetrate[3]) first_num = int(penetrate[2]) result = [] last_result = roll_group(penetrate[1]) result.extend(last_result) number_to_roll = num_equal(last_result, '=', type_of_dice) while number_to_roll != 0: last_result = roll_group(str(number_to_roll) + 'd' + str(type_of_dice)) result.extend(last_result) number_to_roll = num_equal(last_result, '=', type_of_dice) pre_result = result[:first_num] # Add the first rolls with no modifier pre_result.extend([x - 1 for x in result[first_num:]]) # Add the second rolls with a -1 modifier results.append(sum(pre_result)) roll = ','.join(['!' + str(i) if i == type_of_dice else str(i) for i in result[:first_num]]) # Add the first numbers, without the -1 but with a ! when roll is penetration roll += (',' if len(pre_result) > first_num else '') # Only add the comma in between if there's at least one penetration roll += ','.join([('!' + str(i) + '-1' if i == type_of_dice else str(i) + '-1') for i in result[first_num:]]) # Add the penetration dice with the '-1' tacked on the end string.append('[%s]' % roll) elif specific_penetrate is not None: # Handle penetrating dice without a comparison modifier. type_of_dice = int(specific_penetrate[3]) first_num = int(specific_penetrate[2]) comparator = int(specific_penetrate[4]) assert 0 < comparator <= type_of_dice result = [] last_result = roll_group(specific_penetrate[1]) result.extend(last_result) number_to_roll = num_equal(last_result, '=', comparator) while number_to_roll != 0: last_result = roll_group(str(number_to_roll) + 'd' + str(type_of_dice)) result.extend(last_result) number_to_roll = num_equal(last_result, '=', comparator) pre_result = result[:first_num] # Same as normal penetration pre_result.extend([x - 1 for x in result[first_num:]]) results.append(sum(pre_result)) roll = ','.join(['!' + str(i) if i == comparator else str(i) for i in result[:first_num]]) # Same as above roll += (',' if len(pre_result) > first_num else '') roll += ','.join([('!' + str(i) + '-1' if i == comparator else str(i) + '-1') for i in result[first_num:]]) string.append('[%s]' % roll) elif comparison_penetrate is not None: # Handle penetrating dice without a comparison modifier. type_of_dice = int(comparison_penetrate[3]) comparator = int(comparison_penetrate[5]) first_num = int(comparison_penetrate[2]) if comparison_penetrate[4] == '>': # Ensure comparison is within bounds assert 0 < comparator < type_of_dice else: assert 1 < comparator <= type_of_dice result = [] last_result = roll_group(comparison_penetrate[1]) result.extend(last_result) # Do penetration based on more than or less than sign. if comparison_penetrate[4] == '>': number_to_roll = num_equal(last_result, '>', comparator) while number_to_roll != 0: last_result = roll_group(str(number_to_roll) + 'd' + str(type_of_dice)) result.extend(last_result) number_to_roll = num_equal(last_result, '>', comparator) else: number_to_roll = num_equal(last_result, '<', comparator) while number_to_roll != 0: last_result = roll_group(str(number_to_roll) + 'd' + str(type_of_dice)) result.extend(last_result) number_to_roll = num_equal(last_result, '<', comparator) pre_result = result[:first_num] pre_result.extend([x - 1 for x in result[first_num:]]) results.append(sum(pre_result)) if comparison_penetrate[4] == '>': roll = ','.join( ['!' + str(i) if i > comparator else str(i) for i in result[:first_num]]) # Same as above roll += (',' if len(pre_result) > first_num else '') roll += ','.join( [('!' + str(i) + '-1' if i > comparator else str(i) + '-1') for i in result[first_num:]]) else: roll = ','.join( ['!' + str(i) if i < comparator else str(i) for i in result[:first_num]]) # Same as above roll += (',' if len(pre_result) > first_num else '') roll += ','.join( [('!' + str(i) + '-1' if i < comparator else str(i) + '-1') for i in result[first_num:]]) string.append('[%s]' % roll) elif reroll is not None: # Handle rerolling dice without a comparison modifier (ie. on 1) type_of_dice = int(reroll[3]) result_strings = [] roll_strings = [] result = roll_group(reroll[1]) repeat = True if reroll[4] == 'R' else False # Reroll just once or infinite number of times if repeat: #Handle rerolling the dice and building a string of all the rerolled ones for i in range(len(result)): prev = [result[i]] while result[i] == 1: result[i] = random.randint(1, type_of_dice) prev.append(result[i]) roll_strings.append([str(x) for x in prev]) else: for i in range(len(result)): prev = [result[i]] if result[i] == 1: result[i] = random.randint(1, type_of_dice) prev.append(result[i]) roll_strings.append([str(x) for x in prev]) results.append(sum(result)) for roll_string in roll_strings: roll_string.reverse() result_strings.append('%s' % roll_string[0] + ('~' if len(roll_string) > 1 else '') + '~'.join(roll_string[1:])) #Build the string roll = ','.join(result_strings) string.append('[%s]' % roll) elif specific_reroll is not None: # Handle rerolling dice on a specific number, see reroll type_of_dice = int(specific_reroll[3]) comparator = int(specific_reroll[5]) assert 0 < comparator <= type_of_dice # Ensure comparison is within bounds result_strings = [] roll_strings = [] result = roll_group(specific_reroll[1]) repeat = True if specific_reroll[4] == 'R' else False if repeat: for i in range(len(result)): prev = [result[i]] while result[i] == comparator: result[i] = random.randint(1, type_of_dice) prev.append(result[i]) roll_strings.append([str(x) for x in prev]) else: for i in range(len(result)): prev = [result[i]] if result[i] == comparator: result[i] = random.randint(1, type_of_dice) prev.append(result[i]) roll_strings.append([str(x) for x in prev]) results.append(sum(result)) for roll_string in roll_strings: roll_string.reverse() result_strings.append('%s' % roll_string[0] + ('~' if len(roll_string) > 1 else '') + '~'.join(roll_string[1:])) roll = ','.join(result_strings) string.append('[%s]' % roll) elif comparison_reroll is not None: # Handle rerolling dice with a comparison modifier. type_of_dice = int(comparison_reroll[3]) comparator = int(comparison_reroll[6]) if comparison_reroll[5] == '>': # Ensure comparison is within bounds assert 0 < comparator < type_of_dice else: assert 1 < comparator <= type_of_dice result_strings = [] roll_strings = [] result = roll_group(comparison_reroll[1]) repeat = True if comparison_reroll[4] == 'R' else False if comparison_reroll[5] == '>': if repeat: for i in range(len(result)): prev = [result[i]] while result[i] > comparator: result[i] = random.randint(1, type_of_dice) prev.append(result[i]) roll_strings.append([str(x) for x in prev]) else: for i in range(len(result)): prev = [result[i]] if result[i] > comparator: result[i] = random.randint(1, type_of_dice) prev.append(result[i]) roll_strings.append([str(x) for x in prev]) else: if repeat: for i in range(len(result)): prev = [result[i]] while result[i] < comparator: result[i] = random.randint(1, type_of_dice) prev.append(result[i]) roll_strings.append([str(x) for x in prev]) else: for i in range(len(result)): prev = [result[i]] if result[i] < comparator: result[i] = random.randint(1, type_of_dice) prev.append(result[i]) roll_strings.append([str(x) for x in prev]) results.append(sum(result)) for roll_string in roll_strings: roll_string.reverse() result_strings.append('%s' % roll_string[0] + ('~' if len(roll_string) > 1 else '') + '~'.join(roll_string[1:])) roll = ','.join(result_strings) string.append('[%s]' % roll) elif success_comparison is not None: group_result = roll_group(success_comparison[1]) result = [] result_string = [] type_of_dice = int(success_comparison[2]) comparator = int(success_comparison[4]) if success_comparison[3] == '>': # Ensure comparison is within bounds assert 0 < comparator < type_of_dice else: assert 1 < comparator <= type_of_dice for die in group_result: if success_comparison[3] == '>': result.append(1 if die > comparator else 0) result_string.append('!' + str(die) if die > comparator else str(die)) else: result.append(1 if die < comparator else 0) result_string.append('!' + str(die) if die < comparator else str(die)) results.append(sum(result)) roll = ','.join(result_string) # Craft the string, adding an exclamation mark before every string that passed the comparison. string.append('[%s]' % roll) elif success_fail_comparison is not None: group_result = roll_group(success_fail_comparison[1]) result = [] result_string = [] type_of_dice = int(success_fail_comparison[2]) success_comp = int(success_fail_comparison[5]) fail_comp = int(success_fail_comparison[7]) # Ensure both comparisons are within bounds if success_fail_comparison[4] == '>': assert 0 < success_comp < type_of_dice assert 1 < fail_comp <= type_of_dice else: assert 1 < success_comp <= type_of_dice assert 0 < fail_comp < type_of_dice for die in group_result: if success_fail_comparison[4] == '>': # Get the actual list of successes and fails with both comparisons if die > success_comp: result.append(1) result_string.append('!' + str(die)) elif die < fail_comp: result.append(-1) result_string.append('*' + str(die)) else: result.append(0) result_string.append(str(die)) else: if die < success_comp: result.append(1) result_string.append('!' + str(die)) elif die > fail_comp: result.append(-1) result_string.append('*' + str(die)) else: result.append(0) result_string.append(str(die)) results.append(sum(result)) # roll = ','.join(result_string) string.append('[%s]' % roll) elif keep is not None: # Handle rolling dice and keeping the x highest or lowest values group_result = roll_group(keep[1]) group_result.sort(reverse=True if keep[ 2] == 'K' else False) # Uppercase is keep highest and lowercase is keep lowest. num_to_keep = int(keep[3] if keep[3] != '' else 1) assert 1 <= num_to_keep < len(group_result) results.append(sum(group_result[:num_to_keep])) roll = ','.join([str(i) for i in group_result[ :num_to_keep]]) + ' ~~ ' # This time format the string with all kept rolls on the left and dropped rolls on the right roll += ','.join([str(i) for i in group_result[num_to_keep:]]) string.append('[%s]' % roll) elif drop is not None: group_result = roll_group(drop[1]) group_result.sort(reverse=True if drop[2] == 'X' else False) # Same thing as keep dice num_to_drop = int(drop[3] if drop[3] != '' else 1) assert 1 <= num_to_drop < len(group_result) results.append(sum(group_result[:num_to_drop])) roll = ','.join([str(i) for i in group_result[num_to_drop:]]) + ' ~~ ' # Same as above. roll += ','.join([str(i) for i in group_result[:num_to_drop]]) string.append('[%s]' % roll) elif individual is not None: group_result = roll_group(individual[1]) result = [] for i, j in enumerate(group_result): #add to each roll if individual[4] == 'a': result.append(j + int(individual[5])) elif individual[4] == 's': result.append(j - int(individual[5])) elif individual[4] == 'm': result.append(j * int(individual[5])) else: raise ValueError results.append(sum(result)) roll = ','.join([str(x) + individual[4] + individual[5] for x in group_result]) #Create string with the modifier on each roll string.append('[%s]' % roll) elif normal is not None: group_result = roll_group(group) results.append(sum(group_result)) roll = ','.join([str(i) for i in group_result]) string.append('[%s]' % roll) elif literal is not None: results.append(int(literal[1])) # Just append the integer value string.append(literal[1]) elif float_literal is not None: if floats: results.append(float(group)) string.append(group) else: raise TypeError else: raise Exception except Exception: raise DiceGroupException('"%s" is not a valid dicegroup.' % group) parser = SimpleEval(floats=floats, functions=functions) #The parser object parses the dice rolls and functions try: final_result = parser.eval(''.join([str(x) for x in results])) #Call the parser to parse into one value if not floats: final_result = int(final_result) except Exception: raise DiceOperatorException('Error parsing operators and or functions') #Create explanation string and remove extraneous spaces explanation = ''.join(string) explanation = zero_width_split(r"""((?<=[\/%^+])(?![\/,]))| # Split between /, %, ^, and + ((?<![\/,])(?=[\/%^+]))| # Same as above ((?<=[^(])(?=-))(?!-[^[]*])| # Split in front of - that are not in a roll (?<=-)(?=[^\d()a-z])| # Same for splitting after - and before non-literals (?<=[\d)\]]-)(?=.)(?![^[]*])| # Split after a - that is not in a roll (?<=,)(?![^[]*])| # Split after a comma that is not in a roll (?<=([^,]\*))(?!\*)| # Split after a * that is not in a roll (?<![,\*])(?=\*) # Split before a * that is not in a roll""", explanation) #Split on ops to properly format the explanation explanation = ' '.join(explanation) explanation = explanation.strip() explanation = regex.sub(r'[ \t]{2,}', ' ', explanation) return final_result, explanation
python
def roll_dice(roll, *, functions=True, floats=True): """ Rolls dice in dice notation with advanced syntax used according to tinyurl.com/pydice :param roll: Roll in dice notation :return: Result of roll, and an explanation string """ roll = ''.join(roll.split()) roll = regex.sub(r'(?<=d)%', '100', roll, regex.IGNORECASE) roll = roll.replace('^', '**') roll = zero_width_split(r'((?<=[\(\),%^\/+*-])(?=.))|((?<=.)(?=[\(\),%^\/+*-]))', roll) # Split the string on the boundary between operators and other chars string = [] results = [] for group in roll: if group in '()/=<>,%^+*-' or group in DEFAULT_FUNCTIONS: #Append operators without modification results.append(group) string.append(group) continue try: explode = regex.match(r'^((\d*)d(\d+))!$', group, regex.IGNORECASE) # Regex for exploding dice, ie. 2d10!, 4d100!, d12!, etc. specific_explode = regex.match(r'^((\d*)d(\d+))!(\d+)$', group) # Regex for exploding dice on specific number, ie. d20!10 or d12!4 comparison_explode = regex.match(r'^((\d*)d(\d+))!([<>])(\d+)$', group, regex.IGNORECASE) # Regex for exploding dice with a comparison, ie. d20!>10, d6!<2 penetrate = regex.match(r'^((\d*)d(\d+))!p$', group, regex.IGNORECASE) # Penetrating dice are the same as exploding except any dice after the initial number are added with a -1 penalty specific_penetrate = regex.match(r'^((\d*)d(\d+))!p(\d+)$', group, regex.IGNORECASE) # See above comparison_penetrate = regex.match(r'^((\d*)d(\d+))!p([<>])(\d+)$', group, regex.IGNORECASE) # See above reroll = regex.match(r'^((\d*)d(\d+))([Rr])$', group, regex.IGNORECASE) # Reroll on a one, matches 1d6R, 4d12r, etc. specific_reroll = regex.match(r'^((\d*)d(\d+))([Rr])(\d+)$', group, regex.IGNORECASE) # Reroll on a specific number comparison_reroll = regex.match(r'^((\d*)d(\d+))([Rr])([<>])(\d+)$', group, regex.IGNORECASE) # Reroll on a comparison success_comparison = regex.match(r'^((?:\d*)d(\d+))([<>])(\d+)$', group, regex.IGNORECASE) # Regex for dice with comparison, ie. 2d10>4, 5d3<2, etc. success_fail_comparison = regex.match(r'^((?:\d*)d(\d+))(?|((<)(\d+)f(>)(\d+))|((>)(\d+)f(<)(\d+)))$', group, regex.IGNORECASE) # Regex for dice with success comparison and failure comparison. keep = regex.match(r'^((?:\d*)d\d+)([Kk])(\d*)$', group, regex.IGNORECASE) # Regex for keeping a number of dice, ie. 2d10K, 2d10k3, etc. drop = regex.match(r'^((?:\d*)d\d+)([Xx])(\d*)$', group, regex.IGNORECASE) # As above but with dropping dice and X individual = regex.match(r'^((\d*)d(\d+))([asm])(\d+)$', group, regex.IGNORECASE) #Regex for rolling dice with a modifier attached to each roll normal = regex.match(r'^((\d*)d(\d+))$', group, regex.IGNORECASE) # Regex for normal dice rolls literal = regex.match(r'^(\d+)(?!\.)$', group, regex.IGNORECASE) # Regex for number literals. float_literal = regex.match(r'^(\.\d+)|(\d+.\d+)$', group, regex.IGNORECASE) # Regex for floats if explode is not None: # Handle exploding dice without a comparison modifier. type_of_dice = int(explode[3]) result = [] last_result = roll_group(explode[1]) result.extend(last_result) number_to_roll = num_equal(last_result, '=', type_of_dice) while number_to_roll != 0: last_result = roll_group(str(number_to_roll) + 'd' + str(type_of_dice)) # Reroll dice result.extend(last_result) number_to_roll = num_equal(last_result, '=', type_of_dice) # Check how many dice we have to reroll again results.append(sum(result)) roll = ','.join([('!' + str(i) if i == type_of_dice else str(i)) for i in result]) # Build a string of the dice rolls, adding an exclamation mark before every roll that resulted in an explosion. string.append('[%s]' % roll) elif specific_explode is not None: # Handle exploding dice without a comparison modifier. type_of_dice = int(specific_explode[3]) comparator = int(specific_explode[4]) assert 0 < comparator <= type_of_dice result = [] last_result = roll_group(specific_explode[1]) result.extend(last_result) number_to_roll = num_equal(last_result, '=', comparator) while number_to_roll != 0: last_result = roll_group(str(number_to_roll) + 'd' + str(type_of_dice)) result.extend(last_result) number_to_roll = num_equal(last_result, '=', comparator) results.append(sum(result)) roll = ','.join([('!' + str(i) if i == comparator else str(i)) for i in result]) # Build a string of the dice rolls, adding an exclamation mark before every roll that resulted in an explosion. string.append('[%s]' % roll) elif comparison_explode is not None: # Handle exploding dice with a comparison modifier type_of_dice = int(comparison_explode[3]) comparator = int(comparison_explode[5]) if comparison_explode[4] == '>': # Ensure comparison is within bounds assert 0 < comparator < type_of_dice else: assert 1 < comparator <= type_of_dice result = [] last_result = roll_group(comparison_explode[1]) result.extend(last_result) if comparison_explode[4] == '>': number_to_roll = num_equal(last_result, '>', comparator) while number_to_roll != 0: last_result = roll_group(str(number_to_roll) + 'd' + str(type_of_dice)) result.extend(last_result) number_to_roll = num_equal(last_result, '>', comparator) roll = ','.join([('!' + str(i) if i > comparator else str(i)) for i in result]) # Same as on other explodes except with a > or < comparison else: number_to_roll = num_equal(last_result, '<', comparator) while number_to_roll != 0: last_result = roll_group(str(number_to_roll) + 'd' + str(type_of_dice)) result.extend(last_result) number_to_roll = num_equal(last_result, '<', comparator) roll = ','.join([('!' + str(i) if i < comparator else str(i)) for i in result]) # Same as on other explodes except with a > or < comparison results.append(sum(result)) string.append('[%s]' % roll) elif penetrate is not None: # Handle penetrating dice without a comparison modifier. type_of_dice = int(penetrate[3]) first_num = int(penetrate[2]) result = [] last_result = roll_group(penetrate[1]) result.extend(last_result) number_to_roll = num_equal(last_result, '=', type_of_dice) while number_to_roll != 0: last_result = roll_group(str(number_to_roll) + 'd' + str(type_of_dice)) result.extend(last_result) number_to_roll = num_equal(last_result, '=', type_of_dice) pre_result = result[:first_num] # Add the first rolls with no modifier pre_result.extend([x - 1 for x in result[first_num:]]) # Add the second rolls with a -1 modifier results.append(sum(pre_result)) roll = ','.join(['!' + str(i) if i == type_of_dice else str(i) for i in result[:first_num]]) # Add the first numbers, without the -1 but with a ! when roll is penetration roll += (',' if len(pre_result) > first_num else '') # Only add the comma in between if there's at least one penetration roll += ','.join([('!' + str(i) + '-1' if i == type_of_dice else str(i) + '-1') for i in result[first_num:]]) # Add the penetration dice with the '-1' tacked on the end string.append('[%s]' % roll) elif specific_penetrate is not None: # Handle penetrating dice without a comparison modifier. type_of_dice = int(specific_penetrate[3]) first_num = int(specific_penetrate[2]) comparator = int(specific_penetrate[4]) assert 0 < comparator <= type_of_dice result = [] last_result = roll_group(specific_penetrate[1]) result.extend(last_result) number_to_roll = num_equal(last_result, '=', comparator) while number_to_roll != 0: last_result = roll_group(str(number_to_roll) + 'd' + str(type_of_dice)) result.extend(last_result) number_to_roll = num_equal(last_result, '=', comparator) pre_result = result[:first_num] # Same as normal penetration pre_result.extend([x - 1 for x in result[first_num:]]) results.append(sum(pre_result)) roll = ','.join(['!' + str(i) if i == comparator else str(i) for i in result[:first_num]]) # Same as above roll += (',' if len(pre_result) > first_num else '') roll += ','.join([('!' + str(i) + '-1' if i == comparator else str(i) + '-1') for i in result[first_num:]]) string.append('[%s]' % roll) elif comparison_penetrate is not None: # Handle penetrating dice without a comparison modifier. type_of_dice = int(comparison_penetrate[3]) comparator = int(comparison_penetrate[5]) first_num = int(comparison_penetrate[2]) if comparison_penetrate[4] == '>': # Ensure comparison is within bounds assert 0 < comparator < type_of_dice else: assert 1 < comparator <= type_of_dice result = [] last_result = roll_group(comparison_penetrate[1]) result.extend(last_result) # Do penetration based on more than or less than sign. if comparison_penetrate[4] == '>': number_to_roll = num_equal(last_result, '>', comparator) while number_to_roll != 0: last_result = roll_group(str(number_to_roll) + 'd' + str(type_of_dice)) result.extend(last_result) number_to_roll = num_equal(last_result, '>', comparator) else: number_to_roll = num_equal(last_result, '<', comparator) while number_to_roll != 0: last_result = roll_group(str(number_to_roll) + 'd' + str(type_of_dice)) result.extend(last_result) number_to_roll = num_equal(last_result, '<', comparator) pre_result = result[:first_num] pre_result.extend([x - 1 for x in result[first_num:]]) results.append(sum(pre_result)) if comparison_penetrate[4] == '>': roll = ','.join( ['!' + str(i) if i > comparator else str(i) for i in result[:first_num]]) # Same as above roll += (',' if len(pre_result) > first_num else '') roll += ','.join( [('!' + str(i) + '-1' if i > comparator else str(i) + '-1') for i in result[first_num:]]) else: roll = ','.join( ['!' + str(i) if i < comparator else str(i) for i in result[:first_num]]) # Same as above roll += (',' if len(pre_result) > first_num else '') roll += ','.join( [('!' + str(i) + '-1' if i < comparator else str(i) + '-1') for i in result[first_num:]]) string.append('[%s]' % roll) elif reroll is not None: # Handle rerolling dice without a comparison modifier (ie. on 1) type_of_dice = int(reroll[3]) result_strings = [] roll_strings = [] result = roll_group(reroll[1]) repeat = True if reroll[4] == 'R' else False # Reroll just once or infinite number of times if repeat: #Handle rerolling the dice and building a string of all the rerolled ones for i in range(len(result)): prev = [result[i]] while result[i] == 1: result[i] = random.randint(1, type_of_dice) prev.append(result[i]) roll_strings.append([str(x) for x in prev]) else: for i in range(len(result)): prev = [result[i]] if result[i] == 1: result[i] = random.randint(1, type_of_dice) prev.append(result[i]) roll_strings.append([str(x) for x in prev]) results.append(sum(result)) for roll_string in roll_strings: roll_string.reverse() result_strings.append('%s' % roll_string[0] + ('~' if len(roll_string) > 1 else '') + '~'.join(roll_string[1:])) #Build the string roll = ','.join(result_strings) string.append('[%s]' % roll) elif specific_reroll is not None: # Handle rerolling dice on a specific number, see reroll type_of_dice = int(specific_reroll[3]) comparator = int(specific_reroll[5]) assert 0 < comparator <= type_of_dice # Ensure comparison is within bounds result_strings = [] roll_strings = [] result = roll_group(specific_reroll[1]) repeat = True if specific_reroll[4] == 'R' else False if repeat: for i in range(len(result)): prev = [result[i]] while result[i] == comparator: result[i] = random.randint(1, type_of_dice) prev.append(result[i]) roll_strings.append([str(x) for x in prev]) else: for i in range(len(result)): prev = [result[i]] if result[i] == comparator: result[i] = random.randint(1, type_of_dice) prev.append(result[i]) roll_strings.append([str(x) for x in prev]) results.append(sum(result)) for roll_string in roll_strings: roll_string.reverse() result_strings.append('%s' % roll_string[0] + ('~' if len(roll_string) > 1 else '') + '~'.join(roll_string[1:])) roll = ','.join(result_strings) string.append('[%s]' % roll) elif comparison_reroll is not None: # Handle rerolling dice with a comparison modifier. type_of_dice = int(comparison_reroll[3]) comparator = int(comparison_reroll[6]) if comparison_reroll[5] == '>': # Ensure comparison is within bounds assert 0 < comparator < type_of_dice else: assert 1 < comparator <= type_of_dice result_strings = [] roll_strings = [] result = roll_group(comparison_reroll[1]) repeat = True if comparison_reroll[4] == 'R' else False if comparison_reroll[5] == '>': if repeat: for i in range(len(result)): prev = [result[i]] while result[i] > comparator: result[i] = random.randint(1, type_of_dice) prev.append(result[i]) roll_strings.append([str(x) for x in prev]) else: for i in range(len(result)): prev = [result[i]] if result[i] > comparator: result[i] = random.randint(1, type_of_dice) prev.append(result[i]) roll_strings.append([str(x) for x in prev]) else: if repeat: for i in range(len(result)): prev = [result[i]] while result[i] < comparator: result[i] = random.randint(1, type_of_dice) prev.append(result[i]) roll_strings.append([str(x) for x in prev]) else: for i in range(len(result)): prev = [result[i]] if result[i] < comparator: result[i] = random.randint(1, type_of_dice) prev.append(result[i]) roll_strings.append([str(x) for x in prev]) results.append(sum(result)) for roll_string in roll_strings: roll_string.reverse() result_strings.append('%s' % roll_string[0] + ('~' if len(roll_string) > 1 else '') + '~'.join(roll_string[1:])) roll = ','.join(result_strings) string.append('[%s]' % roll) elif success_comparison is not None: group_result = roll_group(success_comparison[1]) result = [] result_string = [] type_of_dice = int(success_comparison[2]) comparator = int(success_comparison[4]) if success_comparison[3] == '>': # Ensure comparison is within bounds assert 0 < comparator < type_of_dice else: assert 1 < comparator <= type_of_dice for die in group_result: if success_comparison[3] == '>': result.append(1 if die > comparator else 0) result_string.append('!' + str(die) if die > comparator else str(die)) else: result.append(1 if die < comparator else 0) result_string.append('!' + str(die) if die < comparator else str(die)) results.append(sum(result)) roll = ','.join(result_string) # Craft the string, adding an exclamation mark before every string that passed the comparison. string.append('[%s]' % roll) elif success_fail_comparison is not None: group_result = roll_group(success_fail_comparison[1]) result = [] result_string = [] type_of_dice = int(success_fail_comparison[2]) success_comp = int(success_fail_comparison[5]) fail_comp = int(success_fail_comparison[7]) # Ensure both comparisons are within bounds if success_fail_comparison[4] == '>': assert 0 < success_comp < type_of_dice assert 1 < fail_comp <= type_of_dice else: assert 1 < success_comp <= type_of_dice assert 0 < fail_comp < type_of_dice for die in group_result: if success_fail_comparison[4] == '>': # Get the actual list of successes and fails with both comparisons if die > success_comp: result.append(1) result_string.append('!' + str(die)) elif die < fail_comp: result.append(-1) result_string.append('*' + str(die)) else: result.append(0) result_string.append(str(die)) else: if die < success_comp: result.append(1) result_string.append('!' + str(die)) elif die > fail_comp: result.append(-1) result_string.append('*' + str(die)) else: result.append(0) result_string.append(str(die)) results.append(sum(result)) # roll = ','.join(result_string) string.append('[%s]' % roll) elif keep is not None: # Handle rolling dice and keeping the x highest or lowest values group_result = roll_group(keep[1]) group_result.sort(reverse=True if keep[ 2] == 'K' else False) # Uppercase is keep highest and lowercase is keep lowest. num_to_keep = int(keep[3] if keep[3] != '' else 1) assert 1 <= num_to_keep < len(group_result) results.append(sum(group_result[:num_to_keep])) roll = ','.join([str(i) for i in group_result[ :num_to_keep]]) + ' ~~ ' # This time format the string with all kept rolls on the left and dropped rolls on the right roll += ','.join([str(i) for i in group_result[num_to_keep:]]) string.append('[%s]' % roll) elif drop is not None: group_result = roll_group(drop[1]) group_result.sort(reverse=True if drop[2] == 'X' else False) # Same thing as keep dice num_to_drop = int(drop[3] if drop[3] != '' else 1) assert 1 <= num_to_drop < len(group_result) results.append(sum(group_result[:num_to_drop])) roll = ','.join([str(i) for i in group_result[num_to_drop:]]) + ' ~~ ' # Same as above. roll += ','.join([str(i) for i in group_result[:num_to_drop]]) string.append('[%s]' % roll) elif individual is not None: group_result = roll_group(individual[1]) result = [] for i, j in enumerate(group_result): #add to each roll if individual[4] == 'a': result.append(j + int(individual[5])) elif individual[4] == 's': result.append(j - int(individual[5])) elif individual[4] == 'm': result.append(j * int(individual[5])) else: raise ValueError results.append(sum(result)) roll = ','.join([str(x) + individual[4] + individual[5] for x in group_result]) #Create string with the modifier on each roll string.append('[%s]' % roll) elif normal is not None: group_result = roll_group(group) results.append(sum(group_result)) roll = ','.join([str(i) for i in group_result]) string.append('[%s]' % roll) elif literal is not None: results.append(int(literal[1])) # Just append the integer value string.append(literal[1]) elif float_literal is not None: if floats: results.append(float(group)) string.append(group) else: raise TypeError else: raise Exception except Exception: raise DiceGroupException('"%s" is not a valid dicegroup.' % group) parser = SimpleEval(floats=floats, functions=functions) #The parser object parses the dice rolls and functions try: final_result = parser.eval(''.join([str(x) for x in results])) #Call the parser to parse into one value if not floats: final_result = int(final_result) except Exception: raise DiceOperatorException('Error parsing operators and or functions') #Create explanation string and remove extraneous spaces explanation = ''.join(string) explanation = zero_width_split(r"""((?<=[\/%^+])(?![\/,]))| # Split between /, %, ^, and + ((?<![\/,])(?=[\/%^+]))| # Same as above ((?<=[^(])(?=-))(?!-[^[]*])| # Split in front of - that are not in a roll (?<=-)(?=[^\d()a-z])| # Same for splitting after - and before non-literals (?<=[\d)\]]-)(?=.)(?![^[]*])| # Split after a - that is not in a roll (?<=,)(?![^[]*])| # Split after a comma that is not in a roll (?<=([^,]\*))(?!\*)| # Split after a * that is not in a roll (?<![,\*])(?=\*) # Split before a * that is not in a roll""", explanation) #Split on ops to properly format the explanation explanation = ' '.join(explanation) explanation = explanation.strip() explanation = regex.sub(r'[ \t]{2,}', ' ', explanation) return final_result, explanation
[ "def", "roll_dice", "(", "roll", ",", "*", ",", "functions", "=", "True", ",", "floats", "=", "True", ")", ":", "roll", "=", "''", ".", "join", "(", "roll", ".", "split", "(", ")", ")", "roll", "=", "regex", ".", "sub", "(", "r'(?<=d)%'", ",", "'100'", ",", "roll", ",", "regex", ".", "IGNORECASE", ")", "roll", "=", "roll", ".", "replace", "(", "'^'", ",", "'**'", ")", "roll", "=", "zero_width_split", "(", "r'((?<=[\\(\\),%^\\/+*-])(?=.))|((?<=.)(?=[\\(\\),%^\\/+*-]))'", ",", "roll", ")", "# Split the string on the boundary between operators and other chars", "string", "=", "[", "]", "results", "=", "[", "]", "for", "group", "in", "roll", ":", "if", "group", "in", "'()/=<>,%^+*-'", "or", "group", "in", "DEFAULT_FUNCTIONS", ":", "#Append operators without modification", "results", ".", "append", "(", "group", ")", "string", ".", "append", "(", "group", ")", "continue", "try", ":", "explode", "=", "regex", ".", "match", "(", "r'^((\\d*)d(\\d+))!$'", ",", "group", ",", "regex", ".", "IGNORECASE", ")", "# Regex for exploding dice, ie. 2d10!, 4d100!, d12!, etc.", "specific_explode", "=", "regex", ".", "match", "(", "r'^((\\d*)d(\\d+))!(\\d+)$'", ",", "group", ")", "# Regex for exploding dice on specific number, ie. d20!10 or d12!4", "comparison_explode", "=", "regex", ".", "match", "(", "r'^((\\d*)d(\\d+))!([<>])(\\d+)$'", ",", "group", ",", "regex", ".", "IGNORECASE", ")", "# Regex for exploding dice with a comparison, ie. d20!>10, d6!<2", "penetrate", "=", "regex", ".", "match", "(", "r'^((\\d*)d(\\d+))!p$'", ",", "group", ",", "regex", ".", "IGNORECASE", ")", "# Penetrating dice are the same as exploding except any dice after the initial number are added with a -1 penalty", "specific_penetrate", "=", "regex", ".", "match", "(", "r'^((\\d*)d(\\d+))!p(\\d+)$'", ",", "group", ",", "regex", ".", "IGNORECASE", ")", "# See above", "comparison_penetrate", "=", "regex", ".", "match", "(", "r'^((\\d*)d(\\d+))!p([<>])(\\d+)$'", ",", "group", ",", "regex", ".", "IGNORECASE", ")", "# See above", "reroll", "=", "regex", ".", "match", "(", "r'^((\\d*)d(\\d+))([Rr])$'", ",", "group", ",", "regex", ".", "IGNORECASE", ")", "# Reroll on a one, matches 1d6R, 4d12r, etc.", "specific_reroll", "=", "regex", ".", "match", "(", "r'^((\\d*)d(\\d+))([Rr])(\\d+)$'", ",", "group", ",", "regex", ".", "IGNORECASE", ")", "# Reroll on a specific number", "comparison_reroll", "=", "regex", ".", "match", "(", "r'^((\\d*)d(\\d+))([Rr])([<>])(\\d+)$'", ",", "group", ",", "regex", ".", "IGNORECASE", ")", "# Reroll on a comparison", "success_comparison", "=", "regex", ".", "match", "(", "r'^((?:\\d*)d(\\d+))([<>])(\\d+)$'", ",", "group", ",", "regex", ".", "IGNORECASE", ")", "# Regex for dice with comparison, ie. 2d10>4, 5d3<2, etc.", "success_fail_comparison", "=", "regex", ".", "match", "(", "r'^((?:\\d*)d(\\d+))(?|((<)(\\d+)f(>)(\\d+))|((>)(\\d+)f(<)(\\d+)))$'", ",", "group", ",", "regex", ".", "IGNORECASE", ")", "# Regex for dice with success comparison and failure comparison.", "keep", "=", "regex", ".", "match", "(", "r'^((?:\\d*)d\\d+)([Kk])(\\d*)$'", ",", "group", ",", "regex", ".", "IGNORECASE", ")", "# Regex for keeping a number of dice, ie. 2d10K, 2d10k3, etc.", "drop", "=", "regex", ".", "match", "(", "r'^((?:\\d*)d\\d+)([Xx])(\\d*)$'", ",", "group", ",", "regex", ".", "IGNORECASE", ")", "# As above but with dropping dice and X", "individual", "=", "regex", ".", "match", "(", "r'^((\\d*)d(\\d+))([asm])(\\d+)$'", ",", "group", ",", "regex", ".", "IGNORECASE", ")", "#Regex for rolling dice with a modifier attached to each roll", "normal", "=", "regex", ".", "match", "(", "r'^((\\d*)d(\\d+))$'", ",", "group", ",", "regex", ".", "IGNORECASE", ")", "# Regex for normal dice rolls", "literal", "=", "regex", ".", "match", "(", "r'^(\\d+)(?!\\.)$'", ",", "group", ",", "regex", ".", "IGNORECASE", ")", "# Regex for number literals.", "float_literal", "=", "regex", ".", "match", "(", "r'^(\\.\\d+)|(\\d+.\\d+)$'", ",", "group", ",", "regex", ".", "IGNORECASE", ")", "# Regex for floats", "if", "explode", "is", "not", "None", ":", "# Handle exploding dice without a comparison modifier.", "type_of_dice", "=", "int", "(", "explode", "[", "3", "]", ")", "result", "=", "[", "]", "last_result", "=", "roll_group", "(", "explode", "[", "1", "]", ")", "result", ".", "extend", "(", "last_result", ")", "number_to_roll", "=", "num_equal", "(", "last_result", ",", "'='", ",", "type_of_dice", ")", "while", "number_to_roll", "!=", "0", ":", "last_result", "=", "roll_group", "(", "str", "(", "number_to_roll", ")", "+", "'d'", "+", "str", "(", "type_of_dice", ")", ")", "# Reroll dice", "result", ".", "extend", "(", "last_result", ")", "number_to_roll", "=", "num_equal", "(", "last_result", ",", "'='", ",", "type_of_dice", ")", "# Check how many dice we have to reroll again", "results", ".", "append", "(", "sum", "(", "result", ")", ")", "roll", "=", "','", ".", "join", "(", "[", "(", "'!'", "+", "str", "(", "i", ")", "if", "i", "==", "type_of_dice", "else", "str", "(", "i", ")", ")", "for", "i", "in", "result", "]", ")", "# Build a string of the dice rolls, adding an exclamation mark before every roll that resulted in an explosion.", "string", ".", "append", "(", "'[%s]'", "%", "roll", ")", "elif", "specific_explode", "is", "not", "None", ":", "# Handle exploding dice without a comparison modifier.", "type_of_dice", "=", "int", "(", "specific_explode", "[", "3", "]", ")", "comparator", "=", "int", "(", "specific_explode", "[", "4", "]", ")", "assert", "0", "<", "comparator", "<=", "type_of_dice", "result", "=", "[", "]", "last_result", "=", "roll_group", "(", "specific_explode", "[", "1", "]", ")", "result", ".", "extend", "(", "last_result", ")", "number_to_roll", "=", "num_equal", "(", "last_result", ",", "'='", ",", "comparator", ")", "while", "number_to_roll", "!=", "0", ":", "last_result", "=", "roll_group", "(", "str", "(", "number_to_roll", ")", "+", "'d'", "+", "str", "(", "type_of_dice", ")", ")", "result", ".", "extend", "(", "last_result", ")", "number_to_roll", "=", "num_equal", "(", "last_result", ",", "'='", ",", "comparator", ")", "results", ".", "append", "(", "sum", "(", "result", ")", ")", "roll", "=", "','", ".", "join", "(", "[", "(", "'!'", "+", "str", "(", "i", ")", "if", "i", "==", "comparator", "else", "str", "(", "i", ")", ")", "for", "i", "in", "result", "]", ")", "# Build a string of the dice rolls, adding an exclamation mark before every roll that resulted in an explosion.", "string", ".", "append", "(", "'[%s]'", "%", "roll", ")", "elif", "comparison_explode", "is", "not", "None", ":", "# Handle exploding dice with a comparison modifier", "type_of_dice", "=", "int", "(", "comparison_explode", "[", "3", "]", ")", "comparator", "=", "int", "(", "comparison_explode", "[", "5", "]", ")", "if", "comparison_explode", "[", "4", "]", "==", "'>'", ":", "# Ensure comparison is within bounds", "assert", "0", "<", "comparator", "<", "type_of_dice", "else", ":", "assert", "1", "<", "comparator", "<=", "type_of_dice", "result", "=", "[", "]", "last_result", "=", "roll_group", "(", "comparison_explode", "[", "1", "]", ")", "result", ".", "extend", "(", "last_result", ")", "if", "comparison_explode", "[", "4", "]", "==", "'>'", ":", "number_to_roll", "=", "num_equal", "(", "last_result", ",", "'>'", ",", "comparator", ")", "while", "number_to_roll", "!=", "0", ":", "last_result", "=", "roll_group", "(", "str", "(", "number_to_roll", ")", "+", "'d'", "+", "str", "(", "type_of_dice", ")", ")", "result", ".", "extend", "(", "last_result", ")", "number_to_roll", "=", "num_equal", "(", "last_result", ",", "'>'", ",", "comparator", ")", "roll", "=", "','", ".", "join", "(", "[", "(", "'!'", "+", "str", "(", "i", ")", "if", "i", ">", "comparator", "else", "str", "(", "i", ")", ")", "for", "i", "in", "result", "]", ")", "# Same as on other explodes except with a > or < comparison", "else", ":", "number_to_roll", "=", "num_equal", "(", "last_result", ",", "'<'", ",", "comparator", ")", "while", "number_to_roll", "!=", "0", ":", "last_result", "=", "roll_group", "(", "str", "(", "number_to_roll", ")", "+", "'d'", "+", "str", "(", "type_of_dice", ")", ")", "result", ".", "extend", "(", "last_result", ")", "number_to_roll", "=", "num_equal", "(", "last_result", ",", "'<'", ",", "comparator", ")", "roll", "=", "','", ".", "join", "(", "[", "(", "'!'", "+", "str", "(", "i", ")", "if", "i", "<", "comparator", "else", "str", "(", "i", ")", ")", "for", "i", "in", "result", "]", ")", "# Same as on other explodes except with a > or < comparison", "results", ".", "append", "(", "sum", "(", "result", ")", ")", "string", ".", "append", "(", "'[%s]'", "%", "roll", ")", "elif", "penetrate", "is", "not", "None", ":", "# Handle penetrating dice without a comparison modifier.", "type_of_dice", "=", "int", "(", "penetrate", "[", "3", "]", ")", "first_num", "=", "int", "(", "penetrate", "[", "2", "]", ")", "result", "=", "[", "]", "last_result", "=", "roll_group", "(", "penetrate", "[", "1", "]", ")", "result", ".", "extend", "(", "last_result", ")", "number_to_roll", "=", "num_equal", "(", "last_result", ",", "'='", ",", "type_of_dice", ")", "while", "number_to_roll", "!=", "0", ":", "last_result", "=", "roll_group", "(", "str", "(", "number_to_roll", ")", "+", "'d'", "+", "str", "(", "type_of_dice", ")", ")", "result", ".", "extend", "(", "last_result", ")", "number_to_roll", "=", "num_equal", "(", "last_result", ",", "'='", ",", "type_of_dice", ")", "pre_result", "=", "result", "[", ":", "first_num", "]", "# Add the first rolls with no modifier", "pre_result", ".", "extend", "(", "[", "x", "-", "1", "for", "x", "in", "result", "[", "first_num", ":", "]", "]", ")", "# Add the second rolls with a -1 modifier", "results", ".", "append", "(", "sum", "(", "pre_result", ")", ")", "roll", "=", "','", ".", "join", "(", "[", "'!'", "+", "str", "(", "i", ")", "if", "i", "==", "type_of_dice", "else", "str", "(", "i", ")", "for", "i", "in", "result", "[", ":", "first_num", "]", "]", ")", "# Add the first numbers, without the -1 but with a ! when roll is penetration", "roll", "+=", "(", "','", "if", "len", "(", "pre_result", ")", ">", "first_num", "else", "''", ")", "# Only add the comma in between if there's at least one penetration", "roll", "+=", "','", ".", "join", "(", "[", "(", "'!'", "+", "str", "(", "i", ")", "+", "'-1'", "if", "i", "==", "type_of_dice", "else", "str", "(", "i", ")", "+", "'-1'", ")", "for", "i", "in", "result", "[", "first_num", ":", "]", "]", ")", "# Add the penetration dice with the '-1' tacked on the end", "string", ".", "append", "(", "'[%s]'", "%", "roll", ")", "elif", "specific_penetrate", "is", "not", "None", ":", "# Handle penetrating dice without a comparison modifier.", "type_of_dice", "=", "int", "(", "specific_penetrate", "[", "3", "]", ")", "first_num", "=", "int", "(", "specific_penetrate", "[", "2", "]", ")", "comparator", "=", "int", "(", "specific_penetrate", "[", "4", "]", ")", "assert", "0", "<", "comparator", "<=", "type_of_dice", "result", "=", "[", "]", "last_result", "=", "roll_group", "(", "specific_penetrate", "[", "1", "]", ")", "result", ".", "extend", "(", "last_result", ")", "number_to_roll", "=", "num_equal", "(", "last_result", ",", "'='", ",", "comparator", ")", "while", "number_to_roll", "!=", "0", ":", "last_result", "=", "roll_group", "(", "str", "(", "number_to_roll", ")", "+", "'d'", "+", "str", "(", "type_of_dice", ")", ")", "result", ".", "extend", "(", "last_result", ")", "number_to_roll", "=", "num_equal", "(", "last_result", ",", "'='", ",", "comparator", ")", "pre_result", "=", "result", "[", ":", "first_num", "]", "# Same as normal penetration", "pre_result", ".", "extend", "(", "[", "x", "-", "1", "for", "x", "in", "result", "[", "first_num", ":", "]", "]", ")", "results", ".", "append", "(", "sum", "(", "pre_result", ")", ")", "roll", "=", "','", ".", "join", "(", "[", "'!'", "+", "str", "(", "i", ")", "if", "i", "==", "comparator", "else", "str", "(", "i", ")", "for", "i", "in", "result", "[", ":", "first_num", "]", "]", ")", "# Same as above", "roll", "+=", "(", "','", "if", "len", "(", "pre_result", ")", ">", "first_num", "else", "''", ")", "roll", "+=", "','", ".", "join", "(", "[", "(", "'!'", "+", "str", "(", "i", ")", "+", "'-1'", "if", "i", "==", "comparator", "else", "str", "(", "i", ")", "+", "'-1'", ")", "for", "i", "in", "result", "[", "first_num", ":", "]", "]", ")", "string", ".", "append", "(", "'[%s]'", "%", "roll", ")", "elif", "comparison_penetrate", "is", "not", "None", ":", "# Handle penetrating dice without a comparison modifier.", "type_of_dice", "=", "int", "(", "comparison_penetrate", "[", "3", "]", ")", "comparator", "=", "int", "(", "comparison_penetrate", "[", "5", "]", ")", "first_num", "=", "int", "(", "comparison_penetrate", "[", "2", "]", ")", "if", "comparison_penetrate", "[", "4", "]", "==", "'>'", ":", "# Ensure comparison is within bounds", "assert", "0", "<", "comparator", "<", "type_of_dice", "else", ":", "assert", "1", "<", "comparator", "<=", "type_of_dice", "result", "=", "[", "]", "last_result", "=", "roll_group", "(", "comparison_penetrate", "[", "1", "]", ")", "result", ".", "extend", "(", "last_result", ")", "# Do penetration based on more than or less than sign.", "if", "comparison_penetrate", "[", "4", "]", "==", "'>'", ":", "number_to_roll", "=", "num_equal", "(", "last_result", ",", "'>'", ",", "comparator", ")", "while", "number_to_roll", "!=", "0", ":", "last_result", "=", "roll_group", "(", "str", "(", "number_to_roll", ")", "+", "'d'", "+", "str", "(", "type_of_dice", ")", ")", "result", ".", "extend", "(", "last_result", ")", "number_to_roll", "=", "num_equal", "(", "last_result", ",", "'>'", ",", "comparator", ")", "else", ":", "number_to_roll", "=", "num_equal", "(", "last_result", ",", "'<'", ",", "comparator", ")", "while", "number_to_roll", "!=", "0", ":", "last_result", "=", "roll_group", "(", "str", "(", "number_to_roll", ")", "+", "'d'", "+", "str", "(", "type_of_dice", ")", ")", "result", ".", "extend", "(", "last_result", ")", "number_to_roll", "=", "num_equal", "(", "last_result", ",", "'<'", ",", "comparator", ")", "pre_result", "=", "result", "[", ":", "first_num", "]", "pre_result", ".", "extend", "(", "[", "x", "-", "1", "for", "x", "in", "result", "[", "first_num", ":", "]", "]", ")", "results", ".", "append", "(", "sum", "(", "pre_result", ")", ")", "if", "comparison_penetrate", "[", "4", "]", "==", "'>'", ":", "roll", "=", "','", ".", "join", "(", "[", "'!'", "+", "str", "(", "i", ")", "if", "i", ">", "comparator", "else", "str", "(", "i", ")", "for", "i", "in", "result", "[", ":", "first_num", "]", "]", ")", "# Same as above", "roll", "+=", "(", "','", "if", "len", "(", "pre_result", ")", ">", "first_num", "else", "''", ")", "roll", "+=", "','", ".", "join", "(", "[", "(", "'!'", "+", "str", "(", "i", ")", "+", "'-1'", "if", "i", ">", "comparator", "else", "str", "(", "i", ")", "+", "'-1'", ")", "for", "i", "in", "result", "[", "first_num", ":", "]", "]", ")", "else", ":", "roll", "=", "','", ".", "join", "(", "[", "'!'", "+", "str", "(", "i", ")", "if", "i", "<", "comparator", "else", "str", "(", "i", ")", "for", "i", "in", "result", "[", ":", "first_num", "]", "]", ")", "# Same as above", "roll", "+=", "(", "','", "if", "len", "(", "pre_result", ")", ">", "first_num", "else", "''", ")", "roll", "+=", "','", ".", "join", "(", "[", "(", "'!'", "+", "str", "(", "i", ")", "+", "'-1'", "if", "i", "<", "comparator", "else", "str", "(", "i", ")", "+", "'-1'", ")", "for", "i", "in", "result", "[", "first_num", ":", "]", "]", ")", "string", ".", "append", "(", "'[%s]'", "%", "roll", ")", "elif", "reroll", "is", "not", "None", ":", "# Handle rerolling dice without a comparison modifier (ie. on 1)", "type_of_dice", "=", "int", "(", "reroll", "[", "3", "]", ")", "result_strings", "=", "[", "]", "roll_strings", "=", "[", "]", "result", "=", "roll_group", "(", "reroll", "[", "1", "]", ")", "repeat", "=", "True", "if", "reroll", "[", "4", "]", "==", "'R'", "else", "False", "# Reroll just once or infinite number of times", "if", "repeat", ":", "#Handle rerolling the dice and building a string of all the rerolled ones", "for", "i", "in", "range", "(", "len", "(", "result", ")", ")", ":", "prev", "=", "[", "result", "[", "i", "]", "]", "while", "result", "[", "i", "]", "==", "1", ":", "result", "[", "i", "]", "=", "random", ".", "randint", "(", "1", ",", "type_of_dice", ")", "prev", ".", "append", "(", "result", "[", "i", "]", ")", "roll_strings", ".", "append", "(", "[", "str", "(", "x", ")", "for", "x", "in", "prev", "]", ")", "else", ":", "for", "i", "in", "range", "(", "len", "(", "result", ")", ")", ":", "prev", "=", "[", "result", "[", "i", "]", "]", "if", "result", "[", "i", "]", "==", "1", ":", "result", "[", "i", "]", "=", "random", ".", "randint", "(", "1", ",", "type_of_dice", ")", "prev", ".", "append", "(", "result", "[", "i", "]", ")", "roll_strings", ".", "append", "(", "[", "str", "(", "x", ")", "for", "x", "in", "prev", "]", ")", "results", ".", "append", "(", "sum", "(", "result", ")", ")", "for", "roll_string", "in", "roll_strings", ":", "roll_string", ".", "reverse", "(", ")", "result_strings", ".", "append", "(", "'%s'", "%", "roll_string", "[", "0", "]", "+", "(", "'~'", "if", "len", "(", "roll_string", ")", ">", "1", "else", "''", ")", "+", "'~'", ".", "join", "(", "roll_string", "[", "1", ":", "]", ")", ")", "#Build the string", "roll", "=", "','", ".", "join", "(", "result_strings", ")", "string", ".", "append", "(", "'[%s]'", "%", "roll", ")", "elif", "specific_reroll", "is", "not", "None", ":", "# Handle rerolling dice on a specific number, see reroll", "type_of_dice", "=", "int", "(", "specific_reroll", "[", "3", "]", ")", "comparator", "=", "int", "(", "specific_reroll", "[", "5", "]", ")", "assert", "0", "<", "comparator", "<=", "type_of_dice", "# Ensure comparison is within bounds", "result_strings", "=", "[", "]", "roll_strings", "=", "[", "]", "result", "=", "roll_group", "(", "specific_reroll", "[", "1", "]", ")", "repeat", "=", "True", "if", "specific_reroll", "[", "4", "]", "==", "'R'", "else", "False", "if", "repeat", ":", "for", "i", "in", "range", "(", "len", "(", "result", ")", ")", ":", "prev", "=", "[", "result", "[", "i", "]", "]", "while", "result", "[", "i", "]", "==", "comparator", ":", "result", "[", "i", "]", "=", "random", ".", "randint", "(", "1", ",", "type_of_dice", ")", "prev", ".", "append", "(", "result", "[", "i", "]", ")", "roll_strings", ".", "append", "(", "[", "str", "(", "x", ")", "for", "x", "in", "prev", "]", ")", "else", ":", "for", "i", "in", "range", "(", "len", "(", "result", ")", ")", ":", "prev", "=", "[", "result", "[", "i", "]", "]", "if", "result", "[", "i", "]", "==", "comparator", ":", "result", "[", "i", "]", "=", "random", ".", "randint", "(", "1", ",", "type_of_dice", ")", "prev", ".", "append", "(", "result", "[", "i", "]", ")", "roll_strings", ".", "append", "(", "[", "str", "(", "x", ")", "for", "x", "in", "prev", "]", ")", "results", ".", "append", "(", "sum", "(", "result", ")", ")", "for", "roll_string", "in", "roll_strings", ":", "roll_string", ".", "reverse", "(", ")", "result_strings", ".", "append", "(", "'%s'", "%", "roll_string", "[", "0", "]", "+", "(", "'~'", "if", "len", "(", "roll_string", ")", ">", "1", "else", "''", ")", "+", "'~'", ".", "join", "(", "roll_string", "[", "1", ":", "]", ")", ")", "roll", "=", "','", ".", "join", "(", "result_strings", ")", "string", ".", "append", "(", "'[%s]'", "%", "roll", ")", "elif", "comparison_reroll", "is", "not", "None", ":", "# Handle rerolling dice with a comparison modifier.", "type_of_dice", "=", "int", "(", "comparison_reroll", "[", "3", "]", ")", "comparator", "=", "int", "(", "comparison_reroll", "[", "6", "]", ")", "if", "comparison_reroll", "[", "5", "]", "==", "'>'", ":", "# Ensure comparison is within bounds", "assert", "0", "<", "comparator", "<", "type_of_dice", "else", ":", "assert", "1", "<", "comparator", "<=", "type_of_dice", "result_strings", "=", "[", "]", "roll_strings", "=", "[", "]", "result", "=", "roll_group", "(", "comparison_reroll", "[", "1", "]", ")", "repeat", "=", "True", "if", "comparison_reroll", "[", "4", "]", "==", "'R'", "else", "False", "if", "comparison_reroll", "[", "5", "]", "==", "'>'", ":", "if", "repeat", ":", "for", "i", "in", "range", "(", "len", "(", "result", ")", ")", ":", "prev", "=", "[", "result", "[", "i", "]", "]", "while", "result", "[", "i", "]", ">", "comparator", ":", "result", "[", "i", "]", "=", "random", ".", "randint", "(", "1", ",", "type_of_dice", ")", "prev", ".", "append", "(", "result", "[", "i", "]", ")", "roll_strings", ".", "append", "(", "[", "str", "(", "x", ")", "for", "x", "in", "prev", "]", ")", "else", ":", "for", "i", "in", "range", "(", "len", "(", "result", ")", ")", ":", "prev", "=", "[", "result", "[", "i", "]", "]", "if", "result", "[", "i", "]", ">", "comparator", ":", "result", "[", "i", "]", "=", "random", ".", "randint", "(", "1", ",", "type_of_dice", ")", "prev", ".", "append", "(", "result", "[", "i", "]", ")", "roll_strings", ".", "append", "(", "[", "str", "(", "x", ")", "for", "x", "in", "prev", "]", ")", "else", ":", "if", "repeat", ":", "for", "i", "in", "range", "(", "len", "(", "result", ")", ")", ":", "prev", "=", "[", "result", "[", "i", "]", "]", "while", "result", "[", "i", "]", "<", "comparator", ":", "result", "[", "i", "]", "=", "random", ".", "randint", "(", "1", ",", "type_of_dice", ")", "prev", ".", "append", "(", "result", "[", "i", "]", ")", "roll_strings", ".", "append", "(", "[", "str", "(", "x", ")", "for", "x", "in", "prev", "]", ")", "else", ":", "for", "i", "in", "range", "(", "len", "(", "result", ")", ")", ":", "prev", "=", "[", "result", "[", "i", "]", "]", "if", "result", "[", "i", "]", "<", "comparator", ":", "result", "[", "i", "]", "=", "random", ".", "randint", "(", "1", ",", "type_of_dice", ")", "prev", ".", "append", "(", "result", "[", "i", "]", ")", "roll_strings", ".", "append", "(", "[", "str", "(", "x", ")", "for", "x", "in", "prev", "]", ")", "results", ".", "append", "(", "sum", "(", "result", ")", ")", "for", "roll_string", "in", "roll_strings", ":", "roll_string", ".", "reverse", "(", ")", "result_strings", ".", "append", "(", "'%s'", "%", "roll_string", "[", "0", "]", "+", "(", "'~'", "if", "len", "(", "roll_string", ")", ">", "1", "else", "''", ")", "+", "'~'", ".", "join", "(", "roll_string", "[", "1", ":", "]", ")", ")", "roll", "=", "','", ".", "join", "(", "result_strings", ")", "string", ".", "append", "(", "'[%s]'", "%", "roll", ")", "elif", "success_comparison", "is", "not", "None", ":", "group_result", "=", "roll_group", "(", "success_comparison", "[", "1", "]", ")", "result", "=", "[", "]", "result_string", "=", "[", "]", "type_of_dice", "=", "int", "(", "success_comparison", "[", "2", "]", ")", "comparator", "=", "int", "(", "success_comparison", "[", "4", "]", ")", "if", "success_comparison", "[", "3", "]", "==", "'>'", ":", "# Ensure comparison is within bounds", "assert", "0", "<", "comparator", "<", "type_of_dice", "else", ":", "assert", "1", "<", "comparator", "<=", "type_of_dice", "for", "die", "in", "group_result", ":", "if", "success_comparison", "[", "3", "]", "==", "'>'", ":", "result", ".", "append", "(", "1", "if", "die", ">", "comparator", "else", "0", ")", "result_string", ".", "append", "(", "'!'", "+", "str", "(", "die", ")", "if", "die", ">", "comparator", "else", "str", "(", "die", ")", ")", "else", ":", "result", ".", "append", "(", "1", "if", "die", "<", "comparator", "else", "0", ")", "result_string", ".", "append", "(", "'!'", "+", "str", "(", "die", ")", "if", "die", "<", "comparator", "else", "str", "(", "die", ")", ")", "results", ".", "append", "(", "sum", "(", "result", ")", ")", "roll", "=", "','", ".", "join", "(", "result_string", ")", "# Craft the string, adding an exclamation mark before every string that passed the comparison.", "string", ".", "append", "(", "'[%s]'", "%", "roll", ")", "elif", "success_fail_comparison", "is", "not", "None", ":", "group_result", "=", "roll_group", "(", "success_fail_comparison", "[", "1", "]", ")", "result", "=", "[", "]", "result_string", "=", "[", "]", "type_of_dice", "=", "int", "(", "success_fail_comparison", "[", "2", "]", ")", "success_comp", "=", "int", "(", "success_fail_comparison", "[", "5", "]", ")", "fail_comp", "=", "int", "(", "success_fail_comparison", "[", "7", "]", ")", "# Ensure both comparisons are within bounds", "if", "success_fail_comparison", "[", "4", "]", "==", "'>'", ":", "assert", "0", "<", "success_comp", "<", "type_of_dice", "assert", "1", "<", "fail_comp", "<=", "type_of_dice", "else", ":", "assert", "1", "<", "success_comp", "<=", "type_of_dice", "assert", "0", "<", "fail_comp", "<", "type_of_dice", "for", "die", "in", "group_result", ":", "if", "success_fail_comparison", "[", "4", "]", "==", "'>'", ":", "# Get the actual list of successes and fails with both comparisons", "if", "die", ">", "success_comp", ":", "result", ".", "append", "(", "1", ")", "result_string", ".", "append", "(", "'!'", "+", "str", "(", "die", ")", ")", "elif", "die", "<", "fail_comp", ":", "result", ".", "append", "(", "-", "1", ")", "result_string", ".", "append", "(", "'*'", "+", "str", "(", "die", ")", ")", "else", ":", "result", ".", "append", "(", "0", ")", "result_string", ".", "append", "(", "str", "(", "die", ")", ")", "else", ":", "if", "die", "<", "success_comp", ":", "result", ".", "append", "(", "1", ")", "result_string", ".", "append", "(", "'!'", "+", "str", "(", "die", ")", ")", "elif", "die", ">", "fail_comp", ":", "result", ".", "append", "(", "-", "1", ")", "result_string", ".", "append", "(", "'*'", "+", "str", "(", "die", ")", ")", "else", ":", "result", ".", "append", "(", "0", ")", "result_string", ".", "append", "(", "str", "(", "die", ")", ")", "results", ".", "append", "(", "sum", "(", "result", ")", ")", "#", "roll", "=", "','", ".", "join", "(", "result_string", ")", "string", ".", "append", "(", "'[%s]'", "%", "roll", ")", "elif", "keep", "is", "not", "None", ":", "# Handle rolling dice and keeping the x highest or lowest values", "group_result", "=", "roll_group", "(", "keep", "[", "1", "]", ")", "group_result", ".", "sort", "(", "reverse", "=", "True", "if", "keep", "[", "2", "]", "==", "'K'", "else", "False", ")", "# Uppercase is keep highest and lowercase is keep lowest.", "num_to_keep", "=", "int", "(", "keep", "[", "3", "]", "if", "keep", "[", "3", "]", "!=", "''", "else", "1", ")", "assert", "1", "<=", "num_to_keep", "<", "len", "(", "group_result", ")", "results", ".", "append", "(", "sum", "(", "group_result", "[", ":", "num_to_keep", "]", ")", ")", "roll", "=", "','", ".", "join", "(", "[", "str", "(", "i", ")", "for", "i", "in", "group_result", "[", ":", "num_to_keep", "]", "]", ")", "+", "' ~~ '", "# This time format the string with all kept rolls on the left and dropped rolls on the right", "roll", "+=", "','", ".", "join", "(", "[", "str", "(", "i", ")", "for", "i", "in", "group_result", "[", "num_to_keep", ":", "]", "]", ")", "string", ".", "append", "(", "'[%s]'", "%", "roll", ")", "elif", "drop", "is", "not", "None", ":", "group_result", "=", "roll_group", "(", "drop", "[", "1", "]", ")", "group_result", ".", "sort", "(", "reverse", "=", "True", "if", "drop", "[", "2", "]", "==", "'X'", "else", "False", ")", "# Same thing as keep dice", "num_to_drop", "=", "int", "(", "drop", "[", "3", "]", "if", "drop", "[", "3", "]", "!=", "''", "else", "1", ")", "assert", "1", "<=", "num_to_drop", "<", "len", "(", "group_result", ")", "results", ".", "append", "(", "sum", "(", "group_result", "[", ":", "num_to_drop", "]", ")", ")", "roll", "=", "','", ".", "join", "(", "[", "str", "(", "i", ")", "for", "i", "in", "group_result", "[", "num_to_drop", ":", "]", "]", ")", "+", "' ~~ '", "# Same as above.", "roll", "+=", "','", ".", "join", "(", "[", "str", "(", "i", ")", "for", "i", "in", "group_result", "[", ":", "num_to_drop", "]", "]", ")", "string", ".", "append", "(", "'[%s]'", "%", "roll", ")", "elif", "individual", "is", "not", "None", ":", "group_result", "=", "roll_group", "(", "individual", "[", "1", "]", ")", "result", "=", "[", "]", "for", "i", ",", "j", "in", "enumerate", "(", "group_result", ")", ":", "#add to each roll", "if", "individual", "[", "4", "]", "==", "'a'", ":", "result", ".", "append", "(", "j", "+", "int", "(", "individual", "[", "5", "]", ")", ")", "elif", "individual", "[", "4", "]", "==", "'s'", ":", "result", ".", "append", "(", "j", "-", "int", "(", "individual", "[", "5", "]", ")", ")", "elif", "individual", "[", "4", "]", "==", "'m'", ":", "result", ".", "append", "(", "j", "*", "int", "(", "individual", "[", "5", "]", ")", ")", "else", ":", "raise", "ValueError", "results", ".", "append", "(", "sum", "(", "result", ")", ")", "roll", "=", "','", ".", "join", "(", "[", "str", "(", "x", ")", "+", "individual", "[", "4", "]", "+", "individual", "[", "5", "]", "for", "x", "in", "group_result", "]", ")", "#Create string with the modifier on each roll", "string", ".", "append", "(", "'[%s]'", "%", "roll", ")", "elif", "normal", "is", "not", "None", ":", "group_result", "=", "roll_group", "(", "group", ")", "results", ".", "append", "(", "sum", "(", "group_result", ")", ")", "roll", "=", "','", ".", "join", "(", "[", "str", "(", "i", ")", "for", "i", "in", "group_result", "]", ")", "string", ".", "append", "(", "'[%s]'", "%", "roll", ")", "elif", "literal", "is", "not", "None", ":", "results", ".", "append", "(", "int", "(", "literal", "[", "1", "]", ")", ")", "# Just append the integer value", "string", ".", "append", "(", "literal", "[", "1", "]", ")", "elif", "float_literal", "is", "not", "None", ":", "if", "floats", ":", "results", ".", "append", "(", "float", "(", "group", ")", ")", "string", ".", "append", "(", "group", ")", "else", ":", "raise", "TypeError", "else", ":", "raise", "Exception", "except", "Exception", ":", "raise", "DiceGroupException", "(", "'\"%s\" is not a valid dicegroup.'", "%", "group", ")", "parser", "=", "SimpleEval", "(", "floats", "=", "floats", ",", "functions", "=", "functions", ")", "#The parser object parses the dice rolls and functions", "try", ":", "final_result", "=", "parser", ".", "eval", "(", "''", ".", "join", "(", "[", "str", "(", "x", ")", "for", "x", "in", "results", "]", ")", ")", "#Call the parser to parse into one value", "if", "not", "floats", ":", "final_result", "=", "int", "(", "final_result", ")", "except", "Exception", ":", "raise", "DiceOperatorException", "(", "'Error parsing operators and or functions'", ")", "#Create explanation string and remove extraneous spaces", "explanation", "=", "''", ".", "join", "(", "string", ")", "explanation", "=", "zero_width_split", "(", "r\"\"\"((?<=[\\/%^+])(?![\\/,]))| # Split between /, %, ^, and +\n ((?<![\\/,])(?=[\\/%^+]))| # Same as above\n ((?<=[^(])(?=-))(?!-[^[]*])| # Split in front of - that are not in a roll\n (?<=-)(?=[^\\d()a-z])| # Same for splitting after - and before non-literals\n (?<=[\\d)\\]]-)(?=.)(?![^[]*])| # Split after a - that is not in a roll\n (?<=,)(?![^[]*])| # Split after a comma that is not in a roll\n (?<=([^,]\\*))(?!\\*)| # Split after a * that is not in a roll\n (?<![,\\*])(?=\\*) # Split before a * that is not in a roll\"\"\"", ",", "explanation", ")", "#Split on ops to properly format the explanation", "explanation", "=", "' '", ".", "join", "(", "explanation", ")", "explanation", "=", "explanation", ".", "strip", "(", ")", "explanation", "=", "regex", ".", "sub", "(", "r'[ \\t]{2,}'", ",", "' '", ",", "explanation", ")", "return", "final_result", ",", "explanation" ]
Rolls dice in dice notation with advanced syntax used according to tinyurl.com/pydice :param roll: Roll in dice notation :return: Result of roll, and an explanation string
[ "Rolls", "dice", "in", "dice", "notation", "with", "advanced", "syntax", "used", "according", "to", "tinyurl", ".", "com", "/", "pydice" ]
train
https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L360-L875
ThePlasmaRailgun/py-rolldice
rolldice/rolldice.py
SimpleEval.eval
def eval(self, expr): """ Evaluates an expression :param expr: Expression to evaluate :return: Result of expression """ # set a copy of the expression aside, so we can give nice errors... self.expr = expr # and evaluate: return self._eval(ast.parse(expr.strip()).body[0].value)
python
def eval(self, expr): """ Evaluates an expression :param expr: Expression to evaluate :return: Result of expression """ # set a copy of the expression aside, so we can give nice errors... self.expr = expr # and evaluate: return self._eval(ast.parse(expr.strip()).body[0].value)
[ "def", "eval", "(", "self", ",", "expr", ")", ":", "# set a copy of the expression aside, so we can give nice errors...", "self", ".", "expr", "=", "expr", "# and evaluate:", "return", "self", ".", "_eval", "(", "ast", ".", "parse", "(", "expr", ".", "strip", "(", ")", ")", ".", "body", "[", "0", "]", ".", "value", ")" ]
Evaluates an expression :param expr: Expression to evaluate :return: Result of expression
[ "Evaluates", "an", "expression" ]
train
https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L139-L151
ThePlasmaRailgun/py-rolldice
rolldice/rolldice.py
SimpleEval._eval
def _eval(self, node): """ Evaluate a node :param node: Node to eval :return: Result of node """ try: handler = self.nodes[type(node)] except KeyError: raise ValueError("Sorry, {0} is not available in this evaluator".format(type(node).__name__)) return handler(node)
python
def _eval(self, node): """ Evaluate a node :param node: Node to eval :return: Result of node """ try: handler = self.nodes[type(node)] except KeyError: raise ValueError("Sorry, {0} is not available in this evaluator".format(type(node).__name__)) return handler(node)
[ "def", "_eval", "(", "self", ",", "node", ")", ":", "try", ":", "handler", "=", "self", ".", "nodes", "[", "type", "(", "node", ")", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "\"Sorry, {0} is not available in this evaluator\"", ".", "format", "(", "type", "(", "node", ")", ".", "__name__", ")", ")", "return", "handler", "(", "node", ")" ]
Evaluate a node :param node: Node to eval :return: Result of node
[ "Evaluate", "a", "node" ]
train
https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L153-L165
ThePlasmaRailgun/py-rolldice
rolldice/rolldice.py
SimpleEval._eval_num
def _eval_num(self, node): """ Evaluate a numerical node :param node: Node to eval :return: Result of node """ if self.floats: return node.n else: return int(node.n)
python
def _eval_num(self, node): """ Evaluate a numerical node :param node: Node to eval :return: Result of node """ if self.floats: return node.n else: return int(node.n)
[ "def", "_eval_num", "(", "self", ",", "node", ")", ":", "if", "self", ".", "floats", ":", "return", "node", ".", "n", "else", ":", "return", "int", "(", "node", ".", "n", ")" ]
Evaluate a numerical node :param node: Node to eval :return: Result of node
[ "Evaluate", "a", "numerical", "node" ]
train
https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L167-L177
ThePlasmaRailgun/py-rolldice
rolldice/rolldice.py
SimpleEval._eval_unaryop
def _eval_unaryop(self, node): """ Evaluate a unary operator node (ie. -2, +3) Currently just supports positive and negative :param node: Node to eval :return: Result of node """ return self.operators[type(node.op)](self._eval(node.operand))
python
def _eval_unaryop(self, node): """ Evaluate a unary operator node (ie. -2, +3) Currently just supports positive and negative :param node: Node to eval :return: Result of node """ return self.operators[type(node.op)](self._eval(node.operand))
[ "def", "_eval_unaryop", "(", "self", ",", "node", ")", ":", "return", "self", ".", "operators", "[", "type", "(", "node", ".", "op", ")", "]", "(", "self", ".", "_eval", "(", "node", ".", "operand", ")", ")" ]
Evaluate a unary operator node (ie. -2, +3) Currently just supports positive and negative :param node: Node to eval :return: Result of node
[ "Evaluate", "a", "unary", "operator", "node", "(", "ie", ".", "-", "2", "+", "3", ")", "Currently", "just", "supports", "positive", "and", "negative" ]
train
https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L179-L187
ThePlasmaRailgun/py-rolldice
rolldice/rolldice.py
SimpleEval._eval_binop
def _eval_binop(self, node): """ Evaluate a binary operator node (ie. 2+3, 5*6, 3 ** 4) :param node: Node to eval :return: Result of node """ return self.operators[type(node.op)](self._eval(node.left), self._eval(node.right))
python
def _eval_binop(self, node): """ Evaluate a binary operator node (ie. 2+3, 5*6, 3 ** 4) :param node: Node to eval :return: Result of node """ return self.operators[type(node.op)](self._eval(node.left), self._eval(node.right))
[ "def", "_eval_binop", "(", "self", ",", "node", ")", ":", "return", "self", ".", "operators", "[", "type", "(", "node", ".", "op", ")", "]", "(", "self", ".", "_eval", "(", "node", ".", "left", ")", ",", "self", ".", "_eval", "(", "node", ".", "right", ")", ")" ]
Evaluate a binary operator node (ie. 2+3, 5*6, 3 ** 4) :param node: Node to eval :return: Result of node
[ "Evaluate", "a", "binary", "operator", "node", "(", "ie", ".", "2", "+", "3", "5", "*", "6", "3", "**", "4", ")" ]
train
https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L189-L197
ThePlasmaRailgun/py-rolldice
rolldice/rolldice.py
SimpleEval._eval_call
def _eval_call(self, node): """ Evaluate a function call :param node: Node to eval :return: Result of node """ try: func = self.functions[node.func.id] except KeyError: raise NameError(node.func.id) value = func( *(self._eval(a) for a in node.args), **dict(self._eval(k) for k in node.keywords) ) if value is True: return 1 elif value is False: return 0 else: return value
python
def _eval_call(self, node): """ Evaluate a function call :param node: Node to eval :return: Result of node """ try: func = self.functions[node.func.id] except KeyError: raise NameError(node.func.id) value = func( *(self._eval(a) for a in node.args), **dict(self._eval(k) for k in node.keywords) ) if value is True: return 1 elif value is False: return 0 else: return value
[ "def", "_eval_call", "(", "self", ",", "node", ")", ":", "try", ":", "func", "=", "self", ".", "functions", "[", "node", ".", "func", ".", "id", "]", "except", "KeyError", ":", "raise", "NameError", "(", "node", ".", "func", ".", "id", ")", "value", "=", "func", "(", "*", "(", "self", ".", "_eval", "(", "a", ")", "for", "a", "in", "node", ".", "args", ")", ",", "*", "*", "dict", "(", "self", ".", "_eval", "(", "k", ")", "for", "k", "in", "node", ".", "keywords", ")", ")", "if", "value", "is", "True", ":", "return", "1", "elif", "value", "is", "False", ":", "return", "0", "else", ":", "return", "value" ]
Evaluate a function call :param node: Node to eval :return: Result of node
[ "Evaluate", "a", "function", "call" ]
train
https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L199-L221
ThePlasmaRailgun/py-rolldice
rolldice/rolldice.py
DiceBag.roll_dice
def roll_dice(self): # Roll dice with current roll """ Rolls dicebag and sets last_roll and last_explanation to roll results :return: Roll results. """ roll = roll_dice(self.roll, floats=self.floats, functions=self.functions) self._last_roll = roll[0] self._last_explanation = roll[1] return self.last_roll, self.last_explanation
python
def roll_dice(self): # Roll dice with current roll """ Rolls dicebag and sets last_roll and last_explanation to roll results :return: Roll results. """ roll = roll_dice(self.roll, floats=self.floats, functions=self.functions) self._last_roll = roll[0] self._last_explanation = roll[1] return self.last_roll, self.last_explanation
[ "def", "roll_dice", "(", "self", ")", ":", "# Roll dice with current roll", "roll", "=", "roll_dice", "(", "self", ".", "roll", ",", "floats", "=", "self", ".", "floats", ",", "functions", "=", "self", ".", "functions", ")", "self", ".", "_last_roll", "=", "roll", "[", "0", "]", "self", ".", "_last_explanation", "=", "roll", "[", "1", "]", "return", "self", ".", "last_roll", ",", "self", ".", "last_explanation" ]
Rolls dicebag and sets last_roll and last_explanation to roll results :return: Roll results.
[ "Rolls", "dicebag", "and", "sets", "last_roll", "and", "last_explanation", "to", "roll", "results" ]
train
https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L242-L253
ThePlasmaRailgun/py-rolldice
rolldice/rolldice.py
DiceBag.roll
def roll(self, value): """ Setter for roll, verifies the roll is valid :param value: Roll :return: None """ if type(value) != str: # Make sure dice roll is a str raise TypeError('Dice roll must be a string in dice notation') try: roll_dice(value) # Make sure dice roll parses as a valid roll and not an error except Exception as e: raise ValueError('Dice roll specified was not a valid diceroll.\n%s\n' % str(e)) else: self._roll = value
python
def roll(self, value): """ Setter for roll, verifies the roll is valid :param value: Roll :return: None """ if type(value) != str: # Make sure dice roll is a str raise TypeError('Dice roll must be a string in dice notation') try: roll_dice(value) # Make sure dice roll parses as a valid roll and not an error except Exception as e: raise ValueError('Dice roll specified was not a valid diceroll.\n%s\n' % str(e)) else: self._roll = value
[ "def", "roll", "(", "self", ",", "value", ")", ":", "if", "type", "(", "value", ")", "!=", "str", ":", "# Make sure dice roll is a str", "raise", "TypeError", "(", "'Dice roll must be a string in dice notation'", ")", "try", ":", "roll_dice", "(", "value", ")", "# Make sure dice roll parses as a valid roll and not an error", "except", "Exception", "as", "e", ":", "raise", "ValueError", "(", "'Dice roll specified was not a valid diceroll.\\n%s\\n'", "%", "str", "(", "e", ")", ")", "else", ":", "self", ".", "_roll", "=", "value" ]
Setter for roll, verifies the roll is valid :param value: Roll :return: None
[ "Setter", "for", "roll", "verifies", "the", "roll", "is", "valid" ]
train
https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L273-L287
alexcouper/captainhook
captainhook/checkers/pdb_checker.py
run
def run(files, temp_folder, arg=''): "Look for pdb.set_trace() commands in python files." parser = get_parser() args = parser.parse_args(arg.split()) py_files = filter_python_files(files) if args.ignore: orig_file_list = original_files(py_files, temp_folder) py_files = set(orig_file_list) - set(args.ignore) py_files = [temp_folder + f for f in py_files] return check_files(py_files).value()
python
def run(files, temp_folder, arg=''): "Look for pdb.set_trace() commands in python files." parser = get_parser() args = parser.parse_args(arg.split()) py_files = filter_python_files(files) if args.ignore: orig_file_list = original_files(py_files, temp_folder) py_files = set(orig_file_list) - set(args.ignore) py_files = [temp_folder + f for f in py_files] return check_files(py_files).value()
[ "def", "run", "(", "files", ",", "temp_folder", ",", "arg", "=", "''", ")", ":", "parser", "=", "get_parser", "(", ")", "args", "=", "parser", ".", "parse_args", "(", "arg", ".", "split", "(", ")", ")", "py_files", "=", "filter_python_files", "(", "files", ")", "if", "args", ".", "ignore", ":", "orig_file_list", "=", "original_files", "(", "py_files", ",", "temp_folder", ")", "py_files", "=", "set", "(", "orig_file_list", ")", "-", "set", "(", "args", ".", "ignore", ")", "py_files", "=", "[", "temp_folder", "+", "f", "for", "f", "in", "py_files", "]", "return", "check_files", "(", "py_files", ")", ".", "value", "(", ")" ]
Look for pdb.set_trace() commands in python files.
[ "Look", "for", "pdb", ".", "set_trace", "()", "commands", "in", "python", "files", "." ]
train
https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/checkers/pdb_checker.py#L15-L26
alexcouper/captainhook
captainhook/pre_commit.py
checks
def checks(): """ An iterator of valid checks that are in the installed checkers package. yields check name, check module """ checkers_dir = os.path.dirname(checkers.__file__) mod_names = [name for _, name, _ in pkgutil.iter_modules([checkers_dir])] for name in mod_names: mod = importlib.import_module("checkers.{0}".format(name)) # Does the module have a "run" function if isinstance(getattr(mod, 'run', None), types.FunctionType): # has a run method, yield it yield getattr(mod, 'CHECK_NAME', name), mod
python
def checks(): """ An iterator of valid checks that are in the installed checkers package. yields check name, check module """ checkers_dir = os.path.dirname(checkers.__file__) mod_names = [name for _, name, _ in pkgutil.iter_modules([checkers_dir])] for name in mod_names: mod = importlib.import_module("checkers.{0}".format(name)) # Does the module have a "run" function if isinstance(getattr(mod, 'run', None), types.FunctionType): # has a run method, yield it yield getattr(mod, 'CHECK_NAME', name), mod
[ "def", "checks", "(", ")", ":", "checkers_dir", "=", "os", ".", "path", ".", "dirname", "(", "checkers", ".", "__file__", ")", "mod_names", "=", "[", "name", "for", "_", ",", "name", ",", "_", "in", "pkgutil", ".", "iter_modules", "(", "[", "checkers_dir", "]", ")", "]", "for", "name", "in", "mod_names", ":", "mod", "=", "importlib", ".", "import_module", "(", "\"checkers.{0}\"", ".", "format", "(", "name", ")", ")", "# Does the module have a \"run\" function", "if", "isinstance", "(", "getattr", "(", "mod", ",", "'run'", ",", "None", ")", ",", "types", ".", "FunctionType", ")", ":", "# has a run method, yield it", "yield", "getattr", "(", "mod", ",", "'CHECK_NAME'", ",", "name", ")", ",", "mod" ]
An iterator of valid checks that are in the installed checkers package. yields check name, check module
[ "An", "iterator", "of", "valid", "checks", "that", "are", "in", "the", "installed", "checkers", "package", "." ]
train
https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/pre_commit.py#L40-L54
alexcouper/captainhook
captainhook/pre_commit.py
files_to_check
def files_to_check(commit_only): """ Validate the commit diff. Make copies of the staged changes for analysis. """ global TEMP_FOLDER safe_directory = tempfile.mkdtemp() TEMP_FOLDER = safe_directory files = get_files(commit_only=commit_only, copy_dest=safe_directory) try: yield files finally: shutil.rmtree(safe_directory)
python
def files_to_check(commit_only): """ Validate the commit diff. Make copies of the staged changes for analysis. """ global TEMP_FOLDER safe_directory = tempfile.mkdtemp() TEMP_FOLDER = safe_directory files = get_files(commit_only=commit_only, copy_dest=safe_directory) try: yield files finally: shutil.rmtree(safe_directory)
[ "def", "files_to_check", "(", "commit_only", ")", ":", "global", "TEMP_FOLDER", "safe_directory", "=", "tempfile", ".", "mkdtemp", "(", ")", "TEMP_FOLDER", "=", "safe_directory", "files", "=", "get_files", "(", "commit_only", "=", "commit_only", ",", "copy_dest", "=", "safe_directory", ")", "try", ":", "yield", "files", "finally", ":", "shutil", ".", "rmtree", "(", "safe_directory", ")" ]
Validate the commit diff. Make copies of the staged changes for analysis.
[ "Validate", "the", "commit", "diff", "." ]
train
https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/pre_commit.py#L66-L81
alexcouper/captainhook
captainhook/pre_commit.py
main
def main(commit_only=True): """ Run the configured code checks. Return system exit code. 1 - reject commit 0 - accept commit """ global TEMP_FOLDER exit_code = 0 hook_checks = HookConfig(get_config_file()) with files_to_check(commit_only) as files: for name, mod in checks(): default = getattr(mod, 'DEFAULT', 'off') if hook_checks.is_enabled(name, default=default): if hasattr(mod, 'REQUIRED_FILES'): for filename in mod.REQUIRED_FILES: if os.path.isfile(filename): try: shutil.copy(filename, TEMP_FOLDER) except shutil.Error: # Copied over by a previous check continue args = hook_checks.arguments(name) tmp_files = [os.path.join(TEMP_FOLDER, f) for f in files] if args: errors = mod.run(tmp_files, TEMP_FOLDER, args) else: errors = mod.run(tmp_files, TEMP_FOLDER) if errors: title_print("Checking {0}".format(name)) print((errors.replace(TEMP_FOLDER + "/", ''))) print("") exit_code = 1 if exit_code == 1: title_print("Rejecting commit") return exit_code
python
def main(commit_only=True): """ Run the configured code checks. Return system exit code. 1 - reject commit 0 - accept commit """ global TEMP_FOLDER exit_code = 0 hook_checks = HookConfig(get_config_file()) with files_to_check(commit_only) as files: for name, mod in checks(): default = getattr(mod, 'DEFAULT', 'off') if hook_checks.is_enabled(name, default=default): if hasattr(mod, 'REQUIRED_FILES'): for filename in mod.REQUIRED_FILES: if os.path.isfile(filename): try: shutil.copy(filename, TEMP_FOLDER) except shutil.Error: # Copied over by a previous check continue args = hook_checks.arguments(name) tmp_files = [os.path.join(TEMP_FOLDER, f) for f in files] if args: errors = mod.run(tmp_files, TEMP_FOLDER, args) else: errors = mod.run(tmp_files, TEMP_FOLDER) if errors: title_print("Checking {0}".format(name)) print((errors.replace(TEMP_FOLDER + "/", ''))) print("") exit_code = 1 if exit_code == 1: title_print("Rejecting commit") return exit_code
[ "def", "main", "(", "commit_only", "=", "True", ")", ":", "global", "TEMP_FOLDER", "exit_code", "=", "0", "hook_checks", "=", "HookConfig", "(", "get_config_file", "(", ")", ")", "with", "files_to_check", "(", "commit_only", ")", "as", "files", ":", "for", "name", ",", "mod", "in", "checks", "(", ")", ":", "default", "=", "getattr", "(", "mod", ",", "'DEFAULT'", ",", "'off'", ")", "if", "hook_checks", ".", "is_enabled", "(", "name", ",", "default", "=", "default", ")", ":", "if", "hasattr", "(", "mod", ",", "'REQUIRED_FILES'", ")", ":", "for", "filename", "in", "mod", ".", "REQUIRED_FILES", ":", "if", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "try", ":", "shutil", ".", "copy", "(", "filename", ",", "TEMP_FOLDER", ")", "except", "shutil", ".", "Error", ":", "# Copied over by a previous check", "continue", "args", "=", "hook_checks", ".", "arguments", "(", "name", ")", "tmp_files", "=", "[", "os", ".", "path", ".", "join", "(", "TEMP_FOLDER", ",", "f", ")", "for", "f", "in", "files", "]", "if", "args", ":", "errors", "=", "mod", ".", "run", "(", "tmp_files", ",", "TEMP_FOLDER", ",", "args", ")", "else", ":", "errors", "=", "mod", ".", "run", "(", "tmp_files", ",", "TEMP_FOLDER", ")", "if", "errors", ":", "title_print", "(", "\"Checking {0}\"", ".", "format", "(", "name", ")", ")", "print", "(", "(", "errors", ".", "replace", "(", "TEMP_FOLDER", "+", "\"/\"", ",", "''", ")", ")", ")", "print", "(", "\"\"", ")", "exit_code", "=", "1", "if", "exit_code", "==", "1", ":", "title_print", "(", "\"Rejecting commit\"", ")", "return", "exit_code" ]
Run the configured code checks. Return system exit code. 1 - reject commit 0 - accept commit
[ "Run", "the", "configured", "code", "checks", "." ]
train
https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/pre_commit.py#L84-L123
alexcouper/captainhook
captainhook/checkers/utils.py
get_files
def get_files(commit_only=True, copy_dest=None): "Get copies of files for analysis." if commit_only: real_files = bash( "git diff --cached --name-status | " "grep -v -E '^D' | " "awk '{ print ( $(NF) ) }' " ).value().strip() else: real_files = bash( "git ls-tree --name-only --full-tree -r HEAD" ).value().strip() if real_files: return create_fake_copies(real_files.split('\n'), copy_dest) return []
python
def get_files(commit_only=True, copy_dest=None): "Get copies of files for analysis." if commit_only: real_files = bash( "git diff --cached --name-status | " "grep -v -E '^D' | " "awk '{ print ( $(NF) ) }' " ).value().strip() else: real_files = bash( "git ls-tree --name-only --full-tree -r HEAD" ).value().strip() if real_files: return create_fake_copies(real_files.split('\n'), copy_dest) return []
[ "def", "get_files", "(", "commit_only", "=", "True", ",", "copy_dest", "=", "None", ")", ":", "if", "commit_only", ":", "real_files", "=", "bash", "(", "\"git diff --cached --name-status | \"", "\"grep -v -E '^D' | \"", "\"awk '{ print ( $(NF) ) }' \"", ")", ".", "value", "(", ")", ".", "strip", "(", ")", "else", ":", "real_files", "=", "bash", "(", "\"git ls-tree --name-only --full-tree -r HEAD\"", ")", ".", "value", "(", ")", ".", "strip", "(", ")", "if", "real_files", ":", "return", "create_fake_copies", "(", "real_files", ".", "split", "(", "'\\n'", ")", ",", "copy_dest", ")", "return", "[", "]" ]
Get copies of files for analysis.
[ "Get", "copies", "of", "files", "for", "analysis", "." ]
train
https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/checkers/utils.py#L34-L49
alexcouper/captainhook
captainhook/checkers/utils.py
create_fake_copies
def create_fake_copies(files, destination): """ Create copies of the given list of files in the destination given. Creates copies of the actual files to be committed using git show :<filename> Return a list of destination files. """ dest_files = [] for filename in files: leaf_dest_folder = os.path.join(destination, os.path.dirname(filename)) if not os.path.exists(leaf_dest_folder): os.makedirs(leaf_dest_folder) dest_file = os.path.join(destination, filename) bash("git show :{filename} > {dest_file}".format( filename=filename, dest_file=dest_file) ) dest_files.append(os.path.realpath(dest_file)) return dest_files
python
def create_fake_copies(files, destination): """ Create copies of the given list of files in the destination given. Creates copies of the actual files to be committed using git show :<filename> Return a list of destination files. """ dest_files = [] for filename in files: leaf_dest_folder = os.path.join(destination, os.path.dirname(filename)) if not os.path.exists(leaf_dest_folder): os.makedirs(leaf_dest_folder) dest_file = os.path.join(destination, filename) bash("git show :{filename} > {dest_file}".format( filename=filename, dest_file=dest_file) ) dest_files.append(os.path.realpath(dest_file)) return dest_files
[ "def", "create_fake_copies", "(", "files", ",", "destination", ")", ":", "dest_files", "=", "[", "]", "for", "filename", "in", "files", ":", "leaf_dest_folder", "=", "os", ".", "path", ".", "join", "(", "destination", ",", "os", ".", "path", ".", "dirname", "(", "filename", ")", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "leaf_dest_folder", ")", ":", "os", ".", "makedirs", "(", "leaf_dest_folder", ")", "dest_file", "=", "os", ".", "path", ".", "join", "(", "destination", ",", "filename", ")", "bash", "(", "\"git show :{filename} > {dest_file}\"", ".", "format", "(", "filename", "=", "filename", ",", "dest_file", "=", "dest_file", ")", ")", "dest_files", ".", "append", "(", "os", ".", "path", ".", "realpath", "(", "dest_file", ")", ")", "return", "dest_files" ]
Create copies of the given list of files in the destination given. Creates copies of the actual files to be committed using git show :<filename> Return a list of destination files.
[ "Create", "copies", "of", "the", "given", "list", "of", "files", "in", "the", "destination", "given", "." ]
train
https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/checkers/utils.py#L52-L72
alexcouper/captainhook
captainhook/checkers/utils.py
filter_python_files
def filter_python_files(files): "Get all python files from the list of files." py_files = [] for f in files: # If we end in .py, or if we don't have an extension and file says that # we are a python script, then add us to the list extension = os.path.splitext(f)[-1] if extension: if extension == '.py': py_files.append(f) elif 'python' in open(f, 'r').readline(): py_files.append(f) elif 'python script' in bash('file {}'.format(f)).value().lower(): py_files.append(f) return py_files
python
def filter_python_files(files): "Get all python files from the list of files." py_files = [] for f in files: # If we end in .py, or if we don't have an extension and file says that # we are a python script, then add us to the list extension = os.path.splitext(f)[-1] if extension: if extension == '.py': py_files.append(f) elif 'python' in open(f, 'r').readline(): py_files.append(f) elif 'python script' in bash('file {}'.format(f)).value().lower(): py_files.append(f) return py_files
[ "def", "filter_python_files", "(", "files", ")", ":", "py_files", "=", "[", "]", "for", "f", "in", "files", ":", "# If we end in .py, or if we don't have an extension and file says that", "# we are a python script, then add us to the list", "extension", "=", "os", ".", "path", ".", "splitext", "(", "f", ")", "[", "-", "1", "]", "if", "extension", ":", "if", "extension", "==", "'.py'", ":", "py_files", ".", "append", "(", "f", ")", "elif", "'python'", "in", "open", "(", "f", ",", "'r'", ")", ".", "readline", "(", ")", ":", "py_files", ".", "append", "(", "f", ")", "elif", "'python script'", "in", "bash", "(", "'file {}'", ".", "format", "(", "f", ")", ")", ".", "value", "(", ")", ".", "lower", "(", ")", ":", "py_files", ".", "append", "(", "f", ")", "return", "py_files" ]
Get all python files from the list of files.
[ "Get", "all", "python", "files", "from", "the", "list", "of", "files", "." ]
train
https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/checkers/utils.py#L75-L91
alexcouper/captainhook
captainhook/checkers/utils.py
HookConfig.configuration
def configuration(self, plugin): """ Get plugin configuration. Return a tuple of (on|off|default, args) """ conf = self.config.get(plugin, "default;").split(';') if len(conf) == 1: conf.append('') return tuple(conf)
python
def configuration(self, plugin): """ Get plugin configuration. Return a tuple of (on|off|default, args) """ conf = self.config.get(plugin, "default;").split(';') if len(conf) == 1: conf.append('') return tuple(conf)
[ "def", "configuration", "(", "self", ",", "plugin", ")", ":", "conf", "=", "self", ".", "config", ".", "get", "(", "plugin", ",", "\"default;\"", ")", ".", "split", "(", "';'", ")", "if", "len", "(", "conf", ")", "==", "1", ":", "conf", ".", "append", "(", "''", ")", "return", "tuple", "(", "conf", ")" ]
Get plugin configuration. Return a tuple of (on|off|default, args)
[ "Get", "plugin", "configuration", "." ]
train
https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/checkers/utils.py#L121-L130
alexcouper/captainhook
captainhook/checkers/frosted_checker.py
run
def run(files, temp_folder): "Check frosted errors in the code base." try: import frosted # NOQA except ImportError: return NO_FROSTED_MSG py_files = filter_python_files(files) cmd = 'frosted {0}'.format(' '.join(py_files)) return bash(cmd).value()
python
def run(files, temp_folder): "Check frosted errors in the code base." try: import frosted # NOQA except ImportError: return NO_FROSTED_MSG py_files = filter_python_files(files) cmd = 'frosted {0}'.format(' '.join(py_files)) return bash(cmd).value()
[ "def", "run", "(", "files", ",", "temp_folder", ")", ":", "try", ":", "import", "frosted", "# NOQA", "except", "ImportError", ":", "return", "NO_FROSTED_MSG", "py_files", "=", "filter_python_files", "(", "files", ")", "cmd", "=", "'frosted {0}'", ".", "format", "(", "' '", ".", "join", "(", "py_files", ")", ")", "return", "bash", "(", "cmd", ")", ".", "value", "(", ")" ]
Check frosted errors in the code base.
[ "Check", "frosted", "errors", "in", "the", "code", "base", "." ]
train
https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/checkers/frosted_checker.py#L14-L24
alexcouper/captainhook
captainhook/checkers/isort_checker.py
run
def run(files, temp_folder): """Check isort errors in the code base. For the --quiet option, at least isort >= 4.1.1 is required. https://github.com/timothycrosley/isort/blob/develop/CHANGELOG.md#411 """ try: import isort # NOQA except ImportError: return NO_ISORT_MSG py_files = filter_python_files(files) # --quiet because isort >= 4.1 outputs its logo in the console by default. return bash('isort -df --quiet {0}'.format(' '.join(py_files))).value()
python
def run(files, temp_folder): """Check isort errors in the code base. For the --quiet option, at least isort >= 4.1.1 is required. https://github.com/timothycrosley/isort/blob/develop/CHANGELOG.md#411 """ try: import isort # NOQA except ImportError: return NO_ISORT_MSG py_files = filter_python_files(files) # --quiet because isort >= 4.1 outputs its logo in the console by default. return bash('isort -df --quiet {0}'.format(' '.join(py_files))).value()
[ "def", "run", "(", "files", ",", "temp_folder", ")", ":", "try", ":", "import", "isort", "# NOQA", "except", "ImportError", ":", "return", "NO_ISORT_MSG", "py_files", "=", "filter_python_files", "(", "files", ")", "# --quiet because isort >= 4.1 outputs its logo in the console by default.", "return", "bash", "(", "'isort -df --quiet {0}'", ".", "format", "(", "' '", ".", "join", "(", "py_files", ")", ")", ")", ".", "value", "(", ")" ]
Check isort errors in the code base. For the --quiet option, at least isort >= 4.1.1 is required. https://github.com/timothycrosley/isort/blob/develop/CHANGELOG.md#411
[ "Check", "isort", "errors", "in", "the", "code", "base", "." ]
train
https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/checkers/isort_checker.py#L13-L28
alexcouper/captainhook
captainhook/checkers/block_branches.py
run
def run(files, temp_folder, arg=None): "Check we're not committing to a blocked branch" parser = get_parser() argos = parser.parse_args(arg.split()) current_branch = bash('git symbolic-ref HEAD').value() current_branch = current_branch.replace('refs/heads/', '').strip() if current_branch in argos.branches: return ("Branch '{0}' is blocked from being " "committed to.".format(current_branch))
python
def run(files, temp_folder, arg=None): "Check we're not committing to a blocked branch" parser = get_parser() argos = parser.parse_args(arg.split()) current_branch = bash('git symbolic-ref HEAD').value() current_branch = current_branch.replace('refs/heads/', '').strip() if current_branch in argos.branches: return ("Branch '{0}' is blocked from being " "committed to.".format(current_branch))
[ "def", "run", "(", "files", ",", "temp_folder", ",", "arg", "=", "None", ")", ":", "parser", "=", "get_parser", "(", ")", "argos", "=", "parser", ".", "parse_args", "(", "arg", ".", "split", "(", ")", ")", "current_branch", "=", "bash", "(", "'git symbolic-ref HEAD'", ")", ".", "value", "(", ")", "current_branch", "=", "current_branch", ".", "replace", "(", "'refs/heads/'", ",", "''", ")", ".", "strip", "(", ")", "if", "current_branch", "in", "argos", ".", "branches", ":", "return", "(", "\"Branch '{0}' is blocked from being \"", "\"committed to.\"", ".", "format", "(", "current_branch", ")", ")" ]
Check we're not committing to a blocked branch
[ "Check", "we", "re", "not", "committing", "to", "a", "blocked", "branch" ]
train
https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/checkers/block_branches.py#L11-L20
alexcouper/captainhook
captainhook/checkers/pylint_checker.py
run
def run(files, temp_folder, arg=None): "Check coding convention of the code base." try: import pylint except ImportError: return NO_PYLINT_MSG # set default level of threshold arg = arg or SCORE py_files = filter_python_files(files) if not py_files: return False str_py_files = " ".join(py_files) cmd = "{0} {1}".format(PYLINT_CMD, str_py_files) output = bash(cmd).value() if 'rated' not in output: return False score = float(re.search("(\d.\d\d)/10", output).group(1)) if score >= float(arg): return False return ("Pylint appreciated your {0} as {1}," "required threshold is {2}".format(PYLINT_TARGET, score, arg) )
python
def run(files, temp_folder, arg=None): "Check coding convention of the code base." try: import pylint except ImportError: return NO_PYLINT_MSG # set default level of threshold arg = arg or SCORE py_files = filter_python_files(files) if not py_files: return False str_py_files = " ".join(py_files) cmd = "{0} {1}".format(PYLINT_CMD, str_py_files) output = bash(cmd).value() if 'rated' not in output: return False score = float(re.search("(\d.\d\d)/10", output).group(1)) if score >= float(arg): return False return ("Pylint appreciated your {0} as {1}," "required threshold is {2}".format(PYLINT_TARGET, score, arg) )
[ "def", "run", "(", "files", ",", "temp_folder", ",", "arg", "=", "None", ")", ":", "try", ":", "import", "pylint", "except", "ImportError", ":", "return", "NO_PYLINT_MSG", "# set default level of threshold", "arg", "=", "arg", "or", "SCORE", "py_files", "=", "filter_python_files", "(", "files", ")", "if", "not", "py_files", ":", "return", "False", "str_py_files", "=", "\" \"", ".", "join", "(", "py_files", ")", "cmd", "=", "\"{0} {1}\"", ".", "format", "(", "PYLINT_CMD", ",", "str_py_files", ")", "output", "=", "bash", "(", "cmd", ")", ".", "value", "(", ")", "if", "'rated'", "not", "in", "output", ":", "return", "False", "score", "=", "float", "(", "re", ".", "search", "(", "\"(\\d.\\d\\d)/10\"", ",", "output", ")", ".", "group", "(", "1", ")", ")", "if", "score", ">=", "float", "(", "arg", ")", ":", "return", "False", "return", "(", "\"Pylint appreciated your {0} as {1},\"", "\"required threshold is {2}\"", ".", "format", "(", "PYLINT_TARGET", ",", "score", ",", "arg", ")", ")" ]
Check coding convention of the code base.
[ "Check", "coding", "convention", "of", "the", "code", "base", "." ]
train
https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/checkers/pylint_checker.py#L17-L42
alexcouper/captainhook
captainhook/checkers/python3.py
run
def run(files, temp_folder): "Check to see if python files are py3 compatible" errors = [] for py_file in filter_python_files(files): # We only want to show errors if we CAN'T compile to py3. # but we want to show all the errors at once. b = bash('python3 -m py_compile {0}'.format(py_file)) if b.stderr: b = bash('2to3-2.7 {file}'.format(file=py_file)) errors.append(b.value()) return "\n".join(errors)
python
def run(files, temp_folder): "Check to see if python files are py3 compatible" errors = [] for py_file in filter_python_files(files): # We only want to show errors if we CAN'T compile to py3. # but we want to show all the errors at once. b = bash('python3 -m py_compile {0}'.format(py_file)) if b.stderr: b = bash('2to3-2.7 {file}'.format(file=py_file)) errors.append(b.value()) return "\n".join(errors)
[ "def", "run", "(", "files", ",", "temp_folder", ")", ":", "errors", "=", "[", "]", "for", "py_file", "in", "filter_python_files", "(", "files", ")", ":", "# We only want to show errors if we CAN'T compile to py3.", "# but we want to show all the errors at once.", "b", "=", "bash", "(", "'python3 -m py_compile {0}'", ".", "format", "(", "py_file", ")", ")", "if", "b", ".", "stderr", ":", "b", "=", "bash", "(", "'2to3-2.7 {file}'", ".", "format", "(", "file", "=", "py_file", ")", ")", "errors", ".", "append", "(", "b", ".", "value", "(", ")", ")", "return", "\"\\n\"", ".", "join", "(", "errors", ")" ]
Check to see if python files are py3 compatible
[ "Check", "to", "see", "if", "python", "files", "are", "py3", "compatible" ]
train
https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/checkers/python3.py#L9-L19
alexcouper/captainhook
captainhook/checkers/flake8_checker.py
run
def run(files, temp_folder): "Check flake8 errors in the code base." try: import flake8 # NOQA except ImportError: return NO_FLAKE_MSG try: from flake8.engine import get_style_guide except ImportError: # We're on a new version of flake8 from flake8.api.legacy import get_style_guide py_files = filter_python_files(files) if not py_files: return DEFAULT_CONFIG = join(temp_folder, get_config_file()) with change_folder(temp_folder): flake8_style = get_style_guide(config_file=DEFAULT_CONFIG) out, err = StringIO(), StringIO() with redirected(out, err): flake8_style.check_files(py_files) return out.getvalue().strip() + err.getvalue().strip()
python
def run(files, temp_folder): "Check flake8 errors in the code base." try: import flake8 # NOQA except ImportError: return NO_FLAKE_MSG try: from flake8.engine import get_style_guide except ImportError: # We're on a new version of flake8 from flake8.api.legacy import get_style_guide py_files = filter_python_files(files) if not py_files: return DEFAULT_CONFIG = join(temp_folder, get_config_file()) with change_folder(temp_folder): flake8_style = get_style_guide(config_file=DEFAULT_CONFIG) out, err = StringIO(), StringIO() with redirected(out, err): flake8_style.check_files(py_files) return out.getvalue().strip() + err.getvalue().strip()
[ "def", "run", "(", "files", ",", "temp_folder", ")", ":", "try", ":", "import", "flake8", "# NOQA", "except", "ImportError", ":", "return", "NO_FLAKE_MSG", "try", ":", "from", "flake8", ".", "engine", "import", "get_style_guide", "except", "ImportError", ":", "# We're on a new version of flake8", "from", "flake8", ".", "api", ".", "legacy", "import", "get_style_guide", "py_files", "=", "filter_python_files", "(", "files", ")", "if", "not", "py_files", ":", "return", "DEFAULT_CONFIG", "=", "join", "(", "temp_folder", ",", "get_config_file", "(", ")", ")", "with", "change_folder", "(", "temp_folder", ")", ":", "flake8_style", "=", "get_style_guide", "(", "config_file", "=", "DEFAULT_CONFIG", ")", "out", ",", "err", "=", "StringIO", "(", ")", ",", "StringIO", "(", ")", "with", "redirected", "(", "out", ",", "err", ")", ":", "flake8_style", ".", "check_files", "(", "py_files", ")", "return", "out", ".", "getvalue", "(", ")", ".", "strip", "(", ")", "+", "err", ".", "getvalue", "(", ")", ".", "strip", "(", ")" ]
Check flake8 errors in the code base.
[ "Check", "flake8", "errors", "in", "the", "code", "base", "." ]
train
https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/checkers/flake8_checker.py#L45-L67
bpython/curtsies
examples/tttplaybitboard.py
tictactoe
def tictactoe(w, i, player, opponent, grid=None): "Put two strategies to a classic battle of wits." grid = grid or empty_grid while True: w.render_to_terminal(w.array_from_text(view(grid))) if is_won(grid): print(whose_move(grid), "wins.") break if not successors(grid): print("A draw.") break grid = player(w, i, grid) player, opponent = opponent, player
python
def tictactoe(w, i, player, opponent, grid=None): "Put two strategies to a classic battle of wits." grid = grid or empty_grid while True: w.render_to_terminal(w.array_from_text(view(grid))) if is_won(grid): print(whose_move(grid), "wins.") break if not successors(grid): print("A draw.") break grid = player(w, i, grid) player, opponent = opponent, player
[ "def", "tictactoe", "(", "w", ",", "i", ",", "player", ",", "opponent", ",", "grid", "=", "None", ")", ":", "grid", "=", "grid", "or", "empty_grid", "while", "True", ":", "w", ".", "render_to_terminal", "(", "w", ".", "array_from_text", "(", "view", "(", "grid", ")", ")", ")", "if", "is_won", "(", "grid", ")", ":", "print", "(", "whose_move", "(", "grid", ")", ",", "\"wins.\"", ")", "break", "if", "not", "successors", "(", "grid", ")", ":", "print", "(", "\"A draw.\"", ")", "break", "grid", "=", "player", "(", "w", ",", "i", ",", "grid", ")", "player", ",", "opponent", "=", "opponent", ",", "player" ]
Put two strategies to a classic battle of wits.
[ "Put", "two", "strategies", "to", "a", "classic", "battle", "of", "wits", "." ]
train
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tttplaybitboard.py#L40-L52
bpython/curtsies
examples/tttplaybitboard.py
memo
def memo(f): "Return a function like f that remembers and reuses results of past calls." table = {} def memo_f(*args): try: return table[args] except KeyError: table[args] = value = f(*args) return value return memo_f
python
def memo(f): "Return a function like f that remembers and reuses results of past calls." table = {} def memo_f(*args): try: return table[args] except KeyError: table[args] = value = f(*args) return value return memo_f
[ "def", "memo", "(", "f", ")", ":", "table", "=", "{", "}", "def", "memo_f", "(", "*", "args", ")", ":", "try", ":", "return", "table", "[", "args", "]", "except", "KeyError", ":", "table", "[", "args", "]", "=", "value", "=", "f", "(", "*", "args", ")", "return", "value", "return", "memo_f" ]
Return a function like f that remembers and reuses results of past calls.
[ "Return", "a", "function", "like", "f", "that", "remembers", "and", "reuses", "results", "of", "past", "calls", "." ]
train
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tttplaybitboard.py#L60-L69
bpython/curtsies
examples/tttplaybitboard.py
human_play
def human_play(w, i, grid): "Just ask for a move." plaint = '' prompt = whose_move(grid) + " move? [1-9] " while True: w.render_to_terminal(w.array_from_text(view(grid) + '\n\n' + plaint + prompt)) key = c = i.next() try: move = int(key) except ValueError: pass else: if 1 <= move <= 9: successor = apply_move(grid, from_human_move(move)) if successor: return successor plaint = ("Hey, that's illegal. Give me one of these digits:\n\n" + (grid_format % tuple(move if apply_move(grid, from_human_move(move)) else '-' for move in range(1, 10)) + '\n\n'))
python
def human_play(w, i, grid): "Just ask for a move." plaint = '' prompt = whose_move(grid) + " move? [1-9] " while True: w.render_to_terminal(w.array_from_text(view(grid) + '\n\n' + plaint + prompt)) key = c = i.next() try: move = int(key) except ValueError: pass else: if 1 <= move <= 9: successor = apply_move(grid, from_human_move(move)) if successor: return successor plaint = ("Hey, that's illegal. Give me one of these digits:\n\n" + (grid_format % tuple(move if apply_move(grid, from_human_move(move)) else '-' for move in range(1, 10)) + '\n\n'))
[ "def", "human_play", "(", "w", ",", "i", ",", "grid", ")", ":", "plaint", "=", "''", "prompt", "=", "whose_move", "(", "grid", ")", "+", "\" move? [1-9] \"", "while", "True", ":", "w", ".", "render_to_terminal", "(", "w", ".", "array_from_text", "(", "view", "(", "grid", ")", "+", "'\\n\\n'", "+", "plaint", "+", "prompt", ")", ")", "key", "=", "c", "=", "i", ".", "next", "(", ")", "try", ":", "move", "=", "int", "(", "key", ")", "except", "ValueError", ":", "pass", "else", ":", "if", "1", "<=", "move", "<=", "9", ":", "successor", "=", "apply_move", "(", "grid", ",", "from_human_move", "(", "move", ")", ")", "if", "successor", ":", "return", "successor", "plaint", "=", "(", "\"Hey, that's illegal. Give me one of these digits:\\n\\n\"", "+", "(", "grid_format", "%", "tuple", "(", "move", "if", "apply_move", "(", "grid", ",", "from_human_move", "(", "move", ")", ")", "else", "'-'", "for", "move", "in", "range", "(", "1", ",", "10", ")", ")", "+", "'\\n\\n'", ")", ")" ]
Just ask for a move.
[ "Just", "ask", "for", "a", "move", "." ]
train
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tttplaybitboard.py#L74-L94
bpython/curtsies
examples/tttplaybitboard.py
max_play
def max_play(w, i, grid): "Play like Spock, except breaking ties by drunk_value." return min(successors(grid), key=lambda succ: (evaluate(succ), drunk_value(succ)))
python
def max_play(w, i, grid): "Play like Spock, except breaking ties by drunk_value." return min(successors(grid), key=lambda succ: (evaluate(succ), drunk_value(succ)))
[ "def", "max_play", "(", "w", ",", "i", ",", "grid", ")", ":", "return", "min", "(", "successors", "(", "grid", ")", ",", "key", "=", "lambda", "succ", ":", "(", "evaluate", "(", "succ", ")", ",", "drunk_value", "(", "succ", ")", ")", ")" ]
Play like Spock, except breaking ties by drunk_value.
[ "Play", "like", "Spock", "except", "breaking", "ties", "by", "drunk_value", "." ]
train
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tttplaybitboard.py#L106-L109
bpython/curtsies
examples/tttplaybitboard.py
drunk_value
def drunk_value(grid): "Return the expected value to the player if both players play at random." if is_won(grid): return -1 succs = successors(grid) return -average(map(drunk_value, succs)) if succs else 0
python
def drunk_value(grid): "Return the expected value to the player if both players play at random." if is_won(grid): return -1 succs = successors(grid) return -average(map(drunk_value, succs)) if succs else 0
[ "def", "drunk_value", "(", "grid", ")", ":", "if", "is_won", "(", "grid", ")", ":", "return", "-", "1", "succs", "=", "successors", "(", "grid", ")", "return", "-", "average", "(", "map", "(", "drunk_value", ",", "succs", ")", ")", "if", "succs", "else", "0" ]
Return the expected value to the player if both players play at random.
[ "Return", "the", "expected", "value", "to", "the", "player", "if", "both", "players", "play", "at", "random", "." ]
train
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tttplaybitboard.py#L112-L116