repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
joestump/django-ajax
ajax/utils.py
https://github.com/joestump/django-ajax/blob/b71619d5c00d8e0bb990ddbea2c93cf303dc2c80/ajax/utils.py#L8-L32
def import_by_path(dotted_path, error_prefix=''): """ Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImproperlyConfigured if something goes wrong. This has come straight from Django 1.6 """ try: module_path, class_name = dotted_path.rsplit('.', 1) except ValueError: raise ImproperlyConfigured("%s%s doesn't look like a module path" % ( error_prefix, dotted_path)) try: module = import_module(module_path) except ImportError as e: raise ImproperlyConfigured('%sError importing module %s: "%s"' % ( error_prefix, module_path, e)) try: attr = getattr(module, class_name) except AttributeError: raise ImproperlyConfigured( '%sModule "%s" does not define a "%s" attribute/class' % ( error_prefix, module_path, class_name ) ) return attr
[ "def", "import_by_path", "(", "dotted_path", ",", "error_prefix", "=", "''", ")", ":", "try", ":", "module_path", ",", "class_name", "=", "dotted_path", ".", "rsplit", "(", "'.'", ",", "1", ")", "except", "ValueError", ":", "raise", "ImproperlyConfigured", "...
Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImproperlyConfigured if something goes wrong. This has come straight from Django 1.6
[ "Import", "a", "dotted", "module", "path", "and", "return", "the", "attribute", "/", "class", "designated", "by", "the", "last", "name", "in", "the", "path", ".", "Raise", "ImproperlyConfigured", "if", "something", "goes", "wrong", ".", "This", "has", "come"...
python
train
unt-libraries/pypairtree
pypairtree/pairtree.py
https://github.com/unt-libraries/pypairtree/blob/2107b46718bbf9ef7ef3d5c63d557d1f772e5d69/pypairtree/pairtree.py#L104-L150
def sanitizeString(name): """Cleans string in preparation for splitting for use as a pairtree identifier.""" newString = name # string cleaning, pass 1 replaceTable = [ ('^', '^5e'), # we need to do this one first ('"', '^22'), ('<', '^3c'), ('?', '^3f'), ('*', '^2a'), ('=', '^3d'), ('+', '^2b'), ('>', '^3e'), ('|', '^7c'), (',', '^2c'), ] # " hex 22 < hex 3c ? hex 3f # * hex 2a = hex 3d ^ hex 5e # + hex 2b > hex 3e | hex 7c # , hex 2c for r in replaceTable: newString = newString.replace(r[0], r[1]) # replace ascii 0-32 for x in range(0, 33): # must add somewhat arbitrary num to avoid conflict at deSanitization # conflict example: is ^x1e supposed to be ^x1 (ascii 1) followed by # letter 'e' or really ^x1e (ascii 30) newString = newString.replace( chr(x), hex(x + sanitizerNum).replace('0x', '^')) replaceTable2 = [ ("/", "="), (":", "+"), (".", ","), ] # / -> = # : -> + # . -> , # string cleaning pass 2 for r in replaceTable2: newString = newString.replace(r[0], r[1]) return newString
[ "def", "sanitizeString", "(", "name", ")", ":", "newString", "=", "name", "# string cleaning, pass 1", "replaceTable", "=", "[", "(", "'^'", ",", "'^5e'", ")", ",", "# we need to do this one first", "(", "'\"'", ",", "'^22'", ")", ",", "(", "'<'", ",", "'^3c...
Cleans string in preparation for splitting for use as a pairtree identifier.
[ "Cleans", "string", "in", "preparation", "for", "splitting", "for", "use", "as", "a", "pairtree", "identifier", "." ]
python
train
sirfoga/pyhal
hal/meta/attributes.py
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/meta/attributes.py#L26-L32
def _parse(self): """Parses file contents :return: Tree hierarchy of file """ with open(self.path, "rt") as reader: return ast.parse(reader.read(), filename=self.path)
[ "def", "_parse", "(", "self", ")", ":", "with", "open", "(", "self", ".", "path", ",", "\"rt\"", ")", "as", "reader", ":", "return", "ast", ".", "parse", "(", "reader", ".", "read", "(", ")", ",", "filename", "=", "self", ".", "path", ")" ]
Parses file contents :return: Tree hierarchy of file
[ "Parses", "file", "contents" ]
python
train
debugloop/saltobserver
saltobserver/views.py
https://github.com/debugloop/saltobserver/blob/55ff20aa2d2504fb85fa2f63cc9b52934245b849/saltobserver/views.py#L18-L22
def get_function_data(minion, jid): """AJAX access for loading function/job details.""" redis = Redis(connection_pool=redis_pool) data = redis.get('{0}:{1}'.format(minion, jid)) return Response(response=data, status=200, mimetype="application/json")
[ "def", "get_function_data", "(", "minion", ",", "jid", ")", ":", "redis", "=", "Redis", "(", "connection_pool", "=", "redis_pool", ")", "data", "=", "redis", ".", "get", "(", "'{0}:{1}'", ".", "format", "(", "minion", ",", "jid", ")", ")", "return", "R...
AJAX access for loading function/job details.
[ "AJAX", "access", "for", "loading", "function", "/", "job", "details", "." ]
python
train
TAPPGuild/sqlalchemy-models
sqlalchemy_models/wallet.py
https://github.com/TAPPGuild/sqlalchemy-models/blob/75988a23bdd98e79af8b8b0711c657c79b2f8eac/sqlalchemy_models/wallet.py#L131-L138
def load_commodities(self): """ Load the commodities for Amounts in this object. """ if isinstance(self.amount, Amount): self.amount = Amount("{0:.8f} {1}".format(self.amount.to_double(), self.currency)) else: self.amount = Amount("{0:.8f} {1}".format(self.amount, self.currency))
[ "def", "load_commodities", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "amount", ",", "Amount", ")", ":", "self", ".", "amount", "=", "Amount", "(", "\"{0:.8f} {1}\"", ".", "format", "(", "self", ".", "amount", ".", "to_double", "(", "...
Load the commodities for Amounts in this object.
[ "Load", "the", "commodities", "for", "Amounts", "in", "this", "object", "." ]
python
train
DarkEnergySurvey/ugali
ugali/utils/binning.py
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/binning.py#L177-L291
def fast_kde(x, y, gridsize=(200,200), extents=None, nocorrelation=False, weights=None): """ Performs a gaussian kernel density estimate over a regular grid using a convolution of the gaussian kernel with a 2D histogram of the data. This function is typically several orders of magnitude faster than scipy.stats.kde.gaussian_kde for large (>1e7) numbers of points and produces an essentially identical result. Input: x: The x-coords of the input data points y: The y-coords of the input data points gridsize: (default: 200x200) A (nx,ny) tuple of the size of the output grid extents: (default: extent of input data) A (xmin, xmax, ymin, ymax) tuple of the extents of output grid nocorrelation: (default: False) If True, the correlation between the x and y coords will be ignored when preforming the KDE. weights: (default: None) An array of the same shape as x & y that weighs each sample (x_i, y_i) by each value in weights (w_i). Defaults to an array of ones the same size as x & y. Output: A gridded 2D kernel density estimate of the input points. """ #---- Setup -------------------------------------------------------------- x, y = np.asarray(x), np.asarray(y) x, y = np.squeeze(x), np.squeeze(y) if x.size != y.size: raise ValueError('Input x & y arrays must be the same size!') nx, ny = gridsize n = x.size if weights is None: # Default: Weight all points equally weights = np.ones(n) else: weights = np.squeeze(np.asarray(weights)) if weights.size != x.size: raise ValueError('Input weights must be an array of the same size' ' as input x & y arrays!') # Default extents are the extent of the data if extents is None: xmin, xmax = x.min(), x.max() ymin, ymax = y.min(), y.max() else: xmin, xmax, ymin, ymax = list(map(float, extents)) dx = (xmax - xmin) / (nx - 1) dy = (ymax - ymin) / (ny - 1) #---- Preliminary Calculations ------------------------------------------- # First convert x & y over to pixel coordinates # (Avoiding np.digitize due to excessive memory usage in numpy < v1.5!) # http://stackoverflow.com/q/8805601/ xyi = np.vstack((x,y)).T xyi -= [xmin, ymin] xyi /= [dx, dy] xyi = np.floor(xyi, xyi).T # Next, make a 2D histogram of x & y # Avoiding np.histogram2d due to excessive memory usage with many points # http://stackoverflow.com/q/8805601/ grid = sp.sparse.coo_matrix((weights, xyi), shape=(nx, ny)).toarray() # Calculate the covariance matrix (in pixel coords) cov = np.cov(xyi) if nocorrelation: cov[1,0] = 0 cov[0,1] = 0 # Scaling factor for bandwidth scotts_factor = np.power(n, -1.0 / 6) # For 2D #---- Make the gaussian kernel ------------------------------------------- # First, determine how big the kernel needs to be std_devs = np.diag(np.sqrt(cov)) kern_nx, kern_ny = np.round(scotts_factor * 2 * np.pi * std_devs) # Determine the bandwidth to use for the gaussian kernel inv_cov = np.linalg.inv(cov * scotts_factor**2) # x & y (pixel) coords of the kernel grid, with <x,y> = <0,0> in center xx = np.arange(kern_nx, dtype=np.float) - kern_nx / 2.0 yy = np.arange(kern_ny, dtype=np.float) - kern_ny / 2.0 xx, yy = np.meshgrid(xx, yy) # Then evaluate the gaussian function on the kernel grid kernel = np.vstack((xx.flatten(), yy.flatten())) kernel = np.dot(inv_cov, kernel) * kernel kernel = np.sum(kernel, axis=0) / 2.0 kernel = np.exp(-kernel) kernel = kernel.reshape((kern_ny, kern_nx)) #---- Produce the kernel density estimate -------------------------------- # Convolve the gaussian kernel with the 2D histogram, producing a gaussian # kernel density estimate on a regular grid grid = sp.signal.convolve2d(grid, kernel, mode='same', boundary='fill').T ### ADW: Commented out for ### # Normalization factor to divide result by so that units are in the same ### # units as scipy.stats.kde.gaussian_kde's output. ### norm_factor = 2 * np.pi * cov * scotts_factor**2 ### norm_factor = np.linalg.det(norm_factor) ### norm_factor = n * dx * dy * np.sqrt(norm_factor) ### ### # Normalize the result ### grid /= norm_factor return grid
[ "def", "fast_kde", "(", "x", ",", "y", ",", "gridsize", "=", "(", "200", ",", "200", ")", ",", "extents", "=", "None", ",", "nocorrelation", "=", "False", ",", "weights", "=", "None", ")", ":", "#---- Setup -----------------------------------------------------...
Performs a gaussian kernel density estimate over a regular grid using a convolution of the gaussian kernel with a 2D histogram of the data. This function is typically several orders of magnitude faster than scipy.stats.kde.gaussian_kde for large (>1e7) numbers of points and produces an essentially identical result. Input: x: The x-coords of the input data points y: The y-coords of the input data points gridsize: (default: 200x200) A (nx,ny) tuple of the size of the output grid extents: (default: extent of input data) A (xmin, xmax, ymin, ymax) tuple of the extents of output grid nocorrelation: (default: False) If True, the correlation between the x and y coords will be ignored when preforming the KDE. weights: (default: None) An array of the same shape as x & y that weighs each sample (x_i, y_i) by each value in weights (w_i). Defaults to an array of ones the same size as x & y. Output: A gridded 2D kernel density estimate of the input points.
[ "Performs", "a", "gaussian", "kernel", "density", "estimate", "over", "a", "regular", "grid", "using", "a", "convolution", "of", "the", "gaussian", "kernel", "with", "a", "2D", "histogram", "of", "the", "data", "." ]
python
train
vanheeringen-lab/gimmemotifs
gimmemotifs/rocmetrics.py
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/rocmetrics.py#L67-L95
def recall_at_fdr(fg_vals, bg_vals, fdr_cutoff=0.1): """ Computes the recall at a specific FDR (default 10%). Parameters ---------- fg_vals : array_like The list of values for the positive set. bg_vals : array_like The list of values for the negative set. fdr : float, optional The FDR (between 0.0 and 1.0). Returns ------- recall : float The recall at the specified FDR. """ if len(fg_vals) == 0: return 0.0 y_true, y_score = values_to_labels(fg_vals, bg_vals) precision, recall, _ = precision_recall_curve(y_true, y_score) fdr = 1 - precision cutoff_index = next(i for i, x in enumerate(fdr) if x <= fdr_cutoff) return recall[cutoff_index]
[ "def", "recall_at_fdr", "(", "fg_vals", ",", "bg_vals", ",", "fdr_cutoff", "=", "0.1", ")", ":", "if", "len", "(", "fg_vals", ")", "==", "0", ":", "return", "0.0", "y_true", ",", "y_score", "=", "values_to_labels", "(", "fg_vals", ",", "bg_vals", ")", ...
Computes the recall at a specific FDR (default 10%). Parameters ---------- fg_vals : array_like The list of values for the positive set. bg_vals : array_like The list of values for the negative set. fdr : float, optional The FDR (between 0.0 and 1.0). Returns ------- recall : float The recall at the specified FDR.
[ "Computes", "the", "recall", "at", "a", "specific", "FDR", "(", "default", "10%", ")", "." ]
python
train
sanger-pathogens/ariba
ariba/ref_genes_getter.py
https://github.com/sanger-pathogens/ariba/blob/16a0b1916ce0e886bd22550ba2d648542977001b/ariba/ref_genes_getter.py#L462-L483
def _fix_virulencefinder_fasta_file(cls, infile, outfile): '''Some line breaks are missing in the FASTA files from viruslence finder. Which means there are lines like this: AAGATCCAATAACTGAAGATGTTGAACAAACAATTCATAATATTTATGGTCAATATGCTATTTTCGTTGA AGGTGTTGCGCATTTACCTGGACATCTCTCTCCATTATTAAAAAAATTACTACTTAAATCTTTATAA>coa:1:BA000018.3 ATGAAAAAGCAAATAATTTCGCTAGGCGCATTAGCAGTTGCATCTAGCTTATTTACATGGGATAACAAAG and therefore the sequences are messed up when we parse them. Also one has a > at the end, then the seq name on the next line. This function fixes the file by adding line breaks''' with open(infile) as f_in, open(outfile, 'w') as f_out: for line in f_in: if line.startswith('>') or '>' not in line: print(line, end='', file=f_out) elif line.endswith('>\n'): print('WARNING: found line with ">" at the end! Fixing. Line:' + line.rstrip() + ' in file ' + infile, file=sys.stderr) print(line.rstrip('>\n'), file=f_out) print('>', end='', file=f_out) else: print('WARNING: found line with ">" not at the start! Fixing. Line:' + line.rstrip() + ' in file ' + infile, file=sys.stderr) line1, line2 = line.split('>') print(line1, file=f_out) print('>', line2, sep='', end='', file=f_out)
[ "def", "_fix_virulencefinder_fasta_file", "(", "cls", ",", "infile", ",", "outfile", ")", ":", "with", "open", "(", "infile", ")", "as", "f_in", ",", "open", "(", "outfile", ",", "'w'", ")", "as", "f_out", ":", "for", "line", "in", "f_in", ":", "if", ...
Some line breaks are missing in the FASTA files from viruslence finder. Which means there are lines like this: AAGATCCAATAACTGAAGATGTTGAACAAACAATTCATAATATTTATGGTCAATATGCTATTTTCGTTGA AGGTGTTGCGCATTTACCTGGACATCTCTCTCCATTATTAAAAAAATTACTACTTAAATCTTTATAA>coa:1:BA000018.3 ATGAAAAAGCAAATAATTTCGCTAGGCGCATTAGCAGTTGCATCTAGCTTATTTACATGGGATAACAAAG and therefore the sequences are messed up when we parse them. Also one has a > at the end, then the seq name on the next line. This function fixes the file by adding line breaks
[ "Some", "line", "breaks", "are", "missing", "in", "the", "FASTA", "files", "from", "viruslence", "finder", ".", "Which", "means", "there", "are", "lines", "like", "this", ":", "AAGATCCAATAACTGAAGATGTTGAACAAACAATTCATAATATTTATGGTCAATATGCTATTTTCGTTGA", "AGGTGTTGCGCATTTACCTGG...
python
train
tethysplatform/condorpy
condorpy/htcondor_object_base.py
https://github.com/tethysplatform/condorpy/blob/a5aaaef0d73198f7d9756dda7abe98b4e209f1f4/condorpy/htcondor_object_base.py#L144-L159
def remove(self, options=[], sub_job_num=None): """Removes a job from the job queue, or from being executed. Args: options (list of str, optional): A list of command line options for the condor_rm command. For details on valid options see: http://research.cs.wisc.edu/htcondor/manual/current/condor_rm.html. Defaults to an empty list. job_num (int, optional): The number of sub_job to remove rather than the whole cluster. Defaults to None. """ args = ['condor_rm'] args.extend(options) job_id = '%s.%s' % (self.cluster_id, sub_job_num) if sub_job_num else str(self.cluster_id) args.append(job_id) out, err = self._execute(args) return out,err
[ "def", "remove", "(", "self", ",", "options", "=", "[", "]", ",", "sub_job_num", "=", "None", ")", ":", "args", "=", "[", "'condor_rm'", "]", "args", ".", "extend", "(", "options", ")", "job_id", "=", "'%s.%s'", "%", "(", "self", ".", "cluster_id", ...
Removes a job from the job queue, or from being executed. Args: options (list of str, optional): A list of command line options for the condor_rm command. For details on valid options see: http://research.cs.wisc.edu/htcondor/manual/current/condor_rm.html. Defaults to an empty list. job_num (int, optional): The number of sub_job to remove rather than the whole cluster. Defaults to None.
[ "Removes", "a", "job", "from", "the", "job", "queue", "or", "from", "being", "executed", "." ]
python
train
shoebot/shoebot
extensions/gedit/gedit2-plugin/shoebotit/__init__.py
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/extensions/gedit/gedit2-plugin/shoebotit/__init__.py#L295-L306
def _create_view(self, name="shoebot-output"): """ Create the gtk.TextView used for shell output """ view = gtk.TextView() view.set_editable(False) fontdesc = pango.FontDescription("Monospace") view.modify_font(fontdesc) view.set_name(name) buff = view.get_buffer() buff.create_tag('error', foreground='red') return view
[ "def", "_create_view", "(", "self", ",", "name", "=", "\"shoebot-output\"", ")", ":", "view", "=", "gtk", ".", "TextView", "(", ")", "view", ".", "set_editable", "(", "False", ")", "fontdesc", "=", "pango", ".", "FontDescription", "(", "\"Monospace\"", ")"...
Create the gtk.TextView used for shell output
[ "Create", "the", "gtk", ".", "TextView", "used", "for", "shell", "output" ]
python
valid
mkoura/dump2polarion
dump2polarion/dumper_cli.py
https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/dumper_cli.py#L79-L87
def process_args(args): """Processes passed arguments.""" passed_args = args if isinstance(args, argparse.Namespace): passed_args = vars(passed_args) elif hasattr(args, "to_dict"): passed_args = passed_args.to_dict() return Box(passed_args, frozen_box=True, default_box=True)
[ "def", "process_args", "(", "args", ")", ":", "passed_args", "=", "args", "if", "isinstance", "(", "args", ",", "argparse", ".", "Namespace", ")", ":", "passed_args", "=", "vars", "(", "passed_args", ")", "elif", "hasattr", "(", "args", ",", "\"to_dict\"",...
Processes passed arguments.
[ "Processes", "passed", "arguments", "." ]
python
train
zhmcclient/python-zhmcclient
zhmcclient/_session.py
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_session.py#L58-L75
def _handle_request_exc(exc, retry_timeout_config): """ Handle a :exc:`request.exceptions.RequestException` exception that was raised. """ if isinstance(exc, requests.exceptions.ConnectTimeout): raise ConnectTimeout(_request_exc_message(exc), exc, retry_timeout_config.connect_timeout, retry_timeout_config.connect_retries) elif isinstance(exc, requests.exceptions.ReadTimeout): raise ReadTimeout(_request_exc_message(exc), exc, retry_timeout_config.read_timeout, retry_timeout_config.read_retries) elif isinstance(exc, requests.exceptions.RetryError): raise RetriesExceeded(_request_exc_message(exc), exc, retry_timeout_config.connect_retries) else: raise ConnectionError(_request_exc_message(exc), exc)
[ "def", "_handle_request_exc", "(", "exc", ",", "retry_timeout_config", ")", ":", "if", "isinstance", "(", "exc", ",", "requests", ".", "exceptions", ".", "ConnectTimeout", ")", ":", "raise", "ConnectTimeout", "(", "_request_exc_message", "(", "exc", ")", ",", ...
Handle a :exc:`request.exceptions.RequestException` exception that was raised.
[ "Handle", "a", ":", "exc", ":", "request", ".", "exceptions", ".", "RequestException", "exception", "that", "was", "raised", "." ]
python
train
etcher-be/emiz
emiz/avwx/core.py
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/core.py#L104-L125
def make_number(num: str, repr_: str = None, speak: str = None): """ Returns a Number or Fraction dataclass for a number string """ if not num or is_unknown(num): return # Check CAVOK if num == 'CAVOK': return Number('CAVOK', 9999, 'ceiling and visibility ok') # type: ignore # Check special if num in SPECIAL_NUMBERS: return Number(repr_ or num, None, SPECIAL_NUMBERS[num]) # type: ignore # Create Fraction if '/' in num: nmr, dnm = [int(i) for i in num.split('/')] unpacked = unpack_fraction(num) spoken = spoken_number(unpacked) return Fraction(repr_ or num, nmr / dnm, spoken, nmr, dnm, unpacked) # type: ignore # Create Number val = num.replace('M', '-') val = float(val) if '.' in num else int(val) # type: ignore return Number(repr_ or num, val, spoken_number(speak or str(val)))
[ "def", "make_number", "(", "num", ":", "str", ",", "repr_", ":", "str", "=", "None", ",", "speak", ":", "str", "=", "None", ")", ":", "if", "not", "num", "or", "is_unknown", "(", "num", ")", ":", "return", "# Check CAVOK", "if", "num", "==", "'CAVO...
Returns a Number or Fraction dataclass for a number string
[ "Returns", "a", "Number", "or", "Fraction", "dataclass", "for", "a", "number", "string" ]
python
train
gbowerman/azurerm
azurerm/networkrp.py
https://github.com/gbowerman/azurerm/blob/79d40431d3b13f8a36aadbff5029888383d72674/azurerm/networkrp.py#L383-L398
def get_network_usage(access_token, subscription_id, location): '''List network usage and limits for a location. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. location (str): Azure data center location. E.g. westus. Returns: HTTP response. JSON body of network usage. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/providers/Microsoft.Network/locations/', location, '/usages?api-version=', NETWORK_API]) return do_get(endpoint, access_token)
[ "def", "get_network_usage", "(", "access_token", ",", "subscription_id", ",", "location", ")", ":", "endpoint", "=", "''", ".", "join", "(", "[", "get_rm_endpoint", "(", ")", ",", "'/subscriptions/'", ",", "subscription_id", ",", "'/providers/Microsoft.Network/locat...
List network usage and limits for a location. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. location (str): Azure data center location. E.g. westus. Returns: HTTP response. JSON body of network usage.
[ "List", "network", "usage", "and", "limits", "for", "a", "location", "." ]
python
train
cmheisel/basecampreporting
src/basecampreporting/basecamp.py
https://github.com/cmheisel/basecampreporting/blob/88ecfc6e835608650ff6be23cbf2421d224c122b/src/basecampreporting/basecamp.py#L409-L425
def create_todo_item(self, list_id, content, party_id=None, notify=False): """ This call lets you add an item to an existing list. The item is added to the bottom of the list. If a person is responsible for the item, give their id as the party_id value. If a company is responsible, prefix their company id with a 'c' and use that as the party_id value. If the item has a person as the responsible party, you can use the notify key to indicate whether an email should be sent to that person to tell them about the assignment. """ path = '/todos/create_item/%u' % list_id req = ET.Element('request') ET.SubElement(req, 'content').text = str(content) if party_id is not None: ET.SubElement(req, 'responsible-party').text = str(party_id) ET.SubElement(req, 'notify').text = str(bool(notify)).lower() return self._request(path, req)
[ "def", "create_todo_item", "(", "self", ",", "list_id", ",", "content", ",", "party_id", "=", "None", ",", "notify", "=", "False", ")", ":", "path", "=", "'/todos/create_item/%u'", "%", "list_id", "req", "=", "ET", ".", "Element", "(", "'request'", ")", ...
This call lets you add an item to an existing list. The item is added to the bottom of the list. If a person is responsible for the item, give their id as the party_id value. If a company is responsible, prefix their company id with a 'c' and use that as the party_id value. If the item has a person as the responsible party, you can use the notify key to indicate whether an email should be sent to that person to tell them about the assignment.
[ "This", "call", "lets", "you", "add", "an", "item", "to", "an", "existing", "list", ".", "The", "item", "is", "added", "to", "the", "bottom", "of", "the", "list", ".", "If", "a", "person", "is", "responsible", "for", "the", "item", "give", "their", "...
python
train
ska-sa/katcp-python
katcp/core.py
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/core.py#L1311-L1326
def set(self, timestamp, status, value): """Set the current value of the sensor. Parameters ---------- timestamp : float in seconds The time at which the sensor value was determined. status : Sensor status constant Whether the value represents an error condition or not. value : object The value of the sensor (the type should be appropriate to the sensor's type). """ reading = self._current_reading = Reading(timestamp, status, value) self.notify(reading)
[ "def", "set", "(", "self", ",", "timestamp", ",", "status", ",", "value", ")", ":", "reading", "=", "self", ".", "_current_reading", "=", "Reading", "(", "timestamp", ",", "status", ",", "value", ")", "self", ".", "notify", "(", "reading", ")" ]
Set the current value of the sensor. Parameters ---------- timestamp : float in seconds The time at which the sensor value was determined. status : Sensor status constant Whether the value represents an error condition or not. value : object The value of the sensor (the type should be appropriate to the sensor's type).
[ "Set", "the", "current", "value", "of", "the", "sensor", "." ]
python
train
bitesofcode/projexui
projexui/widgets/xcombobox.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xcombobox.py#L500-L527
def showPopup( self ): """ Displays a custom popup widget for this system if a checkable state \ is setup. """ if not self.isCheckable(): return super(XComboBox, self).showPopup() if not self.isVisible(): return # update the checkable widget popup point = self.mapToGlobal(QPoint(0, self.height() - 1)) popup = self.checkablePopup() popup.setModel(self.model()) popup.move(point) popup.setFixedWidth(self.width()) height = (self.count() * 19) + 2 if height > 400: height = 400 popup.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) else: popup.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) popup.setFixedHeight(height) popup.show() popup.raise_()
[ "def", "showPopup", "(", "self", ")", ":", "if", "not", "self", ".", "isCheckable", "(", ")", ":", "return", "super", "(", "XComboBox", ",", "self", ")", ".", "showPopup", "(", ")", "if", "not", "self", ".", "isVisible", "(", ")", ":", "return", "#...
Displays a custom popup widget for this system if a checkable state \ is setup.
[ "Displays", "a", "custom", "popup", "widget", "for", "this", "system", "if", "a", "checkable", "state", "\\", "is", "setup", "." ]
python
train
goshuirc/irc
girc/client.py
https://github.com/goshuirc/irc/blob/d6a5e3e04d337566c009b087f108cd76f9e122cc/girc/client.py#L369-L374
def join_channel(self, channel, key=None, tags=None): """Join the given channel.""" params = [channel] if key: params.append(key) self.send('JOIN', params=params, tags=tags)
[ "def", "join_channel", "(", "self", ",", "channel", ",", "key", "=", "None", ",", "tags", "=", "None", ")", ":", "params", "=", "[", "channel", "]", "if", "key", ":", "params", ".", "append", "(", "key", ")", "self", ".", "send", "(", "'JOIN'", "...
Join the given channel.
[ "Join", "the", "given", "channel", "." ]
python
train
quantmind/pulsar-odm
odm/mapper.py
https://github.com/quantmind/pulsar-odm/blob/5955c20beca0a89270c2b390335838deb7d5915e/odm/mapper.py#L327-L336
def table_create(self, remove_existing=False): """Creates all tables. """ for engine in self.engines(): tables = self._get_tables(engine, create_drop=True) logger.info('Create all tables for %s', engine) try: self.metadata.create_all(engine, tables=tables) except Exception as exc: raise
[ "def", "table_create", "(", "self", ",", "remove_existing", "=", "False", ")", ":", "for", "engine", "in", "self", ".", "engines", "(", ")", ":", "tables", "=", "self", ".", "_get_tables", "(", "engine", ",", "create_drop", "=", "True", ")", "logger", ...
Creates all tables.
[ "Creates", "all", "tables", "." ]
python
train
DarkEnergySurvey/ugali
ugali/scratch/simulation/simulate_population.py
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/scratch/simulation/simulate_population.py#L103-L241
def catsimSatellite(config, lon_centroid, lat_centroid, distance, stellar_mass, r_physical, m_maglim_1, m_maglim_2, m_ebv, plot=False, title='test'): """ Simulate a single satellite. This is currently only valid for band_1 = g and band_2 = r. r_physical is azimuthally averaged half-light radius, kpc """ # Probably don't want to parse every time completeness = getCompleteness(config) log_photo_error = getPhotoError(config) s = ugali.analysis.source.Source() # Following McConnachie 2012, ellipticity = 1 - (b/a) , where a is semi-major axis and b is semi-minor axis r_h = np.degrees(np.arcsin(r_physical / distance)) # Azimuthally averaged half-light radius #ellipticity = 0.3 # Semi-arbitrary default for testing purposes # See http://iopscience.iop.org/article/10.3847/1538-4357/833/2/167/pdf # Based loosely on https://arxiv.org/abs/0805.2945 ellipticity = np.random.uniform(0.1, 0.8) position_angle = np.random.uniform(0., 180.) # Random position angle (deg) a_h = r_h / np.sqrt(1. - ellipticity) # semi-major axis (deg) # Elliptical kernels take the "extension" as the semi-major axis ker = ugali.analysis.kernel.EllipticalPlummer(lon=lon_centroid, lat=lat_centroid, ellipticity=ellipticity, position_angle=position_angle) flag_too_extended = False if a_h >= 1.0: print 'Too extended: a_h = %.2f'%(a_h) a_h = 1.0 flag_too_extended = True ker.setp('extension', value=a_h, bounds=[0.0,1.0]) s.set_kernel(ker) age = np.random.choice([10., 12.0, 13.5]) metal_z = np.random.choice([0.0001, 0.0002]) distance_modulus = ugali.utils.projector.distanceToDistanceModulus(distance) iso = isochrone_factory('Bressan2012', survey=config['survey'], age=age, z=metal_z, distance_modulus=distance_modulus) s.set_isochrone(iso) # Simulate takes stellar mass as an argument, NOT richness mag_1, mag_2 = s.isochrone.simulate(stellar_mass) lon, lat = s.kernel.sample_lonlat(len(mag_2)) nside = healpy.npix2nside(len(m_maglim_1)) # Assuming that the two maglim maps have same resolution pix = ugali.utils.healpix.angToPix(nside, lon, lat) maglim_1 = m_maglim_1[pix] maglim_2 = m_maglim_2[pix] if config['survey'] == 'des': # DES Y3 Gold fiducial mag_extinction_1 = 3.186 * m_ebv[pix] mag_extinction_2 = 2.140 * m_ebv[pix] elif config['survey'] == 'ps1': # From Table 6 in Schlafly 2011 with Rv = 3.1 # http://iopscience.iop.org/article/10.1088/0004-637X/737/2/103/pdf mag_extinction_1 = 3.172 * m_ebv[pix] mag_extinction_2 = 2.271 * m_ebv[pix] # Photometric uncertainties are larger in the presence of interstellar dust reddening mag_1_error = 0.01 + 10**(log_photo_error((mag_1 + mag_extinction_1) - maglim_1)) mag_2_error = 0.01 + 10**(log_photo_error((mag_2 + mag_extinction_2) - maglim_2)) # It would be better to convert to a flux uncertainty and then transform back to a magnitude #mag_1_meas = mag_1 + np.random.normal(scale=mag_1_error) #mag_2_meas = mag_2 + np.random.normal(scale=mag_2_error) flux_1_meas = magToFlux(mag_1) + np.random.normal(scale=getFluxError(mag_1, mag_1_error)) mag_1_meas = np.where(flux_1_meas > 0., fluxToMag(flux_1_meas), 99.) flux_2_meas = magToFlux(mag_2) + np.random.normal(scale=getFluxError(mag_2, mag_2_error)) mag_2_meas = np.where(flux_2_meas > 0., fluxToMag(flux_2_meas), 99.) # In the HSC SXDS ultra-deep field: # mean maglim_r_sof_gold_2.0 = 23.46 # median maglim_r_sof_gold_2.0 = 23.47 # m = healpy.read_map('/Users/keithbechtol/Documents/DES/projects/mw_substructure/des/y3a1/data/maps/y3a2_gold_1.0_cmv02-001_v1_nside4096_nest_r_depth.fits.gz') # np.mean(m[ugali.utils.healpix.angToDisc(4096, 34.55, -4.83, 0.75)]) # np.median(m[ugali.utils.healpix.angToDisc(4096, 34.55, -4.83, 0.75)]) # Includes penalty for interstellar extinction and also include variations in depth if config['survey'] == 'des': cut_detect = (np.random.uniform(size=len(mag_2)) < completeness(mag_2 + mag_extinction_2 + (23.46 - np.clip(maglim_2, 20., 26.)))) elif config['survey'] == 'ps1': cut_detect = (np.random.uniform(size=len(mag_2)) < completeness(mag_2 + mag_extinction_2)) n_g22 = np.sum(cut_detect & (mag_1 < 22.)) n_g24 = np.sum(cut_detect & (mag_1 < 24.)) print ' n_sim = %i, n_detect = %i, n_g24 = %i, n_g22 = %i'%(len(mag_1),np.sum(cut_detect),n_g24,n_g22) richness = stellar_mass / s.isochrone.stellarMass() #abs_mag = s.isochrone.absolute_magnitude() #abs_mag_martin = s.isochrone.absolute_magnitude_martin(richness=richness, n_trials=10)[0] # 100 trials seems to be sufficient for rough estimate #print 'abs_mag_martin = %.2f mag'%(abs_mag_martin) # The more clever thing to do would be to sum up the actual simulated stars if config['survey'] == 'des': v = mag_1 - 0.487*(mag_1 - mag_2) - 0.0249 # See https://github.com/DarkEnergySurvey/ugali/blob/master/ugali/isochrone/model.py elif config['survey'] == 'ps1': # https://arxiv.org/pdf/1706.06147.pdf # V - g = C_0 + C_1 * (g - r) C_0 = -0.017 C_1 = -0.508 v = mag_1 + C_0 + C_1 * (mag_1 - mag_2) flux = np.sum(10**(-v/2.5)) abs_mag = -2.5*np.log10(flux) - distance_modulus #print abs_mag, abs_mag_martin #distance = ugali.utils.projector.distanceModulusToDistance(distance_modulus) #r_h = extension * np.sqrt(1. - ellipticity) # Azimuthally averaged half-light radius r_physical = distance * np.tan(np.radians(r_h)) # Azimuthally averaged half-light radius, kpc #print 'distance = %.3f kpc'%(distance) #print 'r_physical = %.3f kpc'%(r_physical) surface_brightness = ugali.analysis.results.surfaceBrightness(abs_mag, r_physical, distance) # Average within azimuthally averaged half-light radius #print 'surface_brightness = %.3f mag arcsec^-2'%(surface_brightness) if plot: import pylab pylab.ion() n_sigma_p = np.sum(cut_detect & (mag_1 < 23.)) pylab.figure(figsize=(6., 6.)) pylab.scatter(mag_1_meas[cut_detect] - mag_2_meas[cut_detect], mag_1_meas[cut_detect], edgecolor='none', c='black', s=5) pylab.xlim(-0.5, 1.) pylab.ylim(26., 16.) pylab.xlabel('g - r') pylab.ylabel('g') pylab.title('Number of stars with g < 23: %i'%(n_sigma_p)) pylab.savefig('y3_sat_sim_cmd_%s.png'%(title), dpi=150.) print 'n_Sigma_p = %i'%(n_sigma_p) raw_input('WAIT') #if flag_too_extended: # # This is a kludge to remove these satellites. fragile!! # n_g24 = 1.e6 return lon[cut_detect], lat[cut_detect], mag_1_meas[cut_detect], mag_2_meas[cut_detect], mag_1_error[cut_detect], mag_2_error[cut_detect], mag_extinction_1[cut_detect], mag_extinction_2[cut_detect], n_g22, n_g24, abs_mag, surface_brightness, ellipticity, position_angle, age, metal_z, flag_too_extended
[ "def", "catsimSatellite", "(", "config", ",", "lon_centroid", ",", "lat_centroid", ",", "distance", ",", "stellar_mass", ",", "r_physical", ",", "m_maglim_1", ",", "m_maglim_2", ",", "m_ebv", ",", "plot", "=", "False", ",", "title", "=", "'test'", ")", ":", ...
Simulate a single satellite. This is currently only valid for band_1 = g and band_2 = r. r_physical is azimuthally averaged half-light radius, kpc
[ "Simulate", "a", "single", "satellite", ".", "This", "is", "currently", "only", "valid", "for", "band_1", "=", "g", "and", "band_2", "=", "r", ".", "r_physical", "is", "azimuthally", "averaged", "half", "-", "light", "radius", "kpc" ]
python
train
churchill-lab/emase
emase/AlignmentPropertyMatrix.py
https://github.com/churchill-lab/emase/blob/ae3c6955bb175c1dec88dbf9fac1a7dcc16f4449/emase/AlignmentPropertyMatrix.py#L299-L317
def get_unique_reads(self, ignore_haplotype=False, shallow=False): """ Pull out alignments of uniquely-aligning reads :param ignore_haplotype: whether to regard allelic multiread as uniquely-aligning read :param shallow: whether to copy sparse 3D matrix only or not :return: a new AlignmentPropertyMatrix object that particular reads are """ if self.finalized: if ignore_haplotype: summat = self.sum(axis=self.Axis.HAPLOTYPE) nnz_per_read = np.diff(summat.tocsr().indptr) unique_reads = np.logical_and(nnz_per_read > 0, nnz_per_read < 2) else: # allelic multireads should be removed alncnt_per_read = self.sum(axis=self.Axis.LOCUS).sum(axis=self.Axis.HAPLOTYPE) unique_reads = np.logical_and(alncnt_per_read > 0, alncnt_per_read < 2) return self.pull_alignments_from(unique_reads, shallow=shallow) else: raise RuntimeError('The matrix is not finalized.')
[ "def", "get_unique_reads", "(", "self", ",", "ignore_haplotype", "=", "False", ",", "shallow", "=", "False", ")", ":", "if", "self", ".", "finalized", ":", "if", "ignore_haplotype", ":", "summat", "=", "self", ".", "sum", "(", "axis", "=", "self", ".", ...
Pull out alignments of uniquely-aligning reads :param ignore_haplotype: whether to regard allelic multiread as uniquely-aligning read :param shallow: whether to copy sparse 3D matrix only or not :return: a new AlignmentPropertyMatrix object that particular reads are
[ "Pull", "out", "alignments", "of", "uniquely", "-", "aligning", "reads", ":", "param", "ignore_haplotype", ":", "whether", "to", "regard", "allelic", "multiread", "as", "uniquely", "-", "aligning", "read", ":", "param", "shallow", ":", "whether", "to", "copy",...
python
valid
pmacosta/pexdoc
pexdoc/exh.py
https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/pexdoc/exh.py#L1280-L1305
def encode_call(self, call): """ Replace callables with tokens to reduce object memory footprint. A callable token is an integer that denotes the order in which the callable was encountered by the encoder, i.e. the first callable encoded is assigned token 0, the second callable encoded is assigned token 1, etc. :param call: Callable name :type call: string :rtype: string """ # Callable name is None when callable is part of exclude list if call is None: return None itokens = call.split(self._callables_separator) otokens = [] for itoken in itokens: otoken = self._clut.get(itoken, None) if not otoken: otoken = str(len(self._clut)) self._clut[itoken] = otoken otokens.append(otoken) return self._callables_separator.join(otokens)
[ "def", "encode_call", "(", "self", ",", "call", ")", ":", "# Callable name is None when callable is part of exclude list", "if", "call", "is", "None", ":", "return", "None", "itokens", "=", "call", ".", "split", "(", "self", ".", "_callables_separator", ")", "otok...
Replace callables with tokens to reduce object memory footprint. A callable token is an integer that denotes the order in which the callable was encountered by the encoder, i.e. the first callable encoded is assigned token 0, the second callable encoded is assigned token 1, etc. :param call: Callable name :type call: string :rtype: string
[ "Replace", "callables", "with", "tokens", "to", "reduce", "object", "memory", "footprint", "." ]
python
train
timothyhahn/rui
rui/rui.py
https://github.com/timothyhahn/rui/blob/ac9f587fb486760d77332866c6e876f78a810f74/rui/rui.py#L215-L223
def set_tag(self, tag): ''' Sets the tag. If the Entity belongs to the world it will check for tag conflicts. ''' if self._world: if self._world.get_entity_by_tag(tag): raise NonUniqueTagError(tag) self._tag = tag
[ "def", "set_tag", "(", "self", ",", "tag", ")", ":", "if", "self", ".", "_world", ":", "if", "self", ".", "_world", ".", "get_entity_by_tag", "(", "tag", ")", ":", "raise", "NonUniqueTagError", "(", "tag", ")", "self", ".", "_tag", "=", "tag" ]
Sets the tag. If the Entity belongs to the world it will check for tag conflicts.
[ "Sets", "the", "tag", ".", "If", "the", "Entity", "belongs", "to", "the", "world", "it", "will", "check", "for", "tag", "conflicts", "." ]
python
train
NAMD/pypln.api
pypln/api.py
https://github.com/NAMD/pypln.api/blob/ccb73fd80ca094669a85bd3991dc84a8564ab016/pypln/api.py#L239-L264
def _retrieve_resources(self, url, class_, full): '''Retrieve HTTP resources, return related objects (with pagination)''' objects_to_return = [] response = self.session.get(url) if response.status_code == 200: result = response.json() resources = result['results'] objects_to_return.extend([class_(session=self.session, **resource) for resource in resources]) while full and result['next'] is not None: response = self.session.get(result['next']) if response.status_code == 200: result = response.json() resources = result['results'] objects_to_return.extend([class_(session=self.session, **resource) for resource in resources]) else: raise RuntimeError("Failed downloading data with status {}" ". The response was: '{}'" .format(response.status_code, response.text)) return objects_to_return else: raise RuntimeError("Failed downloading data with status {}" ". The response was: '{}'" .format(response.status_code, response.text))
[ "def", "_retrieve_resources", "(", "self", ",", "url", ",", "class_", ",", "full", ")", ":", "objects_to_return", "=", "[", "]", "response", "=", "self", ".", "session", ".", "get", "(", "url", ")", "if", "response", ".", "status_code", "==", "200", ":...
Retrieve HTTP resources, return related objects (with pagination)
[ "Retrieve", "HTTP", "resources", "return", "related", "objects", "(", "with", "pagination", ")" ]
python
train
tBaxter/tango-shared-core
build/lib/tango_shared/templatetags/formatting.py
https://github.com/tBaxter/tango-shared-core/blob/35fc10aef1ceedcdb4d6d866d44a22efff718812/build/lib/tango_shared/templatetags/formatting.py#L12-L22
def replace(value, arg): """ Replaces one string with another in a given string usage: {{ foo|replace:"aaa|xxx"}} """ replacement = arg.split('|') try: return value.replace(replacement[0], replacement[1]) except: return value
[ "def", "replace", "(", "value", ",", "arg", ")", ":", "replacement", "=", "arg", ".", "split", "(", "'|'", ")", "try", ":", "return", "value", ".", "replace", "(", "replacement", "[", "0", "]", ",", "replacement", "[", "1", "]", ")", "except", ":",...
Replaces one string with another in a given string usage: {{ foo|replace:"aaa|xxx"}}
[ "Replaces", "one", "string", "with", "another", "in", "a", "given", "string", "usage", ":", "{{", "foo|replace", ":", "aaa|xxx", "}}" ]
python
train
dranjan/python-plyfile
examples/plot.py
https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/examples/plot.py#L27-L51
def plot(ply): ''' Plot vertices and triangles from a PlyData instance. Assumptions: `ply' has a 'vertex' element with 'x', 'y', and 'z' properties; `ply' has a 'face' element with an integral list property 'vertex_indices', all of whose elements have length 3. ''' vertex = ply['vertex'] (x, y, z) = (vertex[t] for t in ('x', 'y', 'z')) mlab.points3d(x, y, z, color=(1, 1, 1), mode='point') if 'face' in ply: tri_idx = ply['face']['vertex_indices'] idx_dtype = tri_idx[0].dtype triangles = numpy.fromiter(tri_idx, [('data', idx_dtype, (3,))], count=len(tri_idx))['data'] mlab.triangular_mesh(x, y, z, triangles, color=(1, 0, 0.4), opacity=0.5)
[ "def", "plot", "(", "ply", ")", ":", "vertex", "=", "ply", "[", "'vertex'", "]", "(", "x", ",", "y", ",", "z", ")", "=", "(", "vertex", "[", "t", "]", "for", "t", "in", "(", "'x'", ",", "'y'", ",", "'z'", ")", ")", "mlab", ".", "points3d", ...
Plot vertices and triangles from a PlyData instance. Assumptions: `ply' has a 'vertex' element with 'x', 'y', and 'z' properties; `ply' has a 'face' element with an integral list property 'vertex_indices', all of whose elements have length 3.
[ "Plot", "vertices", "and", "triangles", "from", "a", "PlyData", "instance", ".", "Assumptions", ":", "ply", "has", "a", "vertex", "element", "with", "x", "y", "and", "z", "properties", ";" ]
python
train
materialsproject/pymatgen
pymatgen/core/structure.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/core/structure.py#L463-L482
def add_spin_by_site(self, spins): """ Add spin states to a structure by site. Args: spins (list): List of spins E.g., [+5, -5, 0, 0] """ if len(spins) != len(self.sites): raise ValueError("Spin of all sites must be " "specified in the dictionary.") for site, spin in zip(self.sites, spins): new_sp = {} for sp, occu in site.species.items(): sym = sp.symbol oxi_state = getattr(sp, "oxi_state", None) new_sp[Specie(sym, oxidation_state=oxi_state, properties={'spin': spin})] = occu site.species = new_sp
[ "def", "add_spin_by_site", "(", "self", ",", "spins", ")", ":", "if", "len", "(", "spins", ")", "!=", "len", "(", "self", ".", "sites", ")", ":", "raise", "ValueError", "(", "\"Spin of all sites must be \"", "\"specified in the dictionary.\"", ")", "for", "sit...
Add spin states to a structure by site. Args: spins (list): List of spins E.g., [+5, -5, 0, 0]
[ "Add", "spin", "states", "to", "a", "structure", "by", "site", "." ]
python
train
tsileo/globster
globster.py
https://github.com/tsileo/globster/blob/9628bce60207b150d39b409cddc3fadb34e70841/globster.py#L60-L71
def add(self, pat, fun): r"""Add a pattern and replacement. The pattern must not contain capturing groups. The replacement might be either a string template in which \& will be replaced with the match, or a function that will get the matching text as argument. It does not get match object, because capturing is forbidden anyway. """ self._pat = None self._pats.append(pat) self._funs.append(fun)
[ "def", "add", "(", "self", ",", "pat", ",", "fun", ")", ":", "self", ".", "_pat", "=", "None", "self", ".", "_pats", ".", "append", "(", "pat", ")", "self", ".", "_funs", ".", "append", "(", "fun", ")" ]
r"""Add a pattern and replacement. The pattern must not contain capturing groups. The replacement might be either a string template in which \& will be replaced with the match, or a function that will get the matching text as argument. It does not get match object, because capturing is forbidden anyway.
[ "r", "Add", "a", "pattern", "and", "replacement", "." ]
python
train
deepmind/sonnet
sonnet/python/modules/pondering_rnn.py
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/pondering_rnn.py#L38-L47
def _nested_unary_mul(nested_a, p): """Multiply `Tensors` in arbitrarily nested `Tensor` `nested_a` with `p`.""" def mul_with_broadcast(tensor): ndims = tensor.shape.ndims if ndims != 2: p_reshaped = tf.reshape(p, [-1] + [1] * (ndims - 1)) return p_reshaped * tensor else: return p * tensor return nest.map(mul_with_broadcast, nested_a)
[ "def", "_nested_unary_mul", "(", "nested_a", ",", "p", ")", ":", "def", "mul_with_broadcast", "(", "tensor", ")", ":", "ndims", "=", "tensor", ".", "shape", ".", "ndims", "if", "ndims", "!=", "2", ":", "p_reshaped", "=", "tf", ".", "reshape", "(", "p",...
Multiply `Tensors` in arbitrarily nested `Tensor` `nested_a` with `p`.
[ "Multiply", "Tensors", "in", "arbitrarily", "nested", "Tensor", "nested_a", "with", "p", "." ]
python
train
odlgroup/odl
odl/solvers/nonsmooth/proximal_operators.py
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/solvers/nonsmooth/proximal_operators.py#L1934-L1993
def proximal_huber(space, gamma): """Proximal factory of the Huber norm. Parameters ---------- space : `TensorSpace` The domain of the functional gamma : float The smoothing parameter of the Huber norm functional. Returns ------- prox_factory : function Factory for the proximal operator to be initialized. See Also -------- odl.solvers.default_functionals.Huber : the Huber norm functional Notes ----- The proximal operator is given by given by the proximal operator of ``1/(2*gamma) * L2 norm`` in points that are ``<= gamma``, and by the proximal operator of the l1 norm in points that are ``> gamma``. """ gamma = float(gamma) class ProximalHuber(Operator): """Proximal operator of Huber norm.""" def __init__(self, sigma): """Initialize a new instance. Parameters ---------- sigma : positive float """ self.sigma = float(sigma) super(ProximalHuber, self).__init__(domain=space, range=space, linear=False) def _call(self, x, out): """Return ``self(x, out=out)``.""" if isinstance(self.domain, ProductSpace): norm = PointwiseNorm(self.domain, 2)(x) else: norm = x.ufuncs.absolute() mask = norm.ufuncs.less_equal(gamma + self.sigma) out[mask] = gamma / (gamma + self.sigma) * x[mask] mask.ufuncs.logical_not(out=mask) sign_x = x.ufuncs.sign() out[mask] = x[mask] - self.sigma * sign_x[mask] return out return ProximalHuber
[ "def", "proximal_huber", "(", "space", ",", "gamma", ")", ":", "gamma", "=", "float", "(", "gamma", ")", "class", "ProximalHuber", "(", "Operator", ")", ":", "\"\"\"Proximal operator of Huber norm.\"\"\"", "def", "__init__", "(", "self", ",", "sigma", ")", ":"...
Proximal factory of the Huber norm. Parameters ---------- space : `TensorSpace` The domain of the functional gamma : float The smoothing parameter of the Huber norm functional. Returns ------- prox_factory : function Factory for the proximal operator to be initialized. See Also -------- odl.solvers.default_functionals.Huber : the Huber norm functional Notes ----- The proximal operator is given by given by the proximal operator of ``1/(2*gamma) * L2 norm`` in points that are ``<= gamma``, and by the proximal operator of the l1 norm in points that are ``> gamma``.
[ "Proximal", "factory", "of", "the", "Huber", "norm", "." ]
python
train
google/importlab
importlab/graph.py
https://github.com/google/importlab/blob/92090a0b4421137d1369c2ed952eda6bb4c7a155/importlab/graph.py#L194-L200
def get_all_unresolved(self): """Returns a set of all unresolved imports.""" assert self.final, 'Call build() before using the graph.' out = set() for v in self.broken_deps.values(): out |= v return out
[ "def", "get_all_unresolved", "(", "self", ")", ":", "assert", "self", ".", "final", ",", "'Call build() before using the graph.'", "out", "=", "set", "(", ")", "for", "v", "in", "self", ".", "broken_deps", ".", "values", "(", ")", ":", "out", "|=", "v", ...
Returns a set of all unresolved imports.
[ "Returns", "a", "set", "of", "all", "unresolved", "imports", "." ]
python
train
graphql-python/graphql-relay-py
graphql_relay/node/node.py
https://github.com/graphql-python/graphql-relay-py/blob/17ce2efa3c396df42791ae00667120b5fae64610/graphql_relay/node/node.py#L15-L49
def node_definitions(id_fetcher, type_resolver=None, id_resolver=None): ''' Given a function to map from an ID to an underlying object, and a function to map from an underlying object to the concrete GraphQLObjectType it corresponds to, constructs a `Node` interface that objects can implement, and a field config for a `node` root field. If the type_resolver is omitted, object resolution on the interface will be handled with the `isTypeOf` method on object types, as with any GraphQL interface without a provided `resolveType` method. ''' node_interface = GraphQLInterfaceType( 'Node', description='An object with an ID', fields=lambda: OrderedDict(( ('id', GraphQLField( GraphQLNonNull(GraphQLID), description='The id of the object.', resolver=id_resolver, )), )), resolve_type=type_resolver ) node_field = GraphQLField( node_interface, description='Fetches an object given its ID', args=OrderedDict(( ('id', GraphQLArgument( GraphQLNonNull(GraphQLID), description='The ID of an object' )), )), resolver=lambda obj, args, *_: id_fetcher(args.get('id'), *_) ) return node_interface, node_field
[ "def", "node_definitions", "(", "id_fetcher", ",", "type_resolver", "=", "None", ",", "id_resolver", "=", "None", ")", ":", "node_interface", "=", "GraphQLInterfaceType", "(", "'Node'", ",", "description", "=", "'An object with an ID'", ",", "fields", "=", "lambda...
Given a function to map from an ID to an underlying object, and a function to map from an underlying object to the concrete GraphQLObjectType it corresponds to, constructs a `Node` interface that objects can implement, and a field config for a `node` root field. If the type_resolver is omitted, object resolution on the interface will be handled with the `isTypeOf` method on object types, as with any GraphQL interface without a provided `resolveType` method.
[ "Given", "a", "function", "to", "map", "from", "an", "ID", "to", "an", "underlying", "object", "and", "a", "function", "to", "map", "from", "an", "underlying", "object", "to", "the", "concrete", "GraphQLObjectType", "it", "corresponds", "to", "constructs", "...
python
train
msiemens/PyGitUp
PyGitUp/gitup.py
https://github.com/msiemens/PyGitUp/blob/b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c/PyGitUp/gitup.py#L374-L424
def log(self, branch, remote): """ Call a log-command, if set by git-up.fetch.all. """ log_hook = self.settings['rebase.log-hook'] if log_hook: if ON_WINDOWS: # pragma: no cover # Running a string in CMD from Python is not that easy on # Windows. Running 'cmd /C log_hook' produces problems when # using multiple statements or things like 'echo'. Therefore, # we write the string to a bat file and execute it. # In addition, we replace occurences of $1 with %1 and so forth # in case the user is used to Bash or sh. # If there are occurences of %something, we'll replace it with # %%something. This is the case when running something like # 'git log --pretty=format:"%Cred%h..."'. # Also, we replace a semicolon with a newline, because if you # start with 'echo' on Windows, it will simply echo the # semicolon and the commands behind instead of echoing and then # running other commands # Prepare log_hook log_hook = re.sub(r'\$(\d+)', r'%\1', log_hook) log_hook = re.sub(r'%(?!\d)', '%%', log_hook) log_hook = re.sub(r'; ?', r'\n', log_hook) # Write log_hook to an temporary file and get it's path with NamedTemporaryFile( prefix='PyGitUp.', suffix='.bat', delete=False ) as bat_file: # Don't echo all commands bat_file.file.write(b'@echo off\n') # Run log_hook bat_file.file.write(log_hook.encode('utf-8')) # Run bat_file state = subprocess.call( [bat_file.name, branch.name, remote.name] ) # Clean up file os.remove(bat_file.name) else: # pragma: no cover # Run log_hook via 'shell -c' state = subprocess.call( [log_hook, 'git-up', branch.name, remote.name], shell=True ) if self.testing: assert state == 0, 'log_hook returned != 0'
[ "def", "log", "(", "self", ",", "branch", ",", "remote", ")", ":", "log_hook", "=", "self", ".", "settings", "[", "'rebase.log-hook'", "]", "if", "log_hook", ":", "if", "ON_WINDOWS", ":", "# pragma: no cover\r", "# Running a string in CMD from Python is not that eas...
Call a log-command, if set by git-up.fetch.all.
[ "Call", "a", "log", "-", "command", "if", "set", "by", "git", "-", "up", ".", "fetch", ".", "all", "." ]
python
train
fermiPy/fermipy
fermipy/jobs/target_sim.py
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/target_sim.py#L195-L233
def _build_skydir_dict(wcsgeom, rand_config): """Build a dictionary of random directions""" step_x = rand_config['step_x'] step_y = rand_config['step_y'] max_x = rand_config['max_x'] max_y = rand_config['max_y'] seed = rand_config['seed'] nsims = rand_config['nsims'] cdelt = wcsgeom.wcs.wcs.cdelt pixstep_x = step_x / cdelt[0] pixstep_y = -1. * step_y / cdelt[1] pixmax_x = max_x / cdelt[0] pixmax_y = max_y / cdelt[0] nstep_x = int(np.ceil(2. * pixmax_x / pixstep_x)) + 1 nstep_y = int(np.ceil(2. * pixmax_y / pixstep_y)) + 1 center = np.array(wcsgeom._center_pix) grid = np.meshgrid(np.linspace(-1 * pixmax_x, pixmax_x, nstep_x), np.linspace(-1 * pixmax_y, pixmax_y, nstep_y)) grid[0] += center[0] grid[1] += center[1] test_grid = wcsgeom.pix_to_coord(grid) glat_vals = test_grid[0].flat glon_vals = test_grid[1].flat conv_vals = SkyCoord(glat_vals * u.deg, glon_vals * u.deg, frame=Galactic).transform_to(ICRS) ra_vals = conv_vals.ra.deg[seed:nsims] dec_vals = conv_vals.dec.deg[seed:nsims] o_dict = {} for i, (ra, dec) in enumerate(zip(ra_vals, dec_vals)): key = i + seed o_dict[key] = dict(ra=ra, dec=dec) return o_dict
[ "def", "_build_skydir_dict", "(", "wcsgeom", ",", "rand_config", ")", ":", "step_x", "=", "rand_config", "[", "'step_x'", "]", "step_y", "=", "rand_config", "[", "'step_y'", "]", "max_x", "=", "rand_config", "[", "'max_x'", "]", "max_y", "=", "rand_config", ...
Build a dictionary of random directions
[ "Build", "a", "dictionary", "of", "random", "directions" ]
python
train
mitsei/dlkit
dlkit/json_/assessment_authoring/sessions.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/assessment_authoring/sessions.py#L286-L309
def get_assessment_parts_by_genus_type(self, assessment_part_genus_type): """Gets an ``AssessmentPartList`` corresponding to the given assessment part genus ``Type`` which does not include assessment parts of types derived from the specified ``Type``. arg: assessment_part_genus_type (osid.type.Type): an assessment part genus type return: (osid.assessment.authoring.AssessmentPartList) - the returned ``AssessmentPart`` list raise: NullArgument - ``assessment_part_genus_type`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for # osid.resource.ResourceLookupSession.get_resources_by_genus_type # NOTE: This implementation currently ignores plenary view collection = JSONClientValidated('assessment_authoring', collection='AssessmentPart', runtime=self._runtime) result = collection.find( dict({'genusTypeId': str(assessment_part_genus_type)}, **self._view_filter())).sort('_id', DESCENDING) return objects.AssessmentPartList(result, runtime=self._runtime, proxy=self._proxy)
[ "def", "get_assessment_parts_by_genus_type", "(", "self", ",", "assessment_part_genus_type", ")", ":", "# Implemented from template for", "# osid.resource.ResourceLookupSession.get_resources_by_genus_type", "# NOTE: This implementation currently ignores plenary view", "collection", "=", "J...
Gets an ``AssessmentPartList`` corresponding to the given assessment part genus ``Type`` which does not include assessment parts of types derived from the specified ``Type``. arg: assessment_part_genus_type (osid.type.Type): an assessment part genus type return: (osid.assessment.authoring.AssessmentPartList) - the returned ``AssessmentPart`` list raise: NullArgument - ``assessment_part_genus_type`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure *compliance: mandatory -- This method must be implemented.*
[ "Gets", "an", "AssessmentPartList", "corresponding", "to", "the", "given", "assessment", "part", "genus", "Type", "which", "does", "not", "include", "assessment", "parts", "of", "types", "derived", "from", "the", "specified", "Type", "." ]
python
train
gwastro/pycbc-glue
pycbc_glue/ligolw/table.py
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/table.py#L143-L149
def getColumnsByName(elem, name): """ Return a list of Column elements named name under elem. The name comparison is done with CompareColumnNames(). """ name = StripColumnName(name) return elem.getElements(lambda e: (e.tagName == ligolw.Column.tagName) and (e.Name == name))
[ "def", "getColumnsByName", "(", "elem", ",", "name", ")", ":", "name", "=", "StripColumnName", "(", "name", ")", "return", "elem", ".", "getElements", "(", "lambda", "e", ":", "(", "e", ".", "tagName", "==", "ligolw", ".", "Column", ".", "tagName", ")"...
Return a list of Column elements named name under elem. The name comparison is done with CompareColumnNames().
[ "Return", "a", "list", "of", "Column", "elements", "named", "name", "under", "elem", ".", "The", "name", "comparison", "is", "done", "with", "CompareColumnNames", "()", "." ]
python
train
wonambi-python/wonambi
wonambi/widgets/analysis.py
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/analysis.py#L1147-L1152
def check_all_local_prep(self): """Check or uncheck all enabled event pre-processing.""" all_local_pp_chk = self.event['global']['all_local_prep'].isChecked() for buttons in self.event['local'].values(): if buttons[1].isEnabled(): buttons[1].setChecked(all_local_pp_chk)
[ "def", "check_all_local_prep", "(", "self", ")", ":", "all_local_pp_chk", "=", "self", ".", "event", "[", "'global'", "]", "[", "'all_local_prep'", "]", ".", "isChecked", "(", ")", "for", "buttons", "in", "self", ".", "event", "[", "'local'", "]", ".", "...
Check or uncheck all enabled event pre-processing.
[ "Check", "or", "uncheck", "all", "enabled", "event", "pre", "-", "processing", "." ]
python
train
kennedyshead/aioasuswrt
aioasuswrt/asuswrt.py
https://github.com/kennedyshead/aioasuswrt/blob/0c4336433727abbb7b324ee29e4c5382be9aaa2b/aioasuswrt/asuswrt.py#L159-L180
async def async_get_connected_devices(self): """Retrieve data from ASUSWRT. Calls various commands on the router and returns the superset of all responses. Some commands will not work on some routers. """ devices = {} dev = await self.async_get_wl() devices.update(dev) dev = await self.async_get_arp() devices.update(dev) dev = await self.async_get_neigh(devices) devices.update(dev) if not self.mode == 'ap': dev = await self.async_get_leases(devices) devices.update(dev) ret_devices = {} for key in devices: if not self.require_ip or devices[key].ip is not None: ret_devices[key] = devices[key] return ret_devices
[ "async", "def", "async_get_connected_devices", "(", "self", ")", ":", "devices", "=", "{", "}", "dev", "=", "await", "self", ".", "async_get_wl", "(", ")", "devices", ".", "update", "(", "dev", ")", "dev", "=", "await", "self", ".", "async_get_arp", "(",...
Retrieve data from ASUSWRT. Calls various commands on the router and returns the superset of all responses. Some commands will not work on some routers.
[ "Retrieve", "data", "from", "ASUSWRT", "." ]
python
train
Jarn/jarn.mkrelease
jarn/mkrelease/mkrelease.py
https://github.com/Jarn/jarn.mkrelease/blob/844377f37a3cdc0a154148790a926f991019ec4a/jarn/mkrelease/mkrelease.py#L371-L386
def get_skipregister(self, location=None): """Return true if the register command is disabled (for the given server.) """ if location is None: return self.skipregister or not self.defaults.register else: server = self.defaults.servers[location] if self.skipregister: return True elif server.register is not None: if not self.defaults.register and self.get_skipupload(): return True # prevent override return not server.register elif not self.defaults.register: return True return False
[ "def", "get_skipregister", "(", "self", ",", "location", "=", "None", ")", ":", "if", "location", "is", "None", ":", "return", "self", ".", "skipregister", "or", "not", "self", ".", "defaults", ".", "register", "else", ":", "server", "=", "self", ".", ...
Return true if the register command is disabled (for the given server.)
[ "Return", "true", "if", "the", "register", "command", "is", "disabled", "(", "for", "the", "given", "server", ".", ")" ]
python
train
edeposit/edeposit.amqp.harvester
src/edeposit/amqp/harvester/scrappers/utils.py
https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/utils.py#L62-L87
def get_first_content(el_list, alt=None, strip=True): """ Return content of the first element in `el_list` or `alt`. Also return `alt` if the content string of first element is blank. Args: el_list (list): List of HTMLElement objects. alt (default None): Value returner when list or content is blank. strip (bool, default True): Call .strip() to content. Returns: str or alt: String representation of the content of the first element \ or `alt` if not found. """ if not el_list: return alt content = el_list[0].getContent() if strip: content = content.strip() if not content: return alt return content
[ "def", "get_first_content", "(", "el_list", ",", "alt", "=", "None", ",", "strip", "=", "True", ")", ":", "if", "not", "el_list", ":", "return", "alt", "content", "=", "el_list", "[", "0", "]", ".", "getContent", "(", ")", "if", "strip", ":", "conten...
Return content of the first element in `el_list` or `alt`. Also return `alt` if the content string of first element is blank. Args: el_list (list): List of HTMLElement objects. alt (default None): Value returner when list or content is blank. strip (bool, default True): Call .strip() to content. Returns: str or alt: String representation of the content of the first element \ or `alt` if not found.
[ "Return", "content", "of", "the", "first", "element", "in", "el_list", "or", "alt", ".", "Also", "return", "alt", "if", "the", "content", "string", "of", "first", "element", "is", "blank", "." ]
python
train
Qiskit/qiskit-terra
qiskit/qasm/qasmparser.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/qasm/qasmparser.py#L1078-L1085
def run(self, data): """Parser runner. To use this module stand-alone. """ ast = self.parser.parse(data, debug=True) self.parser.parse(data, debug=True) ast.to_string(0)
[ "def", "run", "(", "self", ",", "data", ")", ":", "ast", "=", "self", ".", "parser", ".", "parse", "(", "data", ",", "debug", "=", "True", ")", "self", ".", "parser", ".", "parse", "(", "data", ",", "debug", "=", "True", ")", "ast", ".", "to_st...
Parser runner. To use this module stand-alone.
[ "Parser", "runner", "." ]
python
test
libtcod/python-tcod
tcod/libtcodpy.py
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1053-L1065
def console_map_string_to_font(s: str, fontCharX: int, fontCharY: int) -> None: """Remap a string of codes to a contiguous set of tiles. Args: s (AnyStr): A string of character codes to map to new values. The null character `'\\x00'` will prematurely end this function. fontCharX (int): The starting X tile coordinate on the loaded tileset. 0 is the leftmost tile. fontCharY (int): The starting Y tile coordinate on the loaded tileset. 0 is the topmost tile. """ lib.TCOD_console_map_string_to_font_utf(_unicode(s), fontCharX, fontCharY)
[ "def", "console_map_string_to_font", "(", "s", ":", "str", ",", "fontCharX", ":", "int", ",", "fontCharY", ":", "int", ")", "->", "None", ":", "lib", ".", "TCOD_console_map_string_to_font_utf", "(", "_unicode", "(", "s", ")", ",", "fontCharX", ",", "fontChar...
Remap a string of codes to a contiguous set of tiles. Args: s (AnyStr): A string of character codes to map to new values. The null character `'\\x00'` will prematurely end this function. fontCharX (int): The starting X tile coordinate on the loaded tileset. 0 is the leftmost tile. fontCharY (int): The starting Y tile coordinate on the loaded tileset. 0 is the topmost tile.
[ "Remap", "a", "string", "of", "codes", "to", "a", "contiguous", "set", "of", "tiles", "." ]
python
train
Clinical-Genomics/scout
scout/load/case.py
https://github.com/Clinical-Genomics/scout/blob/90a551e2e1653a319e654c2405c2866f93d0ebb9/scout/load/case.py#L9-L36
def load_case(adapter, case_obj, update=False): """Load a case into the database If the case already exists the function will exit. If the user want to load a case that is already in the database 'update' has to be 'True' Args: adapter (MongoAdapter): connection to the database case_obj (dict): case object to persist to the database update(bool): If existing case should be updated Returns: case_obj(dict): A dictionary with the builded case """ logger.info('Loading case {} into database'.format(case_obj['display_name'])) # Check if case exists in database existing_case = adapter.case(case_obj['_id']) if existing_case: if update: adapter.update_case(case_obj) else: raise IntegrityError("Case {0} already exists in database".format(case_obj['_id'])) else: adapter.add_case(case_obj) return case_obj
[ "def", "load_case", "(", "adapter", ",", "case_obj", ",", "update", "=", "False", ")", ":", "logger", ".", "info", "(", "'Loading case {} into database'", ".", "format", "(", "case_obj", "[", "'display_name'", "]", ")", ")", "# Check if case exists in database", ...
Load a case into the database If the case already exists the function will exit. If the user want to load a case that is already in the database 'update' has to be 'True' Args: adapter (MongoAdapter): connection to the database case_obj (dict): case object to persist to the database update(bool): If existing case should be updated Returns: case_obj(dict): A dictionary with the builded case
[ "Load", "a", "case", "into", "the", "database" ]
python
test
gem/oq-engine
openquake/hmtk/seismicity/selector.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/selector.py#L380-L406
def within_magnitude_range(self, lower_mag=None, upper_mag=None): ''' :param float lower_mag: Lower magnitude for consideration :param float upper_mag: Upper magnitude for consideration :returns: Instance of openquake.hmtk.seismicity.catalogue.Catalogue class containing only selected events ''' if not lower_mag: if not upper_mag: # No limiting magnitudes defined - return entire catalogue! return self.catalogue else: lower_mag = -np.inf if not upper_mag: upper_mag = np.inf is_valid = np.logical_and( self.catalogue.data['magnitude'] >= lower_mag, self.catalogue.data['magnitude'] < upper_mag) return self.select_catalogue(is_valid)
[ "def", "within_magnitude_range", "(", "self", ",", "lower_mag", "=", "None", ",", "upper_mag", "=", "None", ")", ":", "if", "not", "lower_mag", ":", "if", "not", "upper_mag", ":", "# No limiting magnitudes defined - return entire catalogue!", "return", "self", ".", ...
:param float lower_mag: Lower magnitude for consideration :param float upper_mag: Upper magnitude for consideration :returns: Instance of openquake.hmtk.seismicity.catalogue.Catalogue class containing only selected events
[ ":", "param", "float", "lower_mag", ":", "Lower", "magnitude", "for", "consideration" ]
python
train
bitesofcode/projexui
projexui/widgets/xganttwidget/xganttwidget.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xganttwidget/xganttwidget.py#L202-L219
def addTopLevelItem(self, item): """ Adds the inputed item to the gantt widget. :param item | <XGanttWidgetItem> """ vitem = item.viewItem() self.treeWidget().addTopLevelItem(item) self.viewWidget().scene().addItem(vitem) item._viewItem = weakref.ref(vitem) if self.updatesEnabled(): try: item.sync(recursive=True) except AttributeError: pass
[ "def", "addTopLevelItem", "(", "self", ",", "item", ")", ":", "vitem", "=", "item", ".", "viewItem", "(", ")", "self", ".", "treeWidget", "(", ")", ".", "addTopLevelItem", "(", "item", ")", "self", ".", "viewWidget", "(", ")", ".", "scene", "(", ")",...
Adds the inputed item to the gantt widget. :param item | <XGanttWidgetItem>
[ "Adds", "the", "inputed", "item", "to", "the", "gantt", "widget", ".", ":", "param", "item", "|", "<XGanttWidgetItem", ">" ]
python
train
robotframework/Rammbock
src/Rammbock/core.py
https://github.com/robotframework/Rammbock/blob/c906058d055a6f7c68fe1a6096d78c2e3f642b1c/src/Rammbock/core.py#L472-L484
def load_copy_of_template(self, name, *parameters): """Load a copy of message template saved with `Save template` when originally saved values need to be preserved from test to test. Optional parameters are default values for message header separated with colon. Examples: | Load Copy Of Template | MyMessage | header_field:value | """ template, fields, header_fields = self._set_templates_fields_and_header_fields(name, parameters) copy_of_template = copy.deepcopy(template) copy_of_fields = copy.deepcopy(fields) self._init_new_message_stack(copy_of_template, copy_of_fields, header_fields)
[ "def", "load_copy_of_template", "(", "self", ",", "name", ",", "*", "parameters", ")", ":", "template", ",", "fields", ",", "header_fields", "=", "self", ".", "_set_templates_fields_and_header_fields", "(", "name", ",", "parameters", ")", "copy_of_template", "=", ...
Load a copy of message template saved with `Save template` when originally saved values need to be preserved from test to test. Optional parameters are default values for message header separated with colon. Examples: | Load Copy Of Template | MyMessage | header_field:value |
[ "Load", "a", "copy", "of", "message", "template", "saved", "with", "Save", "template", "when", "originally", "saved", "values", "need", "to", "be", "preserved", "from", "test", "to", "test", ".", "Optional", "parameters", "are", "default", "values", "for", "...
python
train
pypa/pipenv
pipenv/vendor/yarg/package.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/yarg/package.py#L123-L131
def author(self): """ >>> package = yarg.get('yarg') >>> package.author Author(name=u'Kura', email=u'kura@kura.io') """ author = namedtuple('Author', 'name email') return author(name=self._package['author'], email=self._package['author_email'])
[ "def", "author", "(", "self", ")", ":", "author", "=", "namedtuple", "(", "'Author'", ",", "'name email'", ")", "return", "author", "(", "name", "=", "self", ".", "_package", "[", "'author'", "]", ",", "email", "=", "self", ".", "_package", "[", "'auth...
>>> package = yarg.get('yarg') >>> package.author Author(name=u'Kura', email=u'kura@kura.io')
[ ">>>", "package", "=", "yarg", ".", "get", "(", "yarg", ")", ">>>", "package", ".", "author", "Author", "(", "name", "=", "u", "Kura", "email", "=", "u", "kura" ]
python
train
zhanglab/psamm
psamm/fluxanalysis.py
https://github.com/zhanglab/psamm/blob/dc427848c4f9d109ca590f0afa024c63b685b3f4/psamm/fluxanalysis.py#L35-L40
def _get_fba_problem(model, tfba, solver): """Convenience function for returning the right FBA problem instance""" p = FluxBalanceProblem(model, solver) if tfba: p.add_thermodynamic() return p
[ "def", "_get_fba_problem", "(", "model", ",", "tfba", ",", "solver", ")", ":", "p", "=", "FluxBalanceProblem", "(", "model", ",", "solver", ")", "if", "tfba", ":", "p", ".", "add_thermodynamic", "(", ")", "return", "p" ]
Convenience function for returning the right FBA problem instance
[ "Convenience", "function", "for", "returning", "the", "right", "FBA", "problem", "instance" ]
python
train
aio-libs/aiomcache
aiomcache/client.py
https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L415-L422
def flush_all(self, conn): """Its effect is to invalidate all existing items immediately""" command = b'flush_all\r\n' response = yield from self._execute_simple_command( conn, command) if const.OK != response: raise ClientException('Memcached flush_all failed', response)
[ "def", "flush_all", "(", "self", ",", "conn", ")", ":", "command", "=", "b'flush_all\\r\\n'", "response", "=", "yield", "from", "self", ".", "_execute_simple_command", "(", "conn", ",", "command", ")", "if", "const", ".", "OK", "!=", "response", ":", "rais...
Its effect is to invalidate all existing items immediately
[ "Its", "effect", "is", "to", "invalidate", "all", "existing", "items", "immediately" ]
python
train
sanoma/django-arctic
arctic/utils.py
https://github.com/sanoma/django-arctic/blob/c81b092c2643ca220708bf3c586017d9175161f5/arctic/utils.py#L104-L128
def menu_clean(menu_config): """ Make sure that only the menu item with the largest weight is active. If a child of a menu item is active, the parent should be active too. :param menu: :return: """ max_weight = -1 for _, value in list(menu_config.items()): if value["submenu"]: for _, v in list(value["submenu"].items()): if v["active"]: # parent inherits the weight of the axctive child value["active"] = True value["active_weight"] = v["active_weight"] if value["active"]: max_weight = max(value["active_weight"], max_weight) if max_weight > 0: # one of the items is active: make items with lesser weight inactive for _, value in list(menu_config.items()): if value["active"] and value["active_weight"] < max_weight: value["active"] = False return menu_config
[ "def", "menu_clean", "(", "menu_config", ")", ":", "max_weight", "=", "-", "1", "for", "_", ",", "value", "in", "list", "(", "menu_config", ".", "items", "(", ")", ")", ":", "if", "value", "[", "\"submenu\"", "]", ":", "for", "_", ",", "v", "in", ...
Make sure that only the menu item with the largest weight is active. If a child of a menu item is active, the parent should be active too. :param menu: :return:
[ "Make", "sure", "that", "only", "the", "menu", "item", "with", "the", "largest", "weight", "is", "active", ".", "If", "a", "child", "of", "a", "menu", "item", "is", "active", "the", "parent", "should", "be", "active", "too", ".", ":", "param", "menu", ...
python
train
frictionlessdata/datapackage-pipelines
datapackage_pipelines/utilities/dirtools.py
https://github.com/frictionlessdata/datapackage-pipelines/blob/3a34bbdf042d13c3bec5eef46ff360ee41403874/datapackage_pipelines/utilities/dirtools.py#L138-L153
def hash(self, index_func=os.path.getmtime): """ Hash for the entire directory (except excluded files) recursively. Use mtime instead of sha256 by default for a faster hash. >>> dir.hash(index_func=dirtools.filehash) """ # TODO alternative to filehash => mtime as a faster alternative shadir = hashlib.sha256() for f in self.files(): try: shadir.update(str(index_func(os.path.join(self.path, f)))) except (IOError, OSError): pass return shadir.hexdigest()
[ "def", "hash", "(", "self", ",", "index_func", "=", "os", ".", "path", ".", "getmtime", ")", ":", "# TODO alternative to filehash => mtime as a faster alternative", "shadir", "=", "hashlib", ".", "sha256", "(", ")", "for", "f", "in", "self", ".", "files", "(",...
Hash for the entire directory (except excluded files) recursively. Use mtime instead of sha256 by default for a faster hash. >>> dir.hash(index_func=dirtools.filehash)
[ "Hash", "for", "the", "entire", "directory", "(", "except", "excluded", "files", ")", "recursively", "." ]
python
train
siemens/django-dingos
dingos/models.py
https://github.com/siemens/django-dingos/blob/7154f75b06d2538568e2f2455a76f3d0db0b7d70/dingos/models.py#L1510-L1586
def add_relation(self, target_id=None, relation_types=None, fact_dt_namespace_name=None, fact_dt_namespace_uri=DINGOS_NAMESPACE_URI, fact_dt_kind=FactDataType.UNKNOWN_KIND, fact_dt_name='String', metadata_dict=None, markings=None ): """ Add a relationship between this object and another object. """ if not markings: markings = [] if relation_types == None: relation_types = [] # Create fact-term for relation types relation_type_ft, created = get_or_create_fact_term(iobject_family_name=self.iobject_family.name, fact_term_name=DINGOS_RELATION_TYPE_FACTTERM_NAME, iobject_type_name=self.iobject_type.name, iobject_type_namespace_uri=self.iobject_type.namespace.uri, fact_dt_name=fact_dt_name, fact_dt_namespace_name=fact_dt_namespace_name, fact_dt_kind=fact_dt_kind, fact_dt_namespace_uri=fact_dt_namespace_uri) # Create fact containing relation types relation_type_fact, created = get_or_create_fact(fact_term=relation_type_ft, fact_dt_name=fact_dt_name, fact_dt_namespace_uri=fact_dt_namespace_uri, values=relation_types, value_iobject_id=None, value_iobject_ts=None, ) rel_target_id = target_id rel_source_id = self.identifier # Create relation object relation, created = self._DCM['Relation'].objects.get_or_create( source_id=rel_source_id, target_id=rel_target_id, relation_type=relation_type_fact) # Add markings for marking in markings: Marking2X.objects.create(marked=relation, marking=marking) if metadata_dict: # If the relation already existed and had associated metadata, # we retrieve the identifier of that metadata object and # write the current metadata as new revision. Otherwise, # we create a new identifier. if relation.metadata_id: rel_identifier_uid = relation.metadata_id.uid rel_identifier_namespace_uri = relation.metadata_id.namespace.uri else: rel_identifier_uid = None rel_identifier_namespace_uri = DINGOS_ID_NAMESPACE_URI metadata_iobject, created = get_or_create_iobject(identifier_uid=rel_identifier_uid, identifier_namespace_uri=rel_identifier_namespace_uri, iobject_type_name=DINGOS_RELATION_METADATA_OBJECT_TYPE_NAME, iobject_type_namespace_uri=DINGOS_NAMESPACE_URI, iobject_type_revision_name=DINGOS_REVISION_NAME, iobject_family_name=DINGOS_IOBJECT_FAMILY_NAME, iobject_family_revision_name=DINGOS_REVISION_NAME, timestamp=None, overwrite=False) metadata_iobject.from_dict(metadata_dict) return relation
[ "def", "add_relation", "(", "self", ",", "target_id", "=", "None", ",", "relation_types", "=", "None", ",", "fact_dt_namespace_name", "=", "None", ",", "fact_dt_namespace_uri", "=", "DINGOS_NAMESPACE_URI", ",", "fact_dt_kind", "=", "FactDataType", ".", "UNKNOWN_KIND...
Add a relationship between this object and another object.
[ "Add", "a", "relationship", "between", "this", "object", "and", "another", "object", "." ]
python
train
mikusjelly/apkutils
apkutils/apkfile.py
https://github.com/mikusjelly/apkutils/blob/2db1ed0cdb610dfc55bfd77266e9a91e4764bba4/apkutils/apkfile.py#L758-L806
def readline(self, limit=-1): """Read and return a line from the stream. If limit is specified, at most limit bytes will be read. """ if not self._universal and limit < 0: # Shortcut common case - newline found in buffer. i = self._readbuffer.find(b'\n', self._offset) + 1 if i > 0: line = self._readbuffer[self._offset: i] self._offset = i return line if not self._universal: return io.BufferedIOBase.readline(self, limit) line = b'' while limit < 0 or len(line) < limit: readahead = self.peek(2) if readahead == b'': return line # # Search for universal newlines or line chunks. # # The pattern returns either a line chunk or a newline, but not # both. Combined with peek(2), we are assured that the sequence # '\r\n' is always retrieved completely and never split into # separate newlines - '\r', '\n' due to coincidental readaheads. # match = self.PATTERN.search(readahead) newline = match.group('newline') if newline is not None: if self.newlines is None: self.newlines = [] if newline not in self.newlines: self.newlines.append(newline) self._offset += len(newline) return line + b'\n' chunk = match.group('chunk') if limit >= 0: chunk = chunk[: limit - len(line)] self._offset += len(chunk) line += chunk return line
[ "def", "readline", "(", "self", ",", "limit", "=", "-", "1", ")", ":", "if", "not", "self", ".", "_universal", "and", "limit", "<", "0", ":", "# Shortcut common case - newline found in buffer.", "i", "=", "self", ".", "_readbuffer", ".", "find", "(", "b'\\...
Read and return a line from the stream. If limit is specified, at most limit bytes will be read.
[ "Read", "and", "return", "a", "line", "from", "the", "stream", "." ]
python
train
ingolemo/python-lenses
examples/naughts_and_crosses.py
https://github.com/ingolemo/python-lenses/blob/a3a6ed0a31f6674451e542e7380a8aa16e6f8edf/examples/naughts_and_crosses.py#L42-L47
def make_move(self, x, y): '''Return a board with a cell filled in by the current player. If the cell is already occupied then return the board unchanged.''' if self.board[y][x] == ' ': return lens.board[y][x].set(self.player)(self) return self
[ "def", "make_move", "(", "self", ",", "x", ",", "y", ")", ":", "if", "self", ".", "board", "[", "y", "]", "[", "x", "]", "==", "' '", ":", "return", "lens", ".", "board", "[", "y", "]", "[", "x", "]", ".", "set", "(", "self", ".", "player",...
Return a board with a cell filled in by the current player. If the cell is already occupied then return the board unchanged.
[ "Return", "a", "board", "with", "a", "cell", "filled", "in", "by", "the", "current", "player", ".", "If", "the", "cell", "is", "already", "occupied", "then", "return", "the", "board", "unchanged", "." ]
python
test
tkem/uritools
uritools/split.py
https://github.com/tkem/uritools/blob/e77ba4acd937b68da9850138563debd4c925ef9f/uritools/split.py#L178-L187
def getquery(self, default=None, encoding='utf-8', errors='strict'): """Return the decoded query string, or `default` if the original URI reference did not contain a query component. """ query = self.query if query is None: return default else: return uridecode(query, encoding, errors)
[ "def", "getquery", "(", "self", ",", "default", "=", "None", ",", "encoding", "=", "'utf-8'", ",", "errors", "=", "'strict'", ")", ":", "query", "=", "self", ".", "query", "if", "query", "is", "None", ":", "return", "default", "else", ":", "return", ...
Return the decoded query string, or `default` if the original URI reference did not contain a query component.
[ "Return", "the", "decoded", "query", "string", "or", "default", "if", "the", "original", "URI", "reference", "did", "not", "contain", "a", "query", "component", "." ]
python
train
SheffieldML/GPy
GPy/plotting/gpy_plot/data_plots.py
https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/plotting/gpy_plot/data_plots.py#L199-L223
def plot_errorbars_trainset(self, which_data_rows='all', which_data_ycols='all', fixed_inputs=None, plot_raw=False, apply_link=False, label=None, projection='2d', predict_kw=None, **plot_kwargs): """ Plot the errorbars of the GP likelihood on the training data. These are the errorbars after the appropriate approximations according to the likelihood are done. This also works for heteroscedastic likelihoods. Give the Y_metadata in the predict_kw if you need it. :param which_data_rows: which of the training data to plot (default all) :type which_data_rows: 'all' or a slice object to slice self.X, self.Y :param which_data_ycols: when the data has several columns (independant outputs), only plot these :param fixed_inputs: a list of tuple [(i,v), (i,v)...], specifying that input dimension i should be set to value v. :type fixed_inputs: a list of tuples :param dict predict_kwargs: kwargs for the prediction used to predict the right quantiles. :param kwargs plot_kwargs: kwargs for the data plot for the plotting library you are using """ canvas, kwargs = pl().new_canvas(projection=projection, **plot_kwargs) plots = _plot_errorbars_trainset(self, canvas, which_data_rows, which_data_ycols, fixed_inputs, plot_raw, apply_link, label, projection, predict_kw, **kwargs) return pl().add_to_canvas(canvas, plots)
[ "def", "plot_errorbars_trainset", "(", "self", ",", "which_data_rows", "=", "'all'", ",", "which_data_ycols", "=", "'all'", ",", "fixed_inputs", "=", "None", ",", "plot_raw", "=", "False", ",", "apply_link", "=", "False", ",", "label", "=", "None", ",", "pro...
Plot the errorbars of the GP likelihood on the training data. These are the errorbars after the appropriate approximations according to the likelihood are done. This also works for heteroscedastic likelihoods. Give the Y_metadata in the predict_kw if you need it. :param which_data_rows: which of the training data to plot (default all) :type which_data_rows: 'all' or a slice object to slice self.X, self.Y :param which_data_ycols: when the data has several columns (independant outputs), only plot these :param fixed_inputs: a list of tuple [(i,v), (i,v)...], specifying that input dimension i should be set to value v. :type fixed_inputs: a list of tuples :param dict predict_kwargs: kwargs for the prediction used to predict the right quantiles. :param kwargs plot_kwargs: kwargs for the data plot for the plotting library you are using
[ "Plot", "the", "errorbars", "of", "the", "GP", "likelihood", "on", "the", "training", "data", ".", "These", "are", "the", "errorbars", "after", "the", "appropriate", "approximations", "according", "to", "the", "likelihood", "are", "done", "." ]
python
train
totalgood/nlpia
src/nlpia/gensim_utils.py
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/gensim_utils.py#L44-L90
def to_unicode(sorb, allow_eval=False): r"""Ensure that strings are unicode (UTF-8 encoded). Evaluate bytes literals that are sometimes accidentally created by str(b'whatever') >>> to_unicode(b'whatever') 'whatever' >>> to_unicode(b'b"whatever"') 'whatever' >>> to_unicode(repr(b'b"whatever"')) 'whatever' >>> to_unicode(str(b'b"whatever"')) 'whatever' >>> to_unicode(str(str(b'whatever'))) 'whatever' >>> to_unicode(bytes(u'whatever', 'utf-8')) 'whatever' >>> to_unicode(b'u"whatever"') 'whatever' >>> to_unicode(u'b"whatever"') 'whatever' There seems to be a bug in python3 core: >>> str(b'whatever') # user intended str.decode(b'whatever') (str coercion) rather than python code repr "b'whatever'" >>> repr(str(b'whatever')) '"b\'whatever\'"' >>> str(repr(str(b'whatever'))) '"b\'whatever\'"' >>> repr(str(repr(str(b'whatever')))) '\'"b\\\'whatever\\\'"\'' >>> repr(repr(b'whatever')) '"b\'whatever\'"' >>> str(str(b'whatever')) "b'whatever'" >>> str(repr(b'whatever')) "b'whatever'" """ if sorb is None: return sorb if isinstance(sorb, bytes): sorb = sorb.decode() for i, s in enumerate(["b'", 'b"', "u'", 'u"']): if (sorb.startswith(s) and sorb.endswith(s[-1])): # print(i) return to_unicode(eval(sorb, {'__builtins__': None}, {})) return sorb
[ "def", "to_unicode", "(", "sorb", ",", "allow_eval", "=", "False", ")", ":", "if", "sorb", "is", "None", ":", "return", "sorb", "if", "isinstance", "(", "sorb", ",", "bytes", ")", ":", "sorb", "=", "sorb", ".", "decode", "(", ")", "for", "i", ",", ...
r"""Ensure that strings are unicode (UTF-8 encoded). Evaluate bytes literals that are sometimes accidentally created by str(b'whatever') >>> to_unicode(b'whatever') 'whatever' >>> to_unicode(b'b"whatever"') 'whatever' >>> to_unicode(repr(b'b"whatever"')) 'whatever' >>> to_unicode(str(b'b"whatever"')) 'whatever' >>> to_unicode(str(str(b'whatever'))) 'whatever' >>> to_unicode(bytes(u'whatever', 'utf-8')) 'whatever' >>> to_unicode(b'u"whatever"') 'whatever' >>> to_unicode(u'b"whatever"') 'whatever' There seems to be a bug in python3 core: >>> str(b'whatever') # user intended str.decode(b'whatever') (str coercion) rather than python code repr "b'whatever'" >>> repr(str(b'whatever')) '"b\'whatever\'"' >>> str(repr(str(b'whatever'))) '"b\'whatever\'"' >>> repr(str(repr(str(b'whatever')))) '\'"b\\\'whatever\\\'"\'' >>> repr(repr(b'whatever')) '"b\'whatever\'"' >>> str(str(b'whatever')) "b'whatever'" >>> str(repr(b'whatever')) "b'whatever'"
[ "r", "Ensure", "that", "strings", "are", "unicode", "(", "UTF", "-", "8", "encoded", ")", "." ]
python
train
cloudera/impyla
impala/_thrift_gen/hive_metastore/ThriftHiveMetastore.py
https://github.com/cloudera/impyla/blob/547fa2ba3b6151e2a98b3544301471a643212dc3/impala/_thrift_gen/hive_metastore/ThriftHiveMetastore.py#L3354-L3363
def get_partitions_ps(self, db_name, tbl_name, part_vals, max_parts): """ Parameters: - db_name - tbl_name - part_vals - max_parts """ self.send_get_partitions_ps(db_name, tbl_name, part_vals, max_parts) return self.recv_get_partitions_ps()
[ "def", "get_partitions_ps", "(", "self", ",", "db_name", ",", "tbl_name", ",", "part_vals", ",", "max_parts", ")", ":", "self", ".", "send_get_partitions_ps", "(", "db_name", ",", "tbl_name", ",", "part_vals", ",", "max_parts", ")", "return", "self", ".", "r...
Parameters: - db_name - tbl_name - part_vals - max_parts
[ "Parameters", ":", "-", "db_name", "-", "tbl_name", "-", "part_vals", "-", "max_parts" ]
python
train
saltstack/salt
salt/runners/vault.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/vault.py#L146-L163
def _validate_signature(minion_id, signature, impersonated_by_master): ''' Validate that either minion with id minion_id, or the master, signed the request ''' pki_dir = __opts__['pki_dir'] if impersonated_by_master: public_key = '{0}/master.pub'.format(pki_dir) else: public_key = '{0}/minions/{1}'.format(pki_dir, minion_id) log.trace('Validating signature for %s', minion_id) signature = base64.b64decode(signature) if not salt.crypt.verify_signature(public_key, minion_id, signature): raise salt.exceptions.AuthenticationError( 'Could not validate token request from {0}'.format(minion_id) ) log.trace('Signature ok')
[ "def", "_validate_signature", "(", "minion_id", ",", "signature", ",", "impersonated_by_master", ")", ":", "pki_dir", "=", "__opts__", "[", "'pki_dir'", "]", "if", "impersonated_by_master", ":", "public_key", "=", "'{0}/master.pub'", ".", "format", "(", "pki_dir", ...
Validate that either minion with id minion_id, or the master, signed the request
[ "Validate", "that", "either", "minion", "with", "id", "minion_id", "or", "the", "master", "signed", "the", "request" ]
python
train
carlospalol/money
money/exchange.py
https://github.com/carlospalol/money/blob/1e51f651f93edd62c16eb3d7aa034fec03096046/money/exchange.py#L119-L123
def quotation(self, origin, target): """Return quotation between two currencies (origin, target)""" if not self._backend: raise ExchangeBackendNotInstalled() return self._backend.quotation(origin, target)
[ "def", "quotation", "(", "self", ",", "origin", ",", "target", ")", ":", "if", "not", "self", ".", "_backend", ":", "raise", "ExchangeBackendNotInstalled", "(", ")", "return", "self", ".", "_backend", ".", "quotation", "(", "origin", ",", "target", ")" ]
Return quotation between two currencies (origin, target)
[ "Return", "quotation", "between", "two", "currencies", "(", "origin", "target", ")" ]
python
train
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/list_types.py
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/list_types.py#L208-L212
def process_bind_param(self, value: Optional[List[str]], dialect: Dialect) -> str: """Convert things on the way from Python to the database.""" retval = self._strlist_to_dbstr(value) return retval
[ "def", "process_bind_param", "(", "self", ",", "value", ":", "Optional", "[", "List", "[", "str", "]", "]", ",", "dialect", ":", "Dialect", ")", "->", "str", ":", "retval", "=", "self", ".", "_strlist_to_dbstr", "(", "value", ")", "return", "retval" ]
Convert things on the way from Python to the database.
[ "Convert", "things", "on", "the", "way", "from", "Python", "to", "the", "database", "." ]
python
train
Azure/msrest-for-python
msrest/universal_http/aiohttp.py
https://github.com/Azure/msrest-for-python/blob/0732bc90bdb290e5f58c675ffdd7dbfa9acefc93/msrest/universal_http/aiohttp.py#L50-L64
async def send(self, request: ClientRequest, **config: Any) -> AsyncClientResponse: """Send the request using this HTTP sender. Will pre-load the body into memory to be available with a sync method. pass stream=True to avoid this behavior. """ result = await self._session.request( request.method, request.url, **config ) response = AioHttpClientResponse(request, result) if not config.get("stream", False): await response.load_body() return response
[ "async", "def", "send", "(", "self", ",", "request", ":", "ClientRequest", ",", "*", "*", "config", ":", "Any", ")", "->", "AsyncClientResponse", ":", "result", "=", "await", "self", ".", "_session", ".", "request", "(", "request", ".", "method", ",", ...
Send the request using this HTTP sender. Will pre-load the body into memory to be available with a sync method. pass stream=True to avoid this behavior.
[ "Send", "the", "request", "using", "this", "HTTP", "sender", "." ]
python
train
hyperledger/sawtooth-core
validator/sawtooth_validator/state/batch_tracker.py
https://github.com/hyperledger/sawtooth-core/blob/8cf473bc2207e51f02bd182d825158a57d72b098/validator/sawtooth_validator/state/batch_tracker.py#L187-L190
def _has_no_pendings(self, statuses): """Returns True if a statuses dict has no PENDING statuses. """ return all(s != ClientBatchStatus.PENDING for s in statuses.values())
[ "def", "_has_no_pendings", "(", "self", ",", "statuses", ")", ":", "return", "all", "(", "s", "!=", "ClientBatchStatus", ".", "PENDING", "for", "s", "in", "statuses", ".", "values", "(", ")", ")" ]
Returns True if a statuses dict has no PENDING statuses.
[ "Returns", "True", "if", "a", "statuses", "dict", "has", "no", "PENDING", "statuses", "." ]
python
train
mezz64/pyEight
pyeight/user.py
https://github.com/mezz64/pyEight/blob/e557e4e6876f490d0964298e9475d68b64222d4f/pyeight/user.py#L494-L542
def dynamic_presence(self): """ Determine presence based on bed heating level and end presence time reported by the api. Idea originated from Alex Lee Yuk Cheung SmartThings Code. """ # self.heating_stats() if not self.presence: if self.heating_level > 50: # Can likely make this better if not self.now_heating: self.presence = True elif self.heating_level - self.target_heating_level >= 8: self.presence = True elif self.heating_level > 25: # Catch rising edge if self.past_heating_level(0) - self.past_heating_level(1) >= 2 \ and self.past_heating_level(1) - self.past_heating_level(2) >= 2 \ and self.past_heating_level(2) - self.past_heating_level(3) >= 2: # Values are increasing so we are likely in bed if not self.now_heating: self.presence = True elif self.heating_level - self.target_heating_level >= 8: self.presence = True elif self.presence: if self.heating_level <= 15: # Failsafe, very slow self.presence = False elif self.heating_level < 50: if self.past_heating_level(0) - self.past_heating_level(1) < 0 \ and self.past_heating_level(1) - self.past_heating_level(2) < 0 \ and self.past_heating_level(2) - self.past_heating_level(3) < 0: # Values are decreasing so we are likely out of bed self.presence = False # Last seen can lag real-time by up to 35min so this is # mostly a backup to using the heat values. # seen_delta = datetime.fromtimestamp(time.time()) \ # - datetime.strptime(self.last_seen, '%Y-%m-%dT%H:%M:%S') # _LOGGER.debug('%s Last seen time delta: %s', self.side, # seen_delta.total_seconds()) # if self.presence and seen_delta.total_seconds() > 2100: # self.presence = False _LOGGER.debug('%s Presence Results: %s', self.side, self.presence)
[ "def", "dynamic_presence", "(", "self", ")", ":", "# self.heating_stats()", "if", "not", "self", ".", "presence", ":", "if", "self", ".", "heating_level", ">", "50", ":", "# Can likely make this better", "if", "not", "self", ".", "now_heating", ":", "self", "....
Determine presence based on bed heating level and end presence time reported by the api. Idea originated from Alex Lee Yuk Cheung SmartThings Code.
[ "Determine", "presence", "based", "on", "bed", "heating", "level", "and", "end", "presence", "time", "reported", "by", "the", "api", "." ]
python
train
solocompt/plugs-mail
plugs_mail/management/commands/load_email_templates.py
https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/management/commands/load_email_templates.py#L39-L52
def get_apps(self): """ Get the list of installed apps and return the apps that have an emails module """ templates = [] for app in settings.INSTALLED_APPS: try: app = import_module(app + '.emails') templates += self.get_plugs_mail_classes(app) except ImportError: pass return templates
[ "def", "get_apps", "(", "self", ")", ":", "templates", "=", "[", "]", "for", "app", "in", "settings", ".", "INSTALLED_APPS", ":", "try", ":", "app", "=", "import_module", "(", "app", "+", "'.emails'", ")", "templates", "+=", "self", ".", "get_plugs_mail_...
Get the list of installed apps and return the apps that have an emails module
[ "Get", "the", "list", "of", "installed", "apps", "and", "return", "the", "apps", "that", "have", "an", "emails", "module" ]
python
train
wtsi-hgi/python-hgijson
hgijson/serialization.py
https://github.com/wtsi-hgi/python-hgijson/blob/6e8ccb562eabcaa816a136268a16504c2e0d4664/hgijson/serialization.py#L188-L237
def deserialize(self, to_deserialize: PrimitiveJsonType) \ -> Optional[Union[SerializableType, List[SerializableType]]]: """ Deserializes the given representation of the serialized object. :param to_deserialize: the serialized object as a dictionary :return: the deserialized object or collection of deserialized objects """ if to_deserialize is None: # Implements #17 return None elif isinstance(to_deserialize, List): deserialized = [] for item in to_deserialize: item_deserialized = self.deserialize(item) deserialized.append(item_deserialized) return deserialized else: mappings_not_set_in_constructor = [] # type: List[PropertyMapping] init_kwargs = dict() # type: Dict[str, Any] for mapping in self._property_mappings: if mapping.object_constructor_parameter_name is not None: value = mapping.serialized_property_getter(to_deserialize) if not (mapping.optional and value is None): decoded_value = self._deserialize_property_value(value, mapping.deserializer_cls) if isinstance(decoded_value, list): collection = mapping.collection_factory(decoded_value) decoded_value = collection argument = mapping.object_constructor_argument_modifier(decoded_value) init_kwargs[mapping.object_constructor_parameter_name] = argument else: mappings_not_set_in_constructor.append(mapping) decoded = self._deserializable_cls(**init_kwargs) assert type(decoded) == self._deserializable_cls for mapping in mappings_not_set_in_constructor: assert mapping.object_constructor_parameter_name is None if mapping.serialized_property_getter is not None and mapping.object_property_setter is not None: value = mapping.serialized_property_getter(to_deserialize) if not (mapping.optional and value is None): decoded_value = self._deserialize_property_value(value, mapping.deserializer_cls) if isinstance(decoded_value, list): collection = mapping.collection_factory(decoded_value) decoded_value = collection mapping.object_property_setter(decoded, decoded_value) return decoded
[ "def", "deserialize", "(", "self", ",", "to_deserialize", ":", "PrimitiveJsonType", ")", "->", "Optional", "[", "Union", "[", "SerializableType", ",", "List", "[", "SerializableType", "]", "]", "]", ":", "if", "to_deserialize", "is", "None", ":", "# Implements...
Deserializes the given representation of the serialized object. :param to_deserialize: the serialized object as a dictionary :return: the deserialized object or collection of deserialized objects
[ "Deserializes", "the", "given", "representation", "of", "the", "serialized", "object", ".", ":", "param", "to_deserialize", ":", "the", "serialized", "object", "as", "a", "dictionary", ":", "return", ":", "the", "deserialized", "object", "or", "collection", "of"...
python
train
Opentrons/opentrons
api/src/opentrons/legacy_api/instruments/pipette.py
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/instruments/pipette.py#L1159-L1192
def home(self): """ Home the pipette's plunger axis during a protocol run Notes ----- `Pipette.home()` homes the `Robot` Returns ------- This instance of :class:`Pipette`. Examples -------- .. >>> from opentrons import instruments, robot # doctest: +SKIP >>> robot.reset() # doctest: +SKIP >>> p300 = instruments.P300_Single(mount='right') # doctest: +SKIP >>> p300.home() # doctest: +SKIP """ def _home(mount): self.current_volume = 0 self.instrument_actuator.set_active_current(self._plunger_current) self.robot.poses = self.instrument_actuator.home( self.robot.poses) self.robot.poses = self.instrument_mover.home(self.robot.poses) self.previous_placeable = None # no longer inside a placeable do_publish(self.broker, commands.home, _home, 'before', None, None, self.mount) _home(self.mount) do_publish(self.broker, commands.home, _home, 'after', self, None, self.mount) return self
[ "def", "home", "(", "self", ")", ":", "def", "_home", "(", "mount", ")", ":", "self", ".", "current_volume", "=", "0", "self", ".", "instrument_actuator", ".", "set_active_current", "(", "self", ".", "_plunger_current", ")", "self", ".", "robot", ".", "p...
Home the pipette's plunger axis during a protocol run Notes ----- `Pipette.home()` homes the `Robot` Returns ------- This instance of :class:`Pipette`. Examples -------- .. >>> from opentrons import instruments, robot # doctest: +SKIP >>> robot.reset() # doctest: +SKIP >>> p300 = instruments.P300_Single(mount='right') # doctest: +SKIP >>> p300.home() # doctest: +SKIP
[ "Home", "the", "pipette", "s", "plunger", "axis", "during", "a", "protocol", "run" ]
python
train
gabstopper/smc-python
smc/core/engines.py
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/engines.py#L824-L848
def add_snmp(data, interfaces): """ Format data for adding SNMP to an engine. :param list data: list of interfaces as provided by kw :param list interfaces: interfaces to enable SNMP by id """ snmp_interface = [] if interfaces: # Not providing interfaces will enable SNMP on all NDIs interfaces = map(str, interfaces) for interface in data: interface_id = str(interface.get('interface_id')) for if_def in interface.get('interfaces', []): _interface_id = None if 'vlan_id' in if_def: _interface_id = '{}.{}'.format( interface_id, if_def['vlan_id']) else: _interface_id = interface_id if _interface_id in interfaces and 'type' not in interface: for node in if_def.get('nodes', []): snmp_interface.append( {'address': node.get('address'), 'nicid': _interface_id}) return snmp_interface
[ "def", "add_snmp", "(", "data", ",", "interfaces", ")", ":", "snmp_interface", "=", "[", "]", "if", "interfaces", ":", "# Not providing interfaces will enable SNMP on all NDIs", "interfaces", "=", "map", "(", "str", ",", "interfaces", ")", "for", "interface", "in"...
Format data for adding SNMP to an engine. :param list data: list of interfaces as provided by kw :param list interfaces: interfaces to enable SNMP by id
[ "Format", "data", "for", "adding", "SNMP", "to", "an", "engine", ".", ":", "param", "list", "data", ":", "list", "of", "interfaces", "as", "provided", "by", "kw", ":", "param", "list", "interfaces", ":", "interfaces", "to", "enable", "SNMP", "by", "id" ]
python
train
kdeldycke/maildir-deduplicate
maildir_deduplicate/deduplicate.py
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/deduplicate.py#L361-L380
def delete_bigger(self): """ Delete all bigger duplicates. Only keeps the subset sharing the smallest size. """ logger.info( "Deleting all mails strictly bigger than {} bytes...".format( self.smallest_size)) # Select candidates for deletion. candidates = [ mail for mail in self.pool if mail.size > self.smallest_size] if len(candidates) == self.size: logger.warning( "Skip deletion: all {} mails share the same size." "".format(self.size)) logger.info( "{} candidates found for deletion.".format(len(candidates))) for mail in candidates: self.delete(mail)
[ "def", "delete_bigger", "(", "self", ")", ":", "logger", ".", "info", "(", "\"Deleting all mails strictly bigger than {} bytes...\"", ".", "format", "(", "self", ".", "smallest_size", ")", ")", "# Select candidates for deletion.", "candidates", "=", "[", "mail", "for"...
Delete all bigger duplicates. Only keeps the subset sharing the smallest size.
[ "Delete", "all", "bigger", "duplicates", "." ]
python
train
fprimex/zdesk
zdesk/zdesk_api.py
https://github.com/fprimex/zdesk/blob/851611c13b4d530e9df31390b3ec709baf0a0188/zdesk/zdesk_api.py#L4098-L4102
def user_tags_delete(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/tags#remove-tags" api_path = "/api/v2/users/{id}/tags.json" api_path = api_path.format(id=id) return self.call(api_path, method="DELETE", **kwargs)
[ "def", "user_tags_delete", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/users/{id}/tags.json\"", "api_path", "=", "api_path", ".", "format", "(", "id", "=", "id", ")", "return", "self", ".", "call", "(", "api_path"...
https://developer.zendesk.com/rest_api/docs/core/tags#remove-tags
[ "https", ":", "//", "developer", ".", "zendesk", ".", "com", "/", "rest_api", "/", "docs", "/", "core", "/", "tags#remove", "-", "tags" ]
python
train
SeattleTestbed/seash
pyreadline/modes/emacs.py
https://github.com/SeattleTestbed/seash/blob/40f9d2285662ff8b61e0468b4196acee089b273b/pyreadline/modes/emacs.py#L251-L290
def _process_keyevent(self, keyinfo): u"""return True when line is final """ #Process exit keys. Only exit on empty line log(u"_process_keyevent <%s>"%keyinfo) def nop(e): pass if self.next_meta: self.next_meta = False keyinfo.meta = True keytuple = keyinfo.tuple() if self._insert_verbatim: self.insert_text(keyinfo) self._insert_verbatim = False self.argument = 0 return False if keytuple in self.exit_dispatch: pars = (self.l_buffer, lineobj.EndOfLine(self.l_buffer)) log(u"exit_dispatch:<%s, %s>"%pars) if lineobj.EndOfLine(self.l_buffer) == 0: raise EOFError if keyinfo.keyname or keyinfo.control or keyinfo.meta: default = nop else: default = self.self_insert dispatch_func = self.key_dispatch.get(keytuple, default) log(u"readline from keyboard:<%s,%s>"%(keytuple, dispatch_func)) r = None if dispatch_func: r = dispatch_func(keyinfo) self._keylog(dispatch_func, self.l_buffer) self.l_buffer.push_undo() self.previous_func = dispatch_func return r
[ "def", "_process_keyevent", "(", "self", ",", "keyinfo", ")", ":", "#Process exit keys. Only exit on empty line\r", "log", "(", "u\"_process_keyevent <%s>\"", "%", "keyinfo", ")", "def", "nop", "(", "e", ")", ":", "pass", "if", "self", ".", "next_meta", ":", "se...
u"""return True when line is final
[ "u", "return", "True", "when", "line", "is", "final" ]
python
train
DarkEnergySurvey/ugali
ugali/utils/fileio.py
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/fileio.py#L20-L42
def read(filename,**kwargs): """ Read a generic input file into a recarray. Accepted file formats: [.fits,.fz,.npy,.csv,.txt,.dat] Parameters: filename : input file name kwargs : keyword arguments for the reader Returns: recarray : data array """ base,ext = os.path.splitext(filename) if ext in ('.fits','.fz'): # Abstract fits here... return fitsio.read(filename,**kwargs) elif ext in ('.npy'): return np.load(filename,**kwargs) elif ext in ('.csv'): return np.recfromcsv(filename,**kwargs) elif ext in ('.txt','.dat'): return np.genfromtxt(filename,**kwargs) msg = "Unrecognized file type: %s"%filename raise ValueError(msg)
[ "def", "read", "(", "filename", ",", "*", "*", "kwargs", ")", ":", "base", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "if", "ext", "in", "(", "'.fits'", ",", "'.fz'", ")", ":", "# Abstract fits here...", "return", "fit...
Read a generic input file into a recarray. Accepted file formats: [.fits,.fz,.npy,.csv,.txt,.dat] Parameters: filename : input file name kwargs : keyword arguments for the reader Returns: recarray : data array
[ "Read", "a", "generic", "input", "file", "into", "a", "recarray", ".", "Accepted", "file", "formats", ":", "[", ".", "fits", ".", "fz", ".", "npy", ".", "csv", ".", "txt", ".", "dat", "]", "Parameters", ":", "filename", ":", "input", "file", "name", ...
python
train
Terrance/SkPy
skpy/conn.py
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/conn.py#L59-L89
def handle(*codes, **kwargs): """ Method decorator: if a given status code is received, re-authenticate and try again. Args: codes (int list): status codes to respond to regToken (bool): whether to try retrieving a new token on error Returns: method: decorator function, ready to apply to other methods """ regToken = kwargs.get("regToken", False) subscribe = kwargs.get("subscribe") def decorator(fn): @functools.wraps(fn) def wrapper(self, *args, **kwargs): try: return fn(self, *args, **kwargs) except SkypeApiException as e: if isinstance(e.args[1], requests.Response) and e.args[1].status_code in codes: conn = self if isinstance(self, SkypeConnection) else self.conn if regToken: conn.getRegToken() if subscribe: conn.endpoints[subscribe].subscribe() return fn(self, *args, **kwargs) raise return wrapper return decorator
[ "def", "handle", "(", "*", "codes", ",", "*", "*", "kwargs", ")", ":", "regToken", "=", "kwargs", ".", "get", "(", "\"regToken\"", ",", "False", ")", "subscribe", "=", "kwargs", ".", "get", "(", "\"subscribe\"", ")", "def", "decorator", "(", "fn", ")...
Method decorator: if a given status code is received, re-authenticate and try again. Args: codes (int list): status codes to respond to regToken (bool): whether to try retrieving a new token on error Returns: method: decorator function, ready to apply to other methods
[ "Method", "decorator", ":", "if", "a", "given", "status", "code", "is", "received", "re", "-", "authenticate", "and", "try", "again", "." ]
python
test
lobocv/anonymoususage
anonymoususage/tools.py
https://github.com/lobocv/anonymoususage/blob/847bdad0746ad1cc6c57fb9def201beb59fb8300/anonymoususage/tools.py#L271-L281
def login_hq(host, user, passwd, path='', acct='', port=21, timeout=5): """ Create and return a logged in FTP object. :return: """ ftp = ftplib.FTP() ftp.connect(host=host, port=port, timeout=timeout) ftp.login(user=user, passwd=passwd, acct=acct) ftp.cwd(path) logger.debug('Login to %s successful.' % host) return ftp
[ "def", "login_hq", "(", "host", ",", "user", ",", "passwd", ",", "path", "=", "''", ",", "acct", "=", "''", ",", "port", "=", "21", ",", "timeout", "=", "5", ")", ":", "ftp", "=", "ftplib", ".", "FTP", "(", ")", "ftp", ".", "connect", "(", "h...
Create and return a logged in FTP object. :return:
[ "Create", "and", "return", "a", "logged", "in", "FTP", "object", ".", ":", "return", ":" ]
python
train
bwhite/hadoopy
hadoopy/thirdparty/pyinstaller/PyInstaller/bindepend.py
https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/bindepend.py#L341-L391
def selectImports(pth, xtrapath=None): """ Return the dependencies of a binary that should be included. Return a list of pairs (name, fullpath) """ rv = [] if xtrapath is None: xtrapath = [os.path.dirname(pth)] else: assert isinstance(xtrapath, list) xtrapath = [os.path.dirname(pth)] + xtrapath # make a copy dlls = getImports(pth) for lib in dlls: if seen.get(lib.upper(), 0): continue if not is_win and not is_cygwin: # all other platforms npth = lib dir, lib = os.path.split(lib) else: # plain win case npth = getfullnameof(lib, xtrapath) # now npth is a candidate lib if found # check again for excludes but with regex FIXME: split the list if npth: candidatelib = npth else: candidatelib = lib if not dylib.include_library(candidatelib): if (candidatelib.find('libpython') < 0 and candidatelib.find('Python.framework') < 0): # skip libs not containing (libpython or Python.framework) if not seen.get(npth.upper(), 0): logger.debug("Skipping %s dependency of %s", lib, os.path.basename(pth)) continue else: pass if npth: if not seen.get(npth.upper(), 0): logger.debug("Adding %s dependency of %s", lib, os.path.basename(pth)) rv.append((lib, npth)) else: logger.error("lib not found: %s dependency of %s", lib, pth) return rv
[ "def", "selectImports", "(", "pth", ",", "xtrapath", "=", "None", ")", ":", "rv", "=", "[", "]", "if", "xtrapath", "is", "None", ":", "xtrapath", "=", "[", "os", ".", "path", ".", "dirname", "(", "pth", ")", "]", "else", ":", "assert", "isinstance"...
Return the dependencies of a binary that should be included. Return a list of pairs (name, fullpath)
[ "Return", "the", "dependencies", "of", "a", "binary", "that", "should", "be", "included", "." ]
python
train
hvac/hvac
hvac/api/system_backend/audit.py
https://github.com/hvac/hvac/blob/cce5b86889193f622c2a72a4a1b7e1c9c8aff1ce/hvac/api/system_backend/audit.py#L77-L102
def calculate_hash(self, path, input_to_hash): """Hash the given input data with the specified audit device's hash function and salt. This endpoint can be used to discover whether a given plaintext string (the input parameter) appears in the audit log in obfuscated form. Supported methods: POST: /sys/audit-hash/{path}. Produces: 204 (empty body) :param path: The path of the audit device to generate hashes for. This is part of the request URL. :type path: str | unicode :param input_to_hash: The input string to hash. :type input_to_hash: str | unicode :return: The JSON response of the request. :rtype: requests.Response """ params = { 'input': input_to_hash, } api_path = '/v1/sys/audit-hash/{path}'.format(path=path) response = self._adapter.post( url=api_path, json=params ) return response.json()
[ "def", "calculate_hash", "(", "self", ",", "path", ",", "input_to_hash", ")", ":", "params", "=", "{", "'input'", ":", "input_to_hash", ",", "}", "api_path", "=", "'/v1/sys/audit-hash/{path}'", ".", "format", "(", "path", "=", "path", ")", "response", "=", ...
Hash the given input data with the specified audit device's hash function and salt. This endpoint can be used to discover whether a given plaintext string (the input parameter) appears in the audit log in obfuscated form. Supported methods: POST: /sys/audit-hash/{path}. Produces: 204 (empty body) :param path: The path of the audit device to generate hashes for. This is part of the request URL. :type path: str | unicode :param input_to_hash: The input string to hash. :type input_to_hash: str | unicode :return: The JSON response of the request. :rtype: requests.Response
[ "Hash", "the", "given", "input", "data", "with", "the", "specified", "audit", "device", "s", "hash", "function", "and", "salt", "." ]
python
train
peterwittek/ncpol2sdpa
ncpol2sdpa/nc_utils.py
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L146-L165
def separate_scalar_factor(element): """Construct a monomial with the coefficient separated from an element in a polynomial. """ coeff = 1.0 monomial = S.One if isinstance(element, (int, float, complex)): coeff *= element return monomial, coeff for var in element.as_coeff_mul()[1]: if not (var.is_Number or var.is_imaginary): monomial = monomial * var else: if var.is_Number: coeff = float(var) # If not, then it is imaginary else: coeff = 1j * coeff coeff = float(element.as_coeff_mul()[0]) * coeff return monomial, coeff
[ "def", "separate_scalar_factor", "(", "element", ")", ":", "coeff", "=", "1.0", "monomial", "=", "S", ".", "One", "if", "isinstance", "(", "element", ",", "(", "int", ",", "float", ",", "complex", ")", ")", ":", "coeff", "*=", "element", "return", "mon...
Construct a monomial with the coefficient separated from an element in a polynomial.
[ "Construct", "a", "monomial", "with", "the", "coefficient", "separated", "from", "an", "element", "in", "a", "polynomial", "." ]
python
train
hyperledger/indy-plenum
plenum/server/node.py
https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/node.py#L1890-L1916
def validateNodeMsg(self, wrappedMsg): """ Validate another node's message sent to this node. :param wrappedMsg: Tuple of message and the name of the node that sent the message :return: Tuple of message from node and name of the node """ msg, frm = wrappedMsg if self.isNodeBlacklisted(frm): self.discard(str(msg)[:256], "received from blacklisted node {}".format(frm), logger.display) return None with self.metrics.measure_time(MetricsName.INT_VALIDATE_NODE_MSG_TIME): try: message = node_message_factory.get_instance(**msg) except (MissingNodeOp, InvalidNodeOp) as ex: raise ex except Exception as ex: raise InvalidNodeMsg(str(ex)) try: self.verifySignature(message) except BaseExc as ex: raise SuspiciousNode(frm, ex, message) from ex logger.debug("{} received node message from {}: {}".format(self, frm, message), extra={"cli": False}) return message, frm
[ "def", "validateNodeMsg", "(", "self", ",", "wrappedMsg", ")", ":", "msg", ",", "frm", "=", "wrappedMsg", "if", "self", ".", "isNodeBlacklisted", "(", "frm", ")", ":", "self", ".", "discard", "(", "str", "(", "msg", ")", "[", ":", "256", "]", ",", ...
Validate another node's message sent to this node. :param wrappedMsg: Tuple of message and the name of the node that sent the message :return: Tuple of message from node and name of the node
[ "Validate", "another", "node", "s", "message", "sent", "to", "this", "node", "." ]
python
train
PMEAL/OpenPNM
openpnm/utils/Project.py
https://github.com/PMEAL/OpenPNM/blob/0547b5724ffedc0a593aae48639d36fe10e0baed/openpnm/utils/Project.py#L235-L264
def find_phase(self, obj): r""" Find the Phase associated with a given object. Parameters ---------- obj : OpenPNM Object Can either be a Physics or Algorithm object Returns ------- An OpenPNM Phase object. Raises ------ If no Phase object can be found, then an Exception is raised. """ # If received phase, just return self if obj._isa('phase'): return obj # If phase happens to be in settings (i.e. algorithm), look it up if 'phase' in obj.settings.keys(): phase = self.phases()[obj.settings['phase']] return phase # Otherwise find it using bottom-up approach (i.e. look in phase keys) for phase in self.phases().values(): if ('pore.'+obj.name in phase) or ('throat.'+obj.name in phase): return phase # If all else fails, throw an exception raise Exception('Cannot find a phase associated with '+obj.name)
[ "def", "find_phase", "(", "self", ",", "obj", ")", ":", "# If received phase, just return self", "if", "obj", ".", "_isa", "(", "'phase'", ")", ":", "return", "obj", "# If phase happens to be in settings (i.e. algorithm), look it up", "if", "'phase'", "in", "obj", "."...
r""" Find the Phase associated with a given object. Parameters ---------- obj : OpenPNM Object Can either be a Physics or Algorithm object Returns ------- An OpenPNM Phase object. Raises ------ If no Phase object can be found, then an Exception is raised.
[ "r", "Find", "the", "Phase", "associated", "with", "a", "given", "object", "." ]
python
train
Microsoft/nni
examples/tuners/weight_sharing/ga_customer_tuner/customer_tuner.py
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/tuners/weight_sharing/ga_customer_tuner/customer_tuner.py#L84-L91
def generate_new_id(self): """ generate new id and event hook for new Individual """ self.events.append(Event()) indiv_id = self.indiv_counter self.indiv_counter += 1 return indiv_id
[ "def", "generate_new_id", "(", "self", ")", ":", "self", ".", "events", ".", "append", "(", "Event", "(", ")", ")", "indiv_id", "=", "self", ".", "indiv_counter", "self", ".", "indiv_counter", "+=", "1", "return", "indiv_id" ]
generate new id and event hook for new Individual
[ "generate", "new", "id", "and", "event", "hook", "for", "new", "Individual" ]
python
train
iotile/coretools
iotileemulate/iotile/emulate/reference/controller_features/clock_manager.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/clock_manager.py#L281-L288
def set_time_offset(self, offset, is_utc): """Temporarily set the current time offset.""" is_utc = bool(is_utc) self.clock_manager.time_offset = offset self.clock_manager.is_utc = is_utc return [Error.NO_ERROR]
[ "def", "set_time_offset", "(", "self", ",", "offset", ",", "is_utc", ")", ":", "is_utc", "=", "bool", "(", "is_utc", ")", "self", ".", "clock_manager", ".", "time_offset", "=", "offset", "self", ".", "clock_manager", ".", "is_utc", "=", "is_utc", "return",...
Temporarily set the current time offset.
[ "Temporarily", "set", "the", "current", "time", "offset", "." ]
python
train
DLR-RM/RAFCON
source/rafcon/core/states/hierarchy_state.py
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/hierarchy_state.py#L169-L184
def _handle_backward_execution_before_child_execution(self): """ Sets up all data after receiving a backward execution step from the execution engine :return: a flag to indicate if normal child state execution should abort """ self.backward_execution = True last_history_item = self.execution_history.pop_last_item() if last_history_item.state_reference is self: # if the the next child_state in the history is self exit this hierarchy-state if self.child_state: # do not set the last state to inactive before executing the new one self.child_state.state_execution_status = StateExecutionStatus.INACTIVE return True assert isinstance(last_history_item, ReturnItem) self.scoped_data = last_history_item.scoped_data self.child_state = last_history_item.state_reference return False
[ "def", "_handle_backward_execution_before_child_execution", "(", "self", ")", ":", "self", ".", "backward_execution", "=", "True", "last_history_item", "=", "self", ".", "execution_history", ".", "pop_last_item", "(", ")", "if", "last_history_item", ".", "state_referenc...
Sets up all data after receiving a backward execution step from the execution engine :return: a flag to indicate if normal child state execution should abort
[ "Sets", "up", "all", "data", "after", "receiving", "a", "backward", "execution", "step", "from", "the", "execution", "engine", ":", "return", ":", "a", "flag", "to", "indicate", "if", "normal", "child", "state", "execution", "should", "abort" ]
python
train
yola/yoconfigurator
yoconfigurator/credentials.py
https://github.com/yola/yoconfigurator/blob/dfb60fa1e30ae7cfec2526bb101fc205f5952639/yoconfigurator/credentials.py#L4-L9
def seeded_auth_token(client, service, seed): """Return an auth token based on the client+service+seed tuple.""" hash_func = hashlib.md5() token = ','.join((client, service, seed)).encode('utf-8') hash_func.update(token) return hash_func.hexdigest()
[ "def", "seeded_auth_token", "(", "client", ",", "service", ",", "seed", ")", ":", "hash_func", "=", "hashlib", ".", "md5", "(", ")", "token", "=", "','", ".", "join", "(", "(", "client", ",", "service", ",", "seed", ")", ")", ".", "encode", "(", "'...
Return an auth token based on the client+service+seed tuple.
[ "Return", "an", "auth", "token", "based", "on", "the", "client", "+", "service", "+", "seed", "tuple", "." ]
python
valid
hyperledger/sawtooth-core
rest_api/sawtooth_rest_api/route_handlers.py
https://github.com/hyperledger/sawtooth-core/blob/8cf473bc2207e51f02bd182d825158a57d72b098/rest_api/sawtooth_rest_api/route_handlers.py#L962-L973
def _set_wait(self, request, validator_query): """Parses the `wait` query parameter, and sets the corresponding `wait` and `timeout` properties in the validator query. """ wait = request.url.query.get('wait', 'false') if wait.lower() != 'false': validator_query.wait = True try: validator_query.timeout = int(wait) except ValueError: # By default, waits for 95% of REST API's configured timeout validator_query.timeout = int(self._timeout * 0.95)
[ "def", "_set_wait", "(", "self", ",", "request", ",", "validator_query", ")", ":", "wait", "=", "request", ".", "url", ".", "query", ".", "get", "(", "'wait'", ",", "'false'", ")", "if", "wait", ".", "lower", "(", ")", "!=", "'false'", ":", "validato...
Parses the `wait` query parameter, and sets the corresponding `wait` and `timeout` properties in the validator query.
[ "Parses", "the", "wait", "query", "parameter", "and", "sets", "the", "corresponding", "wait", "and", "timeout", "properties", "in", "the", "validator", "query", "." ]
python
train
C-Pro/pgdocgen
pgdocgen/files.py
https://github.com/C-Pro/pgdocgen/blob/b5d95c1bc1b38e3c7977aeddc20793a7b0f5d0fe/pgdocgen/files.py#L11-L21
def read_dir(input_dir,input_ext,func): '''reads all files with extension input_ext in a directory input_dir and apply function func to their contents''' import os for dirpath, dnames, fnames in os.walk(input_dir): for fname in fnames: if not dirpath.endswith(os.sep): dirpath = dirpath + os.sep if fname.endswith(input_ext): func(read_file(dirpath + fname))
[ "def", "read_dir", "(", "input_dir", ",", "input_ext", ",", "func", ")", ":", "import", "os", "for", "dirpath", ",", "dnames", ",", "fnames", "in", "os", ".", "walk", "(", "input_dir", ")", ":", "for", "fname", "in", "fnames", ":", "if", "not", "dirp...
reads all files with extension input_ext in a directory input_dir and apply function func to their contents
[ "reads", "all", "files", "with", "extension", "input_ext", "in", "a", "directory", "input_dir", "and", "apply", "function", "func", "to", "their", "contents" ]
python
train
praekeltfoundation/seaworthy
seaworthy/definitions.py
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/definitions.py#L246-L267
def setup(self, helper=None, **run_kwargs): """ Creates the container, starts it, and waits for it to completely start. :param helper: The resource helper to use, if one was not provided when this container definition was created. :param **run_kwargs: Keyword arguments passed to :meth:`.run`. :returns: This container definition instance. Useful for creating and setting up a container in a single step:: con = ContainerDefinition('conny', 'nginx').setup(helper=dh) """ if self.created: return self.set_helper(helper) self.run(**run_kwargs) self.wait_for_start() return self
[ "def", "setup", "(", "self", ",", "helper", "=", "None", ",", "*", "*", "run_kwargs", ")", ":", "if", "self", ".", "created", ":", "return", "self", ".", "set_helper", "(", "helper", ")", "self", ".", "run", "(", "*", "*", "run_kwargs", ")", "self"...
Creates the container, starts it, and waits for it to completely start. :param helper: The resource helper to use, if one was not provided when this container definition was created. :param **run_kwargs: Keyword arguments passed to :meth:`.run`. :returns: This container definition instance. Useful for creating and setting up a container in a single step:: con = ContainerDefinition('conny', 'nginx').setup(helper=dh)
[ "Creates", "the", "container", "starts", "it", "and", "waits", "for", "it", "to", "completely", "start", "." ]
python
train
Azure/azure-storage-python
azure-storage-file/azure/storage/file/_deserialization.py
https://github.com/Azure/azure-storage-python/blob/52327354b192cbcf6b7905118ec6b5d57fa46275/azure-storage-file/azure/storage/file/_deserialization.py#L200-L227
def _convert_xml_to_ranges(response): ''' <?xml version="1.0" encoding="utf-8"?> <Ranges> <Range> <Start>Start Byte</Start> <End>End Byte</End> </Range> <Range> <Start>Start Byte</Start> <End>End Byte</End> </Range> </Ranges> ''' if response is None or response.body is None: return None ranges = list() ranges_element = ETree.fromstring(response.body) for range_element in ranges_element.findall('Range'): # Parse range range = FileRange(int(range_element.findtext('Start')), int(range_element.findtext('End'))) # Add range to list ranges.append(range) return ranges
[ "def", "_convert_xml_to_ranges", "(", "response", ")", ":", "if", "response", "is", "None", "or", "response", ".", "body", "is", "None", ":", "return", "None", "ranges", "=", "list", "(", ")", "ranges_element", "=", "ETree", ".", "fromstring", "(", "respon...
<?xml version="1.0" encoding="utf-8"?> <Ranges> <Range> <Start>Start Byte</Start> <End>End Byte</End> </Range> <Range> <Start>Start Byte</Start> <End>End Byte</End> </Range> </Ranges>
[ "<?xml", "version", "=", "1", ".", "0", "encoding", "=", "utf", "-", "8", "?", ">", "<Ranges", ">", "<Range", ">", "<Start", ">", "Start", "Byte<", "/", "Start", ">", "<End", ">", "End", "Byte<", "/", "End", ">", "<", "/", "Range", ">", "<Range",...
python
train
bitprophet/ssh
ssh/util.py
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/util.py#L151-L183
def generate_key_bytes(hashclass, salt, key, nbytes): """ Given a password, passphrase, or other human-source key, scramble it through a secure hash into some keyworthy bytes. This specific algorithm is used for encrypting/decrypting private key files. @param hashclass: class from L{Crypto.Hash} that can be used as a secure hashing function (like C{MD5} or C{SHA}). @type hashclass: L{Crypto.Hash} @param salt: data to salt the hash with. @type salt: string @param key: human-entered password or passphrase. @type key: string @param nbytes: number of bytes to generate. @type nbytes: int @return: key data @rtype: string """ keydata = '' digest = '' if len(salt) > 8: salt = salt[:8] while nbytes > 0: hash_obj = hashclass.new() if len(digest) > 0: hash_obj.update(digest) hash_obj.update(key) hash_obj.update(salt) digest = hash_obj.digest() size = min(nbytes, len(digest)) keydata += digest[:size] nbytes -= size return keydata
[ "def", "generate_key_bytes", "(", "hashclass", ",", "salt", ",", "key", ",", "nbytes", ")", ":", "keydata", "=", "''", "digest", "=", "''", "if", "len", "(", "salt", ")", ">", "8", ":", "salt", "=", "salt", "[", ":", "8", "]", "while", "nbytes", ...
Given a password, passphrase, or other human-source key, scramble it through a secure hash into some keyworthy bytes. This specific algorithm is used for encrypting/decrypting private key files. @param hashclass: class from L{Crypto.Hash} that can be used as a secure hashing function (like C{MD5} or C{SHA}). @type hashclass: L{Crypto.Hash} @param salt: data to salt the hash with. @type salt: string @param key: human-entered password or passphrase. @type key: string @param nbytes: number of bytes to generate. @type nbytes: int @return: key data @rtype: string
[ "Given", "a", "password", "passphrase", "or", "other", "human", "-", "source", "key", "scramble", "it", "through", "a", "secure", "hash", "into", "some", "keyworthy", "bytes", ".", "This", "specific", "algorithm", "is", "used", "for", "encrypting", "/", "dec...
python
train
StackStorm/pybind
pybind/nos/v7_2_0/rbridge_id/interface/ve/ip/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v7_2_0/rbridge_id/interface/ve/ip/__init__.py#L238-L259
def _set_icmp(self, v, load=False): """ Setter method for icmp, mapped from YANG variable /rbridge_id/interface/ve/ip/icmp (container) If this variable is read-only (config: false) in the source YANG file, then _set_icmp is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_icmp() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=icmp.icmp, is_container='container', presence=False, yang_name="icmp", rest_name="icmp", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Internet Control Message Protocol(ICMP)', u'sort-priority': u'118', u'display-when': u'/vcsmode/vcs-mode = "true"', u'cli-incomplete-no': None, u'callpoint': u'IcmpVeIntfConfigCallpoint'}}, namespace='urn:brocade.com:mgmt:brocade-icmp', defining_module='brocade-icmp', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """icmp must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=icmp.icmp, is_container='container', presence=False, yang_name="icmp", rest_name="icmp", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Internet Control Message Protocol(ICMP)', u'sort-priority': u'118', u'display-when': u'/vcsmode/vcs-mode = "true"', u'cli-incomplete-no': None, u'callpoint': u'IcmpVeIntfConfigCallpoint'}}, namespace='urn:brocade.com:mgmt:brocade-icmp', defining_module='brocade-icmp', yang_type='container', is_config=True)""", }) self.__icmp = t if hasattr(self, '_set'): self._set()
[ "def", "_set_icmp", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base", ...
Setter method for icmp, mapped from YANG variable /rbridge_id/interface/ve/ip/icmp (container) If this variable is read-only (config: false) in the source YANG file, then _set_icmp is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_icmp() directly.
[ "Setter", "method", "for", "icmp", "mapped", "from", "YANG", "variable", "/", "rbridge_id", "/", "interface", "/", "ve", "/", "ip", "/", "icmp", "(", "container", ")", "If", "this", "variable", "is", "read", "-", "only", "(", "config", ":", "false", ")...
python
train
odrling/peony-twitter
peony/commands/utils.py
https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/commands/utils.py#L4-L28
def doc(func): """ Find the message shown when someone calls the help command Parameters ---------- func : function the function Returns ------- str The help message for this command """ stripped_chars = " \t" if hasattr(func, '__doc__'): docstring = func.__doc__.lstrip(" \n\t") if "\n" in docstring: i = docstring.index("\n") return docstring[:i].rstrip(stripped_chars) elif docstring: return docstring.rstrip(stripped_chars) return ""
[ "def", "doc", "(", "func", ")", ":", "stripped_chars", "=", "\" \\t\"", "if", "hasattr", "(", "func", ",", "'__doc__'", ")", ":", "docstring", "=", "func", ".", "__doc__", ".", "lstrip", "(", "\" \\n\\t\"", ")", "if", "\"\\n\"", "in", "docstring", ":", ...
Find the message shown when someone calls the help command Parameters ---------- func : function the function Returns ------- str The help message for this command
[ "Find", "the", "message", "shown", "when", "someone", "calls", "the", "help", "command" ]
python
valid
bioasp/iggy
src/query.py
https://github.com/bioasp/iggy/blob/451dee74f277d822d64cf8f3859c94b2f2b6d4db/src/query.py#L83-L102
def get_scenfit(instance, OS, FP, FC, EP): '''returns the scenfit of data and model described by the ``TermSet`` object [instance]. ''' sem = [sign_cons_prg, bwd_prop_prg] if OS : sem.append(one_state_prg) if FP : sem.append(fwd_prop_prg) if FC : sem.append(founded_prg) if EP : sem.append(elem_path_prg) inst = instance.to_file() prg = sem + scenfit + [inst] coptions = '--opt-strategy=5' solver = GringoClasp(clasp_options=coptions) solution = solver.run(prg,collapseTerms=True,collapseAtoms=False) opt = solution[0].score[0] os.unlink(inst) return opt
[ "def", "get_scenfit", "(", "instance", ",", "OS", ",", "FP", ",", "FC", ",", "EP", ")", ":", "sem", "=", "[", "sign_cons_prg", ",", "bwd_prop_prg", "]", "if", "OS", ":", "sem", ".", "append", "(", "one_state_prg", ")", "if", "FP", ":", "sem", ".", ...
returns the scenfit of data and model described by the ``TermSet`` object [instance].
[ "returns", "the", "scenfit", "of", "data", "and", "model", "described", "by", "the", "TermSet", "object", "[", "instance", "]", "." ]
python
train
mfcovington/pubmed-lookup
pubmed_lookup/command_line.py
https://github.com/mfcovington/pubmed-lookup/blob/b0aa2945b354f0945db73da22dd15ea628212da8/pubmed_lookup/command_line.py#L7-L26
def pubmed_citation(args=sys.argv[1:], out=sys.stdout): """Get a citation via the command line using a PubMed ID or PubMed URL""" parser = argparse.ArgumentParser( description='Get a citation using a PubMed ID or PubMed URL') parser.add_argument('query', help='PubMed ID or PubMed URL') parser.add_argument( '-m', '--mini', action='store_true', help='get mini citation') parser.add_argument( '-e', '--email', action='store', help='set user email', default='') args = parser.parse_args(args=args) lookup = PubMedLookup(args.query, args.email) publication = Publication(lookup, resolve_doi=False) if args.mini: out.write(publication.cite_mini() + '\n') else: out.write(publication.cite() + '\n')
[ "def", "pubmed_citation", "(", "args", "=", "sys", ".", "argv", "[", "1", ":", "]", ",", "out", "=", "sys", ".", "stdout", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Get a citation using a PubMed ID or PubMed URL'", ...
Get a citation via the command line using a PubMed ID or PubMed URL
[ "Get", "a", "citation", "via", "the", "command", "line", "using", "a", "PubMed", "ID", "or", "PubMed", "URL" ]
python
train
ArduPilot/MAVProxy
MAVProxy/modules/lib/mp_checklist.py
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/lib/mp_checklist.py#L55-L58
def set_check(self, name, state): '''set a status value''' if self.child.is_alive(): self.parent_pipe.send(CheckItem(name, state))
[ "def", "set_check", "(", "self", ",", "name", ",", "state", ")", ":", "if", "self", ".", "child", ".", "is_alive", "(", ")", ":", "self", ".", "parent_pipe", ".", "send", "(", "CheckItem", "(", "name", ",", "state", ")", ")" ]
set a status value
[ "set", "a", "status", "value" ]
python
train
mapeveri/django-endless-pagination-vue
endless_pagination/utils.py
https://github.com/mapeveri/django-endless-pagination-vue/blob/3faa79a51b11d7ae0bd431abf8c38ecaf9180704/endless_pagination/utils.py#L38-L53
def get_page_number_from_request( request, querystring_key=PAGE_LABEL, default=1): """Retrieve the current page number from *GET* or *POST* data. If the page does not exists in *request*, or is not a number, then *default* number is returned. """ try: if request.method == 'POST': page_number = request.POST[querystring_key] else: page_number = request.GET[querystring_key] return int(page_number) except (KeyError, TypeError, ValueError): return default
[ "def", "get_page_number_from_request", "(", "request", ",", "querystring_key", "=", "PAGE_LABEL", ",", "default", "=", "1", ")", ":", "try", ":", "if", "request", ".", "method", "==", "'POST'", ":", "page_number", "=", "request", ".", "POST", "[", "querystri...
Retrieve the current page number from *GET* or *POST* data. If the page does not exists in *request*, or is not a number, then *default* number is returned.
[ "Retrieve", "the", "current", "page", "number", "from", "*", "GET", "*", "or", "*", "POST", "*", "data", "." ]
python
train
DataDog/integrations-core
rabbitmq/datadog_checks/rabbitmq/rabbitmq.py
https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/rabbitmq/datadog_checks/rabbitmq/rabbitmq.py#L375-L549
def get_stats( self, instance, base_url, object_type, max_detailed, filters, limit_vhosts, custom_tags, auth=None, ssl_verify=True, ): """ instance: the check instance base_url: the url of the rabbitmq management api (e.g. http://localhost:15672/api) object_type: either QUEUE_TYPE or NODE_TYPE or EXCHANGE_TYPE max_detailed: the limit of objects to collect for this type filters: explicit or regexes filters of specified queues or nodes (specified in the yaml file) """ instance_proxy = self.get_instance_proxy(instance, base_url) # Make a copy of this list as we will remove items from it at each # iteration explicit_filters = list(filters['explicit']) regex_filters = filters['regexes'] data = [] # only do this if vhosts were specified, # otherwise it'll just be making more queries for the same data if self._limit_vhosts(instance) and object_type == QUEUE_TYPE: for vhost in limit_vhosts: url = '{}/{}'.format(object_type, quote_plus(vhost)) try: data += self._get_data( urljoin(base_url, url), auth=auth, ssl_verify=ssl_verify, proxies=instance_proxy ) except Exception as e: self.log.debug("Couldn't grab queue data from vhost, {}: {}".format(vhost, e)) else: data = self._get_data( urljoin(base_url, object_type), auth=auth, ssl_verify=ssl_verify, proxies=instance_proxy ) """ data is a list of nodes or queues: data = [ { 'status': 'running', 'node': 'rabbit@host', 'name': 'queue1', 'consumers': 0, 'vhost': '/', 'backing_queue_status': { 'q1': 0, 'q3': 0, 'q2': 0, 'q4': 0, 'avg_ack_egress_rate': 0.0, 'ram_msg_count': 0, 'ram_ack_count': 0, 'len': 0, 'persistent_count': 0, 'target_ram_count': 'infinity', 'next_seq_id': 0, 'delta': ['delta', 'undefined', 0, 'undefined'], 'pending_acks': 0, 'avg_ack_ingress_rate': 0.0, 'avg_egress_rate': 0.0, 'avg_ingress_rate': 0.0 }, 'durable': True, 'idle_since': '2013-10-03 13:38:18', 'exclusive_consumer_tag': '', 'arguments': {}, 'memory': 10956, 'policy': '', 'auto_delete': False }, { 'status': 'running', 'node': 'rabbit@host, 'name': 'queue10', 'consumers': 0, 'vhost': '/', 'backing_queue_status': { 'q1': 0, 'q3': 0, 'q2': 0, 'q4': 0, 'avg_ack_egress_rate': 0.0, 'ram_msg_count': 0, 'ram_ack_count': 0, 'len': 0, 'persistent_count': 0, 'target_ram_count': 'infinity', 'next_seq_id': 0, 'delta': ['delta', 'undefined', 0, 'undefined'], 'pending_acks': 0, 'avg_ack_ingress_rate': 0.0, 'avg_egress_rate': 0.0, 'avg_ingress_rate': 0.0 }, 'durable': True, 'idle_since': '2013-10-03 13:38:18', 'exclusive_consumer_tag': '', 'arguments': {}, 'memory': 10956, 'policy': '', 'auto_delete': False }, { 'status': 'running', 'node': 'rabbit@host', 'name': 'queue11', 'consumers': 0, 'vhost': '/', 'backing_queue_status': { 'q1': 0, 'q3': 0, 'q2': 0, 'q4': 0, 'avg_ack_egress_rate': 0.0, 'ram_msg_count': 0, 'ram_ack_count': 0, 'len': 0, 'persistent_count': 0, 'target_ram_count': 'infinity', 'next_seq_id': 0, 'delta': ['delta', 'undefined', 0, 'undefined'], 'pending_acks': 0, 'avg_ack_ingress_rate': 0.0, 'avg_egress_rate': 0.0, 'avg_ingress_rate': 0.0 }, 'durable': True, 'idle_since': '2013-10-03 13:38:18', 'exclusive_consumer_tag': '', 'arguments': {}, 'memory': 10956, 'policy': '', 'auto_delete': False }, ... ] """ if len(explicit_filters) > max_detailed: raise Exception("The maximum number of {} you can specify is {}.".format(object_type, max_detailed)) # a list of queues/nodes is specified. We process only those data = self._filter_list( data, explicit_filters, regex_filters, object_type, instance.get("tag_families", False) ) # if no filters are specified, check everything according to the limits if len(data) > ALERT_THRESHOLD * max_detailed: # Post a message on the dogweb stream to warn self.alert(base_url, max_detailed, len(data), object_type, custom_tags) if len(data) > max_detailed: # Display a warning in the info page msg = ( "Too many items to fetch. " "You must choose the {} you are interested in by editing the rabbitmq.yaml configuration file" "or get in touch with Datadog support" ).format(object_type) self.warning(msg) for data_line in data[:max_detailed]: # We truncate the list if it's above the limit self._get_metrics(data_line, object_type, custom_tags) # get a list of the number of bindings on a given queue # /api/queues/vhost/name/bindings if object_type is QUEUE_TYPE: self._get_queue_bindings_metrics( base_url, custom_tags, data, instance_proxy, instance, object_type, auth, ssl_verify )
[ "def", "get_stats", "(", "self", ",", "instance", ",", "base_url", ",", "object_type", ",", "max_detailed", ",", "filters", ",", "limit_vhosts", ",", "custom_tags", ",", "auth", "=", "None", ",", "ssl_verify", "=", "True", ",", ")", ":", "instance_proxy", ...
instance: the check instance base_url: the url of the rabbitmq management api (e.g. http://localhost:15672/api) object_type: either QUEUE_TYPE or NODE_TYPE or EXCHANGE_TYPE max_detailed: the limit of objects to collect for this type filters: explicit or regexes filters of specified queues or nodes (specified in the yaml file)
[ "instance", ":", "the", "check", "instance", "base_url", ":", "the", "url", "of", "the", "rabbitmq", "management", "api", "(", "e", ".", "g", ".", "http", ":", "//", "localhost", ":", "15672", "/", "api", ")", "object_type", ":", "either", "QUEUE_TYPE", ...
python
train
googledatalab/pydatalab
solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py#L84-L108
def _scale(x, min_x_value, max_x_value, output_min, output_max): """Scale a column to [output_min, output_max]. Assumes the columns's range is [min_x_value, max_x_value]. If this is not true at training or prediction time, the output value of this scale could be outside the range [output_min, output_max]. Raises: ValueError: if min_x_value = max_x_value, as the column is constant. """ if round(min_x_value - max_x_value, 7) == 0: # There is something wrong with the data. # Why round to 7 places? It's the same as unittest's assertAlmostEqual. raise ValueError('In make_scale_tito, min_x_value == max_x_value') def _scale(x): min_x_valuef = tf.to_float(min_x_value) max_x_valuef = tf.to_float(max_x_value) output_minf = tf.to_float(output_min) output_maxf = tf.to_float(output_max) return ((((tf.to_float(x) - min_x_valuef) * (output_maxf - output_minf)) / (max_x_valuef - min_x_valuef)) + output_minf) return _scale(x)
[ "def", "_scale", "(", "x", ",", "min_x_value", ",", "max_x_value", ",", "output_min", ",", "output_max", ")", ":", "if", "round", "(", "min_x_value", "-", "max_x_value", ",", "7", ")", "==", "0", ":", "# There is something wrong with the data.", "# Why round to ...
Scale a column to [output_min, output_max]. Assumes the columns's range is [min_x_value, max_x_value]. If this is not true at training or prediction time, the output value of this scale could be outside the range [output_min, output_max]. Raises: ValueError: if min_x_value = max_x_value, as the column is constant.
[ "Scale", "a", "column", "to", "[", "output_min", "output_max", "]", "." ]
python
train
opennode/waldur-core
waldur_core/logging/views.py
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/logging/views.py#L270-L281
def acknowledge(self, request, *args, **kwargs): """ To acknowledge alert - run **POST** against */api/alerts/<alert_uuid>/acknowledge/*. No payload is required. All users that can see alerts can also acknowledge it. If alert is already acknowledged endpoint will return error with code 409(conflict). """ alert = self.get_object() if not alert.acknowledged: alert.acknowledge() return response.Response(status=status.HTTP_200_OK) else: return response.Response({'detail': _('Alert is already acknowledged.')}, status=status.HTTP_409_CONFLICT)
[ "def", "acknowledge", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "alert", "=", "self", ".", "get_object", "(", ")", "if", "not", "alert", ".", "acknowledged", ":", "alert", ".", "acknowledge", "(", ")", "return"...
To acknowledge alert - run **POST** against */api/alerts/<alert_uuid>/acknowledge/*. No payload is required. All users that can see alerts can also acknowledge it. If alert is already acknowledged endpoint will return error with code 409(conflict).
[ "To", "acknowledge", "alert", "-", "run", "**", "POST", "**", "against", "*", "/", "api", "/", "alerts", "/", "<alert_uuid", ">", "/", "acknowledge", "/", "*", ".", "No", "payload", "is", "required", ".", "All", "users", "that", "can", "see", "alerts",...
python
train
aliyun/aliyun-odps-python-sdk
odps/ml/metrics/regression.py
https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/ml/metrics/regression.py#L74-L91
def mean_absolute_percentage_error(df, col_true, col_pred=None): """ Compute mean absolute percentage error of a predicted DataFrame. Note that this method will trigger the defined flow to execute. :param df: predicted data frame :type df: DataFrame :param col_true: column name of true value :type col_true: str :param col_true: column name of predicted value, 'prediction_score' by default. :type col_pred: str :return: Mean absolute percentage error :rtype: float """ if not col_pred: col_pred = get_field_name_by_role(df, FieldRole.PREDICTED_VALUE) return _run_evaluation_node(df, col_true, col_pred)['mape']
[ "def", "mean_absolute_percentage_error", "(", "df", ",", "col_true", ",", "col_pred", "=", "None", ")", ":", "if", "not", "col_pred", ":", "col_pred", "=", "get_field_name_by_role", "(", "df", ",", "FieldRole", ".", "PREDICTED_VALUE", ")", "return", "_run_evalua...
Compute mean absolute percentage error of a predicted DataFrame. Note that this method will trigger the defined flow to execute. :param df: predicted data frame :type df: DataFrame :param col_true: column name of true value :type col_true: str :param col_true: column name of predicted value, 'prediction_score' by default. :type col_pred: str :return: Mean absolute percentage error :rtype: float
[ "Compute", "mean", "absolute", "percentage", "error", "of", "a", "predicted", "DataFrame", "." ]
python
train
cocaine/cocaine-tools
cocaine/tools/dispatch.py
https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L1407-L1416
def group_pop(name, app, **kwargs): """ Remove application from the specified routing group. """ ctx = Context(**kwargs) ctx.execute_action('group:app:remove', **{ 'storage': ctx.repo.create_secure_service('storage'), 'name': name, 'app': app, })
[ "def", "group_pop", "(", "name", ",", "app", ",", "*", "*", "kwargs", ")", ":", "ctx", "=", "Context", "(", "*", "*", "kwargs", ")", "ctx", ".", "execute_action", "(", "'group:app:remove'", ",", "*", "*", "{", "'storage'", ":", "ctx", ".", "repo", ...
Remove application from the specified routing group.
[ "Remove", "application", "from", "the", "specified", "routing", "group", "." ]
python
train
symphonyoss/python-symphony
symphony/Agent/base.py
https://github.com/symphonyoss/python-symphony/blob/b939f35fbda461183ec0c01790c754f89a295be0/symphony/Agent/base.py#L29-L37
def create_datafeed(self): ''' create datafeed ''' response, status_code = self.__agent__.Datafeed.post_v4_datafeed_create( sessionToken=self.__session__, keyManagerToken=self.__keymngr__ ).result() # return the token self.logger.debug('%s: %s' % (status_code, response)) return status_code, response['id']
[ "def", "create_datafeed", "(", "self", ")", ":", "response", ",", "status_code", "=", "self", ".", "__agent__", ".", "Datafeed", ".", "post_v4_datafeed_create", "(", "sessionToken", "=", "self", ".", "__session__", ",", "keyManagerToken", "=", "self", ".", "__...
create datafeed
[ "create", "datafeed" ]
python
train