nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
laszukdawid/PyEMD
9caf51c6cd1bc1e869d67d002310c1e81cba541a
PyEMD/CEEMDAN.py
python
CEEMDAN.end_condition
(self, S: np.ndarray, cIMFs: np.ndarray, max_imf: int)
return False
Test for end condition of CEEMDAN. Procedure stops if: * number of components reach provided `max_imf`, or * last component is close to being pure noise (range or power), or * set of provided components reconstructs sufficiently input. Parameters ---------- S : numpy array Original signal on which CEEMDAN was performed. cIMFs : numpy 2D array Set of cIMFs where each row is cIMF. max_imf : int The maximum number of imfs to extract. Returns ------- end : bool Whether to stop CEEMDAN.
Test for end condition of CEEMDAN.
[ "Test", "for", "end", "condition", "of", "CEEMDAN", "." ]
def end_condition(self, S: np.ndarray, cIMFs: np.ndarray, max_imf: int) -> bool: """Test for end condition of CEEMDAN. Procedure stops if: * number of components reach provided `max_imf`, or * last component is close to being pure noise (range or power), or * set of provided components reconstructs sufficiently input. Parameters ---------- S : numpy array Original signal on which CEEMDAN was performed. cIMFs : numpy 2D array Set of cIMFs where each row is cIMF. max_imf : int The maximum number of imfs to extract. Returns ------- end : bool Whether to stop CEEMDAN. """ imfNo = cIMFs.shape[0] # Check if hit maximum number of cIMFs if 0 < max_imf <= imfNo: return True # Compute EMD on residue R = S - np.sum(cIMFs, axis=0) _test_imf = self.emd(R, None, max_imf=1) # Check if residue is IMF or no extrema if _test_imf.shape[0] == 1: self.logger.debug("Not enough extrema") return True # Check for range threshold if np.max(R) - np.min(R) < self.range_thr: self.logger.debug("FINISHED -- RANGE") return True # Check for power threshold if np.sum(np.abs(R)) < self.total_power_thr: self.logger.debug("FINISHED -- SUM POWER") return True return False
[ "def", "end_condition", "(", "self", ",", "S", ":", "np", ".", "ndarray", ",", "cIMFs", ":", "np", ".", "ndarray", ",", "max_imf", ":", "int", ")", "->", "bool", ":", "imfNo", "=", "cIMFs", ".", "shape", "[", "0", "]", "# Check if hit maximum number of...
https://github.com/laszukdawid/PyEMD/blob/9caf51c6cd1bc1e869d67d002310c1e81cba541a/PyEMD/CEEMDAN.py#L265-L313
microsoft/debugpy
be8dd607f6837244e0b565345e497aff7a0c08bf
src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_console.py
python
DebugConsole.runcode
(self, code)
Execute a code object. When an exception occurs, self.showtraceback() is called to display a traceback. All exceptions are caught except SystemExit, which is reraised. A note about KeyboardInterrupt: this exception may occur elsewhere in this code, and may not always be caught. The caller should be prepared to deal with it.
Execute a code object.
[ "Execute", "a", "code", "object", "." ]
def runcode(self, code): """Execute a code object. When an exception occurs, self.showtraceback() is called to display a traceback. All exceptions are caught except SystemExit, which is reraised. A note about KeyboardInterrupt: this exception may occur elsewhere in this code, and may not always be caught. The caller should be prepared to deal with it. """ try: Exec(code, self.frame.f_globals, self.frame.f_locals) pydevd_save_locals.save_locals(self.frame) except SystemExit: raise except: # In case sys.excepthook called, use original excepthook #PyDev-877: Debug console freezes with Python 3.5+ # (showtraceback does it on python 3.5 onwards) sys.excepthook = sys.__excepthook__ try: self.showtraceback() finally: sys.__excepthook__ = sys.excepthook
[ "def", "runcode", "(", "self", ",", "code", ")", ":", "try", ":", "Exec", "(", "code", ",", "self", ".", "frame", ".", "f_globals", ",", "self", ".", "frame", ".", "f_locals", ")", "pydevd_save_locals", ".", "save_locals", "(", "self", ".", "frame", ...
https://github.com/microsoft/debugpy/blob/be8dd607f6837244e0b565345e497aff7a0c08bf/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_console.py#L142-L166
jeanfeydy/geomloss
e0c52369ddd489e66ead204a43b7af4a3509924c
geomloss/examples/sinkhorn_multiscale/plot_epsilon_scaling.py
python
display_scaling
(scaling=0.5, Nits=9, debias=True)
[]
def display_scaling(scaling=0.5, Nits=9, debias=True): plt.figure(figsize=((12, ((Nits - 1) // 3 + 1) * 4))) for i in range(Nits): blur = scaling ** i Loss = SamplesLoss( "sinkhorn", p=2, blur=blur, diameter=1.0, scaling=scaling, debias=debias ) # Create a copy of the data... a_i, x_i = A_i.clone(), X_i.clone() b_j, y_j = B_j.clone(), Y_j.clone() # And require grad: a_i.requires_grad = True x_i.requires_grad = True b_j.requires_grad = True # Compute the loss + gradients: Loss_xy = Loss(a_i, x_i, b_j, y_j) [F_i, G_j, dx_i] = grad(Loss_xy, [a_i, b_j, x_i]) #  The generalized "Brenier map" is (minus) the gradient of the Sinkhorn loss # with respect to the Wasserstein metric: BrenierMap = -dx_i / (a_i.view(-1, 1) + 1e-7) # Fancy display: ----------------------------------------------------------- ax = plt.subplot(((Nits - 1) // 3 + 1), 3, i + 1) ax.scatter([10], [10]) # shameless hack to prevent a slight change of axis... display_potential(ax, G_j, "#E2C5C5") display_potential(ax, F_i, "#C8DFF9") display_samples(ax, y_j, b_j, [(0.55, 0.55, 0.95)]) display_samples(ax, x_i, a_i, [(0.95, 0.55, 0.55)], v=BrenierMap) ax.set_title("iteration {}, blur = {:.3f}".format(i + 1, blur)) ax.set_xticks([0, 1]) ax.set_yticks([0, 1]) ax.axis([0, 1, 0, 1]) ax.set_aspect("equal", adjustable="box") plt.tight_layout()
[ "def", "display_scaling", "(", "scaling", "=", "0.5", ",", "Nits", "=", "9", ",", "debias", "=", "True", ")", ":", "plt", ".", "figure", "(", "figsize", "=", "(", "(", "12", ",", "(", "(", "Nits", "-", "1", ")", "//", "3", "+", "1", ")", "*",...
https://github.com/jeanfeydy/geomloss/blob/e0c52369ddd489e66ead204a43b7af4a3509924c/geomloss/examples/sinkhorn_multiscale/plot_epsilon_scaling.py#L205-L249
jazzband/djangorestframework-simplejwt
8b22bf7f553523270b6c6a1fa290dc8c3a088d54
rest_framework_simplejwt/serializers.py
python
TokenObtainSerializer.__init__
(self, *args, **kwargs)
[]
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields[self.username_field] = serializers.CharField() self.fields["password"] = PasswordField()
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", ")", ".", "__init__", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "fields", "[", "self", ".", "username_field", "]", "=", "seriali...
https://github.com/jazzband/djangorestframework-simplejwt/blob/8b22bf7f553523270b6c6a1fa290dc8c3a088d54/rest_framework_simplejwt/serializers.py#L32-L36
cuthbertLab/music21
bd30d4663e52955ed922c10fdf541419d8c67671
music21/stream/base.py
python
Stream.beatDuration
(self)
return None
unlike other Music21Objects, streams always have beatDuration of None
unlike other Music21Objects, streams always have beatDuration of None
[ "unlike", "other", "Music21Objects", "streams", "always", "have", "beatDuration", "of", "None" ]
def beatDuration(self): ''' unlike other Music21Objects, streams always have beatDuration of None ''' # this returns the duration of the active beat return None
[ "def", "beatDuration", "(", "self", ")", ":", "# this returns the duration of the active beat", "return", "None" ]
https://github.com/cuthbertLab/music21/blob/bd30d4663e52955ed922c10fdf541419d8c67671/music21/stream/base.py#L8698-L8703
phil-bergmann/tracking_wo_bnw
72ee403de01c472f6eb5cde60b56b86aa6a617c8
src/tracktor/datasets/mot_wrapper.py
python
MOT17Wrapper.__init__
(self, split, dets, dataloader)
Initliazes all subset of the dataset. Keyword arguments: split -- the split of the dataset to use dataloader -- args for the MOT_Sequence dataloader
Initliazes all subset of the dataset.
[ "Initliazes", "all", "subset", "of", "the", "dataset", "." ]
def __init__(self, split, dets, dataloader): """Initliazes all subset of the dataset. Keyword arguments: split -- the split of the dataset to use dataloader -- args for the MOT_Sequence dataloader """ mot_dir = 'MOT17' train_sequences = ['MOT17-02', 'MOT17-04', 'MOT17-05', 'MOT17-09', 'MOT17-10', 'MOT17-11', 'MOT17-13'] test_sequences = ['MOT17-01', 'MOT17-03', 'MOT17-06', 'MOT17-07', 'MOT17-08', 'MOT17-12', 'MOT17-14'] if "train" == split: sequences = train_sequences elif "test" == split: sequences = test_sequences elif "all" == split: sequences = train_sequences + test_sequences elif '3_fold' in split: if '_1' in split and 'train' in split: sequences = ['MOT17-04', 'MOT17-05', 'MOT17-09', 'MOT17-11'] elif '_1' in split and 'val' in split: sequences = ['MOT17-02', 'MOT17-10', 'MOT17-13'] elif '_2' in split and 'train' in split: sequences = ['MOT17-02', 'MOT17-05', 'MOT17-09', 'MOT17-10', 'MOT17-13'] elif '_2' in split and 'val' in split: sequences = ['MOT17-04', 'MOT17-11'] elif '_3' in split and 'train' in split: sequences = ['MOT17-02', 'MOT17-04', 'MOT17-10', 'MOT17-11', 'MOT17-13'] elif '_3' in split and 'val' in split: sequences = ['MOT17-05', 'MOT17-09'] else: raise NotImplementedError("MOT split not available.") elif f"MOT17-{split}" in train_sequences + test_sequences: sequences = [f"MOT17-{split}"] else: raise NotImplementedError("MOT split not available.") self._data = [] for s in sequences: if dets == 'ALL': self._data.append(MOTSequence(f"{s}-DPM", mot_dir, **dataloader)) self._data.append(MOTSequence(f"{s}-FRCNN", mot_dir, **dataloader)) self._data.append(MOTSequence(f"{s}-SDP", mot_dir, **dataloader)) elif dets == 'DPM16': self._data.append(MOTSequence(s.replace('17', '16'), 'MOT16', **dataloader)) else: self._data.append(MOTSequence(f"{s}-{dets}", mot_dir, **dataloader))
[ "def", "__init__", "(", "self", ",", "split", ",", "dets", ",", "dataloader", ")", ":", "mot_dir", "=", "'MOT17'", "train_sequences", "=", "[", "'MOT17-02'", ",", "'MOT17-04'", ",", "'MOT17-05'", ",", "'MOT17-09'", ",", "'MOT17-10'", ",", "'MOT17-11'", ",", ...
https://github.com/phil-bergmann/tracking_wo_bnw/blob/72ee403de01c472f6eb5cde60b56b86aa6a617c8/src/tracktor/datasets/mot_wrapper.py#L12-L59
snowflakedb/snowflake-connector-python
1659ec6b78930d1f947b4eff985c891af614d86c
src/snowflake/connector/result_batch.py
python
JSONResultBatch._load
(self, response: "Response")
return json.loads("".join(["[", read_data, "]"]))
This function loads a compressed JSON file into memory. Returns: Whatever ``json.loads`` return, but in a list. Unfortunately there's not type hint for this. For context: https://github.com/python/typing/issues/182
This function loads a compressed JSON file into memory.
[ "This", "function", "loads", "a", "compressed", "JSON", "file", "into", "memory", "." ]
def _load(self, response: "Response") -> List: """This function loads a compressed JSON file into memory. Returns: Whatever ``json.loads`` return, but in a list. Unfortunately there's not type hint for this. For context: https://github.com/python/typing/issues/182 """ read_data = response.text return json.loads("".join(["[", read_data, "]"]))
[ "def", "_load", "(", "self", ",", "response", ":", "\"Response\"", ")", "->", "List", ":", "read_data", "=", "response", ".", "text", "return", "json", ".", "loads", "(", "\"\"", ".", "join", "(", "[", "\"[\"", ",", "read_data", ",", "\"]\"", "]", ")...
https://github.com/snowflakedb/snowflake-connector-python/blob/1659ec6b78930d1f947b4eff985c891af614d86c/src/snowflake/connector/result_batch.py#L440-L449
pyvista/pyvista
012dbb95a9aae406c3cd4cd94fc8c477f871e426
pyvista/examples/downloads.py
python
download_structured_grid_two
(load=True)
return _download_and_read('SampleStructGrid.vtk', load=load)
Download structured grid two dataset. Parameters ---------- load : bool, optional Load the dataset after downloading it when ``True``. Set this to ``False`` and only the filename will be returned. Returns ------- pyvista.StructuredGrid or str DataSet or filename depending on ``load``. Examples -------- >>> from pyvista import examples >>> dataset = examples.download_structured_grid_two() >>> dataset.plot(show_edges=True)
Download structured grid two dataset.
[ "Download", "structured", "grid", "two", "dataset", "." ]
def download_structured_grid_two(load=True): # pragma: no cover """Download structured grid two dataset. Parameters ---------- load : bool, optional Load the dataset after downloading it when ``True``. Set this to ``False`` and only the filename will be returned. Returns ------- pyvista.StructuredGrid or str DataSet or filename depending on ``load``. Examples -------- >>> from pyvista import examples >>> dataset = examples.download_structured_grid_two() >>> dataset.plot(show_edges=True) """ return _download_and_read('SampleStructGrid.vtk', load=load)
[ "def", "download_structured_grid_two", "(", "load", "=", "True", ")", ":", "# pragma: no cover", "return", "_download_and_read", "(", "'SampleStructGrid.vtk'", ",", "load", "=", "load", ")" ]
https://github.com/pyvista/pyvista/blob/012dbb95a9aae406c3cd4cd94fc8c477f871e426/pyvista/examples/downloads.py#L1728-L1749
IntelLabs/coach
dea46ae0d22b0a0cd30b9fc138a4a2642e1b9d9d
rl_coach/utils.py
python
stack_observation
(curr_stack, observation, stack_size)
return curr_stack
Adds a new observation to an existing stack of observations from previous time-steps. :param curr_stack: The current observations stack. :param observation: The new observation :param stack_size: The required stack size :return: The updated observation stack
Adds a new observation to an existing stack of observations from previous time-steps. :param curr_stack: The current observations stack. :param observation: The new observation :param stack_size: The required stack size :return: The updated observation stack
[ "Adds", "a", "new", "observation", "to", "an", "existing", "stack", "of", "observations", "from", "previous", "time", "-", "steps", ".", ":", "param", "curr_stack", ":", "The", "current", "observations", "stack", ".", ":", "param", "observation", ":", "The",...
def stack_observation(curr_stack, observation, stack_size): """ Adds a new observation to an existing stack of observations from previous time-steps. :param curr_stack: The current observations stack. :param observation: The new observation :param stack_size: The required stack size :return: The updated observation stack """ if curr_stack == []: # starting an episode curr_stack = np.vstack(np.expand_dims([observation] * stack_size, 0)) curr_stack = switch_axes_order(curr_stack, from_type='channels_first', to_type='channels_last') else: curr_stack = np.append(curr_stack, np.expand_dims(np.squeeze(observation), axis=-1), axis=-1) curr_stack = np.delete(curr_stack, 0, -1) return curr_stack
[ "def", "stack_observation", "(", "curr_stack", ",", "observation", ",", "stack_size", ")", ":", "if", "curr_stack", "==", "[", "]", ":", "# starting an episode", "curr_stack", "=", "np", ".", "vstack", "(", "np", ".", "expand_dims", "(", "[", "observation", ...
https://github.com/IntelLabs/coach/blob/dea46ae0d22b0a0cd30b9fc138a4a2642e1b9d9d/rl_coach/utils.py#L276-L293
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/packages/site-packages/sqlalchemy/orm/events.py
python
AttributeEvents.init_collection
(self, target, collection, collection_adapter)
Receive a 'collection init' event. This event is triggered for a collection-based attribute, when the initial "empty collection" is first generated for a blank attribute, as well as for when the collection is replaced with a new one, such as via a set event. E.g., given that ``User.addresses`` is a relationship-based collection, the event is triggered here:: u1 = User() u1.addresses.append(a1) # <- new collection and also during replace operations:: u1.addresses = [a2, a3] # <- new collection :param target: the object instance receiving the event. If the listener is registered with ``raw=True``, this will be the :class:`.InstanceState` object. :param collection: the new collection. This will always be generated from what was specified as :paramref:`.RelationshipProperty.collection_class`, and will always be empty. :param collection_adpater: the :class:`.CollectionAdapter` that will mediate internal access to the collection. .. versionadded:: 1.0.0 the :meth:`.AttributeEvents.init_collection` and :meth:`.AttributeEvents.dispose_collection` events supersede the :class:`.collection.linker` hook.
Receive a 'collection init' event.
[ "Receive", "a", "collection", "init", "event", "." ]
def init_collection(self, target, collection, collection_adapter): """Receive a 'collection init' event. This event is triggered for a collection-based attribute, when the initial "empty collection" is first generated for a blank attribute, as well as for when the collection is replaced with a new one, such as via a set event. E.g., given that ``User.addresses`` is a relationship-based collection, the event is triggered here:: u1 = User() u1.addresses.append(a1) # <- new collection and also during replace operations:: u1.addresses = [a2, a3] # <- new collection :param target: the object instance receiving the event. If the listener is registered with ``raw=True``, this will be the :class:`.InstanceState` object. :param collection: the new collection. This will always be generated from what was specified as :paramref:`.RelationshipProperty.collection_class`, and will always be empty. :param collection_adpater: the :class:`.CollectionAdapter` that will mediate internal access to the collection. .. versionadded:: 1.0.0 the :meth:`.AttributeEvents.init_collection` and :meth:`.AttributeEvents.dispose_collection` events supersede the :class:`.collection.linker` hook. """
[ "def", "init_collection", "(", "self", ",", "target", ",", "collection", ",", "collection_adapter", ")", ":" ]
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/packages/site-packages/sqlalchemy/orm/events.py#L1697-L1729
wummel/linkchecker
c2ce810c3fb00b895a841a7be6b2e78c64e7b042
linkcheck/checker/ignoreurl.py
python
IgnoreUrl.is_ignored
(self)
return True
Return True if this URL scheme is ignored.
Return True if this URL scheme is ignored.
[ "Return", "True", "if", "this", "URL", "scheme", "is", "ignored", "." ]
def is_ignored (self): """Return True if this URL scheme is ignored.""" return True
[ "def", "is_ignored", "(", "self", ")", ":", "return", "True" ]
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/checker/ignoreurl.py#L26-L28
TengXiaoDai/DistributedCrawling
f5c2439e6ce68dd9b49bde084d76473ff9ed4963
Lib/site-packages/setuptools/command/alias.py
python
shquote
(arg)
return arg
Quote an argument for later parsing by shlex.split()
Quote an argument for later parsing by shlex.split()
[ "Quote", "an", "argument", "for", "later", "parsing", "by", "shlex", ".", "split", "()" ]
def shquote(arg): """Quote an argument for later parsing by shlex.split()""" for c in '"', "'", "\\", "#": if c in arg: return repr(arg) if arg.split() != [arg]: return repr(arg) return arg
[ "def", "shquote", "(", "arg", ")", ":", "for", "c", "in", "'\"'", ",", "\"'\"", ",", "\"\\\\\"", ",", "\"#\"", ":", "if", "c", "in", "arg", ":", "return", "repr", "(", "arg", ")", "if", "arg", ".", "split", "(", ")", "!=", "[", "arg", "]", ":...
https://github.com/TengXiaoDai/DistributedCrawling/blob/f5c2439e6ce68dd9b49bde084d76473ff9ed4963/Lib/site-packages/setuptools/command/alias.py#L8-L15
pgmpy/pgmpy
24279929a28082ea994c52f3d165ca63fc56b02b
pgmpy/models/SEM.py
python
SEMGraph.__standard_lisrel_masks
(graph, err_graph, weight, var)
return { "B": B_mask, "gamma": gamma_mask, "wedge_y": wedge_y_mask, "wedge_x": wedge_x_mask, "phi": phi_mask, "theta_e": theta_e_mask, "theta_del": theta_del_mask, "psi": psi_mask, }
This method is called by `get_fixed_masks` and `get_masks` methods. Parameters ---------- weight: None | 'weight' If None: Returns a 1.0 for an edge in the graph else 0.0 If 'weight': Returns the weight if a weight is assigned to an edge else 0.0 var: dict Dict with keys eta, xi, y, and x representing the variables in them. Returns ------- np.ndarray: Adjecency matrix of model's graph structure. Notes ----- B: Effect matrix of eta on eta \gamma: Effect matrix of xi on eta \wedge_y: Effect matrix of eta on y \wedge_x: Effect matrix of xi on x \phi: Covariance matrix of xi \psi: Covariance matrix of eta errors \theta_e: Covariance matrix of y errors \theta_del: Covariance matrix of x errors Examples --------
This method is called by `get_fixed_masks` and `get_masks` methods.
[ "This", "method", "is", "called", "by", "get_fixed_masks", "and", "get_masks", "methods", "." ]
def __standard_lisrel_masks(graph, err_graph, weight, var): """ This method is called by `get_fixed_masks` and `get_masks` methods. Parameters ---------- weight: None | 'weight' If None: Returns a 1.0 for an edge in the graph else 0.0 If 'weight': Returns the weight if a weight is assigned to an edge else 0.0 var: dict Dict with keys eta, xi, y, and x representing the variables in them. Returns ------- np.ndarray: Adjecency matrix of model's graph structure. Notes ----- B: Effect matrix of eta on eta \gamma: Effect matrix of xi on eta \wedge_y: Effect matrix of eta on y \wedge_x: Effect matrix of xi on x \phi: Covariance matrix of xi \psi: Covariance matrix of eta errors \theta_e: Covariance matrix of y errors \theta_del: Covariance matrix of x errors Examples -------- """ # Arrage the adjacency matrix in order y, x, eta, xi and then slice masks from it. # y(p) x(q) eta(m) xi(n) # y # x # eta \wedge_y B # xi \wedge_x \Gamma # # But here we are slicing from the transpose of adjacency because we want incoming # edges instead of outgoing because parameters come before variables in equations. # # y(p) x(q) eta(m) xi(n) # y \wedge_y # x \wedge_x # eta B \Gamma # xi y_vars, x_vars, eta_vars, xi_vars = var["y"], var["x"], var["eta"], var["xi"] p, q, m, n = (len(y_vars), len(x_vars), len(eta_vars), len(xi_vars)) nodelist = y_vars + x_vars + eta_vars + xi_vars adj_matrix = nx.to_numpy_matrix(graph, nodelist=nodelist, weight=weight).T B_mask = adj_matrix[p + q : p + q + m, p + q : p + q + m] gamma_mask = adj_matrix[p + q : p + q + m, p + q + m :] wedge_y_mask = adj_matrix[0:p, p + q : p + q + m] wedge_x_mask = adj_matrix[p : p + q, p + q + m :] err_nodelist = y_vars + x_vars + eta_vars + xi_vars err_adj_matrix = nx.to_numpy_matrix( err_graph, nodelist=err_nodelist, weight=weight ) if not weight == "weight": np.fill_diagonal(err_adj_matrix, 1.0) theta_e_mask = err_adj_matrix[:p, :p] theta_del_mask = err_adj_matrix[p : p + q, p : p + q] psi_mask = err_adj_matrix[p + q : p + q + m, p + q : p + q + m] phi_mask = err_adj_matrix[p + q + m :, p + q + m :] return { "B": B_mask, "gamma": gamma_mask, "wedge_y": wedge_y_mask, "wedge_x": wedge_x_mask, "phi": phi_mask, "theta_e": theta_e_mask, "theta_del": theta_del_mask, "psi": psi_mask, }
[ "def", "__standard_lisrel_masks", "(", "graph", ",", "err_graph", ",", "weight", ",", "var", ")", ":", "# Arrage the adjacency matrix in order y, x, eta, xi and then slice masks from it.", "# y(p) x(q) eta(m) xi(n)", "# y", "# x", "# eta \\wedge_y B", "# xi ...
https://github.com/pgmpy/pgmpy/blob/24279929a28082ea994c52f3d165ca63fc56b02b/pgmpy/models/SEM.py#L630-L711
ReactionMechanismGenerator/RMG-Py
2b7baf51febf27157def58fb3f6cee03fb6a684c
rmgpy/molecule/molecule.py
python
Molecule.contains_labeled_atom
(self, label)
return False
Return :data:`True` if the molecule contains an atom with the label `label` and :data:`False` otherwise.
Return :data:`True` if the molecule contains an atom with the label `label` and :data:`False` otherwise.
[ "Return", ":", "data", ":", "True", "if", "the", "molecule", "contains", "an", "atom", "with", "the", "label", "label", "and", ":", "data", ":", "False", "otherwise", "." ]
def contains_labeled_atom(self, label): """ Return :data:`True` if the molecule contains an atom with the label `label` and :data:`False` otherwise. """ for atom in self.vertices: if atom.label == label: return True return False
[ "def", "contains_labeled_atom", "(", "self", ",", "label", ")", ":", "for", "atom", "in", "self", ".", "vertices", ":", "if", "atom", ".", "label", "==", "label", ":", "return", "True", "return", "False" ]
https://github.com/ReactionMechanismGenerator/RMG-Py/blob/2b7baf51febf27157def58fb3f6cee03fb6a684c/rmgpy/molecule/molecule.py#L1417-L1424
frescobaldi/frescobaldi
301cc977fc4ba7caa3df9e4bf905212ad5d06912
frescobaldi_app/fonts/dialog.py
python
FontsDialog.font_full_cmd
(self, approach=None)
return self.font_command_tab.full_cmd(approach)
Return the "full" command with all properties/fonts.
Return the "full" command with all properties/fonts.
[ "Return", "the", "full", "command", "with", "all", "properties", "/", "fonts", "." ]
def font_full_cmd(self, approach=None): """Return the "full" command with all properties/fonts.""" approach = approach or self.font_command_tab.approach return self.font_command_tab.full_cmd(approach)
[ "def", "font_full_cmd", "(", "self", ",", "approach", "=", "None", ")", ":", "approach", "=", "approach", "or", "self", ".", "font_command_tab", ".", "approach", "return", "self", ".", "font_command_tab", ".", "full_cmd", "(", "approach", ")" ]
https://github.com/frescobaldi/frescobaldi/blob/301cc977fc4ba7caa3df9e4bf905212ad5d06912/frescobaldi_app/fonts/dialog.py#L236-L239
YunoHost/yunohost
08efbbb9045eaed8e64d3dfc3f5e22e6ac0b5ecd
src/yunohost/backup.py
python
BackupRestoreTargetsManager.set_wanted
( self, category, wanted_targets, available_targets, error_if_wanted_target_is_unavailable, )
return self.list(category, exclude=["Skipped"])
Define and validate targets to be backuped or to be restored (list of system parts, apps..). The wanted targets are compared and filtered with respect to the available targets. If a wanted targets is not available, a call to "error_if_wanted_target_is_unavailable" is made. Args: category -- The category (apps or system) for which to set the targets ; wanted_targets -- List of targets which are wanted by the user. Can be "None" or [], corresponding to "No targets" or "All targets" ; available_targets -- List of targets which are really available ; error_if_wanted_target_is_unavailable -- Callback for targets which are not available.
Define and validate targets to be backuped or to be restored (list of system parts, apps..). The wanted targets are compared and filtered with respect to the available targets. If a wanted targets is not available, a call to "error_if_wanted_target_is_unavailable" is made.
[ "Define", "and", "validate", "targets", "to", "be", "backuped", "or", "to", "be", "restored", "(", "list", "of", "system", "parts", "apps", "..", ")", ".", "The", "wanted", "targets", "are", "compared", "and", "filtered", "with", "respect", "to", "the", ...
def set_wanted( self, category, wanted_targets, available_targets, error_if_wanted_target_is_unavailable, ): """ Define and validate targets to be backuped or to be restored (list of system parts, apps..). The wanted targets are compared and filtered with respect to the available targets. If a wanted targets is not available, a call to "error_if_wanted_target_is_unavailable" is made. Args: category -- The category (apps or system) for which to set the targets ; wanted_targets -- List of targets which are wanted by the user. Can be "None" or [], corresponding to "No targets" or "All targets" ; available_targets -- List of targets which are really available ; error_if_wanted_target_is_unavailable -- Callback for targets which are not available. """ # If no targets wanted, set as empty list if wanted_targets is None: self.targets[category] = [] # If all targets wanted, use all available targets elif wanted_targets == []: self.targets[category] = available_targets # If the user manually specified which targets to backup, we need to # validate that each target is actually available else: self.targets[category] = [ part for part in wanted_targets if part in available_targets ] # Display an error for each target asked by the user but which is # unknown unavailable_targets = [ part for part in wanted_targets if part not in available_targets ] for target in unavailable_targets: self.set_result(category, target, "Skipped") error_if_wanted_target_is_unavailable(target) # For target with no result yet (like 'Skipped'), set it as unknown if self.targets[category] is not None: for target in self.targets[category]: self.set_result(category, target, "Unknown") return self.list(category, exclude=["Skipped"])
[ "def", "set_wanted", "(", "self", ",", "category", ",", "wanted_targets", ",", "available_targets", ",", "error_if_wanted_target_is_unavailable", ",", ")", ":", "# If no targets wanted, set as empty list", "if", "wanted_targets", "is", "None", ":", "self", ".", "targets...
https://github.com/YunoHost/yunohost/blob/08efbbb9045eaed8e64d3dfc3f5e22e6ac0b5ecd/src/yunohost/backup.py#L121-L178
snwh/suru-icon-theme
2d8102084eaf194f04076ec6949feacb0eb4a1ba
src/cursors/render-cursors.py
python
SVGHandler.parseCoordinates
(self, val)
return val
Strips the units from a coordinate, and returns just the value.
Strips the units from a coordinate, and returns just the value.
[ "Strips", "the", "units", "from", "a", "coordinate", "and", "returns", "just", "the", "value", "." ]
def parseCoordinates(self, val): """Strips the units from a coordinate, and returns just the value.""" if val.endswith('px'): val = float(val.rstrip('px')) elif val.endswith('pt'): val = float(val.rstrip('pt')) elif val.endswith('cm'): val = float(val.rstrip('cm')) elif val.endswith('mm'): val = float(val.rstrip('mm')) elif val.endswith('in'): val = float(val.rstrip('in')) elif val.endswith('%'): val = float(val.rstrip('%')) elif self.isFloat(val): val = float(val) else: fatalError("Coordinate value %s has unrecognised units. Only px,pt,cm,mm,and in units are currently supported." % val) return val
[ "def", "parseCoordinates", "(", "self", ",", "val", ")", ":", "if", "val", ".", "endswith", "(", "'px'", ")", ":", "val", "=", "float", "(", "val", ".", "rstrip", "(", "'px'", ")", ")", "elif", "val", ".", "endswith", "(", "'pt'", ")", ":", "val"...
https://github.com/snwh/suru-icon-theme/blob/2d8102084eaf194f04076ec6949feacb0eb4a1ba/src/cursors/render-cursors.py#L364-L382
myano/jenni
d2e9f86b4d0826f43806bf6baf134147500027db
modules/github_stats.py
python
fetch_github
(jenni, url, term)
[]
def fetch_github(jenni, url, term): t = urllib2.quote(term) if '%' in term: t = urllib.quote(term.replace('%', '')) request = urllib2.Request(url % t, headers=DEFAULT_HEADER) try: content = json.loads(urllib2.urlopen(request).read()) return content except Exception as e: jenni.say("An error occurred fetching information from Github: {0}".format(e)) return None
[ "def", "fetch_github", "(", "jenni", ",", "url", ",", "term", ")", ":", "t", "=", "urllib2", ".", "quote", "(", "term", ")", "if", "'%'", "in", "term", ":", "t", "=", "urllib", ".", "quote", "(", "term", ".", "replace", "(", "'%'", ",", "''", "...
https://github.com/myano/jenni/blob/d2e9f86b4d0826f43806bf6baf134147500027db/modules/github_stats.py#L27-L39
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v7/services/services/campaign_bid_modifier_service/client.py
python
CampaignBidModifierServiceClient.from_service_account_file
(cls, filename: str, *args, **kwargs)
return cls(*args, **kwargs)
Creates an instance of this client using the provided credentials file. Args: filename (str): The path to the service account private key json file. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: CampaignBidModifierServiceClient: The constructed client.
Creates an instance of this client using the provided credentials file.
[ "Creates", "an", "instance", "of", "this", "client", "using", "the", "provided", "credentials", "file", "." ]
def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials file. Args: filename (str): The path to the service account private key json file. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: CampaignBidModifierServiceClient: The constructed client. """ credentials = service_account.Credentials.from_service_account_file( filename ) kwargs["credentials"] = credentials return cls(*args, **kwargs)
[ "def", "from_service_account_file", "(", "cls", ",", "filename", ":", "str", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "credentials", "=", "service_account", ".", "Credentials", ".", "from_service_account_file", "(", "filename", ")", "kwargs", "[", ...
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v7/services/services/campaign_bid_modifier_service/client.py#L134-L151
akfamily/akshare
590e50eece9ec067da3538c7059fd660b71f1339
akshare/currency/currency.py
python
currency_history
( base: str = "USD", date: str = "2020-02-03", api_key: str = "" )
return temp_df
Latest data from currencyscoop.com https://currencyscoop.com/api-documentation :param base: The base currency you would like to use for your rates :type base: str :param date: Specific date, e.g., "2020-02-03" :type date: str :param api_key: Account -> Account Details -> API KEY (use as password in external tools) :type api_key: str :return: Latest data of base currency :rtype: pandas.DataFrame
Latest data from currencyscoop.com https://currencyscoop.com/api-documentation :param base: The base currency you would like to use for your rates :type base: str :param date: Specific date, e.g., "2020-02-03" :type date: str :param api_key: Account -> Account Details -> API KEY (use as password in external tools) :type api_key: str :return: Latest data of base currency :rtype: pandas.DataFrame
[ "Latest", "data", "from", "currencyscoop", ".", "com", "https", ":", "//", "currencyscoop", ".", "com", "/", "api", "-", "documentation", ":", "param", "base", ":", "The", "base", "currency", "you", "would", "like", "to", "use", "for", "your", "rates", "...
def currency_history( base: str = "USD", date: str = "2020-02-03", api_key: str = "" ) -> pd.DataFrame: """ Latest data from currencyscoop.com https://currencyscoop.com/api-documentation :param base: The base currency you would like to use for your rates :type base: str :param date: Specific date, e.g., "2020-02-03" :type date: str :param api_key: Account -> Account Details -> API KEY (use as password in external tools) :type api_key: str :return: Latest data of base currency :rtype: pandas.DataFrame """ payload = {"base": base, "date": date, "api_key": api_key} url = "https://api.currencyscoop.com/v1/historical" r = requests.get(url, params=payload) temp_df = pd.DataFrame.from_dict(r.json()["response"]) temp_df["date"] = pd.to_datetime(temp_df["date"]) return temp_df
[ "def", "currency_history", "(", "base", ":", "str", "=", "\"USD\"", ",", "date", ":", "str", "=", "\"2020-02-03\"", ",", "api_key", ":", "str", "=", "\"\"", ")", "->", "pd", ".", "DataFrame", ":", "payload", "=", "{", "\"base\"", ":", "base", ",", "\...
https://github.com/akfamily/akshare/blob/590e50eece9ec067da3538c7059fd660b71f1339/akshare/currency/currency.py#L32-L52
seemethere/nba_py
f1cd2b0f2702601accf21fef4b721a1564ef4705
nba_py/team.py
python
TeamInGameSplits.by_half
(self)
return _api_scrape(self.json, 1)
[]
def by_half(self): return _api_scrape(self.json, 1)
[ "def", "by_half", "(", "self", ")", ":", "return", "_api_scrape", "(", "self", ".", "json", ",", "1", ")" ]
https://github.com/seemethere/nba_py/blob/f1cd2b0f2702601accf21fef4b721a1564ef4705/nba_py/team.py#L197-L198
IdentityPython/pysaml2
6badb32d212257bd83ffcc816f9b625f68281b47
src/saml2/xmldsig/__init__.py
python
TransformsType_.__init__
(self, transform=None, text=None, extension_elements=None, extension_attributes=None, )
[]
def __init__(self, transform=None, text=None, extension_elements=None, extension_attributes=None, ): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes, ) self.transform = transform or []
[ "def", "__init__", "(", "self", ",", "transform", "=", "None", ",", "text", "=", "None", ",", "extension_elements", "=", "None", ",", "extension_attributes", "=", "None", ",", ")", ":", "SamlBase", ".", "__init__", "(", "self", ",", "text", "=", "text", ...
https://github.com/IdentityPython/pysaml2/blob/6badb32d212257bd83ffcc816f9b625f68281b47/src/saml2/xmldsig/__init__.py#L1137-L1148
perrygeo/simanneal
951e7d89a8b7f19aeb05b64e7cc8b844a734af89
examples/watershed/shapefile.py
python
Reader.__recordFmt
(self)
return (fmt, fmtSize)
Calculates the size of a .shp geometry record.
Calculates the size of a .shp geometry record.
[ "Calculates", "the", "size", "of", "a", ".", "shp", "geometry", "record", "." ]
def __recordFmt(self): """Calculates the size of a .shp geometry record.""" if not self.numRecords: self.__dbfHeader() fmt = ''.join(['%ds' % fieldinfo[2] for fieldinfo in self.fields]) fmtSize = calcsize(fmt) return (fmt, fmtSize)
[ "def", "__recordFmt", "(", "self", ")", ":", "if", "not", "self", ".", "numRecords", ":", "self", ".", "__dbfHeader", "(", ")", "fmt", "=", "''", ".", "join", "(", "[", "'%ds'", "%", "fieldinfo", "[", "2", "]", "for", "fieldinfo", "in", "self", "."...
https://github.com/perrygeo/simanneal/blob/951e7d89a8b7f19aeb05b64e7cc8b844a734af89/examples/watershed/shapefile.py#L347-L353
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/api/v2010/account/transcription.py
python
TranscriptionPage.__repr__
(self)
return '<Twilio.Api.V2010.TranscriptionPage>'
Provide a friendly representation :returns: Machine friendly representation :rtype: str
Provide a friendly representation
[ "Provide", "a", "friendly", "representation" ]
def __repr__(self): """ Provide a friendly representation :returns: Machine friendly representation :rtype: str """ return '<Twilio.Api.V2010.TranscriptionPage>'
[ "def", "__repr__", "(", "self", ")", ":", "return", "'<Twilio.Api.V2010.TranscriptionPage>'" ]
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/api/v2010/account/transcription.py#L173-L180
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/jinja2-2.6/jinja2/parser.py
python
Parser.free_identifier
(self, lineno=None)
return rv
Return a new free identifier as :class:`~jinja2.nodes.InternalName`.
Return a new free identifier as :class:`~jinja2.nodes.InternalName`.
[ "Return", "a", "new", "free", "identifier", "as", ":", "class", ":", "~jinja2", ".", "nodes", ".", "InternalName", "." ]
def free_identifier(self, lineno=None): """Return a new free identifier as :class:`~jinja2.nodes.InternalName`.""" self._last_identifier += 1 rv = object.__new__(nodes.InternalName) nodes.Node.__init__(rv, 'fi%d' % self._last_identifier, lineno=lineno) return rv
[ "def", "free_identifier", "(", "self", ",", "lineno", "=", "None", ")", ":", "self", ".", "_last_identifier", "+=", "1", "rv", "=", "object", ".", "__new__", "(", "nodes", ".", "InternalName", ")", "nodes", ".", "Node", ".", "__init__", "(", "rv", ",",...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/jinja2-2.6/jinja2/parser.py#L106-L111
bendmorris/static-python
2e0f8c4d7ed5b359dc7d8a75b6fb37e6b6c5c473
Lib/logging/__init__.py
python
_showwarning
(message, category, filename, lineno, file=None, line=None)
Implementation of showwarnings which redirects to logging, which will first check to see if the file parameter is None. If a file is specified, it will delegate to the original warnings implementation of showwarning. Otherwise, it will call warnings.formatwarning and will log the resulting string to a warnings logger named "py.warnings" with level logging.WARNING.
Implementation of showwarnings which redirects to logging, which will first check to see if the file parameter is None. If a file is specified, it will delegate to the original warnings implementation of showwarning. Otherwise, it will call warnings.formatwarning and will log the resulting string to a warnings logger named "py.warnings" with level logging.WARNING.
[ "Implementation", "of", "showwarnings", "which", "redirects", "to", "logging", "which", "will", "first", "check", "to", "see", "if", "the", "file", "parameter", "is", "None", ".", "If", "a", "file", "is", "specified", "it", "will", "delegate", "to", "the", ...
def _showwarning(message, category, filename, lineno, file=None, line=None): """ Implementation of showwarnings which redirects to logging, which will first check to see if the file parameter is None. If a file is specified, it will delegate to the original warnings implementation of showwarning. Otherwise, it will call warnings.formatwarning and will log the resulting string to a warnings logger named "py.warnings" with level logging.WARNING. """ if file is not None: if _warnings_showwarning is not None: _warnings_showwarning(message, category, filename, lineno, file, line) else: s = warnings.formatwarning(message, category, filename, lineno, line) logger = getLogger("py.warnings") if not logger.handlers: logger.addHandler(NullHandler()) logger.warning("%s", s)
[ "def", "_showwarning", "(", "message", ",", "category", ",", "filename", ",", "lineno", ",", "file", "=", "None", ",", "line", "=", "None", ")", ":", "if", "file", "is", "not", "None", ":", "if", "_warnings_showwarning", "is", "not", "None", ":", "_war...
https://github.com/bendmorris/static-python/blob/2e0f8c4d7ed5b359dc7d8a75b6fb37e6b6c5c473/Lib/logging/__init__.py#L1890-L1906
quantOS-org/JAQS
959762a518c22592f96433c573d1f99ec0c89152
jaqs/data/dataservice.py
python
RemoteDataService.query_industry_daily
(self, symbol, start_date, end_date, type_='SW', level=1)
return df_industry
Get index components on each day during start_date and end_date. Parameters ---------- symbol : str separated by ',' start_date : int end_date : int type_ : {'SW', 'ZZ'} Returns ------- res : pd.DataFrame index dates, columns symbols values are industry code
Get index components on each day during start_date and end_date. Parameters ---------- symbol : str separated by ',' start_date : int end_date : int type_ : {'SW', 'ZZ'}
[ "Get", "index", "components", "on", "each", "day", "during", "start_date", "and", "end_date", ".", "Parameters", "----------", "symbol", ":", "str", "separated", "by", "start_date", ":", "int", "end_date", ":", "int", "type_", ":", "{", "SW", "ZZ", "}" ]
def query_industry_daily(self, symbol, start_date, end_date, type_='SW', level=1): """ Get index components on each day during start_date and end_date. Parameters ---------- symbol : str separated by ',' start_date : int end_date : int type_ : {'SW', 'ZZ'} Returns ------- res : pd.DataFrame index dates, columns symbols values are industry code """ df_raw = self.query_industry_raw(symbol, type_=type_, level=level) dic_sec = jutil.group_df_to_dict(df_raw, by='symbol') dic_sec = {sec: df.sort_values(by='in_date', axis=0).reset_index() for sec, df in dic_sec.items()} if not dic_sec: return None df_ann_tmp = pd.concat({sec: df.loc[:, 'in_date'] for sec, df in dic_sec.items()}, axis=1) df_value_tmp = pd.concat({sec: df.loc[:, 'industry{:d}_code'.format(level)] for sec, df in dic_sec.items()}, axis=1) idx = np.unique(np.concatenate([df.index.values for df in dic_sec.values()])) symbol_arr = np.sort(symbol.split(',')) df_ann = pd.DataFrame(index=idx, columns=symbol_arr, data=np.nan) df_ann.loc[df_ann_tmp.index, df_ann_tmp.columns] = df_ann_tmp df_value = pd.DataFrame(index=idx, columns=symbol_arr, data=np.nan) df_value.loc[df_value_tmp.index, df_value_tmp.columns] = df_value_tmp dates_arr = self.query_trade_dates(start_date, end_date) df_industry = align.align(df_value, df_ann, dates_arr) # TODO before industry classification is available, we assume they belong to their first group. df_industry = df_industry.fillna(method='bfill') df_industry = df_industry.astype(str) return df_industry
[ "def", "query_industry_daily", "(", "self", ",", "symbol", ",", "start_date", ",", "end_date", ",", "type_", "=", "'SW'", ",", "level", "=", "1", ")", ":", "df_raw", "=", "self", ".", "query_industry_raw", "(", "symbol", ",", "type_", "=", "type_", ",", ...
https://github.com/quantOS-org/JAQS/blob/959762a518c22592f96433c573d1f99ec0c89152/jaqs/data/dataservice.py#L1017-L1065
Calysto/calysto_scheme
15bf81987870bcae1264e5a0a06feb9a8ee12b8b
calysto_scheme/scheme.py
python
b_proc_53_d
()
[]
def b_proc_53_d(): if (False if ((not(length_one_q(args_reg))) is False) else True): GLOBALS['msg_reg'] = "incorrect number of arguments to unbox" GLOBALS['pc'] = runtime_error else: if (False if ((not(box_q((args_reg).car))) is False) else True): GLOBALS['msg_reg'] = format("unbox called on non-box ~s", (args_reg).car) GLOBALS['pc'] = runtime_error else: GLOBALS['value2_reg'] = fail_reg GLOBALS['value1_reg'] = Apply(unbox, args_reg) GLOBALS['k_reg'] = k2_reg GLOBALS['pc'] = apply_cont2
[ "def", "b_proc_53_d", "(", ")", ":", "if", "(", "False", "if", "(", "(", "not", "(", "length_one_q", "(", "args_reg", ")", ")", ")", "is", "False", ")", "else", "True", ")", ":", "GLOBALS", "[", "'msg_reg'", "]", "=", "\"incorrect number of arguments to ...
https://github.com/Calysto/calysto_scheme/blob/15bf81987870bcae1264e5a0a06feb9a8ee12b8b/calysto_scheme/scheme.py#L4085-L4097
TeamMsgExtractor/msg-extractor
8a3a0255a7306bdb8073bd8f222d3be5c688080a
extract_msg/attachment.py
python
Attachment.data
(self)
return self.__data
Returns the attachment data.
Returns the attachment data.
[ "Returns", "the", "attachment", "data", "." ]
def data(self): """ Returns the attachment data. """ return self.__data
[ "def", "data", "(", "self", ")", ":", "return", "self", ".", "__data" ]
https://github.com/TeamMsgExtractor/msg-extractor/blob/8a3a0255a7306bdb8073bd8f222d3be5c688080a/extract_msg/attachment.py#L107-L111
mikedewar/d3py
e8ee5a906768e1c08bc3415375e38a4b1c532d74
d3py/vega.py
python
Vega.__sub__
(self, tuple)
Allow for updating of Vega with sub operator
Allow for updating of Vega with sub operator
[ "Allow", "for", "updating", "of", "Vega", "with", "sub", "operator" ]
def __sub__(self, tuple): '''Allow for updating of Vega with sub operator''' self.update_component('remove', *tuple)
[ "def", "__sub__", "(", "self", ",", "tuple", ")", ":", "self", ".", "update_component", "(", "'remove'", ",", "*", "tuple", ")" ]
https://github.com/mikedewar/d3py/blob/e8ee5a906768e1c08bc3415375e38a4b1c532d74/d3py/vega.py#L70-L72
ifwe/digsby
f5fe00244744aa131e07f09348d10563f3d8fa99
digsby/src/oscar/rendezvous/proxy.py
python
make_proxy_init
(sn, cookie, port=None)
return fullpacket
Creates a proxy packet.
Creates a proxy packet.
[ "Creates", "a", "proxy", "packet", "." ]
def make_proxy_init(sn, cookie, port=None): 'Creates a proxy packet.' # Check for screenname as a string. if not isinstance(sn, str): raise TypeError('screenname must be a str object') # Cookie must be an eight byte string or a long. if isinstance(cookie, long): cookie = struct.pack('!Q', cookie) else: assert isinstance(cookie, str) and len(cookie) == 8 # If a port was specified, use initreceive, since that is the only way # that and 'initsend' differ. command = 'initreceive' if port else 'initsend' # Length is everything that follows the two bytes of length. length = len(sn) + 41 if port is None: # Init sends have two less byes. length -= 2 info(command + ' length: %d', length) data = ProxyHeader(length, ProxyHeader.version, ProxyHeader.commands[command], null = 0, flags = 0).pack() # Screen name as a pascal string data += struct.pack('B', len(sn)) + sn # Add the two byte port if this is an init_receive request if port: assert isinstance(port, int) data += struct.pack('!H', port) fullpacket = data + cookie + _send_file_tlv #Send file capability on the end log.info_s('proxy packet assembled (%d bytes): %s', len(fullpacket),to_hex(fullpacket)) return fullpacket
[ "def", "make_proxy_init", "(", "sn", ",", "cookie", ",", "port", "=", "None", ")", ":", "# Check for screenname as a string.", "if", "not", "isinstance", "(", "sn", ",", "str", ")", ":", "raise", "TypeError", "(", "'screenname must be a str object'", ")", "# Coo...
https://github.com/ifwe/digsby/blob/f5fe00244744aa131e07f09348d10563f3d8fa99/digsby/src/oscar/rendezvous/proxy.py#L43-L85
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/pandas/core/frame.py
python
DataFrame.round
(self, decimals=0, *args, **kwargs)
Round a DataFrame to a variable number of decimal places. .. versionadded:: 0.17.0 Parameters ---------- decimals : int, dict, Series Number of decimal places to round each column to. If an int is given, round each column to the same number of places. Otherwise dict and Series round to variable numbers of places. Column names should be in the keys if `decimals` is a dict-like, or in the index if `decimals` is a Series. Any columns not included in `decimals` will be left as is. Elements of `decimals` which are not columns of the input will be ignored. Examples -------- >>> df = pd.DataFrame(np.random.random([3, 3]), ... columns=['A', 'B', 'C'], index=['first', 'second', 'third']) >>> df A B C first 0.028208 0.992815 0.173891 second 0.038683 0.645646 0.577595 third 0.877076 0.149370 0.491027 >>> df.round(2) A B C first 0.03 0.99 0.17 second 0.04 0.65 0.58 third 0.88 0.15 0.49 >>> df.round({'A': 1, 'C': 2}) A B C first 0.0 0.992815 0.17 second 0.0 0.645646 0.58 third 0.9 0.149370 0.49 >>> decimals = pd.Series([1, 0, 2], index=['A', 'B', 'C']) >>> df.round(decimals) A B C first 0.0 1 0.17 second 0.0 1 0.58 third 0.9 0 0.49 Returns ------- DataFrame object See Also -------- numpy.around Series.round
Round a DataFrame to a variable number of decimal places.
[ "Round", "a", "DataFrame", "to", "a", "variable", "number", "of", "decimal", "places", "." ]
def round(self, decimals=0, *args, **kwargs): """ Round a DataFrame to a variable number of decimal places. .. versionadded:: 0.17.0 Parameters ---------- decimals : int, dict, Series Number of decimal places to round each column to. If an int is given, round each column to the same number of places. Otherwise dict and Series round to variable numbers of places. Column names should be in the keys if `decimals` is a dict-like, or in the index if `decimals` is a Series. Any columns not included in `decimals` will be left as is. Elements of `decimals` which are not columns of the input will be ignored. Examples -------- >>> df = pd.DataFrame(np.random.random([3, 3]), ... columns=['A', 'B', 'C'], index=['first', 'second', 'third']) >>> df A B C first 0.028208 0.992815 0.173891 second 0.038683 0.645646 0.577595 third 0.877076 0.149370 0.491027 >>> df.round(2) A B C first 0.03 0.99 0.17 second 0.04 0.65 0.58 third 0.88 0.15 0.49 >>> df.round({'A': 1, 'C': 2}) A B C first 0.0 0.992815 0.17 second 0.0 0.645646 0.58 third 0.9 0.149370 0.49 >>> decimals = pd.Series([1, 0, 2], index=['A', 'B', 'C']) >>> df.round(decimals) A B C first 0.0 1 0.17 second 0.0 1 0.58 third 0.9 0 0.49 Returns ------- DataFrame object See Also -------- numpy.around Series.round """ from pandas.tools.merge import concat def _dict_round(df, decimals): for col, vals in df.iteritems(): try: yield _series_round(vals, decimals[col]) except KeyError: yield vals def _series_round(s, decimals): if is_integer_dtype(s) or is_float_dtype(s): return s.round(decimals) return s nv.validate_round(args, kwargs) if isinstance(decimals, (dict, Series)): if isinstance(decimals, Series): if not decimals.index.is_unique: raise ValueError("Index of decimals must be unique") new_cols = [col for col in _dict_round(self, decimals)] elif is_integer(decimals): # Dispatch to Series.round new_cols = [_series_round(v, decimals) for _, v in self.iteritems()] else: raise TypeError("decimals must be an integer, a dict-like or a " "Series") if len(new_cols) > 0: return self._constructor(concat(new_cols, axis=1), index=self.index, columns=self.columns) else: return self
[ "def", "round", "(", "self", ",", "decimals", "=", "0", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", "pandas", ".", "tools", ".", "merge", "import", "concat", "def", "_dict_round", "(", "df", ",", "decimals", ")", ":", "for", "col",...
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/pandas/core/frame.py#L4620-L4708
tkamishima/mlmpy
97ad03bc839ab77ce1d5191cc2b9a823ea777531
source/lr3.py
python
LogisticRegression.sigmoid
(x)
return 1.0 / (1.0 + np.exp(-x))
sigmoid function universal function generated by np.vectorize() Parameters ---------- x : array_like, shape=(n_data), dtype=float arguments of function Returns ------- sig : array, shape=(n_data), dtype=float 1.0 / (1.0 + exp(- x))
sigmoid function
[ "sigmoid", "function" ]
def sigmoid(x): """ sigmoid function universal function generated by np.vectorize() Parameters ---------- x : array_like, shape=(n_data), dtype=float arguments of function Returns ------- sig : array, shape=(n_data), dtype=float 1.0 / (1.0 + exp(- x)) """ sigmoid_range = 34.538776394910684 if x <= -sigmoid_range: return 1e-15 if x >= sigmoid_range: return 1.0 - 1e-15 return 1.0 / (1.0 + np.exp(-x))
[ "def", "sigmoid", "(", "x", ")", ":", "sigmoid_range", "=", "34.538776394910684", "if", "x", "<=", "-", "sigmoid_range", ":", "return", "1e-15", "if", "x", ">=", "sigmoid_range", ":", "return", "1.0", "-", "1e-15", "return", "1.0", "/", "(", "1.0", "+", ...
https://github.com/tkamishima/mlmpy/blob/97ad03bc839ab77ce1d5191cc2b9a823ea777531/source/lr3.py#L41-L64
apache/libcloud
90971e17bfd7b6bb97b2489986472c531cc8e140
libcloud/compute/drivers/gandi.py
python
GandiNodeDriver.destroy_node
(self, node)
return False
Destroy a node. :param node: Node object to destroy :type node: :class:`Node` :return: True if successful :rtype: ``bool``
Destroy a node.
[ "Destroy", "a", "node", "." ]
def destroy_node(self, node): """ Destroy a node. :param node: Node object to destroy :type node: :class:`Node` :return: True if successful :rtype: ``bool`` """ vm = self._node_info(node.id) if vm["state"] == "running": # Send vm_stop and wait for accomplish op_stop = self.connection.request("hosting.vm.stop", int(node.id)) if not self._wait_operation(op_stop.object["id"]): raise GandiException(1010, "vm.stop failed") # Delete op = self.connection.request("hosting.vm.delete", int(node.id)) if self._wait_operation(op.object["id"]): return True return False
[ "def", "destroy_node", "(", "self", ",", "node", ")", ":", "vm", "=", "self", ".", "_node_info", "(", "node", ".", "id", ")", "if", "vm", "[", "\"state\"", "]", "==", "\"running\"", ":", "# Send vm_stop and wait for accomplish", "op_stop", "=", "self", "."...
https://github.com/apache/libcloud/blob/90971e17bfd7b6bb97b2489986472c531cc8e140/libcloud/compute/drivers/gandi.py#L206-L226
tensorflow/lingvo
ce10019243d954c3c3ebe739f7589b5eebfdf907
lingvo/core/base_layer.py
python
BaseLayer.accumulators
(self)
return ret
Returns `.NestedMap` of `Accumulator` instances for this and children.
Returns `.NestedMap` of `Accumulator` instances for this and children.
[ "Returns", ".", "NestedMap", "of", "Accumulator", "instances", "for", "this", "and", "children", "." ]
def accumulators(self): """Returns `.NestedMap` of `Accumulator` instances for this and children.""" ret = py_utils.Transform(lambda x: x.accumulators, self.children) for k, acc in self._private_accumulators.items(): ret[k] = acc return ret
[ "def", "accumulators", "(", "self", ")", ":", "ret", "=", "py_utils", ".", "Transform", "(", "lambda", "x", ":", "x", ".", "accumulators", ",", "self", ".", "children", ")", "for", "k", ",", "acc", "in", "self", ".", "_private_accumulators", ".", "item...
https://github.com/tensorflow/lingvo/blob/ce10019243d954c3c3ebe739f7589b5eebfdf907/lingvo/core/base_layer.py#L678-L683
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/_pyio.py
python
RawIOBase.read
(self, n=-1)
return bytes(b)
Read and return up to n bytes. Returns an empty bytes object on EOF, or None if the object is set not to block and has no data to read.
Read and return up to n bytes.
[ "Read", "and", "return", "up", "to", "n", "bytes", "." ]
def read(self, n=-1): """Read and return up to n bytes. Returns an empty bytes object on EOF, or None if the object is set not to block and has no data to read. """ if n is None: n = -1 if n < 0: return self.readall() b = bytearray(n.__index__()) n = self.readinto(b) if n is None: return None del b[n:] return bytes(b)
[ "def", "read", "(", "self", ",", "n", "=", "-", "1", ")", ":", "if", "n", "is", "None", ":", "n", "=", "-", "1", "if", "n", "<", "0", ":", "return", "self", ".", "readall", "(", ")", "b", "=", "bytearray", "(", "n", ".", "__index__", "(", ...
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/_pyio.py#L550-L565
ospalh/anki-addons
4ece13423bd541e29d9b40ebe26ca0999a6962b1
batteries/decimal.py
python
Context.is_zero
(self, a)
return a.is_zero()
Return True if the operand is a zero; otherwise return False. >>> ExtendedContext.is_zero(Decimal('0')) True >>> ExtendedContext.is_zero(Decimal('2.50')) False >>> ExtendedContext.is_zero(Decimal('-0E+2')) True >>> ExtendedContext.is_zero(1) False >>> ExtendedContext.is_zero(0) True
Return True if the operand is a zero; otherwise return False.
[ "Return", "True", "if", "the", "operand", "is", "a", "zero", ";", "otherwise", "return", "False", "." ]
def is_zero(self, a): """Return True if the operand is a zero; otherwise return False. >>> ExtendedContext.is_zero(Decimal('0')) True >>> ExtendedContext.is_zero(Decimal('2.50')) False >>> ExtendedContext.is_zero(Decimal('-0E+2')) True >>> ExtendedContext.is_zero(1) False >>> ExtendedContext.is_zero(0) True """ a = _convert_other(a, raiseit=True) return a.is_zero()
[ "def", "is_zero", "(", "self", ",", "a", ")", ":", "a", "=", "_convert_other", "(", "a", ",", "raiseit", "=", "True", ")", "return", "a", ".", "is_zero", "(", ")" ]
https://github.com/ospalh/anki-addons/blob/4ece13423bd541e29d9b40ebe26ca0999a6962b1/batteries/decimal.py#L4463-L4478
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/autopilot/v1/assistant/__init__.py
python
AssistantInstance.account_sid
(self)
return self._properties['account_sid']
:returns: The SID of the Account that created the resource :rtype: unicode
:returns: The SID of the Account that created the resource :rtype: unicode
[ ":", "returns", ":", "The", "SID", "of", "the", "Account", "that", "created", "the", "resource", ":", "rtype", ":", "unicode" ]
def account_sid(self): """ :returns: The SID of the Account that created the resource :rtype: unicode """ return self._properties['account_sid']
[ "def", "account_sid", "(", "self", ")", ":", "return", "self", ".", "_properties", "[", "'account_sid'", "]" ]
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/autopilot/v1/assistant/__init__.py#L470-L475
gaphor/gaphor
dfe8df33ef3b884afdadf7c91fc7740f8d3c2e88
gaphor/core/modeling/elementdispatcher.py
python
EventWatcher.unsubscribe_all
(self, *_args)
Unregister handlers. Extra arguments are ignored (makes connecting to destroy signals much easier though).
Unregister handlers.
[ "Unregister", "handlers", "." ]
def unsubscribe_all(self, *_args): """Unregister handlers. Extra arguments are ignored (makes connecting to destroy signals much easier though). """ dispatcher = self.element_dispatcher if not dispatcher: return for path, handler in self._watched_paths.items(): dispatcher.unsubscribe(handler)
[ "def", "unsubscribe_all", "(", "self", ",", "*", "_args", ")", ":", "dispatcher", "=", "self", ".", "element_dispatcher", "if", "not", "dispatcher", ":", "return", "for", "path", ",", "handler", "in", "self", ".", "_watched_paths", ".", "items", "(", ")", ...
https://github.com/gaphor/gaphor/blob/dfe8df33ef3b884afdadf7c91fc7740f8d3c2e88/gaphor/core/modeling/elementdispatcher.py#L58-L69
bukun/TorCMS
f7b44e8650aa54774f6b57e7b178edebbbf57e8e
torcms/script/script_review.py
python
__get_diff_recent
()
return diff_str
Generate the difference of posts. recently.
Generate the difference of posts. recently.
[ "Generate", "the", "difference", "of", "posts", ".", "recently", "." ]
def __get_diff_recent(): ''' Generate the difference of posts. recently. ''' diff_str = '' for key in router_post: recent_posts = MPost.query_recent_edited(tools.timestamp() - TIME_LIMIT, kind=key) for recent_post in recent_posts: hist_rec = MPostHist.get_last(recent_post.uid) if hist_rec: raw_title = hist_rec.title new_title = recent_post.title infobox = diff_table(raw_title, new_title) diff_str = diff_str + ''' <h2 style="color:red;font-size:larger;font-weight:70;">TITLE: {0}</h2> '''.format(recent_post.title) + infobox infobox = diff_table(hist_rec.cnt_md, recent_post.cnt_md) diff_str = diff_str + '<h3>CONTENT:{0}</h3>'.format( recent_post.title) + infobox + '</hr>' else: continue return diff_str
[ "def", "__get_diff_recent", "(", ")", ":", "diff_str", "=", "''", "for", "key", "in", "router_post", ":", "recent_posts", "=", "MPost", ".", "query_recent_edited", "(", "tools", ".", "timestamp", "(", ")", "-", "TIME_LIMIT", ",", "kind", "=", "key", ")", ...
https://github.com/bukun/TorCMS/blob/f7b44e8650aa54774f6b57e7b178edebbbf57e8e/torcms/script/script_review.py#L23-L51
facebookresearch/SlowFast
39ef35c9a086443209b458cceaec86a02e27b369
slowfast/datasets/cv2_transform.py
python
center_crop
(size, image)
return cropped
Perform center crop on input images. Args: size (int): size of the cropped height and width. image (array): the image to perform center crop.
Perform center crop on input images. Args: size (int): size of the cropped height and width. image (array): the image to perform center crop.
[ "Perform", "center", "crop", "on", "input", "images", ".", "Args", ":", "size", "(", "int", ")", ":", "size", "of", "the", "cropped", "height", "and", "width", ".", "image", "(", "array", ")", ":", "the", "image", "to", "perform", "center", "crop", "...
def center_crop(size, image): """ Perform center crop on input images. Args: size (int): size of the cropped height and width. image (array): the image to perform center crop. """ height = image.shape[0] width = image.shape[1] y_offset = int(math.ceil((height - size) / 2)) x_offset = int(math.ceil((width - size) / 2)) cropped = image[y_offset : y_offset + size, x_offset : x_offset + size, :] assert cropped.shape[0] == size, "Image height not cropped properly" assert cropped.shape[1] == size, "Image width not cropped properly" return cropped
[ "def", "center_crop", "(", "size", ",", "image", ")", ":", "height", "=", "image", ".", "shape", "[", "0", "]", "width", "=", "image", ".", "shape", "[", "1", "]", "y_offset", "=", "int", "(", "math", ".", "ceil", "(", "(", "height", "-", "size",...
https://github.com/facebookresearch/SlowFast/blob/39ef35c9a086443209b458cceaec86a02e27b369/slowfast/datasets/cv2_transform.py#L458-L472
tychovdo/PacmanDQN
c6b8519bf35eb31390b295752e9c78ba273592e3
util.py
python
PriorityQueueWithFunction.__init__
(self, priorityFunction)
priorityFunction (item) -> priority
priorityFunction (item) -> priority
[ "priorityFunction", "(", "item", ")", "-", ">", "priority" ]
def __init__(self, priorityFunction): "priorityFunction (item) -> priority" self.priorityFunction = priorityFunction # store the priority function PriorityQueue.__init__(self)
[ "def", "__init__", "(", "self", ",", "priorityFunction", ")", ":", "self", ".", "priorityFunction", "=", "priorityFunction", "# store the priority function", "PriorityQueue", ".", "__init__", "(", "self", ")" ]
https://github.com/tychovdo/PacmanDQN/blob/c6b8519bf35eb31390b295752e9c78ba273592e3/util.py#L205-L208
jeffgortmaker/pyblp
33ad24d8a800b8178aafa47304a822077a607558
pyblp/utilities/basics.py
python
generate_items_worker
(args: Tuple[Any, tuple, Callable])
return key, method(instance, *method_args)
Call the specified method of a class instance with any additional arguments. Return the associated key along with the returned object.
Call the specified method of a class instance with any additional arguments. Return the associated key along with the returned object.
[ "Call", "the", "specified", "method", "of", "a", "class", "instance", "with", "any", "additional", "arguments", ".", "Return", "the", "associated", "key", "along", "with", "the", "returned", "object", "." ]
def generate_items_worker(args: Tuple[Any, tuple, Callable]) -> Tuple[Any, Any]: """Call the specified method of a class instance with any additional arguments. Return the associated key along with the returned object. """ key, (instance, *method_args), method = args return key, method(instance, *method_args)
[ "def", "generate_items_worker", "(", "args", ":", "Tuple", "[", "Any", ",", "tuple", ",", "Callable", "]", ")", "->", "Tuple", "[", "Any", ",", "Any", "]", ":", "key", ",", "(", "instance", ",", "*", "method_args", ")", ",", "method", "=", "args", ...
https://github.com/jeffgortmaker/pyblp/blob/33ad24d8a800b8178aafa47304a822077a607558/pyblp/utilities/basics.py#L142-L147
kuri65536/python-for-android
26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891
python-build/python-libs/xmpppy/xmpp/protocol.py
python
JID.__str__
(self,wresource=1)
return jid
Serialise JID into string.
Serialise JID into string.
[ "Serialise", "JID", "into", "string", "." ]
def __str__(self,wresource=1): """ Serialise JID into string. """ if self.node: jid=self.node+'@'+self.domain else: jid=self.domain if wresource and self.resource: return jid+'/'+self.resource return jid
[ "def", "__str__", "(", "self", ",", "wresource", "=", "1", ")", ":", "if", "self", ".", "node", ":", "jid", "=", "self", ".", "node", "+", "'@'", "+", "self", ".", "domain", "else", ":", "jid", "=", "self", ".", "domain", "if", "wresource", "and"...
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python-build/python-libs/xmpppy/xmpp/protocol.py#L315-L320
lanl/qmasm
2222dff00753e6c34c44be2dadf4844ec5caa504
src/qmasm/output.py
python
OutputMixin.open_output_file
(self, oname, mode="w")
return outfile
Open a file or standard output.
Open a file or standard output.
[ "Open", "a", "file", "or", "standard", "output", "." ]
def open_output_file(self, oname, mode="w"): "Open a file or standard output." if oname == "<stdout>": outfile = sys.stdout else: try: outfile = open(oname, mode) except IOError: self.abend('Failed to open %s for output' % oname) return outfile
[ "def", "open_output_file", "(", "self", ",", "oname", ",", "mode", "=", "\"w\"", ")", ":", "if", "oname", "==", "\"<stdout>\"", ":", "outfile", "=", "sys", ".", "stdout", "else", ":", "try", ":", "outfile", "=", "open", "(", "oname", ",", "mode", ")"...
https://github.com/lanl/qmasm/blob/2222dff00753e6c34c44be2dadf4844ec5caa504/src/qmasm/output.py#L16-L25
chipmuenk/pyfda
665310b8548a940a575c0e5ff4bba94608d9ac26
pyfda/input_widgets/input_coeffs.py
python
Input_Coeffs._delete_cells
(self)
Delete all selected elements in self.ba by: - determining the indices of all selected cells in the P and Z arrays - deleting elements with those indices - equalizing the lengths of b and a array by appending the required number of zeros. When nothing is selected, delete the last row. Finally, the QTableWidget is refreshed from self.ba.
Delete all selected elements in self.ba by: - determining the indices of all selected cells in the P and Z arrays - deleting elements with those indices - equalizing the lengths of b and a array by appending the required number of zeros. When nothing is selected, delete the last row. Finally, the QTableWidget is refreshed from self.ba.
[ "Delete", "all", "selected", "elements", "in", "self", ".", "ba", "by", ":", "-", "determining", "the", "indices", "of", "all", "selected", "cells", "in", "the", "P", "and", "Z", "arrays", "-", "deleting", "elements", "with", "those", "indices", "-", "eq...
def _delete_cells(self): """ Delete all selected elements in self.ba by: - determining the indices of all selected cells in the P and Z arrays - deleting elements with those indices - equalizing the lengths of b and a array by appending the required number of zeros. When nothing is selected, delete the last row. Finally, the QTableWidget is refreshed from self.ba. """ sel = qget_selected(self.tblCoeff)['sel'] # get indices of all selected cells if not any(sel) and len(self.ba[0]) > 0: # delete last row self.ba = np.delete(self.ba, -1, axis=1) elif np.all(sel[0] == sel[1]) or fb.fil[0]['ft'] == 'FIR': # only complete rows selected or FIR -> delete row self.ba = np.delete(self.ba, sel[0], axis=1) else: self.ba[0][sel[0]] = 0 self.ba[1][sel[1]] = 0 # self.ba[0] = np.delete(self.ba[0], sel[0]) # self.ba[1] = np.delete(self.ba[1], sel[1]) # test and equalize if b and a array have different lengths: self._equalize_ba_length() # if length is less than 2, clear the table: this ain't no filter! if len(self.ba[0]) < 2: self._clear_table() # sets 'changed' attribute else: self._refresh_table() qstyle_widget(self.ui.butSave, 'changed')
[ "def", "_delete_cells", "(", "self", ")", ":", "sel", "=", "qget_selected", "(", "self", ".", "tblCoeff", ")", "[", "'sel'", "]", "# get indices of all selected cells", "if", "not", "any", "(", "sel", ")", "and", "len", "(", "self", ".", "ba", "[", "0", ...
https://github.com/chipmuenk/pyfda/blob/665310b8548a940a575c0e5ff4bba94608d9ac26/pyfda/input_widgets/input_coeffs.py#L839-L868
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/Xenotix Python Scripting Engine/Lib/ftplib.py
python
FTP.mkd
(self, dirname)
return parse257(resp)
Make a directory, return its full pathname.
Make a directory, return its full pathname.
[ "Make", "a", "directory", "return", "its", "full", "pathname", "." ]
def mkd(self, dirname): '''Make a directory, return its full pathname.''' resp = self.sendcmd('MKD ' + dirname) return parse257(resp)
[ "def", "mkd", "(", "self", ",", "dirname", ")", ":", "resp", "=", "self", ".", "sendcmd", "(", "'MKD '", "+", "dirname", ")", "return", "parse257", "(", "resp", ")" ]
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/Lib/ftplib.py#L556-L559
home-assistant/supervisor
69c2517d5211b483fdfe968b0a2b36b672ee7ab2
supervisor/plugins/cli.py
python
PluginCli.is_running
(self)
return self.instance.is_running()
Return True if Docker container is running. Return a coroutine.
Return True if Docker container is running.
[ "Return", "True", "if", "Docker", "container", "is", "running", "." ]
def is_running(self) -> Awaitable[bool]: """Return True if Docker container is running. Return a coroutine. """ return self.instance.is_running()
[ "def", "is_running", "(", "self", ")", "->", "Awaitable", "[", "bool", "]", ":", "return", "self", ".", "instance", ".", "is_running", "(", ")" ]
https://github.com/home-assistant/supervisor/blob/69c2517d5211b483fdfe968b0a2b36b672ee7ab2/supervisor/plugins/cli.py#L146-L151
ergonomica/ergonomica
62bdec81e8c191b4211bdf6105b1372aa35b5226
ergonomica/lib/lib/ergo_exit.py
python
exit
(argc)
exit: Exit the Ergonomica shell. Usage: exit
exit: Exit the Ergonomica shell.
[ "exit", ":", "Exit", "the", "Ergonomica", "shell", "." ]
def exit(argc): """exit: Exit the Ergonomica shell. Usage: exit """ argc.env.run = False
[ "def", "exit", "(", "argc", ")", ":", "argc", ".", "env", ".", "run", "=", "False" ]
https://github.com/ergonomica/ergonomica/blob/62bdec81e8c191b4211bdf6105b1372aa35b5226/ergonomica/lib/lib/ergo_exit.py#L12-L19
VirtueSecurity/aws-extender
d123b7e1a845847709ba3a481f11996bddc68a1c
BappModules/boto/ec2/autoscale/group.py
python
AutoScalingGroup.shutdown_instances
(self)
Convenience method which shuts down all instances associated with this group.
Convenience method which shuts down all instances associated with this group.
[ "Convenience", "method", "which", "shuts", "down", "all", "instances", "associated", "with", "this", "group", "." ]
def shutdown_instances(self): """ Convenience method which shuts down all instances associated with this group. """ self.min_size = 0 self.max_size = 0 self.desired_capacity = 0 self.update()
[ "def", "shutdown_instances", "(", "self", ")", ":", "self", ".", "min_size", "=", "0", "self", ".", "max_size", "=", "0", "self", ".", "desired_capacity", "=", "0", "self", ".", "update", "(", ")" ]
https://github.com/VirtueSecurity/aws-extender/blob/d123b7e1a845847709ba3a481f11996bddc68a1c/BappModules/boto/ec2/autoscale/group.py#L284-L292
log2timeline/plaso
fe2e316b8c76a0141760c0f2f181d84acb83abc2
plaso/parsers/winreg_plugins/mrulistex.py
python
BaseMRUListExWindowsRegistryPlugin._ParseMRUListExValue
(self, registry_key)
return self._ReadStructureFromByteStream( mrulistex_value.data, 0, mrulistex_entries_map, context=context)
Parses the MRUListEx value in a given Registry key. Args: registry_key (dfwinreg.WinRegistryKey): Windows Registry key that contains the MRUListEx value. Returns: mrulistex_entries: MRUListEx entries or None if not available.
Parses the MRUListEx value in a given Registry key.
[ "Parses", "the", "MRUListEx", "value", "in", "a", "given", "Registry", "key", "." ]
def _ParseMRUListExValue(self, registry_key): """Parses the MRUListEx value in a given Registry key. Args: registry_key (dfwinreg.WinRegistryKey): Windows Registry key that contains the MRUListEx value. Returns: mrulistex_entries: MRUListEx entries or None if not available. """ mrulistex_value = registry_key.GetValueByName('MRUListEx') # The key exists but does not contain a value named "MRUList". if not mrulistex_value: return None mrulistex_entries_map = self._GetDataTypeMap('mrulistex_entries') context = dtfabric_data_maps.DataTypeMapContext(values={ 'data_size': len(mrulistex_value.data)}) return self._ReadStructureFromByteStream( mrulistex_value.data, 0, mrulistex_entries_map, context=context)
[ "def", "_ParseMRUListExValue", "(", "self", ",", "registry_key", ")", ":", "mrulistex_value", "=", "registry_key", ".", "GetValueByName", "(", "'MRUListEx'", ")", "# The key exists but does not contain a value named \"MRUList\".", "if", "not", "mrulistex_value", ":", "retur...
https://github.com/log2timeline/plaso/blob/fe2e316b8c76a0141760c0f2f181d84acb83abc2/plaso/parsers/winreg_plugins/mrulistex.py#L106-L128
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/sunau.py
python
Au_read.__init__
(self, f)
[]
def __init__(self, f): if type(f) == type(''): import builtins f = builtins.open(f, 'rb') self._opened = True else: self._opened = False self.initfp(f)
[ "def", "__init__", "(", "self", ",", "f", ")", ":", "if", "type", "(", "f", ")", "==", "type", "(", "''", ")", ":", "import", "builtins", "f", "=", "builtins", ".", "open", "(", "f", ",", "'rb'", ")", "self", ".", "_opened", "=", "True", "else"...
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/sunau.py#L159-L166
gramps-project/gramps
04d4651a43eb210192f40a9f8c2bad8ee8fa3753
gramps/gui/filters/sidebar/_sidebarfilter.py
python
SidebarFilter.on_db_changed
(self, db)
Called when the database is changed.
Called when the database is changed.
[ "Called", "when", "the", "database", "is", "changed", "." ]
def on_db_changed(self, db): """ Called when the database is changed. """ pass
[ "def", "on_db_changed", "(", "self", ",", "db", ")", ":", "pass" ]
https://github.com/gramps-project/gramps/blob/04d4651a43eb210192f40a9f8c2bad8ee8fa3753/gramps/gui/filters/sidebar/_sidebarfilter.py#L173-L177
nosarthur/gita
faf1a86fccbedfc7b671763c10c432beb7527abe
gita/utils.py
python
delete_repo_from_groups
(repo: str, groups: Dict[str, Dict])
return deleted
Delete repo from groups
Delete repo from groups
[ "Delete", "repo", "from", "groups" ]
def delete_repo_from_groups(repo: str, groups: Dict[str, Dict]) -> bool: """ Delete repo from groups """ deleted = False for name in groups: try: groups[name]['repos'].remove(repo) except ValueError as e: pass else: deleted = True return deleted
[ "def", "delete_repo_from_groups", "(", "repo", ":", "str", ",", "groups", ":", "Dict", "[", "str", ",", "Dict", "]", ")", "->", "bool", ":", "deleted", "=", "False", "for", "name", "in", "groups", ":", "try", ":", "groups", "[", "name", "]", "[", "...
https://github.com/nosarthur/gita/blob/faf1a86fccbedfc7b671763c10c432beb7527abe/gita/utils.py#L117-L129
twisted/twisted
dee676b040dd38b847ea6fb112a712cb5e119490
src/twisted/internet/interfaces.py
python
IReactorFromThreads.callFromThread
( callable: Callable[..., Any], *args: object, **kwargs: object )
Cause a function to be executed by the reactor thread. Use this method when you want to run a function in the reactor's thread from another thread. Calling L{callFromThread} should wake up the main thread (where L{reactor.run() <IReactorCore.run>} is executing) and run the given callable in that thread. If you're writing a multi-threaded application the C{callable} may need to be thread safe, but this method doesn't require it as such. If you want to call a function in the next mainloop iteration, but you're in the same thread, use L{callLater} with a delay of 0.
Cause a function to be executed by the reactor thread.
[ "Cause", "a", "function", "to", "be", "executed", "by", "the", "reactor", "thread", "." ]
def callFromThread( callable: Callable[..., Any], *args: object, **kwargs: object ) -> None: """ Cause a function to be executed by the reactor thread. Use this method when you want to run a function in the reactor's thread from another thread. Calling L{callFromThread} should wake up the main thread (where L{reactor.run() <IReactorCore.run>} is executing) and run the given callable in that thread. If you're writing a multi-threaded application the C{callable} may need to be thread safe, but this method doesn't require it as such. If you want to call a function in the next mainloop iteration, but you're in the same thread, use L{callLater} with a delay of 0. """
[ "def", "callFromThread", "(", "callable", ":", "Callable", "[", "...", ",", "Any", "]", ",", "*", "args", ":", "object", ",", "*", "*", "kwargs", ":", "object", ")", "->", "None", ":" ]
https://github.com/twisted/twisted/blob/dee676b040dd38b847ea6fb112a712cb5e119490/src/twisted/internet/interfaces.py#L1267-L1282
bitcraze/crazyflie-lib-python
876f0dc003b91ba5e4de05daae9d0b79cf600f81
cflib/crtp/crtpstack.py
python
CRTPPacket.is_data_size_valid
(self)
return self.available_data_size() >= 0
[]
def is_data_size_valid(self): return self.available_data_size() >= 0
[ "def", "is_data_size_valid", "(", "self", ")", ":", "return", "self", ".", "available_data_size", "(", ")", ">=", "0" ]
https://github.com/bitcraze/crazyflie-lib-python/blob/876f0dc003b91ba5e4de05daae9d0b79cf600f81/cflib/crtp/crtpstack.py#L152-L153
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/proxy/v1/service/phone_number.py
python
PhoneNumberInstance.capabilities
(self)
return self._properties['capabilities']
:returns: The capabilities of the phone number :rtype: unicode
:returns: The capabilities of the phone number :rtype: unicode
[ ":", "returns", ":", "The", "capabilities", "of", "the", "phone", "number", ":", "rtype", ":", "unicode" ]
def capabilities(self): """ :returns: The capabilities of the phone number :rtype: unicode """ return self._properties['capabilities']
[ "def", "capabilities", "(", "self", ")", ":", "return", "self", ".", "_properties", "[", "'capabilities'", "]" ]
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/proxy/v1/service/phone_number.py#L397-L402
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py
python
Requirement.__init__
(self, requirement_string)
DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!
DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!
[ "DO", "NOT", "CALL", "THIS", "UNDOCUMENTED", "METHOD", ";", "use", "Requirement", ".", "parse", "()", "!" ]
def __init__(self, requirement_string): """DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!""" try: super(Requirement, self).__init__(requirement_string) except packaging.requirements.InvalidRequirement as e: raise RequirementParseError(str(e)) self.unsafe_name = self.name project_name = safe_name(self.name) self.project_name, self.key = project_name, project_name.lower() self.specs = [ (spec.operator, spec.version) for spec in self.specifier] self.extras = tuple(map(safe_extra, self.extras)) self.hashCmp = ( self.key, self.specifier, frozenset(self.extras), str(self.marker) if self.marker else None, ) self.__hash = hash(self.hashCmp)
[ "def", "__init__", "(", "self", ",", "requirement_string", ")", ":", "try", ":", "super", "(", "Requirement", ",", "self", ")", ".", "__init__", "(", "requirement_string", ")", "except", "packaging", ".", "requirements", ".", "InvalidRequirement", "as", "e", ...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py#L2871-L2889
HypothesisWorks/hypothesis
d1bfc4acc86899caa7a40f892322e1a69fbf36f4
hypothesis-python/src/hypothesis/strategies/_internal/strategies.py
python
SearchStrategy.__or__
(self, other: "SearchStrategy[T]")
return OneOfStrategy((self, other))
Return a strategy which produces values by randomly drawing from one of this strategy or the other strategy. This method is part of the public API.
Return a strategy which produces values by randomly drawing from one of this strategy or the other strategy.
[ "Return", "a", "strategy", "which", "produces", "values", "by", "randomly", "drawing", "from", "one", "of", "this", "strategy", "or", "the", "other", "strategy", "." ]
def __or__(self, other: "SearchStrategy[T]") -> "SearchStrategy[Union[Ex, T]]": """Return a strategy which produces values by randomly drawing from one of this strategy or the other strategy. This method is part of the public API. """ if not isinstance(other, SearchStrategy): raise ValueError(f"Cannot | a SearchStrategy with {other!r}") return OneOfStrategy((self, other))
[ "def", "__or__", "(", "self", ",", "other", ":", "\"SearchStrategy[T]\"", ")", "->", "\"SearchStrategy[Union[Ex, T]]\"", ":", "if", "not", "isinstance", "(", "other", ",", "SearchStrategy", ")", ":", "raise", "ValueError", "(", "f\"Cannot | a SearchStrategy with {othe...
https://github.com/HypothesisWorks/hypothesis/blob/d1bfc4acc86899caa7a40f892322e1a69fbf36f4/hypothesis-python/src/hypothesis/strategies/_internal/strategies.py#L387-L395
edfungus/Crouton
ada98b3930192938a48909072b45cb84b945f875
clients/python_clients/venv/lib/python2.7/site-packages/pkg_resources/__init__.py
python
Distribution.insert_on
(self, path, loc = None)
return
Insert self.location in path before its nearest parent directory
Insert self.location in path before its nearest parent directory
[ "Insert", "self", ".", "location", "in", "path", "before", "its", "nearest", "parent", "directory" ]
def insert_on(self, path, loc = None): """Insert self.location in path before its nearest parent directory""" loc = loc or self.location if not loc: return nloc = _normalize_cached(loc) bdir = os.path.dirname(nloc) npath= [(p and _normalize_cached(p) or p) for p in path] for p, item in enumerate(npath): if item == nloc: break elif item == bdir and self.precedence == EGG_DIST: # if it's an .egg, give it precedence over its directory if path is sys.path: self.check_version_conflict() path.insert(p, loc) npath.insert(p, nloc) break else: if path is sys.path: self.check_version_conflict() path.append(loc) return # p is the spot where we found or inserted loc; now remove duplicates while True: try: np = npath.index(nloc, p+1) except ValueError: break else: del npath[np], path[np] # ha! p = np return
[ "def", "insert_on", "(", "self", ",", "path", ",", "loc", "=", "None", ")", ":", "loc", "=", "loc", "or", "self", ".", "location", "if", "not", "loc", ":", "return", "nloc", "=", "_normalize_cached", "(", "loc", ")", "bdir", "=", "os", ".", "path",...
https://github.com/edfungus/Crouton/blob/ada98b3930192938a48909072b45cb84b945f875/clients/python_clients/venv/lib/python2.7/site-packages/pkg_resources/__init__.py#L2700-L2738
rowliny/DiffHelper
ab3a96f58f9579d0023aed9ebd785f4edf26f8af
Tool/SitePackages/PIL/BlpImagePlugin.py
python
decode_dxt1
(data, alpha=False)
return ret
input: one "row" of data (i.e. will produce 4*width pixels)
input: one "row" of data (i.e. will produce 4*width pixels)
[ "input", ":", "one", "row", "of", "data", "(", "i", ".", "e", ".", "will", "produce", "4", "*", "width", "pixels", ")" ]
def decode_dxt1(data, alpha=False): """ input: one "row" of data (i.e. will produce 4*width pixels) """ blocks = len(data) // 8 # number of blocks in row ret = (bytearray(), bytearray(), bytearray(), bytearray()) for block in range(blocks): # Decode next 8-byte block. idx = block * 8 color0, color1, bits = struct.unpack_from("<HHI", data, idx) r0, g0, b0 = unpack_565(color0) r1, g1, b1 = unpack_565(color1) # Decode this block into 4x4 pixels # Accumulate the results onto our 4 row accumulators for j in range(4): for i in range(4): # get next control op and generate a pixel control = bits & 3 bits = bits >> 2 a = 0xFF if control == 0: r, g, b = r0, g0, b0 elif control == 1: r, g, b = r1, g1, b1 elif control == 2: if color0 > color1: r = (2 * r0 + r1) // 3 g = (2 * g0 + g1) // 3 b = (2 * b0 + b1) // 3 else: r = (r0 + r1) // 2 g = (g0 + g1) // 2 b = (b0 + b1) // 2 elif control == 3: if color0 > color1: r = (2 * r1 + r0) // 3 g = (2 * g1 + g0) // 3 b = (2 * b1 + b0) // 3 else: r, g, b, a = 0, 0, 0, 0 if alpha: ret[j].extend([r, g, b, a]) else: ret[j].extend([r, g, b]) return ret
[ "def", "decode_dxt1", "(", "data", ",", "alpha", "=", "False", ")", ":", "blocks", "=", "len", "(", "data", ")", "//", "8", "# number of blocks in row", "ret", "=", "(", "bytearray", "(", ")", ",", "bytearray", "(", ")", ",", "bytearray", "(", ")", "...
https://github.com/rowliny/DiffHelper/blob/ab3a96f58f9579d0023aed9ebd785f4edf26f8af/Tool/SitePackages/PIL/BlpImagePlugin.py#L52-L104
xmengli/H-DenseUNet
06cc436a43196310fe933d114a353839907cc176
Keras-2.0.8/keras/utils/data_utils.py
python
OrderedEnqueuer.get
(self)
Creates a generator to extract data from the queue. Skip the data if it is `None`. # Returns Generator yielding tuples (inputs, targets) or (inputs, targets, sample_weights)
Creates a generator to extract data from the queue.
[ "Creates", "a", "generator", "to", "extract", "data", "from", "the", "queue", "." ]
def get(self): """Creates a generator to extract data from the queue. Skip the data if it is `None`. # Returns Generator yielding tuples (inputs, targets) or (inputs, targets, sample_weights) """ try: while self.is_running(): inputs = self.queue.get(block=True).get() if inputs is not None: yield inputs except Exception as e: self.stop() raise StopIteration(e)
[ "def", "get", "(", "self", ")", ":", "try", ":", "while", "self", ".", "is_running", "(", ")", ":", "inputs", "=", "self", ".", "queue", ".", "get", "(", "block", "=", "True", ")", ".", "get", "(", ")", "if", "inputs", "is", "not", "None", ":",...
https://github.com/xmengli/H-DenseUNet/blob/06cc436a43196310fe933d114a353839907cc176/Keras-2.0.8/keras/utils/data_utils.py#L494-L510
zim-desktop-wiki/zim-desktop-wiki
fe717d7ee64e5c06d90df90eb87758e5e72d25c5
zim/gui/widgets.py
python
InputEntry.clear
(self)
Clear the text in the entry
Clear the text in the entry
[ "Clear", "the", "text", "in", "the", "entry" ]
def clear(self): '''Clear the text in the entry''' self.set_text('')
[ "def", "clear", "(", "self", ")", ":", "self", ".", "set_text", "(", "''", ")" ]
https://github.com/zim-desktop-wiki/zim-desktop-wiki/blob/fe717d7ee64e5c06d90df90eb87758e5e72d25c5/zim/gui/widgets.py#L1525-L1527
SHI-Labs/Pyramid-Attention-Networks
a267cf8ef663212c1e1f7238b6313ff1d780ae94
Demosaic/code/model/utils/tools.py
python
extract_image_patches
(images, ksizes, strides, rates, padding='same')
return patches
Extract patches from images and put them in the C output dimension. :param padding: :param images: [batch, channels, in_rows, in_cols]. A 4-D Tensor with shape :param ksizes: [ksize_rows, ksize_cols]. The size of the sliding window for each dimension of images :param strides: [stride_rows, stride_cols] :param rates: [dilation_rows, dilation_cols] :return: A Tensor
Extract patches from images and put them in the C output dimension. :param padding: :param images: [batch, channels, in_rows, in_cols]. A 4-D Tensor with shape :param ksizes: [ksize_rows, ksize_cols]. The size of the sliding window for each dimension of images :param strides: [stride_rows, stride_cols] :param rates: [dilation_rows, dilation_cols] :return: A Tensor
[ "Extract", "patches", "from", "images", "and", "put", "them", "in", "the", "C", "output", "dimension", ".", ":", "param", "padding", ":", ":", "param", "images", ":", "[", "batch", "channels", "in_rows", "in_cols", "]", ".", "A", "4", "-", "D", "Tensor...
def extract_image_patches(images, ksizes, strides, rates, padding='same'): """ Extract patches from images and put them in the C output dimension. :param padding: :param images: [batch, channels, in_rows, in_cols]. A 4-D Tensor with shape :param ksizes: [ksize_rows, ksize_cols]. The size of the sliding window for each dimension of images :param strides: [stride_rows, stride_cols] :param rates: [dilation_rows, dilation_cols] :return: A Tensor """ assert len(images.size()) == 4 assert padding in ['same', 'valid'] batch_size, channel, height, width = images.size() if padding == 'same': images = same_padding(images, ksizes, strides, rates) elif padding == 'valid': pass else: raise NotImplementedError('Unsupported padding type: {}.\ Only "same" or "valid" are supported.'.format(padding)) unfold = torch.nn.Unfold(kernel_size=ksizes, dilation=rates, padding=0, stride=strides) patches = unfold(images) return patches # [N, C*k*k, L], L is the total number of such blocks
[ "def", "extract_image_patches", "(", "images", ",", "ksizes", ",", "strides", ",", "rates", ",", "padding", "=", "'same'", ")", ":", "assert", "len", "(", "images", ".", "size", "(", ")", ")", "==", "4", "assert", "padding", "in", "[", "'same'", ",", ...
https://github.com/SHI-Labs/Pyramid-Attention-Networks/blob/a267cf8ef663212c1e1f7238b6313ff1d780ae94/Demosaic/code/model/utils/tools.py#L30-L58
Phype/telnet-iot-honeypot
f1d4b75245d72990d339668f37a1670fc85c0c9b
backend/ipdb/ipdb.py
python
IPTable.find
(self, ip)
return self.find_i(ipstr2int(ip), 0, len(self.tzlist) - 1)
[]
def find(self, ip): return self.find_i(ipstr2int(ip), 0, len(self.tzlist) - 1)
[ "def", "find", "(", "self", ",", "ip", ")", ":", "return", "self", ".", "find_i", "(", "ipstr2int", "(", "ip", ")", ",", "0", ",", "len", "(", "self", ".", "tzlist", ")", "-", "1", ")" ]
https://github.com/Phype/telnet-iot-honeypot/blob/f1d4b75245d72990d339668f37a1670fc85c0c9b/backend/ipdb/ipdb.py#L49-L50
xct/ropstar
f025a2e4923b501d68d24fa44b22869a84e29e3e
ropstar/exploit.py
python
Exploit.bss
(self, p, libc=None)
return result
Writes /bin/bash string to bss, used as argument to system. Can work with and without libc.
Writes /bin/bash string to bss, used as argument to system. Can work with and without libc.
[ "Writes", "/", "bin", "/", "bash", "string", "to", "bss", "used", "as", "argument", "to", "system", ".", "Can", "work", "with", "and", "without", "libc", "." ]
def bss(self, p, libc=None): ''' Writes /bin/bash string to bss, used as argument to system. Can work with and without libc. ''' log.info("Exploit: gets(bss); system(bss)") result = False rop = ROP(self.binary) bss = self.binary.bss() gets = None system = None if libc: # ret2libc gets = libc.symbols['gets'] system = libc.symbols['system'] else: # ret2plt try: gets = self.binary.plt['gets'] system = self.binary.plt['system'] except KeyError: pass if gets and system: rop.call(gets, [bss]) rop.call(system, [bss]) log.info(rop.dump()) payload = self.ropstar.fit(rop.chain()) self.ropstar.trigger(p, payload) p.sendline('/bin/bash') result = self.ropstar.check_success(p) if result: save('payload', payload) return result
[ "def", "bss", "(", "self", ",", "p", ",", "libc", "=", "None", ")", ":", "log", ".", "info", "(", "\"Exploit: gets(bss); system(bss)\"", ")", "result", "=", "False", "rop", "=", "ROP", "(", "self", ".", "binary", ")", "bss", "=", "self", ".", "binary...
https://github.com/xct/ropstar/blob/f025a2e4923b501d68d24fa44b22869a84e29e3e/ropstar/exploit.py#L86-L116
pymedusa/Medusa
1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38
ext/rebulk/rebulk.py
python
Rebulk.rebulk
(self, *rebulks)
return self
Add a children rebulk object :param rebulks: :type rebulks: Rebulk :return:
Add a children rebulk object :param rebulks: :type rebulks: Rebulk :return:
[ "Add", "a", "children", "rebulk", "object", ":", "param", "rebulks", ":", ":", "type", "rebulks", ":", "Rebulk", ":", "return", ":" ]
def rebulk(self, *rebulks): """ Add a children rebulk object :param rebulks: :type rebulks: Rebulk :return: """ self._rebulks.extend(rebulks) return self
[ "def", "rebulk", "(", "self", ",", "*", "rebulks", ")", ":", "self", ".", "_rebulks", ".", "extend", "(", "rebulks", ")", "return", "self" ]
https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/ext/rebulk/rebulk.py#L89-L97
CouchPotato/CouchPotatoServer
7260c12f72447ddb6f062367c6dfbda03ecd4e9c
libs/qbittorrent/client.py
python
QBittorrentClient.resume
(self, infohash)
return self._post('command/resume', data={'hash': infohash.lower()})
Resume a paused torrent. :param infohash: INFO HASH of torrent.
Resume a paused torrent.
[ "Resume", "a", "paused", "torrent", "." ]
def resume(self, infohash): """ Resume a paused torrent. :param infohash: INFO HASH of torrent. """ return self._post('command/resume', data={'hash': infohash.lower()})
[ "def", "resume", "(", "self", ",", "infohash", ")", ":", "return", "self", ".", "_post", "(", "'command/resume'", ",", "data", "=", "{", "'hash'", ":", "infohash", ".", "lower", "(", ")", "}", ")" ]
https://github.com/CouchPotato/CouchPotatoServer/blob/7260c12f72447ddb6f062367c6dfbda03ecd4e9c/libs/qbittorrent/client.py#L396-L402
Yukinoshita47/Yuki-Chan-The-Auto-Pentest
bea1af4e1d544eadc166f728be2f543ea10af191
Module/WAFNinja/wafninja.py
python
setHeaders
(cookie)
:Description: This function sets the cookie for the requests. :param cookie: A Cookie String :type cookie: String :todo: Add also other header
:Description: This function sets the cookie for the requests.
[ ":", "Description", ":", "This", "function", "sets", "the", "cookie", "for", "the", "requests", "." ]
def setHeaders(cookie): """ :Description: This function sets the cookie for the requests. :param cookie: A Cookie String :type cookie: String :todo: Add also other header """ if cookie is not None: header.append(['Cookie',cookie])
[ "def", "setHeaders", "(", "cookie", ")", ":", "if", "cookie", "is", "not", "None", ":", "header", ".", "append", "(", "[", "'Cookie'", ",", "cookie", "]", ")" ]
https://github.com/Yukinoshita47/Yuki-Chan-The-Auto-Pentest/blob/bea1af4e1d544eadc166f728be2f543ea10af191/Module/WAFNinja/wafninja.py#L18-L28
urbenlegend/netimpair
0dc608f6c263beb78092f8b28a650dc93b7c0e56
netimpair.py
python
NetemInstance.teardown
(self)
Reset traffic control rules.
Reset traffic control rules.
[ "Reset", "traffic", "control", "rules", "." ]
def teardown(self): '''Reset traffic control rules.''' if self.inbound: self._call( 'tc filter del dev {0} parent ffff: protocol ip prio 1'.format( self.real_nic)) self._call('tc qdisc del dev {0} ingress'.format(self.real_nic)) self._call('ip link set dev ifb0 down') self._call('tc qdisc del root dev {0}'.format(self.nic)) print('Network impairment teardown complete.')
[ "def", "teardown", "(", "self", ")", ":", "if", "self", ".", "inbound", ":", "self", ".", "_call", "(", "'tc filter del dev {0} parent ffff: protocol ip prio 1'", ".", "format", "(", "self", ".", "real_nic", ")", ")", "self", ".", "_call", "(", "'tc qdisc del ...
https://github.com/urbenlegend/netimpair/blob/0dc608f6c263beb78092f8b28a650dc93b7c0e56/netimpair.py#L231-L240
JoelBender/bacpypes
41104c2b565b2ae9a637c941dfb0fe04195c5e96
samples/OpenWeatherServer.py
python
flatten
(x, prefix="$")
Turn a JSON object into (key, value) tuples using JSON-Path like names for the keys.
Turn a JSON object into (key, value) tuples using JSON-Path like names for the keys.
[ "Turn", "a", "JSON", "object", "into", "(", "key", "value", ")", "tuples", "using", "JSON", "-", "Path", "like", "names", "for", "the", "keys", "." ]
def flatten(x, prefix="$"): """Turn a JSON object into (key, value) tuples using JSON-Path like names for the keys.""" if type(x) is dict: for a in x: yield from flatten(x[a], prefix + "." + a) elif type(x) is list: for i, y in enumerate(x): yield from flatten(y, prefix + "[" + str(i) + "]") else: yield (prefix, x)
[ "def", "flatten", "(", "x", ",", "prefix", "=", "\"$\"", ")", ":", "if", "type", "(", "x", ")", "is", "dict", ":", "for", "a", "in", "x", ":", "yield", "from", "flatten", "(", "x", "[", "a", "]", ",", "prefix", "+", "\".\"", "+", "a", ")", ...
https://github.com/JoelBender/bacpypes/blob/41104c2b565b2ae9a637c941dfb0fe04195c5e96/samples/OpenWeatherServer.py#L175-L185
pikepdf/pikepdf
63b660b68b52a0f99ced3015fe4acb66fb6ca8d5
src/pikepdf/models/matrix.py
python
PdfMatrix.__matmul__
(self, other)
return PdfMatrix( [ [sum(float(i) * float(j) for i, j in zip(row, col)) for col in zip(*b)] for row in a ] )
Multiply this matrix by another matrix Can be used to concatenate transformations.
Multiply this matrix by another matrix
[ "Multiply", "this", "matrix", "by", "another", "matrix" ]
def __matmul__(self, other): """Multiply this matrix by another matrix Can be used to concatenate transformations. """ a = self.values b = other.values return PdfMatrix( [ [sum(float(i) * float(j) for i, j in zip(row, col)) for col in zip(*b)] for row in a ] )
[ "def", "__matmul__", "(", "self", ",", "other", ")", ":", "a", "=", "self", ".", "values", "b", "=", "other", ".", "values", "return", "PdfMatrix", "(", "[", "[", "sum", "(", "float", "(", "i", ")", "*", "float", "(", "j", ")", "for", "i", ",",...
https://github.com/pikepdf/pikepdf/blob/63b660b68b52a0f99ced3015fe4acb66fb6ca8d5/src/pikepdf/models/matrix.py#L63-L76
nodesign/weio
1d67d705a5c36a2e825ad13feab910b0aca9a2e8
openWrt/files/usr/lib/python2.7/site-packages/tornado/iostream.py
python
SSLIOStream.read_from_fd
(self)
return chunk
[]
def read_from_fd(self): if self._ssl_accepting: # If the handshake hasn't finished yet, there can't be anything # to read (attempting to read may or may not raise an exception # depending on the SSL version) return None try: # SSLSocket objects have both a read() and recv() method, # while regular sockets only have recv(). # The recv() method blocks (at least in python 2.6) if it is # called when there is nothing to read, so we have to use # read() instead. chunk = self.socket.read(self.read_chunk_size) except ssl.SSLError as e: # SSLError is a subclass of socket.error, so this except # block must come first. if e.args[0] == ssl.SSL_ERROR_WANT_READ: return None else: raise except socket.error as e: if e.args[0] in (errno.EWOULDBLOCK, errno.EAGAIN): return None else: raise if not chunk: self.close() return None return chunk
[ "def", "read_from_fd", "(", "self", ")", ":", "if", "self", ".", "_ssl_accepting", ":", "# If the handshake hasn't finished yet, there can't be anything", "# to read (attempting to read may or may not raise an exception", "# depending on the SSL version)", "return", "None", "try", ...
https://github.com/nodesign/weio/blob/1d67d705a5c36a2e825ad13feab910b0aca9a2e8/openWrt/files/usr/lib/python2.7/site-packages/tornado/iostream.py#L844-L872
sabnzbd/sabnzbd
52d21e94d3cc6e30764a833fe2a256783d1a8931
sabnzbd/utils/apireg.py
python
get_connection_info
(user=True)
return url
Return URL of the API running SABnzbd instance 'user' == True will first try user's registry, otherwise system is used
Return URL of the API running SABnzbd instance 'user' == True will first try user's registry, otherwise system is used
[ "Return", "URL", "of", "the", "API", "running", "SABnzbd", "instance", "user", "==", "True", "will", "first", "try", "user", "s", "registry", "otherwise", "system", "is", "used" ]
def get_connection_info(user=True): """Return URL of the API running SABnzbd instance 'user' == True will first try user's registry, otherwise system is used """ section, keypath = reg_info(user) url = None try: hive = winreg.ConnectRegistry(None, section) key = winreg.OpenKey(hive, keypath + r"\api") for i in range(0, winreg.QueryInfoKey(key)[1]): name, value, val_type = winreg.EnumValue(key, i) if name == "url": url = value winreg.CloseKey(key) except OSError: pass finally: winreg.CloseKey(hive) # Nothing in user's registry, try system registry if user and not url: url = get_connection_info(user=False) return url
[ "def", "get_connection_info", "(", "user", "=", "True", ")", ":", "section", ",", "keypath", "=", "reg_info", "(", "user", ")", "url", "=", "None", "try", ":", "hive", "=", "winreg", ".", "ConnectRegistry", "(", "None", ",", "section", ")", "key", "=",...
https://github.com/sabnzbd/sabnzbd/blob/52d21e94d3cc6e30764a833fe2a256783d1a8931/sabnzbd/utils/apireg.py#L38-L63
proycon/pynlpl
7707f69a91caaa6cde037f0d0379f1d42500a68b
pynlpl/formats/fql.py
python
Correction.__call__
(self, query, action, focus, target,debug=False)
Action delegates to this function
Action delegates to this function
[ "Action", "delegates", "to", "this", "function" ]
def __call__(self, query, action, focus, target,debug=False): """Action delegates to this function""" if debug: print("[FQL EVALUATION DEBUG] Correction - Processing ", repr(focus),file=sys.stderr) isspan = isinstance(action.focus.Class, folia.AbstractSpanAnnotation) actionassignments = {} #make a copy for key, value in action.assignments.items(): if key == 'class': key = 'cls' actionassignments[key] = value for key, value in self.actionassignments.items(): if key == 'class': key = 'cls' actionassignments[key] = value if actionassignments: if (not 'set' in actionassignments or actionassignments['set'] is None) and action.focus.Class: try: actionassignments['set'] = query.defaultsets[action.focus.Class.XMLTAG] except KeyError: actionassignments['set'] = query.doc.defaultset(action.focus.Class) if action.focus.Class.REQUIRED_ATTRIBS and folia.Attrib.ID in action.focus.Class.REQUIRED_ATTRIBS: actionassignments['id'] = getrandomid(query, "corrected." + action.focus.Class.XMLTAG + ".") kwargs = {} if self.set: kwargs['set'] = self.set for key, value in self.assignments.items(): if key == 'class': key = 'cls' kwargs[key] = value if action.action == "SELECT": if not focus: raise QueryError("SELECT requires a focus element") correction = focus.incorrection() if correction: if not self.filter or (self.filter and self.filter.match(query, correction, debug)): yield correction elif action.action in ("EDIT","ADD","PREPEND","APPEND"): if focus: correction = focus.incorrection() else: correction = False inheritchildren = [] if focus and not self.bare: #copy all data within inheritchildren = list(focus.copychildren(query.doc, True)) if action.action == "EDIT" and action.span: #respan #delete all word references from the copy first, we will add new ones inheritchildren = [ c for c in inheritchildren if not isinstance(c, folia.WordReference) ] if not isinstance(focus, folia.AbstractSpanAnnotation): raise QueryError("Can only perform RESPAN on span annotation elements!") contextselector = target if target else query.doc spanset = next(action.span(query, contextselector, True, debug)) #there can be only one for w in spanset: inheritchildren.append(w) if actionassignments: kwargs['new'] = action.focus.Class(query.doc,*inheritchildren, **actionassignments) if focus and action.action not in ('PREPEND','APPEND'): kwargs['original'] = focus #TODO: if not bare, fix all span annotation references to this element elif focus and action.action not in ('PREPEND','APPEND'): if isinstance(focus, folia.AbstractStructureElement): kwargs['current'] = focus #current only needed for structure annotation if correction and (not 'set' in kwargs or correction.set == kwargs['set']) and (not 'cls' in kwargs or correction.cls == kwargs['cls']): #reuse the existing correction element print("Reusing " + correction.id,file=sys.stderr) kwargs['reuse'] = correction if action.action in ('PREPEND','APPEND'): #get parent relative to target parent = target.ancestor( (folia.AbstractStructureElement, folia.AbstractSpanAnnotation, folia.AbstractAnnotationLayer) ) elif focus: if 'reuse' in kwargs and kwargs['reuse']: parent = focus.ancestor( (folia.AbstractStructureElement, folia.AbstractSpanAnnotation, folia.AbstractAnnotationLayer) ) else: parent = focus.ancestor( (folia.AbstractStructureElement, folia.AbstractSpanAnnotation, folia.AbstractAnnotationLayer, folia.Correction) ) else: parent = target if 'id' not in kwargs and 'reuse' not in kwargs: kwargs['id'] = parent.generate_id(folia.Correction) kwargs['suggestions'] = [] for subassignments, suggestionassignments in self.suggestions: subassignments = copy(subassignments) #assignment for the element in the suggestion for key, value in action.assignments.items(): if not key in subassignments: if key == 'class': key = 'cls' subassignments[key] = value if (not 'set' in subassignments or subassignments['set'] is None) and action.focus.Class: try: subassignments['set'] = query.defaultsets[action.focus.Class.XMLTAG] except KeyError: subassignments['set'] = query.doc.defaultset(action.focus.Class) if focus and not self.bare: #copy all data within (we have to do this again for each suggestion as it will generate different ID suffixes) inheritchildren = list(focus.copychildren(query.doc, True)) if action.focus.Class.REQUIRED_ATTRIBS and folia.Attrib.ID in action.focus.Class.REQUIRED_ATTRIBS: subassignments['id'] = getrandomid(query, "suggestion.") kwargs['suggestions'].append( folia.Suggestion(query.doc, action.focus.Class(query.doc, *inheritchildren,**subassignments), **suggestionassignments ) ) if action.action == 'PREPEND': index = parent.getindex(target,True) #recursive if index == -1: raise QueryError("Insertion point for PREPEND action not found") kwargs['insertindex'] = index kwargs['nooriginal'] = True elif action.action == 'APPEND': index = parent.getindex(target,True) #recursive if index == -1: raise QueryError("Insertion point for APPEND action not found") kwargs['insertindex'] = index+1 kwargs['insertindex_offset'] = 1 #used by correct if it needs to recompute the index kwargs['nooriginal'] = True yield parent.correct(**kwargs) #generator elif action.action == "DELETE": if debug: print("[FQL EVALUATION DEBUG] Correction - Deleting ", repr(focus), " (in " + repr(focus.parent) + ")",file=sys.stderr) if not focus: raise QueryError("DELETE AS CORRECTION did not find a focus to operate on") kwargs['original'] = focus kwargs['new'] = [] #empty new c = focus.parent.correct(**kwargs) #generator yield c else: raise QueryError("Correction does not handle action " + action.action)
[ "def", "__call__", "(", "self", ",", "query", ",", "action", ",", "focus", ",", "target", ",", "debug", "=", "False", ")", ":", "if", "debug", ":", "print", "(", "\"[FQL EVALUATION DEBUG] Correction - Processing \"", ",", "repr", "(", "focus", ")", ",", "f...
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/fql.py#L1036-L1159
wistbean/learn_python3_spider
73c873f4845f4385f097e5057407d03dd37a117b
stackoverflow/venv/lib/python3.6/site-packages/twisted/internet/utils.py
python
getProcessOutput
(executable, args=(), env={}, path=None, reactor=None, errortoo=0)
return _callProtocolWithDeferred(lambda d: _BackRelay(d, errortoo=errortoo), executable, args, env, path, reactor)
Spawn a process and return its output as a deferred returning a L{bytes}. @param executable: The file name to run and get the output of - the full path should be used. @param args: the command line arguments to pass to the process; a sequence of strings. The first string should B{NOT} be the executable's name. @param env: the environment variables to pass to the process; a dictionary of strings. @param path: the path to run the subprocess in - defaults to the current directory. @param reactor: the reactor to use - defaults to the default reactor @param errortoo: If true, include stderr in the result. If false, if stderr is received the returned L{Deferred} will errback with an L{IOError} instance with a C{processEnded} attribute. The C{processEnded} attribute refers to a L{Deferred} which fires when the executed process ends.
Spawn a process and return its output as a deferred returning a L{bytes}.
[ "Spawn", "a", "process", "and", "return", "its", "output", "as", "a", "deferred", "returning", "a", "L", "{", "bytes", "}", "." ]
def getProcessOutput(executable, args=(), env={}, path=None, reactor=None, errortoo=0): """ Spawn a process and return its output as a deferred returning a L{bytes}. @param executable: The file name to run and get the output of - the full path should be used. @param args: the command line arguments to pass to the process; a sequence of strings. The first string should B{NOT} be the executable's name. @param env: the environment variables to pass to the process; a dictionary of strings. @param path: the path to run the subprocess in - defaults to the current directory. @param reactor: the reactor to use - defaults to the default reactor @param errortoo: If true, include stderr in the result. If false, if stderr is received the returned L{Deferred} will errback with an L{IOError} instance with a C{processEnded} attribute. The C{processEnded} attribute refers to a L{Deferred} which fires when the executed process ends. """ return _callProtocolWithDeferred(lambda d: _BackRelay(d, errortoo=errortoo), executable, args, env, path, reactor)
[ "def", "getProcessOutput", "(", "executable", ",", "args", "=", "(", ")", ",", "env", "=", "{", "}", ",", "path", "=", "None", ",", "reactor", "=", "None", ",", "errortoo", "=", "0", ")", ":", "return", "_callProtocolWithDeferred", "(", "lambda", "d", ...
https://github.com/wistbean/learn_python3_spider/blob/73c873f4845f4385f097e5057407d03dd37a117b/stackoverflow/venv/lib/python3.6/site-packages/twisted/internet/utils.py#L100-L129
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/rings/asymptotic/asymptotics_multivariate_generating_functions.py
python
FractionWithFactoredDenominatorRing._element_constructor_
(self, *args, **kwargs)
return self.element_class(self, numerator=numerator, denominator_factored=denominator_factored, reduce=reduce)
r""" Returns an element of this ring. See :class:`FractionWithFactoredDenominator` for details. TESTS:: sage: from sage.rings.asymptotic.asymptotics_multivariate_generating_functions import FractionWithFactoredDenominatorRing sage: R.<x,y> = PolynomialRing(QQ) sage: FFPD = FractionWithFactoredDenominatorRing(R) sage: df = [x, 1], [y, 1], [x*y+1, 1] sage: f = FFPD(x, df) # indirect doctest sage: f (1, [(y, 1), (x*y + 1, 1)])
r""" Returns an element of this ring.
[ "r", "Returns", "an", "element", "of", "this", "ring", "." ]
def _element_constructor_(self, *args, **kwargs): r""" Returns an element of this ring. See :class:`FractionWithFactoredDenominator` for details. TESTS:: sage: from sage.rings.asymptotic.asymptotics_multivariate_generating_functions import FractionWithFactoredDenominatorRing sage: R.<x,y> = PolynomialRing(QQ) sage: FFPD = FractionWithFactoredDenominatorRing(R) sage: df = [x, 1], [y, 1], [x*y+1, 1] sage: f = FFPD(x, df) # indirect doctest sage: f (1, [(y, 1), (x*y + 1, 1)]) """ R = self.base() Q = R.fraction_field() # process keyword arguments reduce = kwargs.pop('reduce', None) if kwargs: raise ValueError('Unknown keyword arguments ' '%s given' % (kwargs,)) # process arguments if len(args) > 2: raise ValueError('too many arguments given') elif not args: raise ValueError('No argument given. ' 'We are in serious troubles...') # At this point we have one or two input arguments. x = args[0] try: P = x.parent() except AttributeError: P = None denominator_factored = None # init reduce_default = True if len(args) == 2: numerator, denominator_factored = args if numerator is None: numerator = R(0) if denominator_factored is None: denominator_factored = [] from sage.rings.semirings.non_negative_integer_semiring import NN try: denominator_factored = sorted( (R(d[0]), NN(d[1])) for d in denominator_factored) except TypeError: raise TypeError('factored denominator is not well-formed ' 'or of wrong type') # From now on we only have one input argument; # it's called x and has parent P. elif isinstance(P, FractionWithFactoredDenominatorRing): numerator = x._numerator denominator_factored = self._denominator_factored reduce_default = False elif P == SR: numerator = x.numerator() denominator = x.denominator() reduce_default = False elif x in R: numerator = R(x) denominator_factored = [] elif x in Q: quotient = Q(x) numerator = quotient.numerator() denominator = quotient.denominator() reduce_default = False elif hasattr(x, 'numerator') and hasattr(x, 'denominator'): numerator = x.numerator() denominator = x.denominator() reduce_default = False else: raise TypeError('element {} is not contained in {}'.format(x, self)) if reduce is None: reduce = reduce_default if denominator_factored is None: if denominator not in R: raise TypeError('extracted denominator {} is not in {}'.format(denominator, self)) p = numerator q = R(denominator) from sage.rings.polynomial.polynomial_ring import is_PolynomialRing from sage.rings.polynomial.multi_polynomial_ring_base import is_MPolynomialRing if is_PolynomialRing(R) or is_MPolynomialRing(R): if not R(q).is_unit(): # Factor denominator try: df = q.factor() except NotImplementedError: # Singular's factor() needs 'proof=False'. df = q.factor(proof=False) numerator = p / df.unit() df = sorted(tuple(t) for t in df) # sort for consistency denominator_factored = df else: # At this point, denominator could not be factored. numerator = p / q denominator_factored = [] return self.element_class(self, numerator=numerator, denominator_factored=denominator_factored, reduce=reduce)
[ "def", "_element_constructor_", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "R", "=", "self", ".", "base", "(", ")", "Q", "=", "R", ".", "fraction_field", "(", ")", "# process keyword arguments", "reduce", "=", "kwargs", ".", "pop...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/rings/asymptotic/asymptotics_multivariate_generating_functions.py#L3129-L3250
bigaidream-projects/drmad
a4bb6010595d956f29c5a42a095bab76a60b29eb
cpu_ver/funkyyak/funkyyak/node_types.py
python
FloatNode.zeros
(self)
return 0.0
[]
def zeros(self): return 0.0
[ "def", "zeros", "(", "self", ")", ":", "return", "0.0" ]
https://github.com/bigaidream-projects/drmad/blob/a4bb6010595d956f29c5a42a095bab76a60b29eb/cpu_ver/funkyyak/funkyyak/node_types.py#L25-L26
astropy/photutils
3caa48e4e4d139976ed7457dc41583fb2c56ba20
photutils/background/background_2d.py
python
Background2D.background_mesh_masked
(self)
return data
The background 2D (masked) array mesh prior to any interpolation. The array has NaN values where meshes were excluded.
The background 2D (masked) array mesh prior to any interpolation. The array has NaN values where meshes were excluded.
[ "The", "background", "2D", "(", "masked", ")", "array", "mesh", "prior", "to", "any", "interpolation", ".", "The", "array", "has", "NaN", "values", "where", "meshes", "were", "excluded", "." ]
def background_mesh_masked(self): """ The background 2D (masked) array mesh prior to any interpolation. The array has NaN values where meshes were excluded. """ data = np.full(self.background_mesh.shape, np.nan) data[self._mesh_idx] = self.background_mesh[self._mesh_idx] return data
[ "def", "background_mesh_masked", "(", "self", ")", ":", "data", "=", "np", ".", "full", "(", "self", ".", "background_mesh", ".", "shape", ",", "np", ".", "nan", ")", "data", "[", "self", ".", "_mesh_idx", "]", "=", "self", ".", "background_mesh", "[",...
https://github.com/astropy/photutils/blob/3caa48e4e4d139976ed7457dc41583fb2c56ba20/photutils/background/background_2d.py#L577-L585
TengXiaoDai/DistributedCrawling
f5c2439e6ce68dd9b49bde084d76473ff9ed4963
Lib/site-packages/pip/_vendor/requests/packages/urllib3/poolmanager.py
python
PoolManager.connection_from_pool_key
(self, pool_key)
return pool
Get a :class:`ConnectionPool` based on the provided pool key. ``pool_key`` should be a namedtuple that only contains immutable objects. At a minimum it must have the ``scheme``, ``host``, and ``port`` fields.
Get a :class:`ConnectionPool` based on the provided pool key.
[ "Get", "a", ":", "class", ":", "ConnectionPool", "based", "on", "the", "provided", "pool", "key", "." ]
def connection_from_pool_key(self, pool_key): """ Get a :class:`ConnectionPool` based on the provided pool key. ``pool_key`` should be a namedtuple that only contains immutable objects. At a minimum it must have the ``scheme``, ``host``, and ``port`` fields. """ with self.pools.lock: # If the scheme, host, or port doesn't match existing open # connections, open a new ConnectionPool. pool = self.pools.get(pool_key) if pool: return pool # Make a fresh ConnectionPool of the desired type pool = self._new_pool(pool_key.scheme, pool_key.host, pool_key.port) self.pools[pool_key] = pool return pool
[ "def", "connection_from_pool_key", "(", "self", ",", "pool_key", ")", ":", "with", "self", ".", "pools", ".", "lock", ":", "# If the scheme, host, or port doesn't match existing open", "# connections, open a new ConnectionPool.", "pool", "=", "self", ".", "pools", ".", ...
https://github.com/TengXiaoDai/DistributedCrawling/blob/f5c2439e6ce68dd9b49bde084d76473ff9ed4963/Lib/site-packages/pip/_vendor/requests/packages/urllib3/poolmanager.py#L195-L214
SamJoan/droopescan
37c2a3d9dc6dd957258036392d47848bf877fb42
dscan/plugins/internal/base_plugin_internal.py
python
BasePluginInternal._enumerate_plugin_if
(self, found_list, verb, threads, imu_list, hide_progressbar, timeout=15, headers={})
return found_list
Finds interesting urls within a plugin folder which respond with 200 OK. @param found_list: as returned in self.enumerate. E.g. [{'name': 'this_exists', 'url': 'http://adhwuiaihduhaknbacnckajcwnncwkakncw.com/sites/all/modules/this_exists/'}] @param verb: the verb to use. @param threads: the number of threads to use. @param imu_list: Interesting module urls. @param hide_progressbar: whether to display a progressbar. @param timeout: timeout in seconds for http requests. @param headers: custom headers as expected by requests.
Finds interesting urls within a plugin folder which respond with 200 OK.
[ "Finds", "interesting", "urls", "within", "a", "plugin", "folder", "which", "respond", "with", "200", "OK", "." ]
def _enumerate_plugin_if(self, found_list, verb, threads, imu_list, hide_progressbar, timeout=15, headers={}): """ Finds interesting urls within a plugin folder which respond with 200 OK. @param found_list: as returned in self.enumerate. E.g. [{'name': 'this_exists', 'url': 'http://adhwuiaihduhaknbacnckajcwnncwkakncw.com/sites/all/modules/this_exists/'}] @param verb: the verb to use. @param threads: the number of threads to use. @param imu_list: Interesting module urls. @param hide_progressbar: whether to display a progressbar. @param timeout: timeout in seconds for http requests. @param headers: custom headers as expected by requests. """ if not hide_progressbar: p = ProgressBar(sys.stderr, len(found_list) * len(imu_list), name="IMU") requests_verb = getattr(self.session, verb) with ThreadPoolExecutor(max_workers=threads) as executor: futures = [] for i, found in enumerate(found_list): found_list[i]['imu'] = [] for imu in imu_list: interesting_url = found['url'] + imu[0] future = executor.submit(requests_verb, interesting_url, timeout=timeout, headers=headers) futures.append({ 'url': interesting_url, 'future': future, 'description': imu[1], 'i': i }) for f in futures: if common.shutdown: f['future'].cancel() continue r = f['future'].result() if r.status_code == 200: found_list[f['i']]['imu'].append({ 'url': f['url'], 'description': f['description'] }) if not hide_progressbar: p.increment_progress() if not hide_progressbar: p.hide() return found_list
[ "def", "_enumerate_plugin_if", "(", "self", ",", "found_list", ",", "verb", ",", "threads", ",", "imu_list", ",", "hide_progressbar", ",", "timeout", "=", "15", ",", "headers", "=", "{", "}", ")", ":", "if", "not", "hide_progressbar", ":", "p", "=", "Pro...
https://github.com/SamJoan/droopescan/blob/37c2a3d9dc6dd957258036392d47848bf877fb42/dscan/plugins/internal/base_plugin_internal.py#L865-L918
daid/LegacyCura
eceece558df51845988bed55a4e667638654f7c4
Cura/util/pymclevel/mce.py
python
mce._worldsize
(self, command)
worldsize Computes and prints the dimensions of the world. For infinite worlds, also prints the most negative corner.
worldsize
[ "worldsize" ]
def _worldsize(self, command): """ worldsize Computes and prints the dimensions of the world. For infinite worlds, also prints the most negative corner. """ bounds = self.level.bounds if isinstance(self.level, mclevel.MCInfdevOldLevel): print "\nWorld size: \n {0[0]:7} north to south\n {0[2]:7} east to west\n".format(bounds.size) print "Smallest and largest points: ({0[0]},{0[2]}), ({1[0]},{1[2]})".format(bounds.origin, bounds.maximum) else: print "\nWorld size: \n {0[0]:7} wide\n {0[1]:7} tall\n {0[2]:7} long\n".format(bounds.size)
[ "def", "_worldsize", "(", "self", ",", "command", ")", ":", "bounds", "=", "self", ".", "level", ".", "bounds", "if", "isinstance", "(", "self", ".", "level", ",", "mclevel", ".", "MCInfdevOldLevel", ")", ":", "print", "\"\\nWorld size: \\n {0[0]:7} north to ...
https://github.com/daid/LegacyCura/blob/eceece558df51845988bed55a4e667638654f7c4/Cura/util/pymclevel/mce.py#L1123-L1136
khanhnamle1994/natural-language-processing
01d450d5ac002b0156ef4cf93a07cb508c1bcdc5
assignment1/.env/lib/python2.7/site-packages/IPython/utils/ipstruct.py
python
Struct.hasattr
(self, key)
return key in self
hasattr function available as a method. Implemented like has_key. Examples -------- >>> s = Struct(a=10) >>> s.hasattr('a') True >>> s.hasattr('b') False >>> s.hasattr('get') False
hasattr function available as a method.
[ "hasattr", "function", "available", "as", "a", "method", "." ]
def hasattr(self, key): """hasattr function available as a method. Implemented like has_key. Examples -------- >>> s = Struct(a=10) >>> s.hasattr('a') True >>> s.hasattr('b') False >>> s.hasattr('get') False """ return key in self
[ "def", "hasattr", "(", "self", ",", "key", ")", ":", "return", "key", "in", "self" ]
https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/IPython/utils/ipstruct.py#L247-L263
zulip/python-zulip-api
70b86614bd15347e28ec2cab4c87c01122faae16
zulip/zulip/__init__.py
python
Client.get_subscribers
(self, **request: Any)
return self.call_endpoint( url=url, method="GET", request=request, )
Example usage: client.get_subscribers(stream='devel')
Example usage: client.get_subscribers(stream='devel')
[ "Example", "usage", ":", "client", ".", "get_subscribers", "(", "stream", "=", "devel", ")" ]
def get_subscribers(self, **request: Any) -> Dict[str, Any]: """ Example usage: client.get_subscribers(stream='devel') """ response = self.get_stream_id(request["stream"]) if response["result"] == "error": return response stream_id = response["stream_id"] url = "streams/%d/members" % (stream_id,) return self.call_endpoint( url=url, method="GET", request=request, )
[ "def", "get_subscribers", "(", "self", ",", "*", "*", "request", ":", "Any", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "response", "=", "self", ".", "get_stream_id", "(", "request", "[", "\"stream\"", "]", ")", "if", "response", "[", "\"re...
https://github.com/zulip/python-zulip-api/blob/70b86614bd15347e28ec2cab4c87c01122faae16/zulip/zulip/__init__.py#L1550-L1564
Net-ng/kansha
85b5816da126b1c7098707c98f217d8b2e524ff2
kansha/user/user_profile.py
python
get_userform
(app_title, app_banner, theme, source)
return BasicUserForm
Default method to get UserForm Class In: - ``source`` -- source of user (application, google...)
Default method to get UserForm Class
[ "Default", "method", "to", "get", "UserForm", "Class" ]
def get_userform(app_title, app_banner, theme, source): """ Default method to get UserForm Class In: - ``source`` -- source of user (application, google...) """ return BasicUserForm
[ "def", "get_userform", "(", "app_title", ",", "app_banner", ",", "theme", ",", "source", ")", ":", "return", "BasicUserForm" ]
https://github.com/Net-ng/kansha/blob/85b5816da126b1c7098707c98f217d8b2e524ff2/kansha/user/user_profile.py#L109-L115
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/input_text/__init__.py
python
InputText.unique_id
(self)
return self._config[CONF_ID]
Return unique id for the entity.
Return unique id for the entity.
[ "Return", "unique", "id", "for", "the", "entity", "." ]
def unique_id(self) -> str | None: """Return unique id for the entity.""" return self._config[CONF_ID]
[ "def", "unique_id", "(", "self", ")", "->", "str", "|", "None", ":", "return", "self", ".", "_config", "[", "CONF_ID", "]" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/input_text/__init__.py#L243-L245
MeanEYE/Sunflower
1024bbdde3b8e202ddad3553b321a7b6230bffc9
sunflower/gui/main_window.py
python
MainWindow.configure_accelerators
(self)
Configure main accelerators group
Configure main accelerators group
[ "Configure", "main", "accelerators", "group" ]
def configure_accelerators(self): """Configure main accelerators group""" group = AcceleratorGroup(self) keyval = Gdk.keyval_from_name required_fields = set(('label', 'callback', 'path', 'name')) # configure accelerator group group.set_name('main_menu') group.set_title(_('Main Menu')) # default accelerator map # add other methods group.add_method('restore_handle_position', _('Restore handle position'), self.restore_handle_position) group.add_method('move_handle_left', _('Move handle to the left'), self.move_handle, -1) group.add_method('move_handle_right', _('Move handle to the right'), self.move_handle, 1) group.add_method('create_file', _('Create _file'), self._command_create, 'file') group.add_method('create_directory', _('Create _directory'), self._command_create, 'directory') group.add_method('quit_program',_('_Quit'), self._destroy) group.add_method('preferences', _('_Preferences'), self.preferences_window._show) group.add_method('select_with_pattern', _('S_elect with pattern'), self.select_with_pattern) group.add_method('deselect_with_pattern', _('Deselect with pa_ttern'), self.deselect_with_pattern) group.add_method('select_with_same_extension', _('Select with same e_xtension'), self.select_with_same_extension) group.add_method('deselect_with_same_extension', _('Deselect with same exte_nsion'), self.deselect_with_same_extension) group.add_method('compare_directories', _('Compare _directories'), self.compare_directories) group.add_method('find_files', _('_Find files'), self.show_find_files) group.add_method('advanced_rename', _('_Find files'), self.show_advanced_rename) # group.add_method('mount_manager', _('_Mount manager'), self.mount_manager.show) # group.add_method('keyring_manager', _('_Keyring manager'), self.keyring_manager.show) group.add_method('reload', _('Rel_oad item list'), self._command_reload) group.add_method('fast_media_preview', _('Fast m_edia preview'), self._toggle_media_preview) group.add_method('show_hidden_files', _('Show _hidden files'), self._toggle_show_hidden_files) # set default accelerators group.set_accelerator('restore_handle_position', keyval('Home'), Gdk.ModifierType.MOD1_MASK) group.set_accelerator('move_handle_left', keyval('Page_Up'), Gdk.ModifierType.MOD1_MASK) group.set_accelerator('move_handle_right', keyval('Page_Down'), Gdk.ModifierType.MOD1_MASK) group.set_accelerator('create_file', keyval('F7'), Gdk.ModifierType.CONTROL_MASK) group.set_accelerator('create_directory', keyval('F7'), 0) group.set_accelerator('quit', keyval('Q'), Gdk.ModifierType.CONTROL_MASK) group.set_accelerator('preferences', keyval('P'), Gdk.ModifierType.CONTROL_MASK | Gdk.ModifierType.MOD1_MASK) group.set_accelerator('select_with_pattern', keyval('KP_Add'), 0) group.set_accelerator('deselect_with_pattern', keyval('KP_Subtract'), 0) group.set_accelerator('select_with_same_extension', keyval('KP_Add'), Gdk.ModifierType.MOD1_MASK) group.set_accelerator('deselect_with_same_extension', keyval('KP_Subtract'), Gdk.ModifierType.MOD1_MASK) group.set_accelerator('compare_directories', keyval('F12'), 0) group.set_accelerator('find_files', keyval('F7'), Gdk.ModifierType.MOD1_MASK) group.set_accelerator('advanced_rename', keyval('M'), Gdk.ModifierType.CONTROL_MASK) group.set_accelerator('mount_manager', keyval('O'), Gdk.ModifierType.CONTROL_MASK) group.set_accelerator('reload', keyval('R'), Gdk.ModifierType.CONTROL_MASK) group.set_accelerator('fast_media_preview', keyval('F3'), Gdk.ModifierType.MOD1_MASK) group.set_accelerator('show_hidden_files', keyval('H'), Gdk.ModifierType.CONTROL_MASK) group.set_alt_accelerator('select_with_pattern', keyval('equal'), 0) group.set_alt_accelerator('deselect_with_pattern', keyval('minus'), 0) group.set_alt_accelerator('select_with_same_extension', keyval('equal'), Gdk.ModifierType.MOD1_MASK) group.set_alt_accelerator('deselect_with_same_extension', keyval('minus'), Gdk.ModifierType.MOD1_MASK) # expose object self._accel_group = group
[ "def", "configure_accelerators", "(", "self", ")", ":", "group", "=", "AcceleratorGroup", "(", "self", ")", "keyval", "=", "Gdk", ".", "keyval_from_name", "required_fields", "=", "set", "(", "(", "'label'", ",", "'callback'", ",", "'path'", ",", "'name'", ")...
https://github.com/MeanEYE/Sunflower/blob/1024bbdde3b8e202ddad3553b321a7b6230bffc9/sunflower/gui/main_window.py#L1724-L1785
naftaliharris/tauthon
5587ceec329b75f7caf6d65a036db61ac1bae214
Lib/distutils/ccompiler.py
python
CCompiler._compile
(self, obj, src, ext, cc_args, extra_postargs, pp_opts)
Compile 'src' to product 'obj'.
Compile 'src' to product 'obj'.
[ "Compile", "src", "to", "product", "obj", "." ]
def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): """Compile 'src' to product 'obj'.""" # A concrete compiler class that does not override compile() # should implement _compile(). pass
[ "def", "_compile", "(", "self", ",", "obj", ",", "src", ",", "ext", ",", "cc_args", ",", "extra_postargs", ",", "pp_opts", ")", ":", "# A concrete compiler class that does not override compile()", "# should implement _compile().", "pass" ]
https://github.com/naftaliharris/tauthon/blob/5587ceec329b75f7caf6d65a036db61ac1bae214/Lib/distutils/ccompiler.py#L581-L586
tomplus/kubernetes_asyncio
f028cc793e3a2c519be6a52a49fb77ff0b014c9b
kubernetes_asyncio/client/api/autoscaling_v2beta2_api.py
python
AutoscalingV2beta2Api.patch_namespaced_horizontal_pod_autoscaler_with_http_info
(self, name, namespace, body, **kwargs)
return self.api_client.call_api( '/apis/autoscaling/v2beta2/namespaces/{namespace}/horizontalpodautoscalers/{name}', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V2beta2HorizontalPodAutoscaler', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats)
patch_namespaced_horizontal_pod_autoscaler # noqa: E501 partially update the specified HorizontalPodAutoscaler # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_horizontal_pod_autoscaler_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the HorizontalPodAutoscaler (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V2beta2HorizontalPodAutoscaler, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread.
patch_namespaced_horizontal_pod_autoscaler # noqa: E501
[ "patch_namespaced_horizontal_pod_autoscaler", "#", "noqa", ":", "E501" ]
def patch_namespaced_horizontal_pod_autoscaler_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_horizontal_pod_autoscaler # noqa: E501 partially update the specified HorizontalPodAutoscaler # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_horizontal_pod_autoscaler_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the HorizontalPodAutoscaler (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V2beta2HorizontalPodAutoscaler, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'force' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method patch_namespaced_horizontal_pod_autoscaler" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_horizontal_pod_autoscaler`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_horizontal_pod_autoscaler`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_horizontal_pod_autoscaler`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501 query_params.append(('force', local_var_params['force'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/autoscaling/v2beta2/namespaces/{namespace}/horizontalpodautoscalers/{name}', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V2beta2HorizontalPodAutoscaler', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats)
[ "def", "patch_namespaced_horizontal_pod_autoscaler_with_http_info", "(", "self", ",", "name", ",", "namespace", ",", "body", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "local_var_params", "=", "locals", "(", ")", "all_params", "=", "[", "'name'", ",", "'...
https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/api/autoscaling_v2beta2_api.py#L964-L1087
brian-team/brian2
c212a57cb992b766786b5769ebb830ff12d8a8ad
brian2/spatialneuron/morphology.py
python
Cylinder.volume
(self)
return np.pi * (self._diameter/2)**2 * self.length
r""" The volume of each compartment in this section. The volume of each compartment is calculated as :math:`\pi \frac{d}{2}^2 l` , where :math:`l` is the length of the compartment, and :math:`d` is its diameter.
r""" The volume of each compartment in this section. The volume of each compartment is calculated as :math:`\pi \frac{d}{2}^2 l` , where :math:`l` is the length of the compartment, and :math:`d` is its diameter.
[ "r", "The", "volume", "of", "each", "compartment", "in", "this", "section", ".", "The", "volume", "of", "each", "compartment", "is", "calculated", "as", ":", "math", ":", "\\", "pi", "\\", "frac", "{", "d", "}", "{", "2", "}", "^2", "l", "where", "...
def volume(self): r""" The volume of each compartment in this section. The volume of each compartment is calculated as :math:`\pi \frac{d}{2}^2 l` , where :math:`l` is the length of the compartment, and :math:`d` is its diameter. """ return np.pi * (self._diameter/2)**2 * self.length
[ "def", "volume", "(", "self", ")", ":", "return", "np", ".", "pi", "*", "(", "self", ".", "_diameter", "/", "2", ")", "**", "2", "*", "self", ".", "length" ]
https://github.com/brian-team/brian2/blob/c212a57cb992b766786b5769ebb830ff12d8a8ad/brian2/spatialneuron/morphology.py#L2197-L2205
cylc/cylc-flow
5ec221143476c7c616c156b74158edfbcd83794a
cylc/flow/pathutil.py
python
get_workflow_run_job_dir
(workflow, *args)
return get_workflow_run_dir(workflow, 'log', 'job', *args)
Return workflow run job (log) directory, join any extra args.
Return workflow run job (log) directory, join any extra args.
[ "Return", "workflow", "run", "job", "(", "log", ")", "directory", "join", "any", "extra", "args", "." ]
def get_workflow_run_job_dir(workflow, *args): """Return workflow run job (log) directory, join any extra args.""" return get_workflow_run_dir(workflow, 'log', 'job', *args)
[ "def", "get_workflow_run_job_dir", "(", "workflow", ",", "*", "args", ")", ":", "return", "get_workflow_run_dir", "(", "workflow", ",", "'log'", ",", "'job'", ",", "*", "args", ")" ]
https://github.com/cylc/cylc-flow/blob/5ec221143476c7c616c156b74158edfbcd83794a/cylc/flow/pathutil.py#L76-L78
tabris17/doufen
5de4212f50cc2b31423db0a0ed86ca82bed05213
src/service/worker.py
python
Worker._work
(self, task)
[]
def _work(self, task): self.queue_out.put(Worker.ReturnWorking(self._name, task))
[ "def", "_work", "(", "self", ",", "task", ")", ":", "self", ".", "queue_out", ".", "put", "(", "Worker", ".", "ReturnWorking", "(", "self", ".", "_name", ",", "task", ")", ")" ]
https://github.com/tabris17/doufen/blob/5de4212f50cc2b31423db0a0ed86ca82bed05213/src/service/worker.py#L123-L124
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/idlelib/UndoDelegator.py
python
main
()
[]
def main(): from idlelib.Percolator import Percolator root = Tk() root.wm_protocol("WM_DELETE_WINDOW", root.quit) text = Text() text.pack() text.focus_set() p = Percolator(text) d = UndoDelegator() p.insertfilter(d) root.mainloop()
[ "def", "main", "(", ")", ":", "from", "idlelib", ".", "Percolator", "import", "Percolator", "root", "=", "Tk", "(", ")", "root", ".", "wm_protocol", "(", "\"WM_DELETE_WINDOW\"", ",", "root", ".", "quit", ")", "text", "=", "Text", "(", ")", "text", ".",...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/idlelib/UndoDelegator.py#L339-L349
mcfletch/pyopengl
02d11dad9ff18e50db10e975c4756e17bf198464
OpenGL/GLX/ARB/context_flush_control.py
python
glInitContextFlushControlARB
()
return extensions.hasGLExtension( _EXTENSION_NAME )
Return boolean indicating whether this extension is available
Return boolean indicating whether this extension is available
[ "Return", "boolean", "indicating", "whether", "this", "extension", "is", "available" ]
def glInitContextFlushControlARB(): '''Return boolean indicating whether this extension is available''' from OpenGL import extensions return extensions.hasGLExtension( _EXTENSION_NAME )
[ "def", "glInitContextFlushControlARB", "(", ")", ":", "from", "OpenGL", "import", "extensions", "return", "extensions", ".", "hasGLExtension", "(", "_EXTENSION_NAME", ")" ]
https://github.com/mcfletch/pyopengl/blob/02d11dad9ff18e50db10e975c4756e17bf198464/OpenGL/GLX/ARB/context_flush_control.py#L17-L20
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/google/appengine/tools/devappserver2/endpoints/endpoints_server.py
python
EndpointsDispatcher._add_dispatcher
(self, path_regex, dispatch_function)
Add a request path and dispatch handler. Args: path_regex: A string regex, the path to match against incoming requests. dispatch_function: The function to call for these requests. The function should take (request, start_response) as arguments and return the contents of the response body.
Add a request path and dispatch handler.
[ "Add", "a", "request", "path", "and", "dispatch", "handler", "." ]
def _add_dispatcher(self, path_regex, dispatch_function): """Add a request path and dispatch handler. Args: path_regex: A string regex, the path to match against incoming requests. dispatch_function: The function to call for these requests. The function should take (request, start_response) as arguments and return the contents of the response body. """ self._dispatchers.append((re.compile(path_regex), dispatch_function))
[ "def", "_add_dispatcher", "(", "self", ",", "path_regex", ",", "dispatch_function", ")", ":", "self", ".", "_dispatchers", ".", "append", "(", "(", "re", ".", "compile", "(", "path_regex", ")", ",", "dispatch_function", ")", ")" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/google/appengine/tools/devappserver2/endpoints/endpoints_server.py#L88-L97
cbyn/bitpredict
8ea47d23d604c11bedb2be5b63d710460fe06d9d
model/model.py
python
fit_boosting
(X, y, window=100000, estimators=250, learning=.01, samples_leaf=500, depth=20, validate=False)
return model.fit(X, y)
Fits Gradient Boosting
Fits Gradient Boosting
[ "Fits", "Gradient", "Boosting" ]
def fit_boosting(X, y, window=100000, estimators=250, learning=.01, samples_leaf=500, depth=20, validate=False): ''' Fits Gradient Boosting ''' model = GradientBoostingRegressor(n_estimators=estimators, learning_rate=learning, min_samples_leaf=samples_leaf, max_depth=depth, random_state=42) if validate: return cross_validate(X, y, model, window) return model.fit(X, y)
[ "def", "fit_boosting", "(", "X", ",", "y", ",", "window", "=", "100000", ",", "estimators", "=", "250", ",", "learning", "=", ".01", ",", "samples_leaf", "=", "500", ",", "depth", "=", "20", ",", "validate", "=", "False", ")", ":", "model", "=", "G...
https://github.com/cbyn/bitpredict/blob/8ea47d23d604c11bedb2be5b63d710460fe06d9d/model/model.py#L46-L58
tensorflow/datasets
2e496976d7d45550508395fb2f35cf958c8a3414
tensorflow_datasets/text/c4_utils.py
python
is_realnews_domain
(el, realnews_domains)
return True
Returns False iff page's (sub)domain is not allowed.
Returns False iff page's (sub)domain is not allowed.
[ "Returns", "False", "iff", "page", "s", "(", "sub", ")", "domain", "is", "not", "allowed", "." ]
def is_realnews_domain(el, realnews_domains): """Returns False iff page's (sub)domain is not allowed.""" counter_inc_fn = get_counter_inc_fn("realnews-domain-filter") url, _ = el ext = tfds.core.lazy_imports.tldextract.extract(url) main_domain = ext.domain + "." + ext.suffix if main_domain not in realnews_domains: counter_inc_fn("filtered:bad_domain") return False allowed_subdomains = realnews_domains[main_domain] if (isinstance(allowed_subdomains, list) and ext.subdomain not in allowed_subdomains): counter_inc_fn("filtered:bad_subdomain") return False counter_inc_fn("passed") return True
[ "def", "is_realnews_domain", "(", "el", ",", "realnews_domains", ")", ":", "counter_inc_fn", "=", "get_counter_inc_fn", "(", "\"realnews-domain-filter\"", ")", "url", ",", "_", "=", "el", "ext", "=", "tfds", ".", "core", ".", "lazy_imports", ".", "tldextract", ...
https://github.com/tensorflow/datasets/blob/2e496976d7d45550508395fb2f35cf958c8a3414/tensorflow_datasets/text/c4_utils.py#L467-L482
Azure/azure-cli
6c1b085a0910c6c2139006fcbd8ade44006eb6dd
src/azure-cli/azure/cli/command_modules/resource/custom.py
python
get_lock
(cmd, lock_name=None, resource_group=None, resource_provider_namespace=None, parent_resource_path=None, resource_type=None, resource_name=None, ids=None)
return lock_client.management_locks.get_at_resource_level( resource_group, resource_provider_namespace, parent_resource_path or '', resource_type, resource_name, lock_name)
:param name: The name of the lock. :type name: str
:param name: The name of the lock. :type name: str
[ ":", "param", "name", ":", "The", "name", "of", "the", "lock", ".", ":", "type", "name", ":", "str" ]
def get_lock(cmd, lock_name=None, resource_group=None, resource_provider_namespace=None, parent_resource_path=None, resource_type=None, resource_name=None, ids=None): """ :param name: The name of the lock. :type name: str """ if ids: kwargs_list = [] for id_arg in ids: try: kwargs_list.append(_parse_lock_id(id_arg)) except AttributeError: logger.error('az lock show: error: argument --ids: invalid ResourceId value: \'%s\'', id_arg) return results = [get_lock(cmd, **kwargs) for kwargs in kwargs_list] return results[0] if len(results) == 1 else results lock_client = _resource_lock_client_factory(cmd.cli_ctx) lock_resource = _extract_lock_params(resource_group, resource_provider_namespace, resource_type, resource_name) resource_group = lock_resource[0] resource_name = lock_resource[1] resource_provider_namespace = lock_resource[2] resource_type = lock_resource[3] _validate_lock_params_match_lock(lock_client, lock_name, resource_group, resource_provider_namespace, parent_resource_path, resource_type, resource_name) if resource_group is None: return _call_subscription_get(cmd, lock_client, lock_name) if resource_name is None: return lock_client.management_locks.get_at_resource_group_level(resource_group, lock_name) if cmd.supported_api_version(max_api='2015-01-01'): lock_list = list_locks(resource_group, resource_provider_namespace, parent_resource_path, resource_type, resource_name) return next((lock for lock in lock_list if lock.name == lock_name), None) return lock_client.management_locks.get_at_resource_level( resource_group, resource_provider_namespace, parent_resource_path or '', resource_type, resource_name, lock_name)
[ "def", "get_lock", "(", "cmd", ",", "lock_name", "=", "None", ",", "resource_group", "=", "None", ",", "resource_provider_namespace", "=", "None", ",", "parent_resource_path", "=", "None", ",", "resource_type", "=", "None", ",", "resource_name", "=", "None", "...
https://github.com/Azure/azure-cli/blob/6c1b085a0910c6c2139006fcbd8ade44006eb6dd/src/azure-cli/azure/cli/command_modules/resource/custom.py#L3029-L3070
debian-calibre/calibre
020fc81d3936a64b2ac51459ecb796666ab6a051
src/calibre/ebooks/pdb/__init__.py
python
get_writer
(extension)
return FORMAT_WRITERS.get(extension, None)
Returns None if no writer is found for extension.
Returns None if no writer is found for extension.
[ "Returns", "None", "if", "no", "writer", "is", "found", "for", "extension", "." ]
def get_writer(extension): ''' Returns None if no writer is found for extension. ''' global FORMAT_WRITERS if FORMAT_WRITERS is None: _import_writers() return FORMAT_WRITERS.get(extension, None)
[ "def", "get_writer", "(", "extension", ")", ":", "global", "FORMAT_WRITERS", "if", "FORMAT_WRITERS", "is", "None", ":", "_import_writers", "(", ")", "return", "FORMAT_WRITERS", ".", "get", "(", "extension", ",", "None", ")" ]
https://github.com/debian-calibre/calibre/blob/020fc81d3936a64b2ac51459ecb796666ab6a051/src/calibre/ebooks/pdb/__init__.py#L99-L106
Yonsm/.homeassistant
4d9a0070d0fcd8a5ded46e7884da9a4494bbbf26
extras/homeassistant/loader.py
python
Integration.documentation
(self)
return self.manifest.get("documentation")
Return documentation.
Return documentation.
[ "Return", "documentation", "." ]
def documentation(self) -> str | None: """Return documentation.""" return self.manifest.get("documentation")
[ "def", "documentation", "(", "self", ")", "->", "str", "|", "None", ":", "return", "self", ".", "manifest", ".", "get", "(", "\"documentation\"", ")" ]
https://github.com/Yonsm/.homeassistant/blob/4d9a0070d0fcd8a5ded46e7884da9a4494bbbf26/extras/homeassistant/loader.py#L387-L389