repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
mattja/nsim
nsim/nsim.py
newsim
def newsim(f, G, y0, name='NewModel', modelType=ItoModel, T=60.0, dt=0.005, repeat=1, identical=True): """Make a simulation of the system defined by functions f and G. dy = f(y,t)dt + G(y,t).dW with initial condition y0 This helper function is for convenience, making it easy to define one-off simulati...
python
def newsim(f, G, y0, name='NewModel', modelType=ItoModel, T=60.0, dt=0.005, repeat=1, identical=True): """Make a simulation of the system defined by functions f and G. dy = f(y,t)dt + G(y,t).dW with initial condition y0 This helper function is for convenience, making it easy to define one-off simulati...
[ "def", "newsim", "(", "f", ",", "G", ",", "y0", ",", "name", "=", "'NewModel'", ",", "modelType", "=", "ItoModel", ",", "T", "=", "60.0", ",", "dt", "=", "0.005", ",", "repeat", "=", "1", ",", "identical", "=", "True", ")", ":", "NewModel", "=", ...
Make a simulation of the system defined by functions f and G. dy = f(y,t)dt + G(y,t).dW with initial condition y0 This helper function is for convenience, making it easy to define one-off simulations interactively in ipython. Args: f: callable(y, t) (defined in global scope) returning (n,) arra...
[ "Make", "a", "simulation", "of", "the", "system", "defined", "by", "functions", "f", "and", "G", "." ]
ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L1758-L1791
train
mattja/nsim
nsim/nsim.py
newmodel
def newmodel(f, G, y0, name='NewModel', modelType=ItoModel): """Use the functions f and G to define a new Model class for simulations. It will take functions f and G from global scope and make a new Model class out of them. It will automatically gather any globals used in the definition of f and G and...
python
def newmodel(f, G, y0, name='NewModel', modelType=ItoModel): """Use the functions f and G to define a new Model class for simulations. It will take functions f and G from global scope and make a new Model class out of them. It will automatically gather any globals used in the definition of f and G and...
[ "def", "newmodel", "(", "f", ",", "G", ",", "y0", ",", "name", "=", "'NewModel'", ",", "modelType", "=", "ItoModel", ")", ":", "if", "not", "issubclass", "(", "modelType", ",", "Model", ")", ":", "raise", "SimTypeError", "(", "'modelType must be a subclass...
Use the functions f and G to define a new Model class for simulations. It will take functions f and G from global scope and make a new Model class out of them. It will automatically gather any globals used in the definition of f and G and turn them into attributes of the new Model. Args: f: cal...
[ "Use", "the", "functions", "f", "and", "G", "to", "define", "a", "new", "Model", "class", "for", "simulations", "." ]
ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L1794-L1851
train
mattja/nsim
nsim/nsim.py
__clone_function
def __clone_function(f, name=None): """Make a new version of a function that has its own independent copy of any globals that it uses directly, and has its own name. All other attributes are assigned from the original function. Args: f: the function to clone name (str): the name for the ...
python
def __clone_function(f, name=None): """Make a new version of a function that has its own independent copy of any globals that it uses directly, and has its own name. All other attributes are assigned from the original function. Args: f: the function to clone name (str): the name for the ...
[ "def", "__clone_function", "(", "f", ",", "name", "=", "None", ")", ":", "if", "not", "isinstance", "(", "f", ",", "types", ".", "FunctionType", ")", ":", "raise", "SimTypeError", "(", "'Given parameter is not a function.'", ")", "if", "name", "is", "None", ...
Make a new version of a function that has its own independent copy of any globals that it uses directly, and has its own name. All other attributes are assigned from the original function. Args: f: the function to clone name (str): the name for the new function (if None, keep the same name) ...
[ "Make", "a", "new", "version", "of", "a", "function", "that", "has", "its", "own", "independent", "copy", "of", "any", "globals", "that", "it", "uses", "directly", "and", "has", "its", "own", "name", ".", "All", "other", "attributes", "are", "assigned", ...
ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L1884-L1917
train
mattja/nsim
nsim/nsim.py
DistTimeseries.expand_dims
def expand_dims(self, axis): """Insert a new axis, at a given position in the array shape Args: axis (int): Position (amongst axes) where new axis is to be inserted. """ if axis <= self._distaxis: subaxis = axis new_distaxis = self._distaxis + 1 ...
python
def expand_dims(self, axis): """Insert a new axis, at a given position in the array shape Args: axis (int): Position (amongst axes) where new axis is to be inserted. """ if axis <= self._distaxis: subaxis = axis new_distaxis = self._distaxis + 1 ...
[ "def", "expand_dims", "(", "self", ",", "axis", ")", ":", "if", "axis", "<=", "self", ".", "_distaxis", ":", "subaxis", "=", "axis", "new_distaxis", "=", "self", ".", "_distaxis", "+", "1", "else", ":", "subaxis", "=", "axis", "-", "1", "new_distaxis",...
Insert a new axis, at a given position in the array shape Args: axis (int): Position (amongst axes) where new axis is to be inserted.
[ "Insert", "a", "new", "axis", "at", "a", "given", "position", "in", "the", "array", "shape", "Args", ":", "axis", "(", "int", ")", ":", "Position", "(", "amongst", "axes", ")", "where", "new", "axis", "is", "to", "be", "inserted", "." ]
ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L608-L625
train
mattja/nsim
nsim/nsim.py
DistTimeseries.absolute
def absolute(self): """Calculate the absolute value element-wise. Returns: absolute (Timeseries): Absolute value. For complex input (a + b*j) gives sqrt(a**a + b**2) """ da = distob.vectorize(np.absolute)(self) return _dts_from_da(da, self.tspan, self.label...
python
def absolute(self): """Calculate the absolute value element-wise. Returns: absolute (Timeseries): Absolute value. For complex input (a + b*j) gives sqrt(a**a + b**2) """ da = distob.vectorize(np.absolute)(self) return _dts_from_da(da, self.tspan, self.label...
[ "def", "absolute", "(", "self", ")", ":", "da", "=", "distob", ".", "vectorize", "(", "np", ".", "absolute", ")", "(", "self", ")", "return", "_dts_from_da", "(", "da", ",", "self", ".", "tspan", ",", "self", ".", "labels", ")" ]
Calculate the absolute value element-wise. Returns: absolute (Timeseries): Absolute value. For complex input (a + b*j) gives sqrt(a**a + b**2)
[ "Calculate", "the", "absolute", "value", "element", "-", "wise", "." ]
ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L627-L635
train
mattja/nsim
nsim/nsim.py
DistTimeseries.angle
def angle(self, deg=False): """Return the angle of a complex Timeseries Args: deg (bool, optional): Return angle in degrees if True, radians if False (default). Returns: angle (Timeseries): The counterclockwise angle from the positive real axis on ...
python
def angle(self, deg=False): """Return the angle of a complex Timeseries Args: deg (bool, optional): Return angle in degrees if True, radians if False (default). Returns: angle (Timeseries): The counterclockwise angle from the positive real axis on ...
[ "def", "angle", "(", "self", ",", "deg", "=", "False", ")", ":", "if", "self", ".", "dtype", ".", "str", "[", "1", "]", "!=", "'c'", ":", "warnings", ".", "warn", "(", "'angle() is intended for complex-valued timeseries'", ",", "RuntimeWarning", ",", "1", ...
Return the angle of a complex Timeseries Args: deg (bool, optional): Return angle in degrees if True, radians if False (default). Returns: angle (Timeseries): The counterclockwise angle from the positive real axis on the complex plane, with dtype...
[ "Return", "the", "angle", "of", "a", "complex", "Timeseries" ]
ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L641-L657
train
mattja/nsim
nsim/nsim.py
NetworkModel.coupling
def coupling(self, source_y, target_y, weight): """How to couple the output of one subsystem to the input of another. This is a fallback default coupling function that should usually be replaced with your own. This example coupling function takes the mean of all variables of the ...
python
def coupling(self, source_y, target_y, weight): """How to couple the output of one subsystem to the input of another. This is a fallback default coupling function that should usually be replaced with your own. This example coupling function takes the mean of all variables of the ...
[ "def", "coupling", "(", "self", ",", "source_y", ",", "target_y", ",", "weight", ")", ":", "return", "np", ".", "ones_like", "(", "target_y", ")", "*", "np", ".", "mean", "(", "source_y", ")", "*", "weight" ]
How to couple the output of one subsystem to the input of another. This is a fallback default coupling function that should usually be replaced with your own. This example coupling function takes the mean of all variables of the source subsystem and uses that value weighted by the conn...
[ "How", "to", "couple", "the", "output", "of", "one", "subsystem", "to", "the", "input", "of", "another", "." ]
ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L1113-L1132
train
mattja/nsim
nsim/nsim.py
NetworkModel.f
def f(self, y, t): """Deterministic term f of the complete network system dy = f(y, t)dt + G(y, t).dot(dW) (or for an ODE network system without noise, dy/dt = f(y, t)) Args: y (array of shape (d,)): where d is the dimension of the overall state space of the compl...
python
def f(self, y, t): """Deterministic term f of the complete network system dy = f(y, t)dt + G(y, t).dot(dW) (or for an ODE network system without noise, dy/dt = f(y, t)) Args: y (array of shape (d,)): where d is the dimension of the overall state space of the compl...
[ "def", "f", "(", "self", ",", "y", ",", "t", ")", ":", "coupling", "=", "self", ".", "coupling_function", "[", "0", "]", "res", "=", "np", ".", "empty_like", "(", "self", ".", "y0", ")", "for", "j", ",", "m", "in", "enumerate", "(", "self", "."...
Deterministic term f of the complete network system dy = f(y, t)dt + G(y, t).dot(dW) (or for an ODE network system without noise, dy/dt = f(y, t)) Args: y (array of shape (d,)): where d is the dimension of the overall state space of the complete network system. ...
[ "Deterministic", "term", "f", "of", "the", "complete", "network", "system", "dy", "=", "f", "(", "y", "t", ")", "dt", "+", "G", "(", "y", "t", ")", ".", "dot", "(", "dW", ")" ]
ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L1134-L1160
train
mattja/nsim
nsim/nsim.py
NetworkModel.G
def G(self, y, t): """Noise coefficient matrix G of the complete network system dy = f(y, t)dt + G(y, t).dot(dW) (for an ODE network system without noise this function is not used) Args: y (array of shape (d,)): where d is the dimension of the overall state space ...
python
def G(self, y, t): """Noise coefficient matrix G of the complete network system dy = f(y, t)dt + G(y, t).dot(dW) (for an ODE network system without noise this function is not used) Args: y (array of shape (d,)): where d is the dimension of the overall state space ...
[ "def", "G", "(", "self", ",", "y", ",", "t", ")", ":", "if", "self", ".", "_independent_noise", ":", "# then G matrix consists of submodel Gs diagonally concatenated:", "res", "=", "np", ".", "zeros", "(", "(", "self", ".", "dimension", ",", "self", ".", "nn...
Noise coefficient matrix G of the complete network system dy = f(y, t)dt + G(y, t).dot(dW) (for an ODE network system without noise this function is not used) Args: y (array of shape (d,)): where d is the dimension of the overall state space of the complete network system...
[ "Noise", "coefficient", "matrix", "G", "of", "the", "complete", "network", "system", "dy", "=", "f", "(", "y", "t", ")", "dt", "+", "G", "(", "y", "t", ")", ".", "dot", "(", "dW", ")" ]
ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L1162-L1193
train
mattja/nsim
nsim/nsim.py
NetworkModel._scalar_to_vector
def _scalar_to_vector(self, m): """Allow submodels with scalar equations. Convert to 1D vector systems. Args: m (Model) """ if not isinstance(m.y0, numbers.Number): return m else: m = copy.deepcopy(m) t0 = 0.0 if isinstanc...
python
def _scalar_to_vector(self, m): """Allow submodels with scalar equations. Convert to 1D vector systems. Args: m (Model) """ if not isinstance(m.y0, numbers.Number): return m else: m = copy.deepcopy(m) t0 = 0.0 if isinstanc...
[ "def", "_scalar_to_vector", "(", "self", ",", "m", ")", ":", "if", "not", "isinstance", "(", "m", ".", "y0", ",", "numbers", ".", "Number", ")", ":", "return", "m", "else", ":", "m", "=", "copy", ".", "deepcopy", "(", "m", ")", "t0", "=", "0.0", ...
Allow submodels with scalar equations. Convert to 1D vector systems. Args: m (Model)
[ "Allow", "submodels", "with", "scalar", "equations", ".", "Convert", "to", "1D", "vector", "systems", ".", "Args", ":", "m", "(", "Model", ")" ]
ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L1228-L1267
train
mattja/nsim
nsim/nsim.py
NetworkModel._reshape_timeseries
def _reshape_timeseries(self, ts): """Introduce a new axis 2 that ranges across nodes of the network""" if np.count_nonzero(np.diff(self._sublengths)) == 0: # then all submodels have the same dimension, so can reshape array # in place without copying data: subdim = se...
python
def _reshape_timeseries(self, ts): """Introduce a new axis 2 that ranges across nodes of the network""" if np.count_nonzero(np.diff(self._sublengths)) == 0: # then all submodels have the same dimension, so can reshape array # in place without copying data: subdim = se...
[ "def", "_reshape_timeseries", "(", "self", ",", "ts", ")", ":", "if", "np", ".", "count_nonzero", "(", "np", ".", "diff", "(", "self", ".", "_sublengths", ")", ")", "==", "0", ":", "# then all submodels have the same dimension, so can reshape array", "# in place w...
Introduce a new axis 2 that ranges across nodes of the network
[ "Introduce", "a", "new", "axis", "2", "that", "ranges", "across", "nodes", "of", "the", "network" ]
ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L1272-L1301
train
mattja/nsim
nsim/nsim.py
NetworkModel._reshape_output
def _reshape_output(self, ts): """Introduce a new axis 2 that ranges across nodes of the network""" subodim = len(self.submodels[0].output_vars) shp = list(ts.shape) shp[1] = subodim shp.insert(2, self._n) ts = ts.reshape(tuple(shp)) ts.labels[2] = self._node_labe...
python
def _reshape_output(self, ts): """Introduce a new axis 2 that ranges across nodes of the network""" subodim = len(self.submodels[0].output_vars) shp = list(ts.shape) shp[1] = subodim shp.insert(2, self._n) ts = ts.reshape(tuple(shp)) ts.labels[2] = self._node_labe...
[ "def", "_reshape_output", "(", "self", ",", "ts", ")", ":", "subodim", "=", "len", "(", "self", ".", "submodels", "[", "0", "]", ".", "output_vars", ")", "shp", "=", "list", "(", "ts", ".", "shape", ")", "shp", "[", "1", "]", "=", "subodim", "shp...
Introduce a new axis 2 that ranges across nodes of the network
[ "Introduce", "a", "new", "axis", "2", "that", "ranges", "across", "nodes", "of", "the", "network" ]
ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L1303-L1311
train
mattja/nsim
nsim/nsim.py
Simulation.timeseries
def timeseries(self): """Simulated time series""" if self._timeseries is None: self.compute() if isinstance(self.system, NetworkModel): return self.system._reshape_timeseries(self._timeseries) else: return self._timeseries
python
def timeseries(self): """Simulated time series""" if self._timeseries is None: self.compute() if isinstance(self.system, NetworkModel): return self.system._reshape_timeseries(self._timeseries) else: return self._timeseries
[ "def", "timeseries", "(", "self", ")", ":", "if", "self", ".", "_timeseries", "is", "None", ":", "self", ".", "compute", "(", ")", "if", "isinstance", "(", "self", ".", "system", ",", "NetworkModel", ")", ":", "return", "self", ".", "system", ".", "_...
Simulated time series
[ "Simulated", "time", "series" ]
ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L1362-L1369
train
mattja/nsim
nsim/nsim.py
Simulation.output
def output(self): """Simulated model output""" if self._timeseries is None: self.compute() output = self._timeseries[:, self.system.output_vars] if isinstance(self.system, NetworkModel): return self.system._reshape_output(output) else: return o...
python
def output(self): """Simulated model output""" if self._timeseries is None: self.compute() output = self._timeseries[:, self.system.output_vars] if isinstance(self.system, NetworkModel): return self.system._reshape_output(output) else: return o...
[ "def", "output", "(", "self", ")", ":", "if", "self", ".", "_timeseries", "is", "None", ":", "self", ".", "compute", "(", ")", "output", "=", "self", ".", "_timeseries", "[", ":", ",", "self", ".", "system", ".", "output_vars", "]", "if", "isinstance...
Simulated model output
[ "Simulated", "model", "output" ]
ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L1372-L1380
train
mattja/nsim
nsim/nsim.py
MultipleSim.output
def output(self): """Rank 3 array representing output time series. Axis 0 is time, axis 1 ranges across output variables of a single simulation, axis 2 ranges across different simulation instances.""" subts = [s.output for s in self.sims] sub_ndim = subts[0].ndim if sub...
python
def output(self): """Rank 3 array representing output time series. Axis 0 is time, axis 1 ranges across output variables of a single simulation, axis 2 ranges across different simulation instances.""" subts = [s.output for s in self.sims] sub_ndim = subts[0].ndim if sub...
[ "def", "output", "(", "self", ")", ":", "subts", "=", "[", "s", ".", "output", "for", "s", "in", "self", ".", "sims", "]", "sub_ndim", "=", "subts", "[", "0", "]", ".", "ndim", "if", "sub_ndim", "is", "1", ":", "subts", "=", "[", "distob", ".",...
Rank 3 array representing output time series. Axis 0 is time, axis 1 ranges across output variables of a single simulation, axis 2 ranges across different simulation instances.
[ "Rank", "3", "array", "representing", "output", "time", "series", ".", "Axis", "0", "is", "time", "axis", "1", "ranges", "across", "output", "variables", "of", "a", "single", "simulation", "axis", "2", "ranges", "across", "different", "simulation", "instances"...
ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L1450-L1463
train
mattja/nsim
nsim/nsim.py
DistSim._tosub
def _tosub(self, ix): """Given an integer index ix into the list of sims, returns the pair (s, m) where s is the relevant subsim and m is the subindex into s. So self[ix] == self._subsims[s][m] """ N = self._n if ix >= N or ix < -N: raise IndexError( ...
python
def _tosub(self, ix): """Given an integer index ix into the list of sims, returns the pair (s, m) where s is the relevant subsim and m is the subindex into s. So self[ix] == self._subsims[s][m] """ N = self._n if ix >= N or ix < -N: raise IndexError( ...
[ "def", "_tosub", "(", "self", ",", "ix", ")", ":", "N", "=", "self", ".", "_n", "if", "ix", ">=", "N", "or", "ix", "<", "-", "N", ":", "raise", "IndexError", "(", "'index %d out of bounds for list of %d sims'", "%", "(", "ix", ",", "N", ")", ")", "...
Given an integer index ix into the list of sims, returns the pair (s, m) where s is the relevant subsim and m is the subindex into s. So self[ix] == self._subsims[s][m]
[ "Given", "an", "integer", "index", "ix", "into", "the", "list", "of", "sims", "returns", "the", "pair", "(", "s", "m", ")", "where", "s", "is", "the", "relevant", "subsim", "and", "m", "is", "the", "subindex", "into", "s", ".", "So", "self", "[", "...
ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L1577-L1592
train
mattja/nsim
nsim/nsim.py
DistSim._tosubs
def _tosubs(self, ixlist): """Maps a list of integer indices to sub-indices. ixlist can contain repeated indices and does not need to be sorted. Returns pair (ss, ms) where ss is a list of subsim numbers and ms is a list of lists of subindices m (one list for each subsim in ss). ...
python
def _tosubs(self, ixlist): """Maps a list of integer indices to sub-indices. ixlist can contain repeated indices and does not need to be sorted. Returns pair (ss, ms) where ss is a list of subsim numbers and ms is a list of lists of subindices m (one list for each subsim in ss). ...
[ "def", "_tosubs", "(", "self", ",", "ixlist", ")", ":", "n", "=", "len", "(", "ixlist", ")", "N", "=", "self", ".", "_n", "ss", "=", "[", "]", "ms", "=", "[", "]", "if", "n", "==", "0", ":", "return", "ss", ",", "ms", "j", "=", "0", "# th...
Maps a list of integer indices to sub-indices. ixlist can contain repeated indices and does not need to be sorted. Returns pair (ss, ms) where ss is a list of subsim numbers and ms is a list of lists of subindices m (one list for each subsim in ss).
[ "Maps", "a", "list", "of", "integer", "indices", "to", "sub", "-", "indices", ".", "ixlist", "can", "contain", "repeated", "indices", "and", "does", "not", "need", "to", "be", "sorted", ".", "Returns", "pair", "(", "ss", "ms", ")", "where", "ss", "is",...
ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L1594-L1636
train
mattja/nsim
nsim/nsim.py
DistSim.output
def output(self): """Rank 3 array representing output time series. Axis 0 is time, axis 1 ranges across output variables of a single simulation, axis 2 ranges across different simulation instances.""" subts = [rms.output for rms in self._subsims] distaxis = subts[0].ndim - 1 ...
python
def output(self): """Rank 3 array representing output time series. Axis 0 is time, axis 1 ranges across output variables of a single simulation, axis 2 ranges across different simulation instances.""" subts = [rms.output for rms in self._subsims] distaxis = subts[0].ndim - 1 ...
[ "def", "output", "(", "self", ")", ":", "subts", "=", "[", "rms", ".", "output", "for", "rms", "in", "self", ".", "_subsims", "]", "distaxis", "=", "subts", "[", "0", "]", ".", "ndim", "-", "1", "return", "DistTimeseries", "(", "subts", ",", "dista...
Rank 3 array representing output time series. Axis 0 is time, axis 1 ranges across output variables of a single simulation, axis 2 ranges across different simulation instances.
[ "Rank", "3", "array", "representing", "output", "time", "series", ".", "Axis", "0", "is", "time", "axis", "1", "ranges", "across", "output", "variables", "of", "a", "single", "simulation", "axis", "2", "ranges", "across", "different", "simulation", "instances"...
ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L1676-L1682
train
mattja/nsim
nsim/analyses1/misc.py
crossing_times
def crossing_times(ts, c=0.0, d=0.0): """For a single variable timeseries, find the times at which the value crosses ``c`` from above or below. Can optionally set a non-zero ``d`` to impose the condition that the value must wander at least ``d`` units away from ``c`` between crossings. If the time...
python
def crossing_times(ts, c=0.0, d=0.0): """For a single variable timeseries, find the times at which the value crosses ``c`` from above or below. Can optionally set a non-zero ``d`` to impose the condition that the value must wander at least ``d`` units away from ``c`` between crossings. If the time...
[ "def", "crossing_times", "(", "ts", ",", "c", "=", "0.0", ",", "d", "=", "0.0", ")", ":", "#TODO support multivariate time series", "ts", "=", "ts", ".", "squeeze", "(", ")", "if", "ts", ".", "ndim", "is", "not", "1", ":", "raise", "ValueError", "(", ...
For a single variable timeseries, find the times at which the value crosses ``c`` from above or below. Can optionally set a non-zero ``d`` to impose the condition that the value must wander at least ``d`` units away from ``c`` between crossings. If the timeseries begins (or ends) exactly at ``c``, the...
[ "For", "a", "single", "variable", "timeseries", "find", "the", "times", "at", "which", "the", "value", "crosses", "c", "from", "above", "or", "below", ".", "Can", "optionally", "set", "a", "non", "-", "zero", "d", "to", "impose", "the", "condition", "tha...
ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/analyses1/misc.py#L18-L71
train
mattja/nsim
nsim/analyses1/misc.py
first_return_times
def first_return_times(ts, c=None, d=0.0): """For a single variable time series, first wait until the time series attains the value c for the first time. Then record the time intervals between successive returns to c. If c is not given, the default is the mean of the time series. Args: t...
python
def first_return_times(ts, c=None, d=0.0): """For a single variable time series, first wait until the time series attains the value c for the first time. Then record the time intervals between successive returns to c. If c is not given, the default is the mean of the time series. Args: t...
[ "def", "first_return_times", "(", "ts", ",", "c", "=", "None", ",", "d", "=", "0.0", ")", ":", "ts", "=", "np", ".", "squeeze", "(", "ts", ")", "if", "c", "is", "None", ":", "c", "=", "ts", ".", "mean", "(", ")", "if", "ts", ".", "ndim", "<...
For a single variable time series, first wait until the time series attains the value c for the first time. Then record the time intervals between successive returns to c. If c is not given, the default is the mean of the time series. Args: ts: Timeseries (single variable) c (float): ...
[ "For", "a", "single", "variable", "time", "series", "first", "wait", "until", "the", "time", "series", "attains", "the", "value", "c", "for", "the", "first", "time", ".", "Then", "record", "the", "time", "intervals", "between", "successive", "returns", "to",...
ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/analyses1/misc.py#L74-L98
train
mattja/nsim
nsim/analyses1/misc.py
autocorrelation
def autocorrelation(ts, normalized=False, unbiased=False): """ Returns the discrete, linear convolution of a time series with itself, optionally using unbiased normalization. N.B. Autocorrelation estimates are necessarily inaccurate for longer lags, as there are less pairs of points to convolve s...
python
def autocorrelation(ts, normalized=False, unbiased=False): """ Returns the discrete, linear convolution of a time series with itself, optionally using unbiased normalization. N.B. Autocorrelation estimates are necessarily inaccurate for longer lags, as there are less pairs of points to convolve s...
[ "def", "autocorrelation", "(", "ts", ",", "normalized", "=", "False", ",", "unbiased", "=", "False", ")", ":", "ts", "=", "np", ".", "squeeze", "(", "ts", ")", "if", "ts", ".", "ndim", "<=", "1", ":", "if", "normalized", ":", "ts", "=", "(", "ts"...
Returns the discrete, linear convolution of a time series with itself, optionally using unbiased normalization. N.B. Autocorrelation estimates are necessarily inaccurate for longer lags, as there are less pairs of points to convolve separated by that lag. Therefore best to throw out the results excep...
[ "Returns", "the", "discrete", "linear", "convolution", "of", "a", "time", "series", "with", "itself", "optionally", "using", "unbiased", "normalization", "." ]
ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/analyses1/misc.py#L101-L145
train
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700.fan_speed
def fan_speed(self, value): """Verifies the value is between 1 and 9 inclusively.""" if value not in range(1, 10): raise exceptions.RoasterValueError self._fan_speed.value = value
python
def fan_speed(self, value): """Verifies the value is between 1 and 9 inclusively.""" if value not in range(1, 10): raise exceptions.RoasterValueError self._fan_speed.value = value
[ "def", "fan_speed", "(", "self", ",", "value", ")", ":", "if", "value", "not", "in", "range", "(", "1", ",", "10", ")", ":", "raise", "exceptions", ".", "RoasterValueError", "self", ".", "_fan_speed", ".", "value", "=", "value" ]
Verifies the value is between 1 and 9 inclusively.
[ "Verifies", "the", "value", "is", "between", "1", "and", "9", "inclusively", "." ]
49cf4961444c0f56d051d5ac5088ace480b54f02
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L238-L243
train
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700.heat_setting
def heat_setting(self, value): """Verifies that the heat setting is between 0 and 3.""" if value not in range(0, 4): raise exceptions.RoasterValueError self._heat_setting.value = value
python
def heat_setting(self, value): """Verifies that the heat setting is between 0 and 3.""" if value not in range(0, 4): raise exceptions.RoasterValueError self._heat_setting.value = value
[ "def", "heat_setting", "(", "self", ",", "value", ")", ":", "if", "value", "not", "in", "range", "(", "0", ",", "4", ")", ":", "raise", "exceptions", ".", "RoasterValueError", "self", ".", "_heat_setting", ".", "value", "=", "value" ]
Verifies that the heat setting is between 0 and 3.
[ "Verifies", "that", "the", "heat", "setting", "is", "between", "0", "and", "3", "." ]
49cf4961444c0f56d051d5ac5088ace480b54f02
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L259-L264
train
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700.heater_level
def heater_level(self, value): """Verifies that the heater_level is between 0 and heater_segments. Can only be called when freshroastsr700 object is initialized with ext_sw_heater_drive=True. Will throw RoasterValueError otherwise.""" if self._ext_sw_heater_drive: ...
python
def heater_level(self, value): """Verifies that the heater_level is between 0 and heater_segments. Can only be called when freshroastsr700 object is initialized with ext_sw_heater_drive=True. Will throw RoasterValueError otherwise.""" if self._ext_sw_heater_drive: ...
[ "def", "heater_level", "(", "self", ",", "value", ")", ":", "if", "self", ".", "_ext_sw_heater_drive", ":", "if", "value", "not", "in", "range", "(", "0", ",", "self", ".", "_heater_bangbang_segments", "+", "1", ")", ":", "raise", "exceptions", ".", "Roa...
Verifies that the heater_level is between 0 and heater_segments. Can only be called when freshroastsr700 object is initialized with ext_sw_heater_drive=True. Will throw RoasterValueError otherwise.
[ "Verifies", "that", "the", "heater_level", "is", "between", "0", "and", "heater_segments", ".", "Can", "only", "be", "called", "when", "freshroastsr700", "object", "is", "initialized", "with", "ext_sw_heater_drive", "=", "True", ".", "Will", "throw", "RoasterValue...
49cf4961444c0f56d051d5ac5088ace480b54f02
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L352-L362
train
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700.set_state_transition_func
def set_state_transition_func(self, func): """THIS FUNCTION MUST BE CALLED BEFORE CALLING freshroastsr700.auto_connect(). Set, or re-set, the state transition function callback. The supplied function will be called from a separate thread within freshroastsr700, triggered by a se...
python
def set_state_transition_func(self, func): """THIS FUNCTION MUST BE CALLED BEFORE CALLING freshroastsr700.auto_connect(). Set, or re-set, the state transition function callback. The supplied function will be called from a separate thread within freshroastsr700, triggered by a se...
[ "def", "set_state_transition_func", "(", "self", ",", "func", ")", ":", "if", "self", ".", "_connected", ".", "value", ":", "logging", ".", "error", "(", "\"freshroastsr700.set_state_transition_func must be \"", "\"called before freshroastsr700.auto_connect().\"", "\" Not r...
THIS FUNCTION MUST BE CALLED BEFORE CALLING freshroastsr700.auto_connect(). Set, or re-set, the state transition function callback. The supplied function will be called from a separate thread within freshroastsr700, triggered by a separate, internal child process. This function ...
[ "THIS", "FUNCTION", "MUST", "BE", "CALLED", "BEFORE", "CALLING", "freshroastsr700", ".", "auto_connect", "()", "." ]
49cf4961444c0f56d051d5ac5088ace480b54f02
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L391-L417
train
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700.update_data_run
def update_data_run(self, event_to_wait_on): """This is the thread that listens to an event from the comm process to execute the update_data_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # quit 'automati...
python
def update_data_run(self, event_to_wait_on): """This is the thread that listens to an event from the comm process to execute the update_data_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # quit 'automati...
[ "def", "update_data_run", "(", "self", ",", "event_to_wait_on", ")", ":", "# with the daemon=Turue setting, this thread should", "# quit 'automatically'", "while", "event_to_wait_on", ".", "wait", "(", ")", ":", "event_to_wait_on", ".", "clear", "(", ")", "if", "self", ...
This is the thread that listens to an event from the comm process to execute the update_data_func callback in the context of the main process.
[ "This", "is", "the", "thread", "that", "listens", "to", "an", "event", "from", "the", "comm", "process", "to", "execute", "the", "update_data_func", "callback", "in", "the", "context", "of", "the", "main", "process", "." ]
49cf4961444c0f56d051d5ac5088ace480b54f02
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L419-L430
train
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700.state_transition_run
def state_transition_run(self, event_to_wait_on): """This is the thread that listens to an event from the timer process to execute the state_transition_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # qui...
python
def state_transition_run(self, event_to_wait_on): """This is the thread that listens to an event from the timer process to execute the state_transition_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # qui...
[ "def", "state_transition_run", "(", "self", ",", "event_to_wait_on", ")", ":", "# with the daemon=Turue setting, this thread should", "# quit 'automatically'", "while", "event_to_wait_on", ".", "wait", "(", ")", ":", "event_to_wait_on", ".", "clear", "(", ")", "if", "se...
This is the thread that listens to an event from the timer process to execute the state_transition_func callback in the context of the main process.
[ "This", "is", "the", "thread", "that", "listens", "to", "an", "event", "from", "the", "timer", "process", "to", "execute", "the", "state_transition_func", "callback", "in", "the", "context", "of", "the", "main", "process", "." ]
49cf4961444c0f56d051d5ac5088ace480b54f02
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L432-L443
train
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700._connect
def _connect(self): """Do not call this directly - call auto_connect() or connect(), which will call _connect() for you. Connects to the roaster and creates communication thread. Raises a RoasterLokkupError exception if the hardware is not found. """ # the following call...
python
def _connect(self): """Do not call this directly - call auto_connect() or connect(), which will call _connect() for you. Connects to the roaster and creates communication thread. Raises a RoasterLokkupError exception if the hardware is not found. """ # the following call...
[ "def", "_connect", "(", "self", ")", ":", "# the following call raises a RoasterLookupException when the device", "# is not found. It is", "port", "=", "utils", ".", "find_device", "(", "'1A86:5523'", ")", "# on some systems, after the device port is added to the device list,", "# ...
Do not call this directly - call auto_connect() or connect(), which will call _connect() for you. Connects to the roaster and creates communication thread. Raises a RoasterLokkupError exception if the hardware is not found.
[ "Do", "not", "call", "this", "directly", "-", "call", "auto_connect", "()", "or", "connect", "()", "which", "will", "call", "_connect", "()", "for", "you", "." ]
49cf4961444c0f56d051d5ac5088ace480b54f02
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L445-L483
train
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700._initialize
def _initialize(self): """Sends the initialization packet to the roaster.""" self._header.value = b'\xAA\x55' self._current_state.value = b'\x00\x00' s = self._generate_packet() self._ser.write(s) self._header.value = b'\xAA\xAA' self._current_state.value = b'\x02...
python
def _initialize(self): """Sends the initialization packet to the roaster.""" self._header.value = b'\xAA\x55' self._current_state.value = b'\x00\x00' s = self._generate_packet() self._ser.write(s) self._header.value = b'\xAA\xAA' self._current_state.value = b'\x02...
[ "def", "_initialize", "(", "self", ")", ":", "self", ".", "_header", ".", "value", "=", "b'\\xAA\\x55'", "self", ".", "_current_state", ".", "value", "=", "b'\\x00\\x00'", "s", "=", "self", ".", "_generate_packet", "(", ")", "self", ".", "_ser", ".", "wr...
Sends the initialization packet to the roaster.
[ "Sends", "the", "initialization", "packet", "to", "the", "roaster", "." ]
49cf4961444c0f56d051d5ac5088ace480b54f02
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L485-L494
train
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700.connect
def connect(self): """Attempt to connect to hardware immediately. Will not retry. Check freshroastsr700.connected or freshroastsr700.connect_state to verify result. Raises: freshroastsr700.exeptions.RoasterLookupError No hardware connected to the computer. ...
python
def connect(self): """Attempt to connect to hardware immediately. Will not retry. Check freshroastsr700.connected or freshroastsr700.connect_state to verify result. Raises: freshroastsr700.exeptions.RoasterLookupError No hardware connected to the computer. ...
[ "def", "connect", "(", "self", ")", ":", "self", ".", "_start_connect", "(", "self", ".", "CA_SINGLE_SHOT", ")", "while", "(", "self", ".", "_connect_state", ".", "value", "==", "self", ".", "CS_ATTEMPTING_CONNECT", "or", "self", ".", "_connect_state", ".", ...
Attempt to connect to hardware immediately. Will not retry. Check freshroastsr700.connected or freshroastsr700.connect_state to verify result. Raises: freshroastsr700.exeptions.RoasterLookupError No hardware connected to the computer.
[ "Attempt", "to", "connect", "to", "hardware", "immediately", ".", "Will", "not", "retry", ".", "Check", "freshroastsr700", ".", "connected", "or", "freshroastsr700", ".", "connect_state", "to", "verify", "result", ".", "Raises", ":", "freshroastsr700", ".", "exe...
49cf4961444c0f56d051d5ac5088ace480b54f02
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L539-L552
train
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700._start_connect
def _start_connect(self, connect_type): """Starts the connection process, as called (internally) from the user context, either from auto_connect() or connect(). Never call this from the _comm() process context. """ if self._connect_state.value != self.CS_NOT_CONNECTED: ...
python
def _start_connect(self, connect_type): """Starts the connection process, as called (internally) from the user context, either from auto_connect() or connect(). Never call this from the _comm() process context. """ if self._connect_state.value != self.CS_NOT_CONNECTED: ...
[ "def", "_start_connect", "(", "self", ",", "connect_type", ")", ":", "if", "self", ".", "_connect_state", ".", "value", "!=", "self", ".", "CS_NOT_CONNECTED", ":", "# already done or in process, assume success", "return", "self", ".", "_connected", ".", "value", "...
Starts the connection process, as called (internally) from the user context, either from auto_connect() or connect(). Never call this from the _comm() process context.
[ "Starts", "the", "connection", "process", "as", "called", "(", "internally", ")", "from", "the", "user", "context", "either", "from", "auto_connect", "()", "or", "connect", "()", ".", "Never", "call", "this", "from", "the", "_comm", "()", "process", "context...
49cf4961444c0f56d051d5ac5088ace480b54f02
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L559-L588
train
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700._auto_connect
def _auto_connect(self): """Attempts to connect to the roaster every quarter of a second.""" while not self._teardown.value: try: self._connect() return True except exceptions.RoasterLookupError: time.sleep(.25) return False
python
def _auto_connect(self): """Attempts to connect to the roaster every quarter of a second.""" while not self._teardown.value: try: self._connect() return True except exceptions.RoasterLookupError: time.sleep(.25) return False
[ "def", "_auto_connect", "(", "self", ")", ":", "while", "not", "self", ".", "_teardown", ".", "value", ":", "try", ":", "self", ".", "_connect", "(", ")", "return", "True", "except", "exceptions", ".", "RoasterLookupError", ":", "time", ".", "sleep", "("...
Attempts to connect to the roaster every quarter of a second.
[ "Attempts", "to", "connect", "to", "the", "roaster", "every", "quarter", "of", "a", "second", "." ]
49cf4961444c0f56d051d5ac5088ace480b54f02
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L590-L598
train
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700._comm
def _comm(self, thermostat=False, kp=0.06, ki=0.0075, kd=0.01, heater_segments=8, ext_sw_heater_drive=False, update_data_event=None): """Do not call this directly - call auto_connect(), which will spawn comm() for you. This is the main communications lo...
python
def _comm(self, thermostat=False, kp=0.06, ki=0.0075, kd=0.01, heater_segments=8, ext_sw_heater_drive=False, update_data_event=None): """Do not call this directly - call auto_connect(), which will spawn comm() for you. This is the main communications lo...
[ "def", "_comm", "(", "self", ",", "thermostat", "=", "False", ",", "kp", "=", "0.06", ",", "ki", "=", "0.0075", ",", "kd", "=", "0.01", ",", "heater_segments", "=", "8", ",", "ext_sw_heater_drive", "=", "False", ",", "update_data_event", "=", "None", "...
Do not call this directly - call auto_connect(), which will spawn comm() for you. This is the main communications loop to the roaster. whenever a valid packet is received from the device, if an update_data_event is available, it will be signalled. Args: thermostat (...
[ "Do", "not", "call", "this", "directly", "-", "call", "auto_connect", "()", "which", "will", "spawn", "comm", "()", "for", "you", "." ]
49cf4961444c0f56d051d5ac5088ace480b54f02
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L616-L814
train
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700._timer
def _timer(self, state_transition_event=None): """Timer loop used to keep track of the time while roasting or cooling. If the time remaining reaches zero, the roaster will call the supplied state transistion function or the roaster will be set to the idle state.""" while not self...
python
def _timer(self, state_transition_event=None): """Timer loop used to keep track of the time while roasting or cooling. If the time remaining reaches zero, the roaster will call the supplied state transistion function or the roaster will be set to the idle state.""" while not self...
[ "def", "_timer", "(", "self", ",", "state_transition_event", "=", "None", ")", ":", "while", "not", "self", ".", "_teardown", ".", "value", ":", "state", "=", "self", ".", "get_roaster_state", "(", ")", "if", "(", "state", "==", "'roasting'", "or", "stat...
Timer loop used to keep track of the time while roasting or cooling. If the time remaining reaches zero, the roaster will call the supplied state transistion function or the roaster will be set to the idle state.
[ "Timer", "loop", "used", "to", "keep", "track", "of", "the", "time", "while", "roasting", "or", "cooling", ".", "If", "the", "time", "remaining", "reaches", "zero", "the", "roaster", "will", "call", "the", "supplied", "state", "transistion", "function", "or"...
49cf4961444c0f56d051d5ac5088ace480b54f02
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L889-L907
train
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700.get_roaster_state
def get_roaster_state(self): """Returns a string based upon the current state of the roaster. Will raise an exception if the state is unknown. Returns: 'idle' if idle, 'sleeping' if sleeping, 'cooling' if cooling, 'roasting' if roasting, ...
python
def get_roaster_state(self): """Returns a string based upon the current state of the roaster. Will raise an exception if the state is unknown. Returns: 'idle' if idle, 'sleeping' if sleeping, 'cooling' if cooling, 'roasting' if roasting, ...
[ "def", "get_roaster_state", "(", "self", ")", ":", "value", "=", "self", ".", "_current_state", ".", "value", "if", "(", "value", "==", "b'\\x02\\x01'", ")", ":", "return", "'idle'", "elif", "(", "value", "==", "b'\\x04\\x04'", ")", ":", "return", "'coolin...
Returns a string based upon the current state of the roaster. Will raise an exception if the state is unknown. Returns: 'idle' if idle, 'sleeping' if sleeping, 'cooling' if cooling, 'roasting' if roasting, 'connecting' if in hardware connectio...
[ "Returns", "a", "string", "based", "upon", "the", "current", "state", "of", "the", "roaster", ".", "Will", "raise", "an", "exception", "if", "the", "state", "is", "unknown", "." ]
49cf4961444c0f56d051d5ac5088ace480b54f02
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L909-L934
train
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700._generate_packet
def _generate_packet(self): """Generates a packet based upon the current class variables. Note that current temperature is not sent, as the original application sent zeros to the roaster for the current temperature.""" roaster_time = utils.seconds_to_float(self._time_remaining.value) ...
python
def _generate_packet(self): """Generates a packet based upon the current class variables. Note that current temperature is not sent, as the original application sent zeros to the roaster for the current temperature.""" roaster_time = utils.seconds_to_float(self._time_remaining.value) ...
[ "def", "_generate_packet", "(", "self", ")", ":", "roaster_time", "=", "utils", ".", "seconds_to_float", "(", "self", ".", "_time_remaining", ".", "value", ")", "packet", "=", "(", "self", ".", "_header", ".", "value", "+", "self", ".", "_temp_unit", ".", ...
Generates a packet based upon the current class variables. Note that current temperature is not sent, as the original application sent zeros to the roaster for the current temperature.
[ "Generates", "a", "packet", "based", "upon", "the", "current", "class", "variables", ".", "Note", "that", "current", "temperature", "is", "not", "sent", "as", "the", "original", "application", "sent", "zeros", "to", "the", "roaster", "for", "the", "current", ...
49cf4961444c0f56d051d5ac5088ace480b54f02
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L936-L952
train
Roastero/freshroastsr700
freshroastsr700/__init__.py
heat_controller.heat_level
def heat_level(self, value): """Set the desired output level. Must be between 0 and number_of_segments inclusive.""" if value < 0: self._heat_level = 0 elif round(value) > self._num_segments: self._heat_level = self._num_segments else: self._he...
python
def heat_level(self, value): """Set the desired output level. Must be between 0 and number_of_segments inclusive.""" if value < 0: self._heat_level = 0 elif round(value) > self._num_segments: self._heat_level = self._num_segments else: self._he...
[ "def", "heat_level", "(", "self", ",", "value", ")", ":", "if", "value", "<", "0", ":", "self", ".", "_heat_level", "=", "0", "elif", "round", "(", "value", ")", ">", "self", ".", "_num_segments", ":", "self", ".", "_heat_level", "=", "self", ".", ...
Set the desired output level. Must be between 0 and number_of_segments inclusive.
[ "Set", "the", "desired", "output", "level", ".", "Must", "be", "between", "0", "and", "number_of_segments", "inclusive", "." ]
49cf4961444c0f56d051d5ac5088ace480b54f02
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L1061-L1069
train
Roastero/freshroastsr700
freshroastsr700/__init__.py
heat_controller.generate_bangbang_output
def generate_bangbang_output(self): """Generates the latest on or off pulse in the string of on (True) or off (False) pulses according to the desired heat_level setting. Successive calls to this function will return the next value in the on/off array series. Call th...
python
def generate_bangbang_output(self): """Generates the latest on or off pulse in the string of on (True) or off (False) pulses according to the desired heat_level setting. Successive calls to this function will return the next value in the on/off array series. Call th...
[ "def", "generate_bangbang_output", "(", "self", ")", ":", "if", "self", ".", "_current_index", ">=", "self", ".", "_num_segments", ":", "# we're due to switch over to the next", "# commanded heat_level", "self", ".", "_heat_level_now", "=", "self", ".", "_heat_level", ...
Generates the latest on or off pulse in the string of on (True) or off (False) pulses according to the desired heat_level setting. Successive calls to this function will return the next value in the on/off array series. Call this at control loop rate to obtain th...
[ "Generates", "the", "latest", "on", "or", "off", "pulse", "in", "the", "string", "of", "on", "(", "True", ")", "or", "off", "(", "False", ")", "pulses", "according", "to", "the", "desired", "heat_level", "setting", ".", "Successive", "calls", "to", "this...
49cf4961444c0f56d051d5ac5088ace480b54f02
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L1071-L1092
train
Roastero/freshroastsr700
examples/pid_tune_aid.py
Roaster.update_data
def update_data(self): """This is a method that will be called every time a packet is opened from the roaster.""" time_elapsed = datetime.datetime.now() - self.start_time crntTemp = self.roaster.current_temp targetTemp = self.roaster.target_temp heaterLevel = self.roaster...
python
def update_data(self): """This is a method that will be called every time a packet is opened from the roaster.""" time_elapsed = datetime.datetime.now() - self.start_time crntTemp = self.roaster.current_temp targetTemp = self.roaster.target_temp heaterLevel = self.roaster...
[ "def", "update_data", "(", "self", ")", ":", "time_elapsed", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "-", "self", ".", "start_time", "crntTemp", "=", "self", ".", "roaster", ".", "current_temp", "targetTemp", "=", "self", ".", "roaster", ...
This is a method that will be called every time a packet is opened from the roaster.
[ "This", "is", "a", "method", "that", "will", "be", "called", "every", "time", "a", "packet", "is", "opened", "from", "the", "roaster", "." ]
49cf4961444c0f56d051d5ac5088ace480b54f02
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/examples/pid_tune_aid.py#L122-L134
train
Roastero/freshroastsr700
examples/pid_tune_aid.py
Roaster.next_state
def next_state(self): """This is a method that will be called when the time remaining ends. The current state can be: roasting, cooling, idle, sleeping, connecting, or unkown.""" self.active_recipe_item += 1 if self.active_recipe_item >= len(self.recipe): # we're done...
python
def next_state(self): """This is a method that will be called when the time remaining ends. The current state can be: roasting, cooling, idle, sleeping, connecting, or unkown.""" self.active_recipe_item += 1 if self.active_recipe_item >= len(self.recipe): # we're done...
[ "def", "next_state", "(", "self", ")", ":", "self", ".", "active_recipe_item", "+=", "1", "if", "self", ".", "active_recipe_item", ">=", "len", "(", "self", ".", "recipe", ")", ":", "# we're done!", "return", "# show state step on screen", "print", "(", "\"---...
This is a method that will be called when the time remaining ends. The current state can be: roasting, cooling, idle, sleeping, connecting, or unkown.
[ "This", "is", "a", "method", "that", "will", "be", "called", "when", "the", "time", "remaining", "ends", ".", "The", "current", "state", "can", "be", ":", "roasting", "cooling", "idle", "sleeping", "connecting", "or", "unkown", "." ]
49cf4961444c0f56d051d5ac5088ace480b54f02
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/examples/pid_tune_aid.py#L136-L169
train
dmippolitov/pydnsbl
pydnsbl/checker.py
DNSBLResult.process_results
def process_results(self): """ Process results by providers """ for result in self._results: provider = result.provider self.providers.append(provider) if result.error: self.failed_providers.append(provider) continue if not ...
python
def process_results(self): """ Process results by providers """ for result in self._results: provider = result.provider self.providers.append(provider) if result.error: self.failed_providers.append(provider) continue if not ...
[ "def", "process_results", "(", "self", ")", ":", "for", "result", "in", "self", ".", "_results", ":", "provider", "=", "result", ".", "provider", "self", ".", "providers", ".", "append", "(", "provider", ")", "if", "result", ".", "error", ":", "self", ...
Process results by providers
[ "Process", "results", "by", "providers" ]
76c460f1118213d66498ddafde2053d8de4ccbdb
https://github.com/dmippolitov/pydnsbl/blob/76c460f1118213d66498ddafde2053d8de4ccbdb/pydnsbl/checker.py#L39-L54
train
dmippolitov/pydnsbl
pydnsbl/checker.py
DNSBLChecker.dnsbl_request
async def dnsbl_request(self, addr, provider): """ Make lookup to dnsbl provider Parameters: * addr (string) - ip address to check * provider (string) - dnsbl provider Returns: * DNSBLResponse object Raises: * ValueError "...
python
async def dnsbl_request(self, addr, provider): """ Make lookup to dnsbl provider Parameters: * addr (string) - ip address to check * provider (string) - dnsbl provider Returns: * DNSBLResponse object Raises: * ValueError "...
[ "async", "def", "dnsbl_request", "(", "self", ",", "addr", ",", "provider", ")", ":", "response", "=", "None", "error", "=", "None", "try", ":", "socket", ".", "inet_aton", "(", "addr", ")", "except", "socket", ".", "error", ":", "raise", "ValueError", ...
Make lookup to dnsbl provider Parameters: * addr (string) - ip address to check * provider (string) - dnsbl provider Returns: * DNSBLResponse object Raises: * ValueError
[ "Make", "lookup", "to", "dnsbl", "provider", "Parameters", ":", "*", "addr", "(", "string", ")", "-", "ip", "address", "to", "check", "*", "provider", "(", "string", ")", "-", "dnsbl", "provider" ]
76c460f1118213d66498ddafde2053d8de4ccbdb
https://github.com/dmippolitov/pydnsbl/blob/76c460f1118213d66498ddafde2053d8de4ccbdb/pydnsbl/checker.py#L92-L120
train
dmippolitov/pydnsbl
pydnsbl/checker.py
DNSBLChecker._check_ip
async def _check_ip(self, addr): """ Async check ip with dnsbl providers. Parameters: * addr - ip address to check Returns: * DNSBLResult object """ tasks = [] for provider in self.providers: tasks.append(self.dnsbl_request(ad...
python
async def _check_ip(self, addr): """ Async check ip with dnsbl providers. Parameters: * addr - ip address to check Returns: * DNSBLResult object """ tasks = [] for provider in self.providers: tasks.append(self.dnsbl_request(ad...
[ "async", "def", "_check_ip", "(", "self", ",", "addr", ")", ":", "tasks", "=", "[", "]", "for", "provider", "in", "self", ".", "providers", ":", "tasks", ".", "append", "(", "self", ".", "dnsbl_request", "(", "addr", ",", "provider", ")", ")", "resul...
Async check ip with dnsbl providers. Parameters: * addr - ip address to check Returns: * DNSBLResult object
[ "Async", "check", "ip", "with", "dnsbl", "providers", ".", "Parameters", ":", "*", "addr", "-", "ip", "address", "to", "check" ]
76c460f1118213d66498ddafde2053d8de4ccbdb
https://github.com/dmippolitov/pydnsbl/blob/76c460f1118213d66498ddafde2053d8de4ccbdb/pydnsbl/checker.py#L122-L136
train
dmippolitov/pydnsbl
pydnsbl/checker.py
DNSBLChecker.check_ips
def check_ips(self, addrs): """ sync check multiple ips """ tasks = [] for addr in addrs: tasks.append(self._check_ip(addr)) return self._loop.run_until_complete(asyncio.gather(*tasks))
python
def check_ips(self, addrs): """ sync check multiple ips """ tasks = [] for addr in addrs: tasks.append(self._check_ip(addr)) return self._loop.run_until_complete(asyncio.gather(*tasks))
[ "def", "check_ips", "(", "self", ",", "addrs", ")", ":", "tasks", "=", "[", "]", "for", "addr", "in", "addrs", ":", "tasks", ".", "append", "(", "self", ".", "_check_ip", "(", "addr", ")", ")", "return", "self", ".", "_loop", ".", "run_until_complete...
sync check multiple ips
[ "sync", "check", "multiple", "ips" ]
76c460f1118213d66498ddafde2053d8de4ccbdb
https://github.com/dmippolitov/pydnsbl/blob/76c460f1118213d66498ddafde2053d8de4ccbdb/pydnsbl/checker.py#L150-L157
train
Roastero/freshroastsr700
freshroastsr700/utils.py
frange
def frange(start, stop, step, precision): """A generator that will generate a range of floats.""" value = start while round(value, precision) < stop: yield round(value, precision) value += step
python
def frange(start, stop, step, precision): """A generator that will generate a range of floats.""" value = start while round(value, precision) < stop: yield round(value, precision) value += step
[ "def", "frange", "(", "start", ",", "stop", ",", "step", ",", "precision", ")", ":", "value", "=", "start", "while", "round", "(", "value", ",", "precision", ")", "<", "stop", ":", "yield", "round", "(", "value", ",", "precision", ")", "value", "+=",...
A generator that will generate a range of floats.
[ "A", "generator", "that", "will", "generate", "a", "range", "of", "floats", "." ]
49cf4961444c0f56d051d5ac5088ace480b54f02
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/utils.py#L11-L16
train
Roastero/freshroastsr700
freshroastsr700/utils.py
find_device
def find_device(vidpid): """Finds a connected device with the given VID:PID. Returns the serial port url.""" for port in list_ports.comports(): if re.search(vidpid, port[2], flags=re.IGNORECASE): return port[0] raise exceptions.RoasterLookupError
python
def find_device(vidpid): """Finds a connected device with the given VID:PID. Returns the serial port url.""" for port in list_ports.comports(): if re.search(vidpid, port[2], flags=re.IGNORECASE): return port[0] raise exceptions.RoasterLookupError
[ "def", "find_device", "(", "vidpid", ")", ":", "for", "port", "in", "list_ports", ".", "comports", "(", ")", ":", "if", "re", ".", "search", "(", "vidpid", ",", "port", "[", "2", "]", ",", "flags", "=", "re", ".", "IGNORECASE", ")", ":", "return", ...
Finds a connected device with the given VID:PID. Returns the serial port url.
[ "Finds", "a", "connected", "device", "with", "the", "given", "VID", ":", "PID", ".", "Returns", "the", "serial", "port", "url", "." ]
49cf4961444c0f56d051d5ac5088ace480b54f02
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/utils.py#L19-L26
train
Roastero/freshroastsr700
freshroastsr700/pid.py
PID.update
def update(self, currentTemp, targetTemp): """Calculate PID output value for given reference input and feedback.""" # in this implementation, ki includes the dt multiplier term, # and kd includes the dt divisor term. This is typical practice in # industry. self.targetTemp = targ...
python
def update(self, currentTemp, targetTemp): """Calculate PID output value for given reference input and feedback.""" # in this implementation, ki includes the dt multiplier term, # and kd includes the dt divisor term. This is typical practice in # industry. self.targetTemp = targ...
[ "def", "update", "(", "self", ",", "currentTemp", ",", "targetTemp", ")", ":", "# in this implementation, ki includes the dt multiplier term,", "# and kd includes the dt divisor term. This is typical practice in", "# industry.", "self", ".", "targetTemp", "=", "targetTemp", "sel...
Calculate PID output value for given reference input and feedback.
[ "Calculate", "PID", "output", "value", "for", "given", "reference", "input", "and", "feedback", "." ]
49cf4961444c0f56d051d5ac5088ace480b54f02
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/pid.py#L28-L59
train
Roastero/freshroastsr700
freshroastsr700/pid.py
PID.setPoint
def setPoint(self, targetTemp): """Initilize the setpoint of PID.""" self.targetTemp = targetTemp self.Integrator = 0 self.Derivator = 0
python
def setPoint(self, targetTemp): """Initilize the setpoint of PID.""" self.targetTemp = targetTemp self.Integrator = 0 self.Derivator = 0
[ "def", "setPoint", "(", "self", ",", "targetTemp", ")", ":", "self", ".", "targetTemp", "=", "targetTemp", "self", ".", "Integrator", "=", "0", "self", ".", "Derivator", "=", "0" ]
Initilize the setpoint of PID.
[ "Initilize", "the", "setpoint", "of", "PID", "." ]
49cf4961444c0f56d051d5ac5088ace480b54f02
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/pid.py#L61-L65
train
Roastero/freshroastsr700
examples/advanced.py
Roaster.next_state
def next_state(self): """This is a method that will be called when the time remaining ends. The current state can be: roasting, cooling, idle, sleeping, connecting, or unkown.""" if(self.roaster.get_roaster_state() == 'roasting'): self.roaster.time_remaining = 20 ...
python
def next_state(self): """This is a method that will be called when the time remaining ends. The current state can be: roasting, cooling, idle, sleeping, connecting, or unkown.""" if(self.roaster.get_roaster_state() == 'roasting'): self.roaster.time_remaining = 20 ...
[ "def", "next_state", "(", "self", ")", ":", "if", "(", "self", ".", "roaster", ".", "get_roaster_state", "(", ")", "==", "'roasting'", ")", ":", "self", ".", "roaster", ".", "time_remaining", "=", "20", "self", ".", "roaster", ".", "cool", "(", ")", ...
This is a method that will be called when the time remaining ends. The current state can be: roasting, cooling, idle, sleeping, connecting, or unkown.
[ "This", "is", "a", "method", "that", "will", "be", "called", "when", "the", "time", "remaining", "ends", ".", "The", "current", "state", "can", "be", ":", "roasting", "cooling", "idle", "sleeping", "connecting", "or", "unkown", "." ]
49cf4961444c0f56d051d5ac5088ace480b54f02
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/examples/advanced.py#L21-L29
train
tomislater/RandomWords
random_words/random_words.py
Random.load_nouns
def load_nouns(self, file): """ Load dict from file for random words. :param str file: filename """ with open(os.path.join(main_dir, file + '.dat'), 'r') as f: self.nouns = json.load(f)
python
def load_nouns(self, file): """ Load dict from file for random words. :param str file: filename """ with open(os.path.join(main_dir, file + '.dat'), 'r') as f: self.nouns = json.load(f)
[ "def", "load_nouns", "(", "self", ",", "file", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "main_dir", ",", "file", "+", "'.dat'", ")", ",", "'r'", ")", "as", "f", ":", "self", ".", "nouns", "=", "json", ".", "load", "("...
Load dict from file for random words. :param str file: filename
[ "Load", "dict", "from", "file", "for", "random", "words", "." ]
601aa48732d3c389f4c17ba0ed98ffe0e4821d78
https://github.com/tomislater/RandomWords/blob/601aa48732d3c389f4c17ba0ed98ffe0e4821d78/random_words/random_words.py#L30-L37
train
tomislater/RandomWords
random_words/random_words.py
Random.load_dmails
def load_dmails(self, file): """ Load list from file for random mails :param str file: filename """ with open(os.path.join(main_dir, file + '.dat'), 'r') as f: self.dmails = frozenset(json.load(f))
python
def load_dmails(self, file): """ Load list from file for random mails :param str file: filename """ with open(os.path.join(main_dir, file + '.dat'), 'r') as f: self.dmails = frozenset(json.load(f))
[ "def", "load_dmails", "(", "self", ",", "file", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "main_dir", ",", "file", "+", "'.dat'", ")", ",", "'r'", ")", "as", "f", ":", "self", ".", "dmails", "=", "frozenset", "(", "json"...
Load list from file for random mails :param str file: filename
[ "Load", "list", "from", "file", "for", "random", "mails" ]
601aa48732d3c389f4c17ba0ed98ffe0e4821d78
https://github.com/tomislater/RandomWords/blob/601aa48732d3c389f4c17ba0ed98ffe0e4821d78/random_words/random_words.py#L39-L46
train
tomislater/RandomWords
random_words/random_words.py
Random.load_nicknames
def load_nicknames(self, file): """ Load dict from file for random nicknames. :param str file: filename """ with open(os.path.join(main_dir, file + '.dat'), 'r') as f: self.nicknames = json.load(f)
python
def load_nicknames(self, file): """ Load dict from file for random nicknames. :param str file: filename """ with open(os.path.join(main_dir, file + '.dat'), 'r') as f: self.nicknames = json.load(f)
[ "def", "load_nicknames", "(", "self", ",", "file", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "main_dir", ",", "file", "+", "'.dat'", ")", ",", "'r'", ")", "as", "f", ":", "self", ".", "nicknames", "=", "json", ".", "load...
Load dict from file for random nicknames. :param str file: filename
[ "Load", "dict", "from", "file", "for", "random", "nicknames", "." ]
601aa48732d3c389f4c17ba0ed98ffe0e4821d78
https://github.com/tomislater/RandomWords/blob/601aa48732d3c389f4c17ba0ed98ffe0e4821d78/random_words/random_words.py#L48-L55
train
tomislater/RandomWords
random_words/random_words.py
RandomWords.random_words
def random_words(self, letter=None, count=1): """ Returns list of random words. :param str letter: letter :param int count: how much words :rtype: list :returns: list of random words :raises: ValueError """ self.check_count(count) words =...
python
def random_words(self, letter=None, count=1): """ Returns list of random words. :param str letter: letter :param int count: how much words :rtype: list :returns: list of random words :raises: ValueError """ self.check_count(count) words =...
[ "def", "random_words", "(", "self", ",", "letter", "=", "None", ",", "count", "=", "1", ")", ":", "self", ".", "check_count", "(", "count", ")", "words", "=", "[", "]", "if", "letter", "is", "None", ":", "all_words", "=", "list", "(", "chain", ".",...
Returns list of random words. :param str letter: letter :param int count: how much words :rtype: list :returns: list of random words :raises: ValueError
[ "Returns", "list", "of", "random", "words", "." ]
601aa48732d3c389f4c17ba0ed98ffe0e4821d78
https://github.com/tomislater/RandomWords/blob/601aa48732d3c389f4c17ba0ed98ffe0e4821d78/random_words/random_words.py#L88-L129
train
tomislater/RandomWords
random_words/random_words.py
RandomNicknames.random_nicks
def random_nicks(self, letter=None, gender='u', count=1): """ Return list of random nicks. :param str letter: letter :param str gender: ``'f'`` for female, ``'m'`` for male and None for both :param int count: how much nicks :rtype: list :returns: list of random n...
python
def random_nicks(self, letter=None, gender='u', count=1): """ Return list of random nicks. :param str letter: letter :param str gender: ``'f'`` for female, ``'m'`` for male and None for both :param int count: how much nicks :rtype: list :returns: list of random n...
[ "def", "random_nicks", "(", "self", ",", "letter", "=", "None", ",", "gender", "=", "'u'", ",", "count", "=", "1", ")", ":", "self", ".", "check_count", "(", "count", ")", "nicks", "=", "[", "]", "if", "gender", "not", "in", "(", "'f'", ",", "'m'...
Return list of random nicks. :param str letter: letter :param str gender: ``'f'`` for female, ``'m'`` for male and None for both :param int count: how much nicks :rtype: list :returns: list of random nicks :raises: ValueError
[ "Return", "list", "of", "random", "nicks", "." ]
601aa48732d3c389f4c17ba0ed98ffe0e4821d78
https://github.com/tomislater/RandomWords/blob/601aa48732d3c389f4c17ba0ed98ffe0e4821d78/random_words/random_words.py#L153-L199
train
tomislater/RandomWords
random_words/random_words.py
RandomEmails.randomMails
def randomMails(self, count=1): """ Return random e-mails. :rtype: list :returns: list of random e-mails """ self.check_count(count) random_nicks = self.rn.random_nicks(count=count) random_domains = sample(self.dmails, count) return [ ...
python
def randomMails(self, count=1): """ Return random e-mails. :rtype: list :returns: list of random e-mails """ self.check_count(count) random_nicks = self.rn.random_nicks(count=count) random_domains = sample(self.dmails, count) return [ ...
[ "def", "randomMails", "(", "self", ",", "count", "=", "1", ")", ":", "self", ".", "check_count", "(", "count", ")", "random_nicks", "=", "self", ".", "rn", ".", "random_nicks", "(", "count", "=", "count", ")", "random_domains", "=", "sample", "(", "sel...
Return random e-mails. :rtype: list :returns: list of random e-mails
[ "Return", "random", "e", "-", "mails", "." ]
601aa48732d3c389f4c17ba0ed98ffe0e4821d78
https://github.com/tomislater/RandomWords/blob/601aa48732d3c389f4c17ba0ed98ffe0e4821d78/random_words/random_words.py#L218-L233
train
tomislater/RandomWords
random_words/lorem_ipsum.py
LoremIpsum.get_sentences_list
def get_sentences_list(self, sentences=1): """ Return sentences in list. :param int sentences: how many sentences :returns: list of strings with sentence :rtype: list """ if sentences < 1: raise ValueError('Param "sentences" must be greater than 0.') ...
python
def get_sentences_list(self, sentences=1): """ Return sentences in list. :param int sentences: how many sentences :returns: list of strings with sentence :rtype: list """ if sentences < 1: raise ValueError('Param "sentences" must be greater than 0.') ...
[ "def", "get_sentences_list", "(", "self", ",", "sentences", "=", "1", ")", ":", "if", "sentences", "<", "1", ":", "raise", "ValueError", "(", "'Param \"sentences\" must be greater than 0.'", ")", "sentences_list", "=", "[", "]", "while", "sentences", ":", "num_r...
Return sentences in list. :param int sentences: how many sentences :returns: list of strings with sentence :rtype: list
[ "Return", "sentences", "in", "list", "." ]
601aa48732d3c389f4c17ba0ed98ffe0e4821d78
https://github.com/tomislater/RandomWords/blob/601aa48732d3c389f4c17ba0ed98ffe0e4821d78/random_words/lorem_ipsum.py#L27-L49
train
tomislater/RandomWords
random_words/lorem_ipsum.py
LoremIpsum.make_sentence
def make_sentence(list_words): """ Return a sentence from list of words. :param list list_words: list of words :returns: sentence :rtype: str """ lw_len = len(list_words) if lw_len > 6: list_words.insert(lw_len // 2 + random.choice(range(-2, ...
python
def make_sentence(list_words): """ Return a sentence from list of words. :param list list_words: list of words :returns: sentence :rtype: str """ lw_len = len(list_words) if lw_len > 6: list_words.insert(lw_len // 2 + random.choice(range(-2, ...
[ "def", "make_sentence", "(", "list_words", ")", ":", "lw_len", "=", "len", "(", "list_words", ")", "if", "lw_len", ">", "6", ":", "list_words", ".", "insert", "(", "lw_len", "//", "2", "+", "random", ".", "choice", "(", "range", "(", "-", "2", ",", ...
Return a sentence from list of words. :param list list_words: list of words :returns: sentence :rtype: str
[ "Return", "a", "sentence", "from", "list", "of", "words", "." ]
601aa48732d3c389f4c17ba0ed98ffe0e4821d78
https://github.com/tomislater/RandomWords/blob/601aa48732d3c389f4c17ba0ed98ffe0e4821d78/random_words/lorem_ipsum.py#L62-L77
train
paulocheque/epub-meta
epub_meta/collector.py
_discover_cover_image
def _discover_cover_image(zf, opf_xmldoc, opf_filepath): ''' Find the cover image path in the OPF file. Returns a tuple: (image content in base64, file extension) ''' content = None filepath = None extension = None # Strategies to discover the cover-image path: # e.g.: <meta name="...
python
def _discover_cover_image(zf, opf_xmldoc, opf_filepath): ''' Find the cover image path in the OPF file. Returns a tuple: (image content in base64, file extension) ''' content = None filepath = None extension = None # Strategies to discover the cover-image path: # e.g.: <meta name="...
[ "def", "_discover_cover_image", "(", "zf", ",", "opf_xmldoc", ",", "opf_filepath", ")", ":", "content", "=", "None", "filepath", "=", "None", "extension", "=", "None", "# Strategies to discover the cover-image path:", "# e.g.: <meta name=\"cover\" content=\"cover\"/>", "tag...
Find the cover image path in the OPF file. Returns a tuple: (image content in base64, file extension)
[ "Find", "the", "cover", "image", "path", "in", "the", "OPF", "file", ".", "Returns", "a", "tuple", ":", "(", "image", "content", "in", "base64", "file", "extension", ")" ]
3f0efb9f29a286b1a6896ad05422b23f10e10164
https://github.com/paulocheque/epub-meta/blob/3f0efb9f29a286b1a6896ad05422b23f10e10164/epub_meta/collector.py#L183-L215
train
paulocheque/epub-meta
epub_meta/collector.py
_discover_toc
def _discover_toc(zf, opf_xmldoc, opf_filepath): ''' Returns a list of objects: {title: str, src: str, level: int, index: int} ''' toc = None # ePub 3.x tag = find_tag(opf_xmldoc, 'item', 'properties', 'nav') if tag and 'href' in tag.attributes.keys(): filepath = unquote(tag.attribu...
python
def _discover_toc(zf, opf_xmldoc, opf_filepath): ''' Returns a list of objects: {title: str, src: str, level: int, index: int} ''' toc = None # ePub 3.x tag = find_tag(opf_xmldoc, 'item', 'properties', 'nav') if tag and 'href' in tag.attributes.keys(): filepath = unquote(tag.attribu...
[ "def", "_discover_toc", "(", "zf", ",", "opf_xmldoc", ",", "opf_filepath", ")", ":", "toc", "=", "None", "# ePub 3.x", "tag", "=", "find_tag", "(", "opf_xmldoc", ",", "'item'", ",", "'properties'", ",", "'nav'", ")", "if", "tag", "and", "'href'", "in", "...
Returns a list of objects: {title: str, src: str, level: int, index: int}
[ "Returns", "a", "list", "of", "objects", ":", "{", "title", ":", "str", "src", ":", "str", "level", ":", "int", "index", ":", "int", "}" ]
3f0efb9f29a286b1a6896ad05422b23f10e10164
https://github.com/paulocheque/epub-meta/blob/3f0efb9f29a286b1a6896ad05422b23f10e10164/epub_meta/collector.py#L218-L332
train
paulocheque/epub-meta
epub_meta/collector.py
get_epub_metadata
def get_epub_metadata(filepath, read_cover_image=True, read_toc=True): ''' References: http://idpf.org/epub/201 and http://idpf.org/epub/301 1. Parse META-INF/container.xml file and find the .OPF file path. 2. In the .OPF file, find the metadata ''' if not zipfile.is_zipfile(filepath): r...
python
def get_epub_metadata(filepath, read_cover_image=True, read_toc=True): ''' References: http://idpf.org/epub/201 and http://idpf.org/epub/301 1. Parse META-INF/container.xml file and find the .OPF file path. 2. In the .OPF file, find the metadata ''' if not zipfile.is_zipfile(filepath): r...
[ "def", "get_epub_metadata", "(", "filepath", ",", "read_cover_image", "=", "True", ",", "read_toc", "=", "True", ")", ":", "if", "not", "zipfile", ".", "is_zipfile", "(", "filepath", ")", ":", "raise", "EPubException", "(", "'Unknown file'", ")", "# print('Rea...
References: http://idpf.org/epub/201 and http://idpf.org/epub/301 1. Parse META-INF/container.xml file and find the .OPF file path. 2. In the .OPF file, find the metadata
[ "References", ":", "http", ":", "//", "idpf", ".", "org", "/", "epub", "/", "201", "and", "http", ":", "//", "idpf", ".", "org", "/", "epub", "/", "301", "1", ".", "Parse", "META", "-", "INF", "/", "container", ".", "xml", "file", "and", "find", ...
3f0efb9f29a286b1a6896ad05422b23f10e10164
https://github.com/paulocheque/epub-meta/blob/3f0efb9f29a286b1a6896ad05422b23f10e10164/epub_meta/collector.py#L335-L395
train
paulocheque/epub-meta
epub_meta/collector.py
get_epub_opf_xml
def get_epub_opf_xml(filepath): ''' Returns the file.OPF contents of the ePub file ''' if not zipfile.is_zipfile(filepath): raise EPubException('Unknown file') # print('Reading ePub file: {}'.format(filepath)) zf = zipfile.ZipFile(filepath, 'r', compression=zipfile.ZIP_DEFLATED, allowZi...
python
def get_epub_opf_xml(filepath): ''' Returns the file.OPF contents of the ePub file ''' if not zipfile.is_zipfile(filepath): raise EPubException('Unknown file') # print('Reading ePub file: {}'.format(filepath)) zf = zipfile.ZipFile(filepath, 'r', compression=zipfile.ZIP_DEFLATED, allowZi...
[ "def", "get_epub_opf_xml", "(", "filepath", ")", ":", "if", "not", "zipfile", ".", "is_zipfile", "(", "filepath", ")", ":", "raise", "EPubException", "(", "'Unknown file'", ")", "# print('Reading ePub file: {}'.format(filepath))", "zf", "=", "zipfile", ".", "ZipFile...
Returns the file.OPF contents of the ePub file
[ "Returns", "the", "file", ".", "OPF", "contents", "of", "the", "ePub", "file" ]
3f0efb9f29a286b1a6896ad05422b23f10e10164
https://github.com/paulocheque/epub-meta/blob/3f0efb9f29a286b1a6896ad05422b23f10e10164/epub_meta/collector.py#L398-L411
train
damirazo/Petrovich
petrovich/main.py
Petrovich.firstname
def firstname(self, value, case, gender=None): u""" Склонение имени :param value: Значение для склонения :param case: Падеж для склонения (значение из класса Case) :param gender: Грамматический род """ if not value: raise ValueError('Firstname cannot ...
python
def firstname(self, value, case, gender=None): u""" Склонение имени :param value: Значение для склонения :param case: Падеж для склонения (значение из класса Case) :param gender: Грамматический род """ if not value: raise ValueError('Firstname cannot ...
[ "def", "firstname", "(", "self", ",", "value", ",", "case", ",", "gender", "=", "None", ")", ":", "if", "not", "value", ":", "raise", "ValueError", "(", "'Firstname cannot be empty.'", ")", "return", "self", ".", "__inflect", "(", "value", ",", "case", "...
u""" Склонение имени :param value: Значение для склонения :param case: Падеж для склонения (значение из класса Case) :param gender: Грамматический род
[ "u", "Склонение", "имени" ]
b587158896a87d21ad6520d8e2e570d71e4338b4
https://github.com/damirazo/Petrovich/blob/b587158896a87d21ad6520d8e2e570d71e4338b4/petrovich/main.py#L43-L54
train
damirazo/Petrovich
petrovich/main.py
Petrovich.lastname
def lastname(self, value, case, gender=None): u""" Склонение фамилии :param value: Значение для склонения :param case: Падеж для склонения (значение из класса Case) :param gender: Грамматический род """ if not value: raise ValueError('Lastname cannot ...
python
def lastname(self, value, case, gender=None): u""" Склонение фамилии :param value: Значение для склонения :param case: Падеж для склонения (значение из класса Case) :param gender: Грамматический род """ if not value: raise ValueError('Lastname cannot ...
[ "def", "lastname", "(", "self", ",", "value", ",", "case", ",", "gender", "=", "None", ")", ":", "if", "not", "value", ":", "raise", "ValueError", "(", "'Lastname cannot be empty.'", ")", "return", "self", ".", "__inflect", "(", "value", ",", "case", ","...
u""" Склонение фамилии :param value: Значение для склонения :param case: Падеж для склонения (значение из класса Case) :param gender: Грамматический род
[ "u", "Склонение", "фамилии" ]
b587158896a87d21ad6520d8e2e570d71e4338b4
https://github.com/damirazo/Petrovich/blob/b587158896a87d21ad6520d8e2e570d71e4338b4/petrovich/main.py#L56-L67
train
damirazo/Petrovich
petrovich/main.py
Petrovich.middlename
def middlename(self, value, case, gender=None): u""" Склонение отчества :param value: Значение для склонения :param case: Падеж для склонения (значение из класса Case) :param gender: Грамматический род """ if not value: raise ValueError('Middlename ca...
python
def middlename(self, value, case, gender=None): u""" Склонение отчества :param value: Значение для склонения :param case: Падеж для склонения (значение из класса Case) :param gender: Грамматический род """ if not value: raise ValueError('Middlename ca...
[ "def", "middlename", "(", "self", ",", "value", ",", "case", ",", "gender", "=", "None", ")", ":", "if", "not", "value", ":", "raise", "ValueError", "(", "'Middlename cannot be empty.'", ")", "return", "self", ".", "__inflect", "(", "value", ",", "case", ...
u""" Склонение отчества :param value: Значение для склонения :param case: Падеж для склонения (значение из класса Case) :param gender: Грамматический род
[ "u", "Склонение", "отчества" ]
b587158896a87d21ad6520d8e2e570d71e4338b4
https://github.com/damirazo/Petrovich/blob/b587158896a87d21ad6520d8e2e570d71e4338b4/petrovich/main.py#L69-L80
train
damirazo/Petrovich
petrovich/main.py
Petrovich.__split_name
def __split_name(self, name): u""" Разделяет имя на сегменты по разделителям в self.separators :param name: имя :return: разделённое имя вместе с разделителями """ def gen(name, separators): if len(separators) == 0: yield name else:...
python
def __split_name(self, name): u""" Разделяет имя на сегменты по разделителям в self.separators :param name: имя :return: разделённое имя вместе с разделителями """ def gen(name, separators): if len(separators) == 0: yield name else:...
[ "def", "__split_name", "(", "self", ",", "name", ")", ":", "def", "gen", "(", "name", ",", "separators", ")", ":", "if", "len", "(", "separators", ")", "==", "0", ":", "yield", "name", "else", ":", "segments", "=", "name", ".", "split", "(", "separ...
u""" Разделяет имя на сегменты по разделителям в self.separators :param name: имя :return: разделённое имя вместе с разделителями
[ "u", "Разделяет", "имя", "на", "сегменты", "по", "разделителям", "в", "self", ".", "separators", ":", "param", "name", ":", "имя", ":", "return", ":", "разделённое", "имя", "вместе", "с", "разделителями" ]
b587158896a87d21ad6520d8e2e570d71e4338b4
https://github.com/damirazo/Petrovich/blob/b587158896a87d21ad6520d8e2e570d71e4338b4/petrovich/main.py#L82-L100
train
xigt/xigt
xigt/ref.py
expand
def expand(expression): """ Expand a reference expression to individual spans. Also works on space-separated ID lists, although a sequence of space characters will be considered a delimiter. >>> expand('a1') 'a1' >>> expand('a1[3:5]') 'a1[3:5]' >>> expand('a1[3:5+6:7]') 'a1[3:5]...
python
def expand(expression): """ Expand a reference expression to individual spans. Also works on space-separated ID lists, although a sequence of space characters will be considered a delimiter. >>> expand('a1') 'a1' >>> expand('a1[3:5]') 'a1[3:5]' >>> expand('a1[3:5+6:7]') 'a1[3:5]...
[ "def", "expand", "(", "expression", ")", ":", "tokens", "=", "[", "]", "for", "(", "pre", ",", "_id", ",", "_range", ")", "in", "robust_ref_re", ".", "findall", "(", "expression", ")", ":", "if", "not", "_range", ":", "tokens", ".", "append", "(", ...
Expand a reference expression to individual spans. Also works on space-separated ID lists, although a sequence of space characters will be considered a delimiter. >>> expand('a1') 'a1' >>> expand('a1[3:5]') 'a1[3:5]' >>> expand('a1[3:5+6:7]') 'a1[3:5]+a1[6:7]' >>> expand('a1 a2 a3'...
[ "Expand", "a", "reference", "expression", "to", "individual", "spans", ".", "Also", "works", "on", "space", "-", "separated", "ID", "lists", "although", "a", "sequence", "of", "space", "characters", "will", "be", "considered", "a", "delimiter", "." ]
3736fbb6d26887181de57bd189cbd731cec91289
https://github.com/xigt/xigt/blob/3736fbb6d26887181de57bd189cbd731cec91289/xigt/ref.py#L36-L62
train
xigt/xigt
xigt/ref.py
compress
def compress(expression): """ Compress a reference expression to group spans on the same id. Also works on space-separated ID lists, although a sequence of space characters will be considered a delimiter. >>> compress('a1') 'a1' >>> compress('a1[3:5]') 'a1[3:5]' >>> compress('a1[3:5...
python
def compress(expression): """ Compress a reference expression to group spans on the same id. Also works on space-separated ID lists, although a sequence of space characters will be considered a delimiter. >>> compress('a1') 'a1' >>> compress('a1[3:5]') 'a1[3:5]' >>> compress('a1[3:5...
[ "def", "compress", "(", "expression", ")", ":", "tokens", "=", "[", "]", "selection", "=", "[", "]", "last_id", "=", "None", "for", "(", "pre", ",", "_id", ",", "_range", ")", "in", "robust_ref_re", ".", "findall", "(", "expression", ")", ":", "if", ...
Compress a reference expression to group spans on the same id. Also works on space-separated ID lists, although a sequence of space characters will be considered a delimiter. >>> compress('a1') 'a1' >>> compress('a1[3:5]') 'a1[3:5]' >>> compress('a1[3:5+6:7]') 'a1[3:5+6:7]' >>> comp...
[ "Compress", "a", "reference", "expression", "to", "group", "spans", "on", "the", "same", "id", ".", "Also", "works", "on", "space", "-", "separated", "ID", "lists", "although", "a", "sequence", "of", "space", "characters", "will", "be", "considered", "a", ...
3736fbb6d26887181de57bd189cbd731cec91289
https://github.com/xigt/xigt/blob/3736fbb6d26887181de57bd189cbd731cec91289/xigt/ref.py#L65-L101
train
xigt/xigt
xigt/ref.py
selections
def selections(expression, keep_delimiters=True): """ Split the expression into individual selection expressions. The delimiters will be kept as separate items if keep_delimters=True. Also works on space-separated ID lists, although a sequence of space characters will be considered a delimiter. ...
python
def selections(expression, keep_delimiters=True): """ Split the expression into individual selection expressions. The delimiters will be kept as separate items if keep_delimters=True. Also works on space-separated ID lists, although a sequence of space characters will be considered a delimiter. ...
[ "def", "selections", "(", "expression", ",", "keep_delimiters", "=", "True", ")", ":", "tokens", "=", "[", "]", "for", "(", "pre", ",", "_id", ",", "_range", ")", "in", "robust_ref_re", ".", "findall", "(", "expression", ")", ":", "if", "keep_delimiters"...
Split the expression into individual selection expressions. The delimiters will be kept as separate items if keep_delimters=True. Also works on space-separated ID lists, although a sequence of space characters will be considered a delimiter. >>> selections('a1') ['a1'] >>> selections('a1[3:5]')...
[ "Split", "the", "expression", "into", "individual", "selection", "expressions", ".", "The", "delimiters", "will", "be", "kept", "as", "separate", "items", "if", "keep_delimters", "=", "True", ".", "Also", "works", "on", "space", "-", "separated", "ID", "lists"...
3736fbb6d26887181de57bd189cbd731cec91289
https://github.com/xigt/xigt/blob/3736fbb6d26887181de57bd189cbd731cec91289/xigt/ref.py#L104-L134
train
xigt/xigt
xigt/ref.py
resolve
def resolve(container, expression): """ Return the string that is the resolution of the alignment expression `expression`, which selects ids from `container`. """ itemgetter = getattr(container, 'get_item', container.get) tokens = [] expression = expression.strip() for sel_delim, _id, _r...
python
def resolve(container, expression): """ Return the string that is the resolution of the alignment expression `expression`, which selects ids from `container`. """ itemgetter = getattr(container, 'get_item', container.get) tokens = [] expression = expression.strip() for sel_delim, _id, _r...
[ "def", "resolve", "(", "container", ",", "expression", ")", ":", "itemgetter", "=", "getattr", "(", "container", ",", "'get_item'", ",", "container", ".", "get", ")", "tokens", "=", "[", "]", "expression", "=", "expression", ".", "strip", "(", ")", "for"...
Return the string that is the resolution of the alignment expression `expression`, which selects ids from `container`.
[ "Return", "the", "string", "that", "is", "the", "resolution", "of", "the", "alignment", "expression", "expression", "which", "selects", "ids", "from", "container", "." ]
3736fbb6d26887181de57bd189cbd731cec91289
https://github.com/xigt/xigt/blob/3736fbb6d26887181de57bd189cbd731cec91289/xigt/ref.py#L181-L210
train
xigt/xigt
xigt/ref.py
referents
def referents(igt, id, refattrs=None): """ Return a list of ids denoting objects (tiers or items) in `igt` that are referred by the object denoted by `id` using a reference attribute in `refattrs`. If `refattrs` is None, then consider all known reference attributes for the type of object denoted by ...
python
def referents(igt, id, refattrs=None): """ Return a list of ids denoting objects (tiers or items) in `igt` that are referred by the object denoted by `id` using a reference attribute in `refattrs`. If `refattrs` is None, then consider all known reference attributes for the type of object denoted by ...
[ "def", "referents", "(", "igt", ",", "id", ",", "refattrs", "=", "None", ")", ":", "obj", "=", "igt", ".", "get_any", "(", "id", ")", "if", "obj", "is", "None", ":", "raise", "XigtLookupError", "(", "id", ")", "if", "refattrs", "is", "None", ":", ...
Return a list of ids denoting objects (tiers or items) in `igt` that are referred by the object denoted by `id` using a reference attribute in `refattrs`. If `refattrs` is None, then consider all known reference attributes for the type of object denoted by _id_. In other words, if 'b1' refers to 'a1' us...
[ "Return", "a", "list", "of", "ids", "denoting", "objects", "(", "tiers", "or", "items", ")", "in", "igt", "that", "are", "referred", "by", "the", "object", "denoted", "by", "id", "using", "a", "reference", "attribute", "in", "refattrs", ".", "If", "refat...
3736fbb6d26887181de57bd189cbd731cec91289
https://github.com/xigt/xigt/blob/3736fbb6d26887181de57bd189cbd731cec91289/xigt/ref.py#L213-L227
train
xigt/xigt
xigt/ref.py
referrers
def referrers(igt, id, refattrs=None): """ Return a list of ids denoting objects (tiers or items) in `igt` that refer to the given `id`. In other words, if 'b1' refers to 'a1', then `referrers(igt, 'a1')` returns `['b1']`. """ if refattrs is None: result = {} else: result = {...
python
def referrers(igt, id, refattrs=None): """ Return a list of ids denoting objects (tiers or items) in `igt` that refer to the given `id`. In other words, if 'b1' refers to 'a1', then `referrers(igt, 'a1')` returns `['b1']`. """ if refattrs is None: result = {} else: result = {...
[ "def", "referrers", "(", "igt", ",", "id", ",", "refattrs", "=", "None", ")", ":", "if", "refattrs", "is", "None", ":", "result", "=", "{", "}", "else", ":", "result", "=", "{", "ra", ":", "[", "]", "for", "ra", "in", "refattrs", "}", "# if the i...
Return a list of ids denoting objects (tiers or items) in `igt` that refer to the given `id`. In other words, if 'b1' refers to 'a1', then `referrers(igt, 'a1')` returns `['b1']`.
[ "Return", "a", "list", "of", "ids", "denoting", "objects", "(", "tiers", "or", "items", ")", "in", "igt", "that", "refer", "to", "the", "given", "id", ".", "In", "other", "words", "if", "b1", "refers", "to", "a1", "then", "referrers", "(", "igt", "a1...
3736fbb6d26887181de57bd189cbd731cec91289
https://github.com/xigt/xigt/blob/3736fbb6d26887181de57bd189cbd731cec91289/xigt/ref.py#L230-L265
train
xigt/xigt
xigt/query.py
ancestors
def ancestors(obj, refattrs=(ALIGNMENT, SEGMENTATION)): """ >>> for anc in query.ancestors(igt.get_item('g1'), refattrs=(ALIGNMENT, SEGMENTATION)): ... print(anc) (<Tier object (id: g type: glosses) at ...>, 'alignment', <Tier object (id: m type: morphemes) at ...>, [<Item object (id: m1) at ...>]) ...
python
def ancestors(obj, refattrs=(ALIGNMENT, SEGMENTATION)): """ >>> for anc in query.ancestors(igt.get_item('g1'), refattrs=(ALIGNMENT, SEGMENTATION)): ... print(anc) (<Tier object (id: g type: glosses) at ...>, 'alignment', <Tier object (id: m type: morphemes) at ...>, [<Item object (id: m1) at ...>]) ...
[ "def", "ancestors", "(", "obj", ",", "refattrs", "=", "(", "ALIGNMENT", ",", "SEGMENTATION", ")", ")", ":", "if", "hasattr", "(", "obj", ",", "'tier'", ")", ":", "tier", "=", "obj", ".", "tier", "items", "=", "[", "obj", "]", "else", ":", "tier", ...
>>> for anc in query.ancestors(igt.get_item('g1'), refattrs=(ALIGNMENT, SEGMENTATION)): ... print(anc) (<Tier object (id: g type: glosses) at ...>, 'alignment', <Tier object (id: m type: morphemes) at ...>, [<Item object (id: m1) at ...>]) (<Tier object (id: m type: morphemes) at ...>, 'segmentation', <...
[ ">>>", "for", "anc", "in", "query", ".", "ancestors", "(", "igt", ".", "get_item", "(", "g1", ")", "refattrs", "=", "(", "ALIGNMENT", "SEGMENTATION", "))", ":", "...", "print", "(", "anc", ")", "(", "<Tier", "object", "(", "id", ":", "g", "type", "...
3736fbb6d26887181de57bd189cbd731cec91289
https://github.com/xigt/xigt/blob/3736fbb6d26887181de57bd189cbd731cec91289/xigt/query.py#L13-L46
train
xigt/xigt
xigt/query.py
descendants
def descendants(obj, refattrs=(SEGMENTATION, ALIGNMENT), follow='first'): """ >>> for des in query.descendants(igt.get_item('p1'), refattrs=(SEGMENTATION, ALIGNMENT)): ... print(des) (<Tier object (id: p type: phrases) at ...>, 'segmentation', <Tier object (id: w type: words) at ...>, [<Item object ...
python
def descendants(obj, refattrs=(SEGMENTATION, ALIGNMENT), follow='first'): """ >>> for des in query.descendants(igt.get_item('p1'), refattrs=(SEGMENTATION, ALIGNMENT)): ... print(des) (<Tier object (id: p type: phrases) at ...>, 'segmentation', <Tier object (id: w type: words) at ...>, [<Item object ...
[ "def", "descendants", "(", "obj", ",", "refattrs", "=", "(", "SEGMENTATION", ",", "ALIGNMENT", ")", ",", "follow", "=", "'first'", ")", ":", "if", "hasattr", "(", "obj", ",", "'tier'", ")", ":", "tier", "=", "obj", ".", "tier", "items", "=", "[", "...
>>> for des in query.descendants(igt.get_item('p1'), refattrs=(SEGMENTATION, ALIGNMENT)): ... print(des) (<Tier object (id: p type: phrases) at ...>, 'segmentation', <Tier object (id: w type: words) at ...>, [<Item object (id: w1) at ...>]) (<Tier object (id: p type: phrases) at ...>, 'alignment', <Tier...
[ ">>>", "for", "des", "in", "query", ".", "descendants", "(", "igt", ".", "get_item", "(", "p1", ")", "refattrs", "=", "(", "SEGMENTATION", "ALIGNMENT", "))", ":", "...", "print", "(", "des", ")", "(", "<Tier", "object", "(", "id", ":", "p", "type", ...
3736fbb6d26887181de57bd189cbd731cec91289
https://github.com/xigt/xigt/blob/3736fbb6d26887181de57bd189cbd731cec91289/xigt/query.py#L49-L93
train
xigt/xigt
xigt/codecs/xigtxml.py
default_decode
def default_decode(events, mode='full'): """Decode a XigtCorpus element.""" event, elem = next(events) root = elem # store root for later instantiation while (event, elem.tag) not in [('start', 'igt'), ('end', 'xigt-corpus')]: event, elem = next(events) igts = None if event == 'start' a...
python
def default_decode(events, mode='full'): """Decode a XigtCorpus element.""" event, elem = next(events) root = elem # store root for later instantiation while (event, elem.tag) not in [('start', 'igt'), ('end', 'xigt-corpus')]: event, elem = next(events) igts = None if event == 'start' a...
[ "def", "default_decode", "(", "events", ",", "mode", "=", "'full'", ")", ":", "event", ",", "elem", "=", "next", "(", "events", ")", "root", "=", "elem", "# store root for later instantiation", "while", "(", "event", ",", "elem", ".", "tag", ")", "not", ...
Decode a XigtCorpus element.
[ "Decode", "a", "XigtCorpus", "element", "." ]
3736fbb6d26887181de57bd189cbd731cec91289
https://github.com/xigt/xigt/blob/3736fbb6d26887181de57bd189cbd731cec91289/xigt/codecs/xigtxml.py#L212-L227
train
willkg/socorro-siggen
siggen/siglists_utils.py
_get_file_content
def _get_file_content(source): """Return a tuple, each value being a line of the source file. Remove empty lines and comments (lines starting with a '#'). """ filepath = os.path.join('siglists', source + '.txt') lines = [] with resource_stream(__name__, filepath) as f: for i, line in ...
python
def _get_file_content(source): """Return a tuple, each value being a line of the source file. Remove empty lines and comments (lines starting with a '#'). """ filepath = os.path.join('siglists', source + '.txt') lines = [] with resource_stream(__name__, filepath) as f: for i, line in ...
[ "def", "_get_file_content", "(", "source", ")", ":", "filepath", "=", "os", ".", "path", ".", "join", "(", "'siglists'", ",", "source", "+", "'.txt'", ")", "lines", "=", "[", "]", "with", "resource_stream", "(", "__name__", ",", "filepath", ")", "as", ...
Return a tuple, each value being a line of the source file. Remove empty lines and comments (lines starting with a '#').
[ "Return", "a", "tuple", "each", "value", "being", "a", "line", "of", "the", "source", "file", "." ]
db7e3233e665a458a961c48da22e93a69b1d08d6
https://github.com/willkg/socorro-siggen/blob/db7e3233e665a458a961c48da22e93a69b1d08d6/siggen/siglists_utils.py#L30-L61
train
JohnDoee/thomas
thomas/processors/rar.py
_get_rar_version
def _get_rar_version(xfile): """Check quickly whether file is rar archive. """ buf = xfile.read(len(RAR5_ID)) if buf.startswith(RAR_ID): return 3 elif buf.startswith(RAR5_ID): xfile.read(1) return 5 return 0
python
def _get_rar_version(xfile): """Check quickly whether file is rar archive. """ buf = xfile.read(len(RAR5_ID)) if buf.startswith(RAR_ID): return 3 elif buf.startswith(RAR5_ID): xfile.read(1) return 5 return 0
[ "def", "_get_rar_version", "(", "xfile", ")", ":", "buf", "=", "xfile", ".", "read", "(", "len", "(", "RAR5_ID", ")", ")", "if", "buf", ".", "startswith", "(", "RAR_ID", ")", ":", "return", "3", "elif", "buf", ".", "startswith", "(", "RAR5_ID", ")", ...
Check quickly whether file is rar archive.
[ "Check", "quickly", "whether", "file", "is", "rar", "archive", "." ]
51916dd110098b189a1c2fbcb71794fd9ec94832
https://github.com/JohnDoee/thomas/blob/51916dd110098b189a1c2fbcb71794fd9ec94832/thomas/processors/rar.py#L155-L164
train
JohnDoee/thomas
thomas/processors/rar.py
VirtualDirectReader._open_next
def _open_next(self): """Proceed to next volume.""" # is the file split over archives? if (self._cur.flags & rarfile.RAR_FILE_SPLIT_AFTER) == 0: return False if self._fd: self._fd.close() self._fd = None # open next part self._volfil...
python
def _open_next(self): """Proceed to next volume.""" # is the file split over archives? if (self._cur.flags & rarfile.RAR_FILE_SPLIT_AFTER) == 0: return False if self._fd: self._fd.close() self._fd = None # open next part self._volfil...
[ "def", "_open_next", "(", "self", ")", ":", "# is the file split over archives?", "if", "(", "self", ".", "_cur", ".", "flags", "&", "rarfile", ".", "RAR_FILE_SPLIT_AFTER", ")", "==", "0", ":", "return", "False", "if", "self", ".", "_fd", ":", "self", ".",...
Proceed to next volume.
[ "Proceed", "to", "next", "volume", "." ]
51916dd110098b189a1c2fbcb71794fd9ec94832
https://github.com/JohnDoee/thomas/blob/51916dd110098b189a1c2fbcb71794fd9ec94832/thomas/processors/rar.py#L168-L200
train
JohnDoee/thomas
thomas/processors/rar.py
VirtualDirectReader._check
def _check(self): # TODO: fix? """Do not check final CRC.""" if self._returncode: rarfile.check_returncode(self, '') if self._remain != 0: raise rarfile.BadRarFile("Failed the read enough data")
python
def _check(self): # TODO: fix? """Do not check final CRC.""" if self._returncode: rarfile.check_returncode(self, '') if self._remain != 0: raise rarfile.BadRarFile("Failed the read enough data")
[ "def", "_check", "(", "self", ")", ":", "# TODO: fix?", "if", "self", ".", "_returncode", ":", "rarfile", ".", "check_returncode", "(", "self", ",", "''", ")", "if", "self", ".", "_remain", "!=", "0", ":", "raise", "rarfile", ".", "BadRarFile", "(", "\...
Do not check final CRC.
[ "Do", "not", "check", "final", "CRC", "." ]
51916dd110098b189a1c2fbcb71794fd9ec94832
https://github.com/JohnDoee/thomas/blob/51916dd110098b189a1c2fbcb71794fd9ec94832/thomas/processors/rar.py#L202-L207
train
KnorrFG/pyparadigm
pyparadigm/extras.py
_normalize
def _normalize(mat: np.ndarray): """rescales a numpy array, so that min is 0 and max is 255""" return ((mat - mat.min()) * (255 / mat.max())).astype(np.uint8)
python
def _normalize(mat: np.ndarray): """rescales a numpy array, so that min is 0 and max is 255""" return ((mat - mat.min()) * (255 / mat.max())).astype(np.uint8)
[ "def", "_normalize", "(", "mat", ":", "np", ".", "ndarray", ")", ":", "return", "(", "(", "mat", "-", "mat", ".", "min", "(", ")", ")", "*", "(", "255", "/", "mat", ".", "max", "(", ")", ")", ")", ".", "astype", "(", "np", ".", "uint8", ")"...
rescales a numpy array, so that min is 0 and max is 255
[ "rescales", "a", "numpy", "array", "so", "that", "min", "is", "0", "and", "max", "is", "255" ]
69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/extras.py#L15-L17
train
KnorrFG/pyparadigm
pyparadigm/extras.py
to_24bit_gray
def to_24bit_gray(mat: np.ndarray): """returns a matrix that contains RGB channels, and colors scaled from 0 to 255""" return np.repeat(np.expand_dims(_normalize(mat), axis=2), 3, axis=2)
python
def to_24bit_gray(mat: np.ndarray): """returns a matrix that contains RGB channels, and colors scaled from 0 to 255""" return np.repeat(np.expand_dims(_normalize(mat), axis=2), 3, axis=2)
[ "def", "to_24bit_gray", "(", "mat", ":", "np", ".", "ndarray", ")", ":", "return", "np", ".", "repeat", "(", "np", ".", "expand_dims", "(", "_normalize", "(", "mat", ")", ",", "axis", "=", "2", ")", ",", "3", ",", "axis", "=", "2", ")" ]
returns a matrix that contains RGB channels, and colors scaled from 0 to 255
[ "returns", "a", "matrix", "that", "contains", "RGB", "channels", "and", "colors", "scaled", "from", "0", "to", "255" ]
69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/extras.py#L20-L23
train
KnorrFG/pyparadigm
pyparadigm/extras.py
apply_color_map
def apply_color_map(name: str, mat: np.ndarray = None): """returns an RGB matrix scaled by a matplotlib color map""" def apply_map(mat): return (cm.get_cmap(name)(_normalize(mat))[:, :, :3] * 255).astype(np.uint8) return apply_map if mat is None else apply_map(mat)
python
def apply_color_map(name: str, mat: np.ndarray = None): """returns an RGB matrix scaled by a matplotlib color map""" def apply_map(mat): return (cm.get_cmap(name)(_normalize(mat))[:, :, :3] * 255).astype(np.uint8) return apply_map if mat is None else apply_map(mat)
[ "def", "apply_color_map", "(", "name", ":", "str", ",", "mat", ":", "np", ".", "ndarray", "=", "None", ")", ":", "def", "apply_map", "(", "mat", ")", ":", "return", "(", "cm", ".", "get_cmap", "(", "name", ")", "(", "_normalize", "(", "mat", ")", ...
returns an RGB matrix scaled by a matplotlib color map
[ "returns", "an", "RGB", "matrix", "scaled", "by", "a", "matplotlib", "color", "map" ]
69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/extras.py#L26-L31
train
KnorrFG/pyparadigm
pyparadigm/extras.py
mat_to_surface
def mat_to_surface(mat: np.ndarray, transformer=to_24bit_gray): """Can be used to create a pygame.Surface from a 2d numpy array. By default a grey image with scaled colors is returned, but using the transformer argument any transformation can be used. :param mat: the matrix to create the surface of. ...
python
def mat_to_surface(mat: np.ndarray, transformer=to_24bit_gray): """Can be used to create a pygame.Surface from a 2d numpy array. By default a grey image with scaled colors is returned, but using the transformer argument any transformation can be used. :param mat: the matrix to create the surface of. ...
[ "def", "mat_to_surface", "(", "mat", ":", "np", ".", "ndarray", ",", "transformer", "=", "to_24bit_gray", ")", ":", "return", "pygame", ".", "pixelcopy", ".", "make_surface", "(", "transformer", "(", "mat", ".", "transpose", "(", ")", ")", "if", "transform...
Can be used to create a pygame.Surface from a 2d numpy array. By default a grey image with scaled colors is returned, but using the transformer argument any transformation can be used. :param mat: the matrix to create the surface of. :type mat: np.ndarray :param transformer: function that transfo...
[ "Can", "be", "used", "to", "create", "a", "pygame", ".", "Surface", "from", "a", "2d", "numpy", "array", "." ]
69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/extras.py#L34-L49
train
BlackEarth/bl
bl/id.py
random_id
def random_id(length=16, charset=alphanum_chars, first_charset=alpha_chars, sep='', group=0): """Creates a random id with the given length and charset. ## Parameters * length the number of characters in the id * charset what character set to use (a list of characters) * first_c...
python
def random_id(length=16, charset=alphanum_chars, first_charset=alpha_chars, sep='', group=0): """Creates a random id with the given length and charset. ## Parameters * length the number of characters in the id * charset what character set to use (a list of characters) * first_c...
[ "def", "random_id", "(", "length", "=", "16", ",", "charset", "=", "alphanum_chars", ",", "first_charset", "=", "alpha_chars", ",", "sep", "=", "''", ",", "group", "=", "0", ")", ":", "t", "=", "[", "]", "first_chars", "=", "list", "(", "set", "(", ...
Creates a random id with the given length and charset. ## Parameters * length the number of characters in the id * charset what character set to use (a list of characters) * first_charset what character set for the first character * sep='' what character to insert be...
[ "Creates", "a", "random", "id", "with", "the", "given", "length", "and", "charset", ".", "##", "Parameters", "*", "length", "the", "number", "of", "characters", "in", "the", "id", "*", "charset", "what", "character", "set", "to", "use", "(", "a", "list",...
edf6f37dac718987260b90ad0e7f7fe084a7c1a3
https://github.com/BlackEarth/bl/blob/edf6f37dac718987260b90ad0e7f7fe084a7c1a3/bl/id.py#L60-L82
train
michaeltcoelho/pagarme.py
pagarme/common/util.py
merge_dict
def merge_dict(data, *args): """Merge any number of dictionaries """ results = {} for current in (data,) + args: results.update(current) return results
python
def merge_dict(data, *args): """Merge any number of dictionaries """ results = {} for current in (data,) + args: results.update(current) return results
[ "def", "merge_dict", "(", "data", ",", "*", "args", ")", ":", "results", "=", "{", "}", "for", "current", "in", "(", "data", ",", ")", "+", "args", ":", "results", ".", "update", "(", "current", ")", "return", "results" ]
Merge any number of dictionaries
[ "Merge", "any", "number", "of", "dictionaries" ]
469fdd6e61e7c24a9eaf23d474d25316c3b5450b
https://github.com/michaeltcoelho/pagarme.py/blob/469fdd6e61e7c24a9eaf23d474d25316c3b5450b/pagarme/common/util.py#L5-L11
train
michaeltcoelho/pagarme.py
pagarme/common/util.py
make_url
def make_url(url, *paths): """Joins individual URL strings together, and returns a single string. """ for path in paths: url = re.sub(r'/?$', re.sub(r'^/?', '/', path), url) return url
python
def make_url(url, *paths): """Joins individual URL strings together, and returns a single string. """ for path in paths: url = re.sub(r'/?$', re.sub(r'^/?', '/', path), url) return url
[ "def", "make_url", "(", "url", ",", "*", "paths", ")", ":", "for", "path", "in", "paths", ":", "url", "=", "re", ".", "sub", "(", "r'/?$'", ",", "re", ".", "sub", "(", "r'^/?'", ",", "'/'", ",", "path", ")", ",", "url", ")", "return", "url" ]
Joins individual URL strings together, and returns a single string.
[ "Joins", "individual", "URL", "strings", "together", "and", "returns", "a", "single", "string", "." ]
469fdd6e61e7c24a9eaf23d474d25316c3b5450b
https://github.com/michaeltcoelho/pagarme.py/blob/469fdd6e61e7c24a9eaf23d474d25316c3b5450b/pagarme/common/util.py#L14-L19
train
Eyepea/tanto
monitoring_agent/outputs/email.py
Email.aggregate_result
def aggregate_result(self, return_code, output, service_description='', specific_servers=None): ''' aggregate result ''' if specific_servers == None: specific_servers = self.servers else: specific_servers = set(self.servers).intersection(specific_servers) ...
python
def aggregate_result(self, return_code, output, service_description='', specific_servers=None): ''' aggregate result ''' if specific_servers == None: specific_servers = self.servers else: specific_servers = set(self.servers).intersection(specific_servers) ...
[ "def", "aggregate_result", "(", "self", ",", "return_code", ",", "output", ",", "service_description", "=", "''", ",", "specific_servers", "=", "None", ")", ":", "if", "specific_servers", "==", "None", ":", "specific_servers", "=", "self", ".", "servers", "els...
aggregate result
[ "aggregate", "result" ]
ad8fd32e0fd3b7bc3dee5dabb984a2567ae46fe9
https://github.com/Eyepea/tanto/blob/ad8fd32e0fd3b7bc3dee5dabb984a2567ae46fe9/monitoring_agent/outputs/email.py#L35-L51
train
Eyepea/tanto
monitoring_agent/outputs/email.py
Email.send_results
def send_results(self): ''' send results ''' for server in self.servers: if self.servers[server]['results']: if len(self.servers[server]['results']) == 1: msg = MIMEText('') msg['Subject'] = '[%(custom_fqdn)s] [%(servic...
python
def send_results(self): ''' send results ''' for server in self.servers: if self.servers[server]['results']: if len(self.servers[server]['results']) == 1: msg = MIMEText('') msg['Subject'] = '[%(custom_fqdn)s] [%(servic...
[ "def", "send_results", "(", "self", ")", ":", "for", "server", "in", "self", ".", "servers", ":", "if", "self", ".", "servers", "[", "server", "]", "[", "'results'", "]", ":", "if", "len", "(", "self", ".", "servers", "[", "server", "]", "[", "'res...
send results
[ "send", "results" ]
ad8fd32e0fd3b7bc3dee5dabb984a2567ae46fe9
https://github.com/Eyepea/tanto/blob/ad8fd32e0fd3b7bc3dee5dabb984a2567ae46fe9/monitoring_agent/outputs/email.py#L53-L86
train
RobotStudio/bors
example.py
main
def main(): """MAIN""" config = { "api": { "services": [ { "name": "my_api", "testkey": "testval", }, ], "calls": { "hello_world": { "delay": 5, ...
python
def main(): """MAIN""" config = { "api": { "services": [ { "name": "my_api", "testkey": "testval", }, ], "calls": { "hello_world": { "delay": 5, ...
[ "def", "main", "(", ")", ":", "config", "=", "{", "\"api\"", ":", "{", "\"services\"", ":", "[", "{", "\"name\"", ":", "\"my_api\"", ",", "\"testkey\"", ":", "\"testval\"", ",", "}", ",", "]", ",", "\"calls\"", ":", "{", "\"hello_world\"", ":", "{", ...
MAIN
[ "MAIN" ]
38bf338fc6905d90819faa56bd832140116720f0
https://github.com/RobotStudio/bors/blob/38bf338fc6905d90819faa56bd832140116720f0/example.py#L104-L132
train
RobotStudio/bors
example.py
RequestSchema.make_request
def make_request(self, data): """Parse the outgoing schema""" sch = MockItemSchema() return Request(**{ "callname": self.context.get("callname"), "payload": sch.dump(data), })
python
def make_request(self, data): """Parse the outgoing schema""" sch = MockItemSchema() return Request(**{ "callname": self.context.get("callname"), "payload": sch.dump(data), })
[ "def", "make_request", "(", "self", ",", "data", ")", ":", "sch", "=", "MockItemSchema", "(", ")", "return", "Request", "(", "*", "*", "{", "\"callname\"", ":", "self", ".", "context", ".", "get", "(", "\"callname\"", ")", ",", "\"payload\"", ":", "sch...
Parse the outgoing schema
[ "Parse", "the", "outgoing", "schema" ]
38bf338fc6905d90819faa56bd832140116720f0
https://github.com/RobotStudio/bors/blob/38bf338fc6905d90819faa56bd832140116720f0/example.py#L58-L64
train
RobotStudio/bors
example.py
ResponseSchema.populate_data
def populate_data(self, data): """Parse the outgoing schema""" sch = MockItemSchema() return Result(**{ "callname": self.context.get("callname"), "result": sch.dump(data), })
python
def populate_data(self, data): """Parse the outgoing schema""" sch = MockItemSchema() return Result(**{ "callname": self.context.get("callname"), "result": sch.dump(data), })
[ "def", "populate_data", "(", "self", ",", "data", ")", ":", "sch", "=", "MockItemSchema", "(", ")", "return", "Result", "(", "*", "*", "{", "\"callname\"", ":", "self", ".", "context", ".", "get", "(", "\"callname\"", ")", ",", "\"result\"", ":", "sch"...
Parse the outgoing schema
[ "Parse", "the", "outgoing", "schema" ]
38bf338fc6905d90819faa56bd832140116720f0
https://github.com/RobotStudio/bors/blob/38bf338fc6905d90819faa56bd832140116720f0/example.py#L74-L80
train
KnorrFG/pyparadigm
pyparadigm/eventlistener.py
Handler.key_press
def key_press(keys): """returns a handler that can be used with EventListener.listen() and returns when a key in keys is pressed""" return lambda e: e.key if e.type == pygame.KEYDOWN \ and e.key in keys else EventConsumerInfo.DONT_CARE
python
def key_press(keys): """returns a handler that can be used with EventListener.listen() and returns when a key in keys is pressed""" return lambda e: e.key if e.type == pygame.KEYDOWN \ and e.key in keys else EventConsumerInfo.DONT_CARE
[ "def", "key_press", "(", "keys", ")", ":", "return", "lambda", "e", ":", "e", ".", "key", "if", "e", ".", "type", "==", "pygame", ".", "KEYDOWN", "and", "e", ".", "key", "in", "keys", "else", "EventConsumerInfo", ".", "DONT_CARE" ]
returns a handler that can be used with EventListener.listen() and returns when a key in keys is pressed
[ "returns", "a", "handler", "that", "can", "be", "used", "with", "EventListener", ".", "listen", "()", "and", "returns", "when", "a", "key", "in", "keys", "is", "pressed" ]
69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/eventlistener.py#L70-L74
train
KnorrFG/pyparadigm
pyparadigm/eventlistener.py
Handler.unicode_char
def unicode_char(ignored_chars=None): """returns a handler that listens for unicode characters""" return lambda e: e.unicode if e.type == pygame.KEYDOWN \ and ((ignored_chars is None) or (e.unicode not in ignored_chars))\ else EventConsumerInfo.DONT_CARE
python
def unicode_char(ignored_chars=None): """returns a handler that listens for unicode characters""" return lambda e: e.unicode if e.type == pygame.KEYDOWN \ and ((ignored_chars is None) or (e.unicode not in ignored_chars))\ else EventConsumerInfo.DONT_CARE
[ "def", "unicode_char", "(", "ignored_chars", "=", "None", ")", ":", "return", "lambda", "e", ":", "e", ".", "unicode", "if", "e", ".", "type", "==", "pygame", ".", "KEYDOWN", "and", "(", "(", "ignored_chars", "is", "None", ")", "or", "(", "e", ".", ...
returns a handler that listens for unicode characters
[ "returns", "a", "handler", "that", "listens", "for", "unicode", "characters" ]
69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/eventlistener.py#L77-L82
train
KnorrFG/pyparadigm
pyparadigm/eventlistener.py
EventListener.mouse_area
def mouse_area(self, handler, group=0, ident=None): """Adds a new MouseProxy for the given group to the EventListener.mouse_proxies dict if it is not in there yet, and returns the (new) MouseProxy. In listen() all entries in the current group of mouse_proxies are used.""" key = ...
python
def mouse_area(self, handler, group=0, ident=None): """Adds a new MouseProxy for the given group to the EventListener.mouse_proxies dict if it is not in there yet, and returns the (new) MouseProxy. In listen() all entries in the current group of mouse_proxies are used.""" key = ...
[ "def", "mouse_area", "(", "self", ",", "handler", ",", "group", "=", "0", ",", "ident", "=", "None", ")", ":", "key", "=", "ident", "or", "id", "(", "handler", ")", "if", "key", "not", "in", "self", ".", "mouse_proxies", "[", "group", "]", ":", "...
Adds a new MouseProxy for the given group to the EventListener.mouse_proxies dict if it is not in there yet, and returns the (new) MouseProxy. In listen() all entries in the current group of mouse_proxies are used.
[ "Adds", "a", "new", "MouseProxy", "for", "the", "given", "group", "to", "the", "EventListener", ".", "mouse_proxies", "dict", "if", "it", "is", "not", "in", "there", "yet", "and", "returns", "the", "(", "new", ")", "MouseProxy", ".", "In", "listen", "()"...
69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/eventlistener.py#L167-L175
train
KnorrFG/pyparadigm
pyparadigm/eventlistener.py
EventListener.listen
def listen(self, *temporary_handlers): """When listen() is called all queued pygame.Events will be passed to all registered listeners. There are two ways to register a listener: 1. as a permanent listener, that is always executed for every event. These are registered by passing the ...
python
def listen(self, *temporary_handlers): """When listen() is called all queued pygame.Events will be passed to all registered listeners. There are two ways to register a listener: 1. as a permanent listener, that is always executed for every event. These are registered by passing the ...
[ "def", "listen", "(", "self", ",", "*", "temporary_handlers", ")", ":", "funcs", "=", "tuple", "(", "itt", ".", "chain", "(", "self", ".", "permanent_handlers", ",", "(", "proxy", ".", "listener", "for", "proxy", "in", "self", ".", "mouse_proxies", "[", ...
When listen() is called all queued pygame.Events will be passed to all registered listeners. There are two ways to register a listener: 1. as a permanent listener, that is always executed for every event. These are registered by passing the handler-functions during construction 2. ...
[ "When", "listen", "()", "is", "called", "all", "queued", "pygame", ".", "Events", "will", "be", "passed", "to", "all", "registered", "listeners", ".", "There", "are", "two", "ways", "to", "register", "a", "listener", ":" ]
69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/eventlistener.py#L183-L225
train
KnorrFG/pyparadigm
pyparadigm/eventlistener.py
EventListener.listen_until_return
def listen_until_return(self, *temporary_handlers, timeout=0): """Calls listen repeatedly until listen returns something else than None. Then returns listen's result. If timeout is not zero listen_until_return stops after timeout seconds and returns None.""" start = time.time() w...
python
def listen_until_return(self, *temporary_handlers, timeout=0): """Calls listen repeatedly until listen returns something else than None. Then returns listen's result. If timeout is not zero listen_until_return stops after timeout seconds and returns None.""" start = time.time() w...
[ "def", "listen_until_return", "(", "self", ",", "*", "temporary_handlers", ",", "timeout", "=", "0", ")", ":", "start", "=", "time", ".", "time", "(", ")", "while", "timeout", "==", "0", "or", "time", ".", "time", "(", ")", "-", "start", "<", "timeou...
Calls listen repeatedly until listen returns something else than None. Then returns listen's result. If timeout is not zero listen_until_return stops after timeout seconds and returns None.
[ "Calls", "listen", "repeatedly", "until", "listen", "returns", "something", "else", "than", "None", ".", "Then", "returns", "listen", "s", "result", ".", "If", "timeout", "is", "not", "zero", "listen_until_return", "stops", "after", "timeout", "seconds", "and", ...
69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/eventlistener.py#L227-L235
train
KnorrFG/pyparadigm
pyparadigm/eventlistener.py
EventListener.wait_for_n_keypresses
def wait_for_n_keypresses(self, key, n=1): """Waits till one key was pressed n times. :param key: the key to be pressed as defined by pygame. E.g. pygame.K_LEFT for the left arrow key :type key: int :param n: number of repetitions till the function returns :type n: i...
python
def wait_for_n_keypresses(self, key, n=1): """Waits till one key was pressed n times. :param key: the key to be pressed as defined by pygame. E.g. pygame.K_LEFT for the left arrow key :type key: int :param n: number of repetitions till the function returns :type n: i...
[ "def", "wait_for_n_keypresses", "(", "self", ",", "key", ",", "n", "=", "1", ")", ":", "my_const", "=", "\"key_consumed\"", "counter", "=", "0", "def", "keypress_listener", "(", "e", ")", ":", "return", "my_const", "if", "e", ".", "type", "==", "pygame",...
Waits till one key was pressed n times. :param key: the key to be pressed as defined by pygame. E.g. pygame.K_LEFT for the left arrow key :type key: int :param n: number of repetitions till the function returns :type n: int
[ "Waits", "till", "one", "key", "was", "pressed", "n", "times", "." ]
69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/eventlistener.py#L237-L255
train
KnorrFG/pyparadigm
pyparadigm/eventlistener.py
EventListener.wait_for_keys
def wait_for_keys(self, *keys, timeout=0): """Waits until one of the specified keys was pressed, and returns which key was pressed. :param keys: iterable of integers of pygame-keycodes, or simply multiple keys passed via multiple arguments :type keys: iterable :par...
python
def wait_for_keys(self, *keys, timeout=0): """Waits until one of the specified keys was pressed, and returns which key was pressed. :param keys: iterable of integers of pygame-keycodes, or simply multiple keys passed via multiple arguments :type keys: iterable :par...
[ "def", "wait_for_keys", "(", "self", ",", "*", "keys", ",", "timeout", "=", "0", ")", ":", "if", "len", "(", "keys", ")", "==", "1", "and", "_is_iterable", "(", "keys", "[", "0", "]", ")", ":", "keys", "=", "keys", "[", "0", "]", "return", "sel...
Waits until one of the specified keys was pressed, and returns which key was pressed. :param keys: iterable of integers of pygame-keycodes, or simply multiple keys passed via multiple arguments :type keys: iterable :param timeout: number of seconds to wait till the functio...
[ "Waits", "until", "one", "of", "the", "specified", "keys", "was", "pressed", "and", "returns", "which", "key", "was", "pressed", "." ]
69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/eventlistener.py#L257-L273
train
KnorrFG/pyparadigm
pyparadigm/eventlistener.py
EventListener.wait_for_keys_modified
def wait_for_keys_modified(self, *keys, modifiers_to_check=_mod_keys, timeout=0): """The same as wait_for_keys, but returns a frozen_set which contains the pressed key, and the modifier keys. :param modifiers_to_check: iterable of modifiers for which the function...
python
def wait_for_keys_modified(self, *keys, modifiers_to_check=_mod_keys, timeout=0): """The same as wait_for_keys, but returns a frozen_set which contains the pressed key, and the modifier keys. :param modifiers_to_check: iterable of modifiers for which the function...
[ "def", "wait_for_keys_modified", "(", "self", ",", "*", "keys", ",", "modifiers_to_check", "=", "_mod_keys", ",", "timeout", "=", "0", ")", ":", "set_mods", "=", "pygame", ".", "key", ".", "get_mods", "(", ")", "return", "frozenset", ".", "union", "(", "...
The same as wait_for_keys, but returns a frozen_set which contains the pressed key, and the modifier keys. :param modifiers_to_check: iterable of modifiers for which the function will check whether they are pressed :type modifiers: Iterable[int]
[ "The", "same", "as", "wait_for_keys", "but", "returns", "a", "frozen_set", "which", "contains", "the", "pressed", "key", "and", "the", "modifier", "keys", "." ]
69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/eventlistener.py#L275-L288
train
KnorrFG/pyparadigm
pyparadigm/eventlistener.py
EventListener.wait_for_unicode_char
def wait_for_unicode_char(self, ignored_chars=None, timeout=0): """Returns a str that contains the single character that was pressed. This already respects modifier keys and keyboard layouts. If timeout is not none and no key is pressed within the specified timeout, None is returned. If ...
python
def wait_for_unicode_char(self, ignored_chars=None, timeout=0): """Returns a str that contains the single character that was pressed. This already respects modifier keys and keyboard layouts. If timeout is not none and no key is pressed within the specified timeout, None is returned. If ...
[ "def", "wait_for_unicode_char", "(", "self", ",", "ignored_chars", "=", "None", ",", "timeout", "=", "0", ")", ":", "return", "self", ".", "listen_until_return", "(", "Handler", ".", "unicode_char", "(", "ignored_chars", ")", ",", "timeout", "=", "timeout", ...
Returns a str that contains the single character that was pressed. This already respects modifier keys and keyboard layouts. If timeout is not none and no key is pressed within the specified timeout, None is returned. If a key is ingnored_chars it will be ignored. As argument for irgnore...
[ "Returns", "a", "str", "that", "contains", "the", "single", "character", "that", "was", "pressed", ".", "This", "already", "respects", "modifier", "keys", "and", "keyboard", "layouts", ".", "If", "timeout", "is", "not", "none", "and", "no", "key", "is", "p...
69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/eventlistener.py#L295-L303
train
JohnDoee/thomas
thomas/streamers/rar.py
RarStreamer._find_all_first_files
def _find_all_first_files(self, item): """ Does not support the full range of ways rar can split as it'd require reading the file to ensure you are using the correct way. """ for listed_item in item.list(): new_style = re.findall(r'(?i)\.part(\d+)\.rar^', list...
python
def _find_all_first_files(self, item): """ Does not support the full range of ways rar can split as it'd require reading the file to ensure you are using the correct way. """ for listed_item in item.list(): new_style = re.findall(r'(?i)\.part(\d+)\.rar^', list...
[ "def", "_find_all_first_files", "(", "self", ",", "item", ")", ":", "for", "listed_item", "in", "item", ".", "list", "(", ")", ":", "new_style", "=", "re", ".", "findall", "(", "r'(?i)\\.part(\\d+)\\.rar^'", ",", "listed_item", ".", "id", ")", "if", "new_s...
Does not support the full range of ways rar can split as it'd require reading the file to ensure you are using the correct way.
[ "Does", "not", "support", "the", "full", "range", "of", "ways", "rar", "can", "split", "as", "it", "d", "require", "reading", "the", "file", "to", "ensure", "you", "are", "using", "the", "correct", "way", "." ]
51916dd110098b189a1c2fbcb71794fd9ec94832
https://github.com/JohnDoee/thomas/blob/51916dd110098b189a1c2fbcb71794fd9ec94832/thomas/streamers/rar.py#L15-L27
train