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
kyuupichan/aiorpcX
aiorpcx/jsonrpc.py
https://github.com/kyuupichan/aiorpcX/blob/707c989ed1c67ac9a40cd20b0161b1ce1f4d7db0/aiorpcx/jsonrpc.py#L284-L287
def request_message(cls, item, request_id): '''Convert an RPCRequest item to a message.''' assert isinstance(item, Request) return cls.encode_payload(cls.request_payload(item, request_id))
[ "def", "request_message", "(", "cls", ",", "item", ",", "request_id", ")", ":", "assert", "isinstance", "(", "item", ",", "Request", ")", "return", "cls", ".", "encode_payload", "(", "cls", ".", "request_payload", "(", "item", ",", "request_id", ")", ")" ]
Convert an RPCRequest item to a message.
[ "Convert", "an", "RPCRequest", "item", "to", "a", "message", "." ]
python
train
materialsproject/pymatgen
pymatgen/analysis/gb/grain.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/gb/grain.py#L110-L122
def copy(self): """ Convenience method to get a copy of the structure, with options to add site properties. Returns: A copy of the Structure, with optionally new site_properties and optionally sanitized. """ return GrainBoundary(self.lattice, self.species_and_occu, self.frac_coords, self.rotation_axis, self.rotation_angle, self.gb_plane, self.join_plane, self.init_cell, self.vacuum_thickness, self.ab_shift, self.site_properties, self.oriented_unit_cell)
[ "def", "copy", "(", "self", ")", ":", "return", "GrainBoundary", "(", "self", ".", "lattice", ",", "self", ".", "species_and_occu", ",", "self", ".", "frac_coords", ",", "self", ".", "rotation_axis", ",", "self", ".", "rotation_angle", ",", "self", ".", ...
Convenience method to get a copy of the structure, with options to add site properties. Returns: A copy of the Structure, with optionally new site_properties and optionally sanitized.
[ "Convenience", "method", "to", "get", "a", "copy", "of", "the", "structure", "with", "options", "to", "add", "site", "properties", "." ]
python
train
monarch-initiative/dipper
dipper/models/Genotype.py
https://github.com/monarch-initiative/dipper/blob/24cc80db355bbe15776edc5c7b41e0886959ba41/dipper/models/Genotype.py#L56-L77
def addAllele( self, allele_id, allele_label, allele_type=None, allele_description=None): """ Make an allele object. If no allele_type is added, it will default to a geno:allele :param allele_id: curie for allele (required) :param allele_label: label for allele (required) :param allele_type: id for an allele type (optional, recommended SO or GENO class) :param allele_description: a free-text description of the allele :return: """ # TODO should we accept a list of allele types? if allele_type is None: allele_type = self.globaltt['allele'] # TODO is this a good idea? self.model.addIndividualToGraph( allele_id, allele_label, allele_type, allele_description) return
[ "def", "addAllele", "(", "self", ",", "allele_id", ",", "allele_label", ",", "allele_type", "=", "None", ",", "allele_description", "=", "None", ")", ":", "# TODO should we accept a list of allele types?", "if", "allele_type", "is", "None", ":", "allele_type", "=", ...
Make an allele object. If no allele_type is added, it will default to a geno:allele :param allele_id: curie for allele (required) :param allele_label: label for allele (required) :param allele_type: id for an allele type (optional, recommended SO or GENO class) :param allele_description: a free-text description of the allele :return:
[ "Make", "an", "allele", "object", ".", "If", "no", "allele_type", "is", "added", "it", "will", "default", "to", "a", "geno", ":", "allele", ":", "param", "allele_id", ":", "curie", "for", "allele", "(", "required", ")", ":", "param", "allele_label", ":",...
python
train
isislovecruft/python-gnupg
pretty_bad_protocol/_meta.py
https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_meta.py#L352-L360
def default_preference_list(self, prefs): """Set the default preference list. :param str prefs: A string containing the default preferences for ciphers, digests, and compression algorithms. """ prefs = _check_preferences(prefs) if prefs is not None: self._prefs = prefs
[ "def", "default_preference_list", "(", "self", ",", "prefs", ")", ":", "prefs", "=", "_check_preferences", "(", "prefs", ")", "if", "prefs", "is", "not", "None", ":", "self", ".", "_prefs", "=", "prefs" ]
Set the default preference list. :param str prefs: A string containing the default preferences for ciphers, digests, and compression algorithms.
[ "Set", "the", "default", "preference", "list", "." ]
python
train
fermiPy/fermipy
fermipy/srcmap_utils.py
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/srcmap_utils.py#L380-L403
def delete_source_map(srcmap_file, names, logger=None): """Delete a map from a binned analysis source map file if it exists. Parameters ---------- srcmap_file : str Path to the source map file. names : list List of HDU keys of source maps to be deleted. """ with fits.open(srcmap_file) as hdulist: hdunames = [hdu.name.upper() for hdu in hdulist] if not isinstance(names, list): names = [names] for name in names: if not name.upper() in hdunames: continue del hdulist[name.upper()] hdulist.writeto(srcmap_file, overwrite=True)
[ "def", "delete_source_map", "(", "srcmap_file", ",", "names", ",", "logger", "=", "None", ")", ":", "with", "fits", ".", "open", "(", "srcmap_file", ")", "as", "hdulist", ":", "hdunames", "=", "[", "hdu", ".", "name", ".", "upper", "(", ")", "for", "...
Delete a map from a binned analysis source map file if it exists. Parameters ---------- srcmap_file : str Path to the source map file. names : list List of HDU keys of source maps to be deleted.
[ "Delete", "a", "map", "from", "a", "binned", "analysis", "source", "map", "file", "if", "it", "exists", "." ]
python
train
QuantEcon/QuantEcon.py
quantecon/game_theory/repeated_game.py
https://github.com/QuantEcon/QuantEcon.py/blob/26a66c552f2a73967d7efb6e1f4b4c4985a12643/quantecon/game_theory/repeated_game.py#L306-L366
def _find_C(C, points, vertices, equations, extended_payoff, IC, tol): """ Find all the intersection points between the current convex hull and the two IC constraints. It is done by iterating simplex counterclockwise. Parameters ---------- C : ndarray(float, ndim=2) The 4 by 2 array for storing the generated potential extreme points of one action profile. One action profile can only generate at most 4 points. points : ndarray(float, ndim=2) Coordinates of the points in the W, which construct a feasible payoff convex hull. vertices : ndarray(float, ndim=1) Indices of points forming the vertices of the convex hull, which are in counterclockwise order. equations : ndarray(float, ndim=2) [normal, offset] forming the hyperplane equation of the facet extended_payoff : ndarray(float, ndim=1) The array [payoff0, payoff1, 1] for checking if [payoff0, payoff1] is in the feasible payoff convex hull. IC : ndarray(float, ndim=1) The minimum IC continuation values. tol : scalar(float) The tolerance for checking if two values are equal. Returns ------- C : ndarray(float, ndim=2) The generated potential extreme points. n : scalar(int) The number of found intersection points. """ n = 0 weights = np.empty(2) # vertices is ordered counterclockwise for i in range(len(vertices)-1): n = _intersect(C, n, weights, IC, points[vertices[i]], points[vertices[i+1]], tol) n = _intersect(C, n, weights, IC, points[vertices[-1]], points[vertices[0]], tol) # check the case that IC is an interior point of the convex hull extended_payoff[:2] = IC if (np.dot(equations, extended_payoff) <= tol).all(): C[n, :] = IC n += 1 return C, n
[ "def", "_find_C", "(", "C", ",", "points", ",", "vertices", ",", "equations", ",", "extended_payoff", ",", "IC", ",", "tol", ")", ":", "n", "=", "0", "weights", "=", "np", ".", "empty", "(", "2", ")", "# vertices is ordered counterclockwise", "for", "i",...
Find all the intersection points between the current convex hull and the two IC constraints. It is done by iterating simplex counterclockwise. Parameters ---------- C : ndarray(float, ndim=2) The 4 by 2 array for storing the generated potential extreme points of one action profile. One action profile can only generate at most 4 points. points : ndarray(float, ndim=2) Coordinates of the points in the W, which construct a feasible payoff convex hull. vertices : ndarray(float, ndim=1) Indices of points forming the vertices of the convex hull, which are in counterclockwise order. equations : ndarray(float, ndim=2) [normal, offset] forming the hyperplane equation of the facet extended_payoff : ndarray(float, ndim=1) The array [payoff0, payoff1, 1] for checking if [payoff0, payoff1] is in the feasible payoff convex hull. IC : ndarray(float, ndim=1) The minimum IC continuation values. tol : scalar(float) The tolerance for checking if two values are equal. Returns ------- C : ndarray(float, ndim=2) The generated potential extreme points. n : scalar(int) The number of found intersection points.
[ "Find", "all", "the", "intersection", "points", "between", "the", "current", "convex", "hull", "and", "the", "two", "IC", "constraints", ".", "It", "is", "done", "by", "iterating", "simplex", "counterclockwise", "." ]
python
train
Clinical-Genomics/housekeeper
housekeeper/store/models.py
https://github.com/Clinical-Genomics/housekeeper/blob/a7d10d327dc9f06274bdef5504ed1b9413f2c8c1/housekeeper/store/models.py#L52-L54
def relative_root_dir(self): """Build the relative root dir path for the bundle version.""" return Path(self.bundle.name) / str(self.created_at.date())
[ "def", "relative_root_dir", "(", "self", ")", ":", "return", "Path", "(", "self", ".", "bundle", ".", "name", ")", "/", "str", "(", "self", ".", "created_at", ".", "date", "(", ")", ")" ]
Build the relative root dir path for the bundle version.
[ "Build", "the", "relative", "root", "dir", "path", "for", "the", "bundle", "version", "." ]
python
train
viniciuschiele/flask-apscheduler
flask_apscheduler/auth.py
https://github.com/viniciuschiele/flask-apscheduler/blob/cc52c39e1948c4e8de5da0d01db45f1779f61997/flask_apscheduler/auth.py#L82-L102
def get_authorization(self): """ Get the username and password for Basic authentication header. :return Authentication: The authentication data or None if it is not present or invalid. """ auth = get_authorization_header() if not auth: return None auth_type, auth_info = auth if auth_type != b'basic': return None try: username, password = base64.b64decode(auth_info).split(b':', 1) except Exception: return None return Authorization('basic', username=bytes_to_wsgi(username), password=bytes_to_wsgi(password))
[ "def", "get_authorization", "(", "self", ")", ":", "auth", "=", "get_authorization_header", "(", ")", "if", "not", "auth", ":", "return", "None", "auth_type", ",", "auth_info", "=", "auth", "if", "auth_type", "!=", "b'basic'", ":", "return", "None", "try", ...
Get the username and password for Basic authentication header. :return Authentication: The authentication data or None if it is not present or invalid.
[ "Get", "the", "username", "and", "password", "for", "Basic", "authentication", "header", ".", ":", "return", "Authentication", ":", "The", "authentication", "data", "or", "None", "if", "it", "is", "not", "present", "or", "invalid", "." ]
python
train
annoviko/pyclustering
pyclustering/nnet/sync.py
https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/nnet/sync.py#L258-L299
def allocate_phase_matrix(self, grid_width = None, grid_height = None, iteration = None): """! @brief Returns 2D matrix of phase values of oscillators at the specified iteration of simulation. @details User should ensure correct matrix sizes in line with following expression grid_width x grid_height that should be equal to amount of oscillators otherwise exception is thrown. If grid_width or grid_height are not specified than phase matrix size will by calculated automatically by square root. @param[in] grid_width (uint): Width of the allocated matrix. @param[in] grid_height (uint): Height of the allocated matrix. @param[in] iteration (uint): Number of iteration of simulation for which correlation matrix should be allocated. If iternation number is not specified, the last step of simulation is used for the matrix allocation. @return (list) Phase value matrix of oscillators with size [number_oscillators x number_oscillators]. """ output_dynamic = self.output; if ( (output_dynamic is None) or (len(output_dynamic) == 0) ): return []; current_dynamic = output_dynamic[len(output_dynamic) - 1]; if (iteration is not None): current_dynamic = output_dynamic[iteration]; width_matrix = grid_width; height_matrix = grid_height; number_oscillators = len(current_dynamic); if ( (width_matrix is None) or (height_matrix is None) ): width_matrix = int(math.ceil(math.sqrt(number_oscillators))); height_matrix = width_matrix; if (number_oscillators != width_matrix * height_matrix): raise NameError("Impossible to allocate phase matrix with specified sizes, amout of neurons should be equal to grid_width * grid_height."); phase_matrix = [ [ 0.0 for i in range(width_matrix) ] for j in range(height_matrix) ]; for i in range(height_matrix): for j in range(width_matrix): phase_matrix[i][j] = current_dynamic[j + i * width_matrix]; return phase_matrix;
[ "def", "allocate_phase_matrix", "(", "self", ",", "grid_width", "=", "None", ",", "grid_height", "=", "None", ",", "iteration", "=", "None", ")", ":", "output_dynamic", "=", "self", ".", "output", "if", "(", "(", "output_dynamic", "is", "None", ")", "or", ...
! @brief Returns 2D matrix of phase values of oscillators at the specified iteration of simulation. @details User should ensure correct matrix sizes in line with following expression grid_width x grid_height that should be equal to amount of oscillators otherwise exception is thrown. If grid_width or grid_height are not specified than phase matrix size will by calculated automatically by square root. @param[in] grid_width (uint): Width of the allocated matrix. @param[in] grid_height (uint): Height of the allocated matrix. @param[in] iteration (uint): Number of iteration of simulation for which correlation matrix should be allocated. If iternation number is not specified, the last step of simulation is used for the matrix allocation. @return (list) Phase value matrix of oscillators with size [number_oscillators x number_oscillators].
[ "!" ]
python
valid
mozilla-iot/webthing-python
webthing/property.py
https://github.com/mozilla-iot/webthing-python/blob/65d467c89ed79d0bbc42b8b3c8f9e5a320edd237/webthing/property.py#L91-L98
def set_value(self, value): """ Set the current value of the property. value -- the value to set """ self.validate_value(value) self.value.set(value)
[ "def", "set_value", "(", "self", ",", "value", ")", ":", "self", ".", "validate_value", "(", "value", ")", "self", ".", "value", ".", "set", "(", "value", ")" ]
Set the current value of the property. value -- the value to set
[ "Set", "the", "current", "value", "of", "the", "property", "." ]
python
test
awslabs/aws-cfn-template-flip
cfn_flip/__init__.py
https://github.com/awslabs/aws-cfn-template-flip/blob/837576bea243e3f5efb0a20b84802371272e2d33/cfn_flip/__init__.py#L63-L73
def to_yaml(template, clean_up=False, long_form=False): """ Assume the input is JSON and convert to YAML """ data = load_json(template) if clean_up: data = clean(data) return dump_yaml(data, clean_up, long_form)
[ "def", "to_yaml", "(", "template", ",", "clean_up", "=", "False", ",", "long_form", "=", "False", ")", ":", "data", "=", "load_json", "(", "template", ")", "if", "clean_up", ":", "data", "=", "clean", "(", "data", ")", "return", "dump_yaml", "(", "data...
Assume the input is JSON and convert to YAML
[ "Assume", "the", "input", "is", "JSON", "and", "convert", "to", "YAML" ]
python
train
chaosmail/python-fs
fs/fs.py
https://github.com/chaosmail/python-fs/blob/2567922ced9387e327e65f3244caff3b7af35684/fs/fs.py#L175-L180
def listdirs(path='.'): """generator that returns all directories of *path*""" import os for f in os.listdir(path): if isdir(join(path, f)): yield join(path, f) if path != '.' else f
[ "def", "listdirs", "(", "path", "=", "'.'", ")", ":", "import", "os", "for", "f", "in", "os", ".", "listdir", "(", "path", ")", ":", "if", "isdir", "(", "join", "(", "path", ",", "f", ")", ")", ":", "yield", "join", "(", "path", ",", "f", ")"...
generator that returns all directories of *path*
[ "generator", "that", "returns", "all", "directories", "of", "*", "path", "*" ]
python
train
cuihantao/andes
andes/filters/card.py
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/filters/card.py#L26-L110
def read(file, system): """Parse an ANDES card file into internal variables""" try: fid = open(file, 'r') raw_file = fid.readlines() except IOError: print('* IOError while reading input card file.') return ret_dict = dict() ret_dict['outfile'] = file.split('.')[0].lower() + '.py' key, val = None, None for idx, line in enumerate(raw_file): line = line.strip() if not line: continue if line.startswith('#'): continue elif '#' in line: line = line.split('#')[0] if '=' in line: # defining a field key, val = line.split('=') key, val = key.strip(), val.strip() val = [] if val == '' else val ret_dict.update({key: val}) if val: val = val.split(';') else: val.extend(line.split(';')) if val: val = de_blank(val) ret_dict[key] = val ret_dict_ord = dict(ret_dict) for key, val in ret_dict.items(): if not val: continue if type(val) == list: if ':' in val[0]: new_val = {} # return in a dictionary new_val_ord = [ ] # return in an ordered list with the dict keys at 0 for item in val: try: m, n = item.split(':') except ValueError: print('* Error: check line <{}>'.format(item)) return m, n = m.strip(), n.strip() if ',' in n: n = n.split(',') n = de_blank(n) n = [to_number(i) for i in n] else: n = to_number(n) new_val.update({m.strip(): n}) new_val_ord.append([m.strip(), n]) ret_dict[key] = new_val ret_dict_ord[key] = new_val_ord ret_dict['name'] = ret_dict['name'][0] ret_dict['doc_string'] = ret_dict['doc_string'][0] ret_dict['group'] = ret_dict['group'][0] ret_dict['service_keys'] = list(ret_dict['service_eq'].keys()) ret_dict['consts'] = list(ret_dict['data'].keys()) + list( ret_dict['service_eq'].keys()) ret_dict['init1_eq'] = ret_dict_ord['init1_eq'] ret_dict['service_eq'] = ret_dict_ord['service_eq'] ret_dict['ctrl'] = ret_dict_ord['ctrl'] copy_algebs = [] copy_states = [] for item in ret_dict['ctrl']: key, val = item if val[3] == 'y': copy_algebs.append(key) elif val[3] == 'x': copy_states.append(key) elif val[3] == 'c': ret_dict['consts'].append(key) ret_dict['copy_algebs'] = copy_algebs ret_dict['copy_states'] = copy_states return run(system, **ret_dict)
[ "def", "read", "(", "file", ",", "system", ")", ":", "try", ":", "fid", "=", "open", "(", "file", ",", "'r'", ")", "raw_file", "=", "fid", ".", "readlines", "(", ")", "except", "IOError", ":", "print", "(", "'* IOError while reading input card file.'", "...
Parse an ANDES card file into internal variables
[ "Parse", "an", "ANDES", "card", "file", "into", "internal", "variables" ]
python
train
transifex/transifex-python-library
txlib/api/resources.py
https://github.com/transifex/transifex-python-library/blob/9fea86b718973de35ccca6d54bd1f445c9632406/txlib/api/resources.py#L27-L32
def retrieve_content(self): """Retrieve the content of a resource.""" path = self._construct_path_to_source_content() res = self._http.get(path) self._populated_fields['content'] = res['content'] return res['content']
[ "def", "retrieve_content", "(", "self", ")", ":", "path", "=", "self", ".", "_construct_path_to_source_content", "(", ")", "res", "=", "self", ".", "_http", ".", "get", "(", "path", ")", "self", ".", "_populated_fields", "[", "'content'", "]", "=", "res", ...
Retrieve the content of a resource.
[ "Retrieve", "the", "content", "of", "a", "resource", "." ]
python
train
woolfson-group/isambard
isambard/add_ons/filesystem.py
https://github.com/woolfson-group/isambard/blob/ebc33b48a28ad217e18f93b910dfba46e6e71e07/isambard/add_ons/filesystem.py#L131-L179
def fastas(self, download=False): """ Dict of filepaths for all fasta files associated with code. Parameters ---------- download : bool If True, downloads the fasta file from the PDB. If False, uses the ampal Protein.fasta property Defaults to False - this is definitely the recommended behaviour. Notes ----- Calls self.mmols, and so downloads mmol files if not already present. See .fasta property of isambard.ampal.base_ampal.Protein for more information. Returns ------- fastas_dict : dict, or None. Keys : int mmol number Values : str Filepath for the corresponding fasta file. """ fastas_dict = {} fasta_dir = os.path.join(self.parent_dir, 'fasta') if not os.path.exists(fasta_dir): os.makedirs(fasta_dir) for i, mmol_file in self.mmols.items(): mmol_name = os.path.basename(mmol_file) fasta_file_name = '{0}.fasta'.format(mmol_name) fasta_file = os.path.join(fasta_dir, fasta_file_name) if not os.path.exists(fasta_file): if download: pdb_url = "http://www.rcsb.org/pdb/files/fasta.txt?structureIdList={0}".format(self.code.upper()) r = requests.get(pdb_url) if r.status_code == 200: fasta_string = r.text else: fasta_string = None else: a = convert_pdb_to_ampal(mmol_file) # take first object if AmpalContainer (i.e. NMR structure). if type(a) == AmpalContainer: a = a[0] fasta_string = a.fasta with open(fasta_file, 'w') as foo: foo.write(fasta_string) fastas_dict[i] = fasta_file return fastas_dict
[ "def", "fastas", "(", "self", ",", "download", "=", "False", ")", ":", "fastas_dict", "=", "{", "}", "fasta_dir", "=", "os", ".", "path", ".", "join", "(", "self", ".", "parent_dir", ",", "'fasta'", ")", "if", "not", "os", ".", "path", ".", "exists...
Dict of filepaths for all fasta files associated with code. Parameters ---------- download : bool If True, downloads the fasta file from the PDB. If False, uses the ampal Protein.fasta property Defaults to False - this is definitely the recommended behaviour. Notes ----- Calls self.mmols, and so downloads mmol files if not already present. See .fasta property of isambard.ampal.base_ampal.Protein for more information. Returns ------- fastas_dict : dict, or None. Keys : int mmol number Values : str Filepath for the corresponding fasta file.
[ "Dict", "of", "filepaths", "for", "all", "fasta", "files", "associated", "with", "code", "." ]
python
train
markovmodel/msmtools
msmtools/analysis/dense/pcca.py
https://github.com/markovmodel/msmtools/blob/54dc76dd2113a0e8f3d15d5316abab41402941be/msmtools/analysis/dense/pcca.py#L194-L219
def _fill_matrix(rot_crop_matrix, eigvectors): """ Helper function for opt_soft """ (x, y) = rot_crop_matrix.shape row_sums = np.sum(rot_crop_matrix, axis=1) row_sums = np.reshape(row_sums, (x, 1)) # add -row_sums as leftmost column to rot_crop_matrix rot_crop_matrix = np.concatenate((-row_sums, rot_crop_matrix), axis=1) tmp = -np.dot(eigvectors[:, 1:], rot_crop_matrix) tmp_col_max = np.max(tmp, axis=0) tmp_col_max = np.reshape(tmp_col_max, (1, y + 1)) tmp_col_max_sum = np.sum(tmp_col_max) # add col_max as top row to rot_crop_matrix and normalize rot_matrix = np.concatenate((tmp_col_max, rot_crop_matrix), axis=0) rot_matrix /= tmp_col_max_sum return rot_matrix
[ "def", "_fill_matrix", "(", "rot_crop_matrix", ",", "eigvectors", ")", ":", "(", "x", ",", "y", ")", "=", "rot_crop_matrix", ".", "shape", "row_sums", "=", "np", ".", "sum", "(", "rot_crop_matrix", ",", "axis", "=", "1", ")", "row_sums", "=", "np", "."...
Helper function for opt_soft
[ "Helper", "function", "for", "opt_soft" ]
python
train
biocore/deblur
deblur/workflow.py
https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/workflow.py#L532-L570
def remove_chimeras_denovo_from_seqs(seqs_fp, working_dir, threads=1): """Remove chimeras de novo using UCHIME (VSEARCH implementation). Parameters ---------- seqs_fp: string file path to FASTA input sequence file output_fp: string file path to store chimera-free results threads : int number of threads (0 for all cores) Returns ------- output_fp the chimera removed fasta file name """ logger = logging.getLogger(__name__) logger.info('remove_chimeras_denovo_from_seqs seqs file %s' 'to working dir %s' % (seqs_fp, working_dir)) output_fp = join( working_dir, "%s.no_chimeras" % basename(seqs_fp)) # we use the parameters dn=0.000001, xn=1000, minh=10000000 # so 1 mismatch in the A/B region will cancel it being labeled as chimera # and ~3 unique reads in each region will make it a chimera if # no mismatches params = ['vsearch', '--uchime_denovo', seqs_fp, '--nonchimeras', output_fp, '-dn', '0.000001', '-xn', '1000', '-minh', '10000000', '--mindiffs', '5', '--fasta_width', '0', '--threads', str(threads)] sout, serr, res = _system_call(params) if not res == 0: logger.error('problem with chimera removal for file %s' % seqs_fp) logger.debug('stdout : %s' % sout) logger.debug('stderr : %s' % serr) return output_fp
[ "def", "remove_chimeras_denovo_from_seqs", "(", "seqs_fp", ",", "working_dir", ",", "threads", "=", "1", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "info", "(", "'remove_chimeras_denovo_from_seqs seqs file %s'", "'to w...
Remove chimeras de novo using UCHIME (VSEARCH implementation). Parameters ---------- seqs_fp: string file path to FASTA input sequence file output_fp: string file path to store chimera-free results threads : int number of threads (0 for all cores) Returns ------- output_fp the chimera removed fasta file name
[ "Remove", "chimeras", "de", "novo", "using", "UCHIME", "(", "VSEARCH", "implementation", ")", "." ]
python
train
genesluder/python-agiletixapi
agiletixapi/utils.py
https://github.com/genesluder/python-agiletixapi/blob/a7a3907414cd5623f4542b03cb970862368a894a/agiletixapi/utils.py#L79-L83
def to_pascal_case(s): """Transform underscore separated string to pascal case """ return re.sub(r'(?!^)_([a-zA-Z])', lambda m: m.group(1).upper(), s.capitalize())
[ "def", "to_pascal_case", "(", "s", ")", ":", "return", "re", ".", "sub", "(", "r'(?!^)_([a-zA-Z])'", ",", "lambda", "m", ":", "m", ".", "group", "(", "1", ")", ".", "upper", "(", ")", ",", "s", ".", "capitalize", "(", ")", ")" ]
Transform underscore separated string to pascal case
[ "Transform", "underscore", "separated", "string", "to", "pascal", "case" ]
python
train
mandiant/ioc_writer
ioc_writer/ioc_api.py
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/ioc_api.py#L694-L704
def get_i_text(node): """ Get the text for an Indicator node. :param node: Indicator node. :return: """ if node.tag != 'Indicator': raise IOCParseError('Invalid tag: {}'.format(node.tag)) s = node.get('operator').upper() return s
[ "def", "get_i_text", "(", "node", ")", ":", "if", "node", ".", "tag", "!=", "'Indicator'", ":", "raise", "IOCParseError", "(", "'Invalid tag: {}'", ".", "format", "(", "node", ".", "tag", ")", ")", "s", "=", "node", ".", "get", "(", "'operator'", ")", ...
Get the text for an Indicator node. :param node: Indicator node. :return:
[ "Get", "the", "text", "for", "an", "Indicator", "node", "." ]
python
train
Alignak-monitoring/alignak
alignak/objects/service.py
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L1346-L1356
def apply_inheritance(self): """ For all items and templates inherit properties and custom variables. :return: None """ super(Services, self).apply_inheritance() # add_item only ensure we can build a key for services later (after explode) for item in list(self.items.values()): self.add_item(item, False)
[ "def", "apply_inheritance", "(", "self", ")", ":", "super", "(", "Services", ",", "self", ")", ".", "apply_inheritance", "(", ")", "# add_item only ensure we can build a key for services later (after explode)", "for", "item", "in", "list", "(", "self", ".", "items", ...
For all items and templates inherit properties and custom variables. :return: None
[ "For", "all", "items", "and", "templates", "inherit", "properties", "and", "custom", "variables", "." ]
python
train
saltstack/salt
salt/states/cron.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cron.py#L451-L669
def file(name, source_hash='', source_hash_name=None, user='root', template=None, context=None, replace=True, defaults=None, backup='', **kwargs): ''' Provides file.managed-like functionality (templating, etc.) for a pre-made crontab file, to be assigned to a given user. name The source file to be used as the crontab. This source file can be hosted on either the salt master server, or on an HTTP or FTP server. For files hosted on the salt file server, if the file is located on the master in the directory named spam, and is called eggs, the source string is ``salt://spam/eggs`` If the file is hosted on a HTTP or FTP server then the source_hash argument is also required source_hash This can be either a file which contains a source hash string for the source, or a source hash string. The source hash string is the hash algorithm followed by the hash of the file: ``md5=e138491e9d5b97023cea823fe17bac22`` source_hash_name When ``source_hash`` refers to a hash file, Salt will try to find the correct hash by matching the filename/URI associated with that hash. By default, Salt will look for the filename being managed. When managing a file at path ``/tmp/foo.txt``, then the following line in a hash file would match: .. code-block:: text acbd18db4cc2f85cedef654fccc4a4d8 foo.txt However, sometimes a hash file will include multiple similar paths: .. code-block:: text 37b51d194a7513e45b56f6524f2d51f2 ./dir1/foo.txt acbd18db4cc2f85cedef654fccc4a4d8 ./dir2/foo.txt 73feffa4b7f6bb68e44cf984c85f6e88 ./dir3/foo.txt In cases like this, Salt may match the incorrect hash. This argument can be used to tell Salt which filename to match, to ensure that the correct hash is identified. For example: .. code-block:: yaml foo_crontab: cron.file: - name: https://mydomain.tld/dir2/foo.txt - source_hash: https://mydomain.tld/hashes - source_hash_name: ./dir2/foo.txt .. note:: This argument must contain the full filename entry from the checksum file, as this argument is meant to disambiguate matches for multiple files that have the same basename. So, in the example above, simply using ``foo.txt`` would not match. .. versionadded:: 2016.3.5 user The user to whom the crontab should be assigned. This defaults to root. template If this setting is applied then the named templating engine will be used to render the downloaded file. Currently, jinja and mako are supported. context Overrides default context variables passed to the template. replace If the crontab should be replaced, if False then this command will be ignored if a crontab exists for the specified user. Default is True. defaults Default context passed to the template. backup Overrides the default backup mode for the user's crontab. ''' # Initial set up mode = '0600' try: group = __salt__['user.info'](user)['groups'][0] except Exception: ret = {'changes': {}, 'comment': "Could not identify group for user {0}".format(user), 'name': name, 'result': False} return ret cron_path = salt.utils.files.mkstemp() with salt.utils.files.fopen(cron_path, 'w+') as fp_: raw_cron = __salt__['cron.raw_cron'](user) if not raw_cron.endswith('\n'): raw_cron = "{0}\n".format(raw_cron) fp_.write(salt.utils.stringutils.to_str(raw_cron)) ret = {'changes': {}, 'comment': '', 'name': name, 'result': True} # Avoid variable naming confusion in below module calls, since ID # declaration for this state will be a source URI. source = name if not replace and os.stat(cron_path).st_size > 0: ret['comment'] = 'User {0} already has a crontab. No changes ' \ 'made'.format(user) os.unlink(cron_path) return ret if __opts__['test']: fcm = __salt__['file.check_managed'](name=cron_path, source=source, source_hash=source_hash, source_hash_name=source_hash_name, user=user, group=group, mode=mode, attrs=[], # no special attrs for cron template=template, context=context, defaults=defaults, saltenv=__env__, **kwargs ) ret['result'], ret['comment'] = fcm os.unlink(cron_path) return ret # If the source is a list then find which file exists source, source_hash = __salt__['file.source_list'](source, source_hash, __env__) # Gather the source file from the server try: sfn, source_sum, comment = __salt__['file.get_managed']( name=cron_path, template=template, source=source, source_hash=source_hash, source_hash_name=source_hash_name, user=user, group=group, mode=mode, attrs=[], saltenv=__env__, context=context, defaults=defaults, skip_verify=False, # skip_verify **kwargs ) except Exception as exc: ret['result'] = False ret['changes'] = {} ret['comment'] = 'Unable to manage file: {0}'.format(exc) return ret if comment: ret['comment'] = comment ret['result'] = False os.unlink(cron_path) return ret try: ret = __salt__['file.manage_file']( name=cron_path, sfn=sfn, ret=ret, source=source, source_sum=source_sum, user=user, group=group, mode=mode, attrs=[], saltenv=__env__, backup=backup ) except Exception as exc: ret['result'] = False ret['changes'] = {} ret['comment'] = 'Unable to manage file: {0}'.format(exc) return ret cron_ret = None if "diff" in ret['changes']: cron_ret = __salt__['cron.write_cron_file_verbose'](user, cron_path) # Check cmd return code and show success or failure if cron_ret['retcode'] == 0: ret['comment'] = 'Crontab for user {0} was updated'.format(user) ret['result'] = True ret['changes'] = ret['changes'] else: ret['comment'] = 'Unable to update user {0} crontab {1}.' \ ' Error: {2}'.format(user, cron_path, cron_ret['stderr']) ret['result'] = False ret['changes'] = {} elif ret['result']: ret['comment'] = 'Crontab for user {0} is in the correct ' \ 'state'.format(user) ret['changes'] = {} os.unlink(cron_path) return ret
[ "def", "file", "(", "name", ",", "source_hash", "=", "''", ",", "source_hash_name", "=", "None", ",", "user", "=", "'root'", ",", "template", "=", "None", ",", "context", "=", "None", ",", "replace", "=", "True", ",", "defaults", "=", "None", ",", "b...
Provides file.managed-like functionality (templating, etc.) for a pre-made crontab file, to be assigned to a given user. name The source file to be used as the crontab. This source file can be hosted on either the salt master server, or on an HTTP or FTP server. For files hosted on the salt file server, if the file is located on the master in the directory named spam, and is called eggs, the source string is ``salt://spam/eggs`` If the file is hosted on a HTTP or FTP server then the source_hash argument is also required source_hash This can be either a file which contains a source hash string for the source, or a source hash string. The source hash string is the hash algorithm followed by the hash of the file: ``md5=e138491e9d5b97023cea823fe17bac22`` source_hash_name When ``source_hash`` refers to a hash file, Salt will try to find the correct hash by matching the filename/URI associated with that hash. By default, Salt will look for the filename being managed. When managing a file at path ``/tmp/foo.txt``, then the following line in a hash file would match: .. code-block:: text acbd18db4cc2f85cedef654fccc4a4d8 foo.txt However, sometimes a hash file will include multiple similar paths: .. code-block:: text 37b51d194a7513e45b56f6524f2d51f2 ./dir1/foo.txt acbd18db4cc2f85cedef654fccc4a4d8 ./dir2/foo.txt 73feffa4b7f6bb68e44cf984c85f6e88 ./dir3/foo.txt In cases like this, Salt may match the incorrect hash. This argument can be used to tell Salt which filename to match, to ensure that the correct hash is identified. For example: .. code-block:: yaml foo_crontab: cron.file: - name: https://mydomain.tld/dir2/foo.txt - source_hash: https://mydomain.tld/hashes - source_hash_name: ./dir2/foo.txt .. note:: This argument must contain the full filename entry from the checksum file, as this argument is meant to disambiguate matches for multiple files that have the same basename. So, in the example above, simply using ``foo.txt`` would not match. .. versionadded:: 2016.3.5 user The user to whom the crontab should be assigned. This defaults to root. template If this setting is applied then the named templating engine will be used to render the downloaded file. Currently, jinja and mako are supported. context Overrides default context variables passed to the template. replace If the crontab should be replaced, if False then this command will be ignored if a crontab exists for the specified user. Default is True. defaults Default context passed to the template. backup Overrides the default backup mode for the user's crontab.
[ "Provides", "file", ".", "managed", "-", "like", "functionality", "(", "templating", "etc", ".", ")", "for", "a", "pre", "-", "made", "crontab", "file", "to", "be", "assigned", "to", "a", "given", "user", "." ]
python
train
mulkieran/justbases
src/justbases/_rationals.py
https://github.com/mulkieran/justbases/blob/dd52ff4b3d11609f54b2673599ee4eeb20f9734f/src/justbases/_rationals.py#L562-L589
def _increment(sign, integer_part, non_repeating_part, base): """ Return an increment radix. :param int sign: -1, 0, or 1 as appropriate :param integer_part: the integer part :type integer_part: list of int :param non_repeating_part: the fractional part :type non_repeating_part: list of int :param int base: the base :returns: a Radix object with ``non_repeating_part`` rounded up :rtype: Radix Complexity: O(len(non_repeating_part + integer_part) """ (carry, non_repeating_part) = \ Nats.carry_in(non_repeating_part, 1, base) (carry, integer_part) = \ Nats.carry_in(integer_part, carry, base) return Radix( sign, integer_part if carry == 0 else [carry] + integer_part, non_repeating_part, [], base, False )
[ "def", "_increment", "(", "sign", ",", "integer_part", ",", "non_repeating_part", ",", "base", ")", ":", "(", "carry", ",", "non_repeating_part", ")", "=", "Nats", ".", "carry_in", "(", "non_repeating_part", ",", "1", ",", "base", ")", "(", "carry", ",", ...
Return an increment radix. :param int sign: -1, 0, or 1 as appropriate :param integer_part: the integer part :type integer_part: list of int :param non_repeating_part: the fractional part :type non_repeating_part: list of int :param int base: the base :returns: a Radix object with ``non_repeating_part`` rounded up :rtype: Radix Complexity: O(len(non_repeating_part + integer_part)
[ "Return", "an", "increment", "radix", "." ]
python
train
Kortemme-Lab/klab
klab/bio/uniprot.py
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/uniprot.py#L892-L915
def get_common_PDB_IDs(pdb_id, cache_dir = None, exception_on_failure = True): '''This function takes a PDB ID, maps it to UniProt ACCs, then returns the common set of PDB IDs related to those ACCs. The purpose is to find any PDB files related to pdb_id, particularly for complexes, such that the other PDB files contain identical sequences or mutant complexes.''' m = pdb_to_uniparc([pdb_id], cache_dir = cache_dir) UniProtACs = [] if pdb_id in m: for entry in m[pdb_id]: if entry.UniProtACs: UniProtACs.extend(entry.UniProtACs) elif exception_on_failure: raise Exception('No UniProtAC for one entry.Lookup failed.') elif exception_on_failure: raise Exception('Lookup failed.') if not UniProtACs: if exception_on_failure: raise Exception('Lookup failed.') else: return None common_set = set(uniprot_map('ACC', 'PDB_ID', [UniProtACs[0]], cache_dir = cache_dir).get(UniProtACs[0], [])) for acc in UniProtACs[1:]: common_set = common_set.intersection(set(uniprot_map('ACC', 'PDB_ID', [acc], cache_dir = cache_dir).get(acc, []))) return sorted(common_set)
[ "def", "get_common_PDB_IDs", "(", "pdb_id", ",", "cache_dir", "=", "None", ",", "exception_on_failure", "=", "True", ")", ":", "m", "=", "pdb_to_uniparc", "(", "[", "pdb_id", "]", ",", "cache_dir", "=", "cache_dir", ")", "UniProtACs", "=", "[", "]", "if", ...
This function takes a PDB ID, maps it to UniProt ACCs, then returns the common set of PDB IDs related to those ACCs. The purpose is to find any PDB files related to pdb_id, particularly for complexes, such that the other PDB files contain identical sequences or mutant complexes.
[ "This", "function", "takes", "a", "PDB", "ID", "maps", "it", "to", "UniProt", "ACCs", "then", "returns", "the", "common", "set", "of", "PDB", "IDs", "related", "to", "those", "ACCs", ".", "The", "purpose", "is", "to", "find", "any", "PDB", "files", "re...
python
train
opencobra/memote
memote/support/consistency_helpers.py
https://github.com/opencobra/memote/blob/276630fcd4449fb7b914186edfd38c239e7052df/memote/support/consistency_helpers.py#L216-L233
def get_internals(model): """ Return non-boundary reactions and their metabolites. Boundary reactions are unbalanced by their nature. They are excluded here and only the metabolites of the others are considered. Parameters ---------- model : cobra.Model The metabolic model under investigation. """ biomass = set(find_biomass_reaction(model)) if len(biomass) == 0: LOGGER.warning("No biomass reaction detected. Consistency test results " "are unreliable if one exists.") return set(model.reactions) - (set(model.boundary) | biomass)
[ "def", "get_internals", "(", "model", ")", ":", "biomass", "=", "set", "(", "find_biomass_reaction", "(", "model", ")", ")", "if", "len", "(", "biomass", ")", "==", "0", ":", "LOGGER", ".", "warning", "(", "\"No biomass reaction detected. Consistency test result...
Return non-boundary reactions and their metabolites. Boundary reactions are unbalanced by their nature. They are excluded here and only the metabolites of the others are considered. Parameters ---------- model : cobra.Model The metabolic model under investigation.
[ "Return", "non", "-", "boundary", "reactions", "and", "their", "metabolites", "." ]
python
train
borntyping/python-riemann-client
riemann_client/command.py
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/command.py#L131-L134
def query(transport, query): """Query the Riemann server""" with CommandLineClient(transport) as client: echo_event(client.query(query))
[ "def", "query", "(", "transport", ",", "query", ")", ":", "with", "CommandLineClient", "(", "transport", ")", "as", "client", ":", "echo_event", "(", "client", ".", "query", "(", "query", ")", ")" ]
Query the Riemann server
[ "Query", "the", "Riemann", "server" ]
python
train
apache/spark
python/pyspark/sql/functions.py
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/functions.py#L1761-L1770
def regexp_replace(str, pattern, replacement): r"""Replace all substrings of the specified string value that match regexp with rep. >>> df = spark.createDataFrame([('100-200',)], ['str']) >>> df.select(regexp_replace('str', r'(\d+)', '--').alias('d')).collect() [Row(d=u'-----')] """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.regexp_replace(_to_java_column(str), pattern, replacement) return Column(jc)
[ "def", "regexp_replace", "(", "str", ",", "pattern", ",", "replacement", ")", ":", "sc", "=", "SparkContext", ".", "_active_spark_context", "jc", "=", "sc", ".", "_jvm", ".", "functions", ".", "regexp_replace", "(", "_to_java_column", "(", "str", ")", ",", ...
r"""Replace all substrings of the specified string value that match regexp with rep. >>> df = spark.createDataFrame([('100-200',)], ['str']) >>> df.select(regexp_replace('str', r'(\d+)', '--').alias('d')).collect() [Row(d=u'-----')]
[ "r", "Replace", "all", "substrings", "of", "the", "specified", "string", "value", "that", "match", "regexp", "with", "rep", "." ]
python
train
pyviz/holoviews
holoviews/plotting/mpl/element.py
https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/plotting/mpl/element.py#L527-L537
def update_handles(self, key, axis, element, ranges, style): """ Update the elements of the plot. """ self.teardown_handles() plot_data, plot_kwargs, axis_kwargs = self.get_data(element, ranges, style) with abbreviated_exception(): handles = self.init_artists(axis, plot_data, plot_kwargs) self.handles.update(handles) return axis_kwargs
[ "def", "update_handles", "(", "self", ",", "key", ",", "axis", ",", "element", ",", "ranges", ",", "style", ")", ":", "self", ".", "teardown_handles", "(", ")", "plot_data", ",", "plot_kwargs", ",", "axis_kwargs", "=", "self", ".", "get_data", "(", "elem...
Update the elements of the plot.
[ "Update", "the", "elements", "of", "the", "plot", "." ]
python
train
fhs/pyhdf
pyhdf/SD.py
https://github.com/fhs/pyhdf/blob/dbdc1810a74a38df50dcad81fe903e239d2b388d/pyhdf/SD.py#L2959-L3018
def getscale(self): """Obtain the scale values along a dimension. Args:: no argument Returns:: list with the scale values; the list length is equal to the dimension length; the element type is equal to the dimension data type, as set when the 'setdimscale()' method was called. C library equivalent : SDgetdimscale """ # Get dimension info. If data_type is 0, no scale have been set # on the dimension. status, dim_name, dim_size, data_type, n_attrs = _C.SDdiminfo(self._id) _checkErr('getscale', status, 'cannot execute') if data_type == 0: raise HDF4Error("no scale set on that dimension") # dim_size is 0 for an unlimited dimension. The actual length is # obtained through SDgetinfo. if dim_size == 0: dim_size = self._sds.info()[2][self._index] # Get scale values. if data_type in [SDC.UCHAR8, SDC.UINT8]: buf = _C.array_byte(dim_size) elif data_type == SDC.INT8: buf = _C.array_int8(dim_size) elif data_type == SDC.INT16: buf = _C.array_int16(dim_size) elif data_type == SDC.UINT16: buf = _C.array_uint16(dim_size) elif data_type == SDC.INT32: buf = _C.array_int32(dim_size) elif data_type == SDC.UINT32: buf = _C.array_uint32(dim_size) elif data_type == SDC.FLOAT32: buf = _C.array_float32(dim_size) elif data_type == SDC.FLOAT64: buf = _C.array_float64(dim_size) else: raise HDF4Error("getscale: dimension has an "\ "illegal or unsupported type %d" % data_type) status = _C.SDgetdimscale(self._id, buf) _checkErr('getscale', status, 'cannot execute') return _array_to_ret(buf, dim_size)
[ "def", "getscale", "(", "self", ")", ":", "# Get dimension info. If data_type is 0, no scale have been set", "# on the dimension.", "status", ",", "dim_name", ",", "dim_size", ",", "data_type", ",", "n_attrs", "=", "_C", ".", "SDdiminfo", "(", "self", ".", "_id", ")...
Obtain the scale values along a dimension. Args:: no argument Returns:: list with the scale values; the list length is equal to the dimension length; the element type is equal to the dimension data type, as set when the 'setdimscale()' method was called. C library equivalent : SDgetdimscale
[ "Obtain", "the", "scale", "values", "along", "a", "dimension", "." ]
python
train
PmagPy/PmagPy
programs/pmag_gui.py
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/pmag_gui.py#L765-L782
def on_menu_exit(self, event): """ Exit the GUI """ # also delete appropriate copy file try: self.help_window.Destroy() except: pass if '-i' in sys.argv: self.Destroy() try: sys.exit() # can raise TypeError if wx inspector was used except Exception as ex: if isinstance(ex, TypeError): pass else: raise ex
[ "def", "on_menu_exit", "(", "self", ",", "event", ")", ":", "# also delete appropriate copy file", "try", ":", "self", ".", "help_window", ".", "Destroy", "(", ")", "except", ":", "pass", "if", "'-i'", "in", "sys", ".", "argv", ":", "self", ".", "Destroy",...
Exit the GUI
[ "Exit", "the", "GUI" ]
python
train
apache/spark
python/pyspark/sql/functions.py
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/functions.py#L314-L329
def approx_count_distinct(col, rsd=None): """Aggregate function: returns a new :class:`Column` for approximate distinct count of column `col`. :param rsd: maximum estimation error allowed (default = 0.05). For rsd < 0.01, it is more efficient to use :func:`countDistinct` >>> df.agg(approx_count_distinct(df.age).alias('distinct_ages')).collect() [Row(distinct_ages=2)] """ sc = SparkContext._active_spark_context if rsd is None: jc = sc._jvm.functions.approx_count_distinct(_to_java_column(col)) else: jc = sc._jvm.functions.approx_count_distinct(_to_java_column(col), rsd) return Column(jc)
[ "def", "approx_count_distinct", "(", "col", ",", "rsd", "=", "None", ")", ":", "sc", "=", "SparkContext", ".", "_active_spark_context", "if", "rsd", "is", "None", ":", "jc", "=", "sc", ".", "_jvm", ".", "functions", ".", "approx_count_distinct", "(", "_to_...
Aggregate function: returns a new :class:`Column` for approximate distinct count of column `col`. :param rsd: maximum estimation error allowed (default = 0.05). For rsd < 0.01, it is more efficient to use :func:`countDistinct` >>> df.agg(approx_count_distinct(df.age).alias('distinct_ages')).collect() [Row(distinct_ages=2)]
[ "Aggregate", "function", ":", "returns", "a", "new", ":", "class", ":", "Column", "for", "approximate", "distinct", "count", "of", "column", "col", "." ]
python
train
chaimleib/intervaltree
intervaltree/node.py
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/node.py#L216-L223
def discard(self, interval): """ Returns self after removing interval and balancing. If interval is not present, do nothing. """ done = [] return self.remove_interval_helper(interval, done, should_raise_error=False)
[ "def", "discard", "(", "self", ",", "interval", ")", ":", "done", "=", "[", "]", "return", "self", ".", "remove_interval_helper", "(", "interval", ",", "done", ",", "should_raise_error", "=", "False", ")" ]
Returns self after removing interval and balancing. If interval is not present, do nothing.
[ "Returns", "self", "after", "removing", "interval", "and", "balancing", "." ]
python
train
neurodata/ndio
ndio/convert/tiff.py
https://github.com/neurodata/ndio/blob/792dd5816bc770b05a3db2f4327da42ff6253531/ndio/convert/tiff.py#L98-L133
def load_tiff_multipage(tiff_filename, dtype='float32'): """ Load a multipage tiff into a single variable in x,y,z format. Arguments: tiff_filename: Filename of source data dtype: data type to use for the returned tensor Returns: Array containing contents from input tiff file in xyz order """ if not os.path.isfile(tiff_filename): raise RuntimeError('could not find file "%s"' % tiff_filename) # load the data from multi-layer TIF files data = tiff.imread(tiff_filename) im = [] while True: Xi = numpy.array(data, dtype=dtype) if Xi.ndim == 2: Xi = Xi[numpy.newaxis, ...] # add slice dimension im.append(Xi) try: data.seek(data.tell()+1) except EOFError: break # this just means hit end of file (not really an error) im = numpy.concatenate(im, axis=0) # list of 2d -> tensor im = numpy.rollaxis(im, 1) im = numpy.rollaxis(im, 2) return im
[ "def", "load_tiff_multipage", "(", "tiff_filename", ",", "dtype", "=", "'float32'", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "tiff_filename", ")", ":", "raise", "RuntimeError", "(", "'could not find file \"%s\"'", "%", "tiff_filename", ")", ...
Load a multipage tiff into a single variable in x,y,z format. Arguments: tiff_filename: Filename of source data dtype: data type to use for the returned tensor Returns: Array containing contents from input tiff file in xyz order
[ "Load", "a", "multipage", "tiff", "into", "a", "single", "variable", "in", "x", "y", "z", "format", "." ]
python
test
cherrypy/cheroot
cheroot/ssl/pyopenssl.py
https://github.com/cherrypy/cheroot/blob/2af3b1798d66da697957480d3a8b4831a405770b/cheroot/ssl/pyopenssl.py#L270-L278
def get_context(self): """Return an SSL.Context from self attributes.""" # See https://code.activestate.com/recipes/442473/ c = SSL.Context(SSL.SSLv23_METHOD) c.use_privatekey_file(self.private_key) if self.certificate_chain: c.load_verify_locations(self.certificate_chain) c.use_certificate_file(self.certificate) return c
[ "def", "get_context", "(", "self", ")", ":", "# See https://code.activestate.com/recipes/442473/", "c", "=", "SSL", ".", "Context", "(", "SSL", ".", "SSLv23_METHOD", ")", "c", ".", "use_privatekey_file", "(", "self", ".", "private_key", ")", "if", "self", ".", ...
Return an SSL.Context from self attributes.
[ "Return", "an", "SSL", ".", "Context", "from", "self", "attributes", "." ]
python
train
sethmlarson/virtualbox-python
virtualbox/library.py
https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L9585-L9628
def set_final_values(self, enabled, v_box_values, extra_config_values): """This method allows the appliance's user to change the configuration for the virtual system descriptions. For each array item returned from :py:func:`get_description` , you must pass in one boolean value and one configuration value. Each item in the boolean array determines whether the particular configuration item should be enabled. You can only disable items of the types HardDiskControllerIDE, HardDiskControllerSATA, HardDiskControllerSCSI, HardDiskImage, CDROM, Floppy, NetworkAdapter, USBController and SoundCard. For the "vbox" and "extra configuration" values, if you pass in the same arrays as returned in the aVBoxValues and aExtraConfigValues arrays from :py:func:`get_description` , the configuration remains unchanged. Please see the documentation for :py:func:`get_description` for valid configuration values for the individual array item types. If the corresponding item in the aEnabled array is @c false, the configuration value is ignored. in enabled of type bool in v_box_values of type str in extra_config_values of type str """ if not isinstance(enabled, list): raise TypeError("enabled can only be an instance of type list") for a in enabled[:10]: if not isinstance(a, bool): raise TypeError( "array can only contain objects of type bool") if not isinstance(v_box_values, list): raise TypeError("v_box_values can only be an instance of type list") for a in v_box_values[:10]: if not isinstance(a, basestring): raise TypeError( "array can only contain objects of type basestring") if not isinstance(extra_config_values, list): raise TypeError("extra_config_values can only be an instance of type list") for a in extra_config_values[:10]: if not isinstance(a, basestring): raise TypeError( "array can only contain objects of type basestring") self._call("setFinalValues", in_p=[enabled, v_box_values, extra_config_values])
[ "def", "set_final_values", "(", "self", ",", "enabled", ",", "v_box_values", ",", "extra_config_values", ")", ":", "if", "not", "isinstance", "(", "enabled", ",", "list", ")", ":", "raise", "TypeError", "(", "\"enabled can only be an instance of type list\"", ")", ...
This method allows the appliance's user to change the configuration for the virtual system descriptions. For each array item returned from :py:func:`get_description` , you must pass in one boolean value and one configuration value. Each item in the boolean array determines whether the particular configuration item should be enabled. You can only disable items of the types HardDiskControllerIDE, HardDiskControllerSATA, HardDiskControllerSCSI, HardDiskImage, CDROM, Floppy, NetworkAdapter, USBController and SoundCard. For the "vbox" and "extra configuration" values, if you pass in the same arrays as returned in the aVBoxValues and aExtraConfigValues arrays from :py:func:`get_description` , the configuration remains unchanged. Please see the documentation for :py:func:`get_description` for valid configuration values for the individual array item types. If the corresponding item in the aEnabled array is @c false, the configuration value is ignored. in enabled of type bool in v_box_values of type str in extra_config_values of type str
[ "This", "method", "allows", "the", "appliance", "s", "user", "to", "change", "the", "configuration", "for", "the", "virtual", "system", "descriptions", ".", "For", "each", "array", "item", "returned", "from", ":", "py", ":", "func", ":", "get_description", "...
python
train
tritemio/PyBroMo
pybromo/psflib.py
https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/psflib.py#L132-L137
def load_PSFLab_file(fname): """Load the array `data` in the .mat file `fname`.""" if os.path.exists(fname) or os.path.exists(fname + '.mat'): return loadmat(fname)['data'] else: raise IOError("Can't find PSF file '%s'" % fname)
[ "def", "load_PSFLab_file", "(", "fname", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "fname", ")", "or", "os", ".", "path", ".", "exists", "(", "fname", "+", "'.mat'", ")", ":", "return", "loadmat", "(", "fname", ")", "[", "'data'", "]",...
Load the array `data` in the .mat file `fname`.
[ "Load", "the", "array", "data", "in", "the", ".", "mat", "file", "fname", "." ]
python
valid
archman/beamline
beamline/lattice.py
https://github.com/archman/beamline/blob/417bc5dc13e754bc89d246427984590fced64d07/beamline/lattice.py#L580-L589
def getElementCtrlConf(self, elementKw): """ return keyword's EPICS control configs, if not setup, return {} """ try: retval = self.all_elements['_epics'][elementKw.upper()] except KeyError: retval = {} return retval
[ "def", "getElementCtrlConf", "(", "self", ",", "elementKw", ")", ":", "try", ":", "retval", "=", "self", ".", "all_elements", "[", "'_epics'", "]", "[", "elementKw", ".", "upper", "(", ")", "]", "except", "KeyError", ":", "retval", "=", "{", "}", "retu...
return keyword's EPICS control configs, if not setup, return {}
[ "return", "keyword", "s", "EPICS", "control", "configs", "if", "not", "setup", "return", "{}" ]
python
train
PyPSA/PyPSA
pypsa/geo.py
https://github.com/PyPSA/PyPSA/blob/46954b1b3c21460550f7104681517065279a53b7/pypsa/geo.py#L36-L83
def haversine(a0,a1): """ Compute the distance in km between two sets of points in long/lat. One dimension of a* should be 2; longitude then latitude. Uses haversine formula. Parameters ---------- a0: array/list of at most 2 dimensions One dimension must be 2 a1: array/list of at most 2 dimensions One dimension must be 2 Returns ------- distance_km: np.array 2-dimensional array of distances in km between points in a0, a1 Examples -------- haversine([10.1,52.6],[[10.8,52.1],[-34,56.]]) returns array([[ 73.15416698, 2836.6707696 ]]) """ a = [np.asarray(a0,dtype=float),np.asarray(a1,dtype=float)] for i in range(2): if len(a[i].shape) == 1: a[i] = np.reshape(a[i],(1,a[i].shape[0])) if a[i].shape[1] != 2: logger.error("Inputs to haversine have the wrong shape!") return a[i] = np.deg2rad(a[i]) distance_km = np.zeros((a[0].shape[0],a[1].shape[0])) for i in range(a[1].shape[0]): b = np.sin((a[0][:,1] - a[1][i,1])/2.)**2 + np.cos(a[0][:,1]) * np.cos(a[1][i,1]) * np.sin((a[0][:,0] - a[1][i,0])/2.)**2 distance_km[:,i] = 6371.000 * 2 * np.arctan2( np.sqrt(b), np.sqrt(1-b) ) return distance_km
[ "def", "haversine", "(", "a0", ",", "a1", ")", ":", "a", "=", "[", "np", ".", "asarray", "(", "a0", ",", "dtype", "=", "float", ")", ",", "np", ".", "asarray", "(", "a1", ",", "dtype", "=", "float", ")", "]", "for", "i", "in", "range", "(", ...
Compute the distance in km between two sets of points in long/lat. One dimension of a* should be 2; longitude then latitude. Uses haversine formula. Parameters ---------- a0: array/list of at most 2 dimensions One dimension must be 2 a1: array/list of at most 2 dimensions One dimension must be 2 Returns ------- distance_km: np.array 2-dimensional array of distances in km between points in a0, a1 Examples -------- haversine([10.1,52.6],[[10.8,52.1],[-34,56.]]) returns array([[ 73.15416698, 2836.6707696 ]])
[ "Compute", "the", "distance", "in", "km", "between", "two", "sets", "of", "points", "in", "long", "/", "lat", "." ]
python
train
UDST/pandana
pandana/network.py
https://github.com/UDST/pandana/blob/961a7ef8d3b0144b190cb60bbd61845fca6fb314/pandana/network.py#L495-L581
def nearest_pois(self, distance, category, num_pois=1, max_distance=None, imp_name=None, include_poi_ids=False): """ Find the distance to the nearest pois from each source node. The bigger values in this case mean less accessibility. Parameters ---------- distance : float The maximum distance to look for pois. This will usually be a distance unit in meters however if you have customized the impedance this could be in other units such as utility or time etc. category : string The name of the category of poi to look for num_pois : int The number of pois to look for, this also sets the number of columns in the DataFrame that gets returned max_distance : float, optional The value to set the distance to if there is NO poi within the specified distance - if not specified, gets set to distance. This will usually be a distance unit in meters however if you have customized the impedance this could be in other units such as utility or time etc. imp_name : string, optional The impedance name to use for the aggregation on this network. Must be one of the impedance names passed in the constructor of this object. If not specified, there must be only one impedance passed in the constructor, which will be used. include_poi_ids : bool, optional If this flag is set to true, the call will add columns to the return DataFrame - instead of just returning the distance for the nth POI, it will also return the id of that POI. The names of the columns with the poi ids will be poi1, poi2, etc - it will take roughly twice as long to include these ids as to not include them Returns ------- d : Pandas DataFrame Like aggregate, this series has an index of all the node ids for the network. Unlike aggregate, this method returns a dataframe with the number of columns equal to the distances to the Nth closest poi. For instance, if you ask for the 10 closest poi to each node, column d[1] wil be the distance to the 1st closest poi of that category while column d[2] will be the distance to the 2nd closest poi, and so on. """ if max_distance is None: max_distance = distance if category not in self.poi_category_names: assert 0, "Need to call set_pois for this category" if num_pois > self.max_pois: assert 0, "Asking for more pois than set in init_pois" imp_num = self._imp_name_to_num(imp_name) dists, poi_ids = self.net.find_all_nearest_pois( distance, num_pois, category.encode('utf-8'), imp_num) dists[dists == -1] = max_distance df = pd.DataFrame(dists, index=self.node_ids) df.columns = list(range(1, num_pois+1)) if include_poi_ids: df2 = pd.DataFrame(poi_ids, index=self.node_ids) df2.columns = ["poi%d" % i for i in range(1, num_pois+1)] for col in df2.columns: # if this is still all working according to plan at this point # the great magic trick is now to turn the integer position of # the poi, which is painstakingly returned from the c++ code, # and turn it into the actual index that was used when it was # initialized as a pandas series - this really is pandas-like # thinking. it's complicated on the inside, but quite # intuitive to the user I think s = df2[col].astype('int') df2[col] = self.poi_category_indexes[category].values[s] df2.loc[s == -1, col] = np.nan df = pd.concat([df, df2], axis=1) return df
[ "def", "nearest_pois", "(", "self", ",", "distance", ",", "category", ",", "num_pois", "=", "1", ",", "max_distance", "=", "None", ",", "imp_name", "=", "None", ",", "include_poi_ids", "=", "False", ")", ":", "if", "max_distance", "is", "None", ":", "max...
Find the distance to the nearest pois from each source node. The bigger values in this case mean less accessibility. Parameters ---------- distance : float The maximum distance to look for pois. This will usually be a distance unit in meters however if you have customized the impedance this could be in other units such as utility or time etc. category : string The name of the category of poi to look for num_pois : int The number of pois to look for, this also sets the number of columns in the DataFrame that gets returned max_distance : float, optional The value to set the distance to if there is NO poi within the specified distance - if not specified, gets set to distance. This will usually be a distance unit in meters however if you have customized the impedance this could be in other units such as utility or time etc. imp_name : string, optional The impedance name to use for the aggregation on this network. Must be one of the impedance names passed in the constructor of this object. If not specified, there must be only one impedance passed in the constructor, which will be used. include_poi_ids : bool, optional If this flag is set to true, the call will add columns to the return DataFrame - instead of just returning the distance for the nth POI, it will also return the id of that POI. The names of the columns with the poi ids will be poi1, poi2, etc - it will take roughly twice as long to include these ids as to not include them Returns ------- d : Pandas DataFrame Like aggregate, this series has an index of all the node ids for the network. Unlike aggregate, this method returns a dataframe with the number of columns equal to the distances to the Nth closest poi. For instance, if you ask for the 10 closest poi to each node, column d[1] wil be the distance to the 1st closest poi of that category while column d[2] will be the distance to the 2nd closest poi, and so on.
[ "Find", "the", "distance", "to", "the", "nearest", "pois", "from", "each", "source", "node", ".", "The", "bigger", "values", "in", "this", "case", "mean", "less", "accessibility", "." ]
python
test
saltstack/salt
salt/utils/asynchronous.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/asynchronous.py#L15-L24
def current_ioloop(io_loop): ''' A context manager that will set the current ioloop to io_loop for the context ''' orig_loop = tornado.ioloop.IOLoop.current() io_loop.make_current() try: yield finally: orig_loop.make_current()
[ "def", "current_ioloop", "(", "io_loop", ")", ":", "orig_loop", "=", "tornado", ".", "ioloop", ".", "IOLoop", ".", "current", "(", ")", "io_loop", ".", "make_current", "(", ")", "try", ":", "yield", "finally", ":", "orig_loop", ".", "make_current", "(", ...
A context manager that will set the current ioloop to io_loop for the context
[ "A", "context", "manager", "that", "will", "set", "the", "current", "ioloop", "to", "io_loop", "for", "the", "context" ]
python
train
ValvePython/steam
steam/util/binary.py
https://github.com/ValvePython/steam/blob/2de1364c47598410b572114e6129eab8fff71d5b/steam/util/binary.py#L51-L61
def unpack(self, format_text): """Unpack bytes using struct modules format :param format_text: struct's module format :type format_text: :class:`str` :return data: result from :func:`struct.unpack_from` :rtype: :class:`tuple` """ data = _unpack_from(format_text, self.data, self.offset) self.offset += _calcsize(format_text) return data
[ "def", "unpack", "(", "self", ",", "format_text", ")", ":", "data", "=", "_unpack_from", "(", "format_text", ",", "self", ".", "data", ",", "self", ".", "offset", ")", "self", ".", "offset", "+=", "_calcsize", "(", "format_text", ")", "return", "data" ]
Unpack bytes using struct modules format :param format_text: struct's module format :type format_text: :class:`str` :return data: result from :func:`struct.unpack_from` :rtype: :class:`tuple`
[ "Unpack", "bytes", "using", "struct", "modules", "format" ]
python
train
cltrudeau/django-flowr
flowr/models.py
https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L226-L236
def ancestors(self): """Returns a list of the ancestors of this node.""" ancestors = set([]) self._depth_ascend(self, ancestors) try: ancestors.remove(self) except KeyError: # we weren't ancestor of ourself, that's ok pass return list(ancestors)
[ "def", "ancestors", "(", "self", ")", ":", "ancestors", "=", "set", "(", "[", "]", ")", "self", ".", "_depth_ascend", "(", "self", ",", "ancestors", ")", "try", ":", "ancestors", ".", "remove", "(", "self", ")", "except", "KeyError", ":", "# we weren't...
Returns a list of the ancestors of this node.
[ "Returns", "a", "list", "of", "the", "ancestors", "of", "this", "node", "." ]
python
valid
numenta/nupic
src/nupic/database/connection.py
https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/connection.py#L643-L656
def _getCommonSteadyDBArgsDict(): """ Returns a dictionary of arguments for DBUtils.SteadyDB.SteadyDBConnection constructor. """ return dict( creator = pymysql, host = Configuration.get('nupic.cluster.database.host'), port = int(Configuration.get('nupic.cluster.database.port')), user = Configuration.get('nupic.cluster.database.user'), passwd = Configuration.get('nupic.cluster.database.passwd'), charset = 'utf8', use_unicode = True, setsession = ['SET AUTOCOMMIT = 1'])
[ "def", "_getCommonSteadyDBArgsDict", "(", ")", ":", "return", "dict", "(", "creator", "=", "pymysql", ",", "host", "=", "Configuration", ".", "get", "(", "'nupic.cluster.database.host'", ")", ",", "port", "=", "int", "(", "Configuration", ".", "get", "(", "'...
Returns a dictionary of arguments for DBUtils.SteadyDB.SteadyDBConnection constructor.
[ "Returns", "a", "dictionary", "of", "arguments", "for", "DBUtils", ".", "SteadyDB", ".", "SteadyDBConnection", "constructor", "." ]
python
valid
pycontribs/pyrax
pyrax/cloudmonitoring.py
https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/cloudmonitoring.py#L1321-L1327
def update_alarm(self, entity, alarm, criteria=None, disabled=False, label=None, name=None, metadata=None): """ Updates an existing alarm on the given entity. """ return entity.update_alarm(alarm, criteria=criteria, disabled=disabled, label=label, name=name, metadata=metadata)
[ "def", "update_alarm", "(", "self", ",", "entity", ",", "alarm", ",", "criteria", "=", "None", ",", "disabled", "=", "False", ",", "label", "=", "None", ",", "name", "=", "None", ",", "metadata", "=", "None", ")", ":", "return", "entity", ".", "updat...
Updates an existing alarm on the given entity.
[ "Updates", "an", "existing", "alarm", "on", "the", "given", "entity", "." ]
python
train
gtalarico/airtable-python-wrapper
airtable/airtable.py
https://github.com/gtalarico/airtable-python-wrapper/blob/48b2d806178085b52a31817571e5a1fc3dce4045/airtable/airtable.py#L420-L445
def update_by_field(self, field_name, field_value, fields, typecast=False, **options): """ Updates the first record to match field name and value. Only Fields passed are updated, the rest are left as is. >>> record = {'Name': 'John', 'Tel': '540-255-5522'} >>> airtable.update_by_field('Name', 'John', record) Args: field_name (``str``): Name of field to match (column name). field_value (``str``): Value of field to match. fields(``dict``): Fields to update. Must be dictionary with Column names as Key typecast(``boolean``): Automatic data conversion from string values. Keyword Args: view (``str``, optional): The name or ID of a view. See :any:`ViewParam`. sort (``list``, optional): List of fields to sort by. Default order is ascending. See :any:`SortParam`. Returns: record (``dict``): Updated record """ record = self.match(field_name, field_value, **options) return {} if not record else self.update(record['id'], fields, typecast)
[ "def", "update_by_field", "(", "self", ",", "field_name", ",", "field_value", ",", "fields", ",", "typecast", "=", "False", ",", "*", "*", "options", ")", ":", "record", "=", "self", ".", "match", "(", "field_name", ",", "field_value", ",", "*", "*", "...
Updates the first record to match field name and value. Only Fields passed are updated, the rest are left as is. >>> record = {'Name': 'John', 'Tel': '540-255-5522'} >>> airtable.update_by_field('Name', 'John', record) Args: field_name (``str``): Name of field to match (column name). field_value (``str``): Value of field to match. fields(``dict``): Fields to update. Must be dictionary with Column names as Key typecast(``boolean``): Automatic data conversion from string values. Keyword Args: view (``str``, optional): The name or ID of a view. See :any:`ViewParam`. sort (``list``, optional): List of fields to sort by. Default order is ascending. See :any:`SortParam`. Returns: record (``dict``): Updated record
[ "Updates", "the", "first", "record", "to", "match", "field", "name", "and", "value", ".", "Only", "Fields", "passed", "are", "updated", "the", "rest", "are", "left", "as", "is", ".", ">>>", "record", "=", "{", "Name", ":", "John", "Tel", ":", "540", ...
python
train
acrisci/i3ipc-python
i3ipc/i3ipc.py
https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L534-L549
def get_bar_config(self, bar_id=None): """ Get the configuration of a single bar. Defaults to the first if none is specified. Use :meth:`get_bar_config_list` to obtain a list of valid IDs. :rtype: BarConfigReply """ if not bar_id: bar_config_list = self.get_bar_config_list() if not bar_config_list: return None bar_id = bar_config_list[0] data = self.message(MessageType.GET_BAR_CONFIG, bar_id) return json.loads(data, object_hook=BarConfigReply)
[ "def", "get_bar_config", "(", "self", ",", "bar_id", "=", "None", ")", ":", "if", "not", "bar_id", ":", "bar_config_list", "=", "self", ".", "get_bar_config_list", "(", ")", "if", "not", "bar_config_list", ":", "return", "None", "bar_id", "=", "bar_config_li...
Get the configuration of a single bar. Defaults to the first if none is specified. Use :meth:`get_bar_config_list` to obtain a list of valid IDs. :rtype: BarConfigReply
[ "Get", "the", "configuration", "of", "a", "single", "bar", ".", "Defaults", "to", "the", "first", "if", "none", "is", "specified", ".", "Use", ":", "meth", ":", "get_bar_config_list", "to", "obtain", "a", "list", "of", "valid", "IDs", "." ]
python
train
MillionIntegrals/vel
vel/util/intepolate.py
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/util/intepolate.py#L48-L50
def interpolate_series(start, end, steps, how='linear'): """ Interpolate series between start and end in given number of steps """ return INTERP_DICT[how](start, end, steps)
[ "def", "interpolate_series", "(", "start", ",", "end", ",", "steps", ",", "how", "=", "'linear'", ")", ":", "return", "INTERP_DICT", "[", "how", "]", "(", "start", ",", "end", ",", "steps", ")" ]
Interpolate series between start and end in given number of steps
[ "Interpolate", "series", "between", "start", "and", "end", "in", "given", "number", "of", "steps" ]
python
train
Qiskit/qiskit-terra
qiskit/visualization/text.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/text.py#L473-L481
def dump(self, filename, encoding="utf8"): """ Dumps the ascii art in the file. Args: filename (str): File to dump the ascii art. encoding (str): Optional. Default "utf-8". """ with open(filename, mode='w', encoding=encoding) as text_file: text_file.write(self.single_string())
[ "def", "dump", "(", "self", ",", "filename", ",", "encoding", "=", "\"utf8\"", ")", ":", "with", "open", "(", "filename", ",", "mode", "=", "'w'", ",", "encoding", "=", "encoding", ")", "as", "text_file", ":", "text_file", ".", "write", "(", "self", ...
Dumps the ascii art in the file. Args: filename (str): File to dump the ascii art. encoding (str): Optional. Default "utf-8".
[ "Dumps", "the", "ascii", "art", "in", "the", "file", ".", "Args", ":", "filename", "(", "str", ")", ":", "File", "to", "dump", "the", "ascii", "art", ".", "encoding", "(", "str", ")", ":", "Optional", ".", "Default", "utf", "-", "8", "." ]
python
test
raiden-network/raiden
raiden/transfer/merkle_tree.py
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/merkle_tree.py#L16-L33
def hash_pair(first: Keccak256, second: Optional[Keccak256]) -> Keccak256: """ Computes the keccak hash of the elements ordered topologically. Since a merkle proof will not include all the elements, but only the path starting from the leaves up to the root, the order of the elements is not known by the proof checker. The topological order is used as a deterministic way of ordering the elements making sure the smart contract verification and the python code are compatible. """ assert first is not None if second is None: return first if first > second: return sha3(second + first) return sha3(first + second)
[ "def", "hash_pair", "(", "first", ":", "Keccak256", ",", "second", ":", "Optional", "[", "Keccak256", "]", ")", "->", "Keccak256", ":", "assert", "first", "is", "not", "None", "if", "second", "is", "None", ":", "return", "first", "if", "first", ">", "s...
Computes the keccak hash of the elements ordered topologically. Since a merkle proof will not include all the elements, but only the path starting from the leaves up to the root, the order of the elements is not known by the proof checker. The topological order is used as a deterministic way of ordering the elements making sure the smart contract verification and the python code are compatible.
[ "Computes", "the", "keccak", "hash", "of", "the", "elements", "ordered", "topologically", "." ]
python
train
oz123/blogit
blogit/blogit.py
https://github.com/oz123/blogit/blob/15b94969fa43aaf8dc677a8184b144ae8c0f7700/blogit/blogit.py#L349-L354
def render_archive(entries): """Creates the archive page""" context = GLOBAL_TEMPLATE_CONTEXT.copy() context['entries'] = entries _render(context, 'archive_index.html', os.path.join(CONFIG['output_to'], 'archive/index.html')),
[ "def", "render_archive", "(", "entries", ")", ":", "context", "=", "GLOBAL_TEMPLATE_CONTEXT", ".", "copy", "(", ")", "context", "[", "'entries'", "]", "=", "entries", "_render", "(", "context", ",", "'archive_index.html'", ",", "os", ".", "path", ".", "join"...
Creates the archive page
[ "Creates", "the", "archive", "page" ]
python
train
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/textio.py
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/textio.py#L1799-L1814
def __logfile_error(self, e): """ Shows an error message to standard error if the log file can't be written to. Used internally. @type e: Exception @param e: Exception raised when trying to write to the log file. """ from sys import stderr msg = "Warning, error writing log file %s: %s\n" msg = msg % (self.logfile, str(e)) stderr.write(DebugLog.log_text(msg)) self.logfile = None self.fd = None
[ "def", "__logfile_error", "(", "self", ",", "e", ")", ":", "from", "sys", "import", "stderr", "msg", "=", "\"Warning, error writing log file %s: %s\\n\"", "msg", "=", "msg", "%", "(", "self", ".", "logfile", ",", "str", "(", "e", ")", ")", "stderr", ".", ...
Shows an error message to standard error if the log file can't be written to. Used internally. @type e: Exception @param e: Exception raised when trying to write to the log file.
[ "Shows", "an", "error", "message", "to", "standard", "error", "if", "the", "log", "file", "can", "t", "be", "written", "to", "." ]
python
train
rueckstiess/mtools
mtools/mlogfilter/filters/logline_filter.py
https://github.com/rueckstiess/mtools/blob/a6a22910c3569c0c8a3908660ca218a4557e4249/mtools/mlogfilter/filters/logline_filter.py#L124-L152
def accept(self, logevent): """ Process line. Overwrite BaseFilter.accept() and return True if the provided logevent should be accepted (causing output), or False if not. """ # if several filters are active, all have to agree if self.components and logevent.component not in self.components: return False if self.levels and logevent.level not in self.levels: return False if self.namespaces and logevent.namespace not in self.namespaces: return False if self.commands and logevent.command not in self.commands: return False if self.operations and logevent.operation not in self.operations: return False if self.threads: if (logevent.thread not in self.threads and logevent.conn not in self.threads): return False if self.pattern and logevent.pattern != self.pattern: return False if (self.planSummaries and logevent.planSummary not in self.planSummaries): return False return True
[ "def", "accept", "(", "self", ",", "logevent", ")", ":", "# if several filters are active, all have to agree", "if", "self", ".", "components", "and", "logevent", ".", "component", "not", "in", "self", ".", "components", ":", "return", "False", "if", "self", "."...
Process line. Overwrite BaseFilter.accept() and return True if the provided logevent should be accepted (causing output), or False if not.
[ "Process", "line", "." ]
python
train
Qiskit/qiskit-terra
qiskit/providers/basicaer/basicaertools.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/basicaertools.py#L127-L175
def _einsum_matmul_index_helper(gate_indices, number_of_qubits): """Return the index string for Numpy.eignsum matrix multiplication. The returned indices are to perform a matrix multiplication A.v where the matrix A is an M-qubit matrix, matrix v is an N-qubit vector, and M <= N, and identity matrices are implied on the subsystems where A has no support on v. Args: gate_indices (list[int]): the indices of the right matrix subsystems to contract with the left matrix. number_of_qubits (int): the total number of qubits for the right matrix. Returns: tuple: (mat_left, mat_right, tens_in, tens_out) of index strings for that may be combined into a Numpy.einsum function string. Raises: QiskitError: if the total number of qubits plus the number of contracted indices is greater than 26. """ # Since we use ASCII alphabet for einsum index labels we are limited # to 26 total free left (lowercase) and 26 right (uppercase) indexes. # The rank of the contracted tensor reduces this as we need to use that # many characters for the contracted indices if len(gate_indices) + number_of_qubits > 26: raise QiskitError("Total number of free indexes limited to 26") # Indicies for N-qubit input tensor tens_in = ascii_lowercase[:number_of_qubits] # Indices for the N-qubit output tensor tens_out = list(tens_in) # Left and right indices for the M-qubit multiplying tensor mat_left = "" mat_right = "" # Update left indices for mat and output for pos, idx in enumerate(reversed(gate_indices)): mat_left += ascii_lowercase[-1 - pos] mat_right += tens_in[-1 - idx] tens_out[-1 - idx] = ascii_lowercase[-1 - pos] tens_out = "".join(tens_out) # Combine indices into matrix multiplication string format # for numpy.einsum function return mat_left, mat_right, tens_in, tens_out
[ "def", "_einsum_matmul_index_helper", "(", "gate_indices", ",", "number_of_qubits", ")", ":", "# Since we use ASCII alphabet for einsum index labels we are limited", "# to 26 total free left (lowercase) and 26 right (uppercase) indexes.", "# The rank of the contracted tensor reduces this as we n...
Return the index string for Numpy.eignsum matrix multiplication. The returned indices are to perform a matrix multiplication A.v where the matrix A is an M-qubit matrix, matrix v is an N-qubit vector, and M <= N, and identity matrices are implied on the subsystems where A has no support on v. Args: gate_indices (list[int]): the indices of the right matrix subsystems to contract with the left matrix. number_of_qubits (int): the total number of qubits for the right matrix. Returns: tuple: (mat_left, mat_right, tens_in, tens_out) of index strings for that may be combined into a Numpy.einsum function string. Raises: QiskitError: if the total number of qubits plus the number of contracted indices is greater than 26.
[ "Return", "the", "index", "string", "for", "Numpy", ".", "eignsum", "matrix", "multiplication", "." ]
python
test
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1385-L1416
def sepconv_relu_sepconv(inputs, filter_size, output_size, first_kernel_size=(1, 1), second_kernel_size=(1, 1), padding="LEFT", nonpadding_mask=None, dropout=0.0, name=None): """Hidden layer with RELU activation followed by linear projection.""" with tf.variable_scope(name, "sepconv_relu_sepconv", [inputs]): inputs = maybe_zero_out_padding(inputs, first_kernel_size, nonpadding_mask) if inputs.get_shape().ndims == 3: is_3d = True inputs = tf.expand_dims(inputs, 2) else: is_3d = False h = separable_conv( inputs, filter_size, first_kernel_size, activation=tf.nn.relu, padding=padding, name="conv1") if dropout != 0.0: h = tf.nn.dropout(h, 1.0 - dropout) h = maybe_zero_out_padding(h, second_kernel_size, nonpadding_mask) ret = separable_conv( h, output_size, second_kernel_size, padding=padding, name="conv2") if is_3d: ret = tf.squeeze(ret, 2) return ret
[ "def", "sepconv_relu_sepconv", "(", "inputs", ",", "filter_size", ",", "output_size", ",", "first_kernel_size", "=", "(", "1", ",", "1", ")", ",", "second_kernel_size", "=", "(", "1", ",", "1", ")", ",", "padding", "=", "\"LEFT\"", ",", "nonpadding_mask", ...
Hidden layer with RELU activation followed by linear projection.
[ "Hidden", "layer", "with", "RELU", "activation", "followed", "by", "linear", "projection", "." ]
python
train
roboogle/gtkmvc3
gtkmvco/gtkmvc3/adapters/containers.py
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/adapters/containers.py#L165-L177
def update_widget(self, idx=None): """Forces the widget at given index to be updated from the property value. If index is not given, all controlled widgets will be updated. This method should be called directly by the user when the property is not observable, or in very unusual conditions.""" if idx is None: for w in self._widgets: idx = self._get_idx_from_widget(w) self._write_widget(self._read_property(idx), idx) pass else: self._write_widget(self._read_property(idx), idx) return
[ "def", "update_widget", "(", "self", ",", "idx", "=", "None", ")", ":", "if", "idx", "is", "None", ":", "for", "w", "in", "self", ".", "_widgets", ":", "idx", "=", "self", ".", "_get_idx_from_widget", "(", "w", ")", "self", ".", "_write_widget", "(",...
Forces the widget at given index to be updated from the property value. If index is not given, all controlled widgets will be updated. This method should be called directly by the user when the property is not observable, or in very unusual conditions.
[ "Forces", "the", "widget", "at", "given", "index", "to", "be", "updated", "from", "the", "property", "value", ".", "If", "index", "is", "not", "given", "all", "controlled", "widgets", "will", "be", "updated", ".", "This", "method", "should", "be", "called"...
python
train
androguard/androguard
androguard/core/bytecodes/apk.py
https://github.com/androguard/androguard/blob/984c0d981be2950cf0451e484f7b0d4d53bc4911/androguard/core/bytecodes/apk.py#L1082-L1093
def get_main_activity(self): """ Return the name of the main activity This value is read from the AndroidManifest.xml :rtype: str """ activities = self.get_main_activities() if len(activities) > 0: return self._format_value(activities.pop()) return None
[ "def", "get_main_activity", "(", "self", ")", ":", "activities", "=", "self", ".", "get_main_activities", "(", ")", "if", "len", "(", "activities", ")", ">", "0", ":", "return", "self", ".", "_format_value", "(", "activities", ".", "pop", "(", ")", ")", ...
Return the name of the main activity This value is read from the AndroidManifest.xml :rtype: str
[ "Return", "the", "name", "of", "the", "main", "activity" ]
python
train
saltstack/salt
salt/states/selinux.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/selinux.py#L318-L396
def fcontext_policy_present(name, sel_type, filetype='a', sel_user=None, sel_level=None): ''' .. versionadded:: 2017.7.0 Makes sure a SELinux policy for a given filespec (name), filetype and SELinux context type is present. name filespec of the file or directory. Regex syntax is allowed. sel_type SELinux context type. There are many. filetype The SELinux filetype specification. Use one of [a, f, d, c, b, s, l, p]. See also `man semanage-fcontext`. Defaults to 'a' (all files). sel_user The SELinux user. sel_level The SELinux MLS range. ''' ret = {'name': name, 'result': False, 'changes': {}, 'comment': ''} new_state = {} old_state = {} filetype_str = __salt__['selinux.filetype_id_to_string'](filetype) current_state = __salt__['selinux.fcontext_get_policy']( name=name, filetype=filetype, sel_type=sel_type, sel_user=sel_user, sel_level=sel_level) if not current_state: new_state = {name: {'filetype': filetype_str, 'sel_type': sel_type}} if __opts__['test']: ret.update({'result': None}) else: add_ret = __salt__['selinux.fcontext_add_policy']( name=name, filetype=filetype, sel_type=sel_type, sel_user=sel_user, sel_level=sel_level) if add_ret['retcode'] != 0: ret.update({'comment': 'Error adding new rule: {0}'.format(add_ret)}) else: ret.update({'result': True}) else: if current_state['sel_type'] != sel_type: old_state.update({name: {'sel_type': current_state['sel_type']}}) new_state.update({name: {'sel_type': sel_type}}) else: ret.update({'result': True, 'comment': 'SELinux policy for "{0}" already present '.format(name) + 'with specified filetype "{0}" and sel_type "{1}".'.format( filetype_str, sel_type)}) return ret # Removal of current rule is not neccesary, since adding a new rule for the same # filespec and the same filetype automatically overwrites if __opts__['test']: ret.update({'result': None}) else: change_ret = __salt__['selinux.fcontext_add_policy']( name=name, filetype=filetype, sel_type=sel_type, sel_user=sel_user, sel_level=sel_level) if change_ret['retcode'] != 0: ret.update({'comment': 'Error adding new rule: {0}'.format(change_ret)}) else: ret.update({'result': True}) if ret['result'] and (new_state or old_state): ret['changes'].update({'old': old_state, 'new': new_state}) return ret
[ "def", "fcontext_policy_present", "(", "name", ",", "sel_type", ",", "filetype", "=", "'a'", ",", "sel_user", "=", "None", ",", "sel_level", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "False", ",", "'changes'", ...
.. versionadded:: 2017.7.0 Makes sure a SELinux policy for a given filespec (name), filetype and SELinux context type is present. name filespec of the file or directory. Regex syntax is allowed. sel_type SELinux context type. There are many. filetype The SELinux filetype specification. Use one of [a, f, d, c, b, s, l, p]. See also `man semanage-fcontext`. Defaults to 'a' (all files). sel_user The SELinux user. sel_level The SELinux MLS range.
[ "..", "versionadded", "::", "2017", ".", "7", ".", "0" ]
python
train
jilljenn/tryalgo
tryalgo/dfs.py
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/dfs.py#L66-L82
def dfs_grid_recursive(grid, i, j, mark='X', free='.'): """DFS on a grid, mark connected component, iterative version :param grid: matrix, 4-neighborhood :param i,j: cell in this matrix, start of DFS exploration :param free: symbol for walkable cells :param mark: symbol to overwrite visited vertices :complexity: linear """ height = len(grid) width = len(grid[0]) grid[i][j] = mark # mark path for ni, nj in [(i + 1, j), (i, j + 1), (i - 1, j), (i, j - 1)]: if 0 <= ni < height and 0 <= nj < width: if grid[ni][nj] == free: dfs_grid(grid, ni, nj)
[ "def", "dfs_grid_recursive", "(", "grid", ",", "i", ",", "j", ",", "mark", "=", "'X'", ",", "free", "=", "'.'", ")", ":", "height", "=", "len", "(", "grid", ")", "width", "=", "len", "(", "grid", "[", "0", "]", ")", "grid", "[", "i", "]", "["...
DFS on a grid, mark connected component, iterative version :param grid: matrix, 4-neighborhood :param i,j: cell in this matrix, start of DFS exploration :param free: symbol for walkable cells :param mark: symbol to overwrite visited vertices :complexity: linear
[ "DFS", "on", "a", "grid", "mark", "connected", "component", "iterative", "version" ]
python
train
ubyssey/dispatch
dispatch/api/views.py
https://github.com/ubyssey/dispatch/blob/8da6084fe61726f20e9cf675190480cfc45ee764/dispatch/api/views.py#L76-L112
def get_queryset(self): """Optionally restricts the returned articles by filtering against a `topic` query parameter in the URL.""" # Get base queryset from DispatchPublishableMixin queryset = self.get_publishable_queryset() # Optimize queries by prefetching related data queryset = queryset \ .select_related('featured_image', 'featured_video', 'topic', 'section', 'subsection') \ .prefetch_related( 'tags', 'featured_image__image__authors', 'authors' ) queryset = queryset.order_by('-updated_at') q = self.request.query_params.get('q', None) section = self.request.query_params.get('section', None) tags = self.request.query_params.getlist('tags', None) author = self.request.query_params.get('author', None) if q is not None: queryset = queryset.filter(headline__icontains=q) if section is not None: queryset = queryset.filter(section_id=section) if tags is not None: for tag in tags: queryset = queryset.filter(tags__id=tag) if author is not None: queryset = queryset.filter(authors__person_id=author) return queryset
[ "def", "get_queryset", "(", "self", ")", ":", "# Get base queryset from DispatchPublishableMixin", "queryset", "=", "self", ".", "get_publishable_queryset", "(", ")", "# Optimize queries by prefetching related data", "queryset", "=", "queryset", ".", "select_related", "(", ...
Optionally restricts the returned articles by filtering against a `topic` query parameter in the URL.
[ "Optionally", "restricts", "the", "returned", "articles", "by", "filtering", "against", "a", "topic", "query", "parameter", "in", "the", "URL", "." ]
python
test
CEA-COSMIC/ModOpt
modopt/base/transform.py
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/transform.py#L16-L60
def cube2map(data_cube, layout): r"""Cube to Map This method transforms the input data from a 3D cube to a 2D map with a specified layout Parameters ---------- data_cube : np.ndarray Input data cube, 3D array of 2D images Layout : tuple 2D layout of 2D images Returns ------- np.ndarray 2D map Raises ------ ValueError For invalid data dimensions ValueError For invalid layout Examples -------- >>> from modopt.base.transform import cube2map >>> a = np.arange(16).reshape((4, 2, 2)) >>> cube2map(a, (2, 2)) array([[ 0, 1, 4, 5], [ 2, 3, 6, 7], [ 8, 9, 12, 13], [10, 11, 14, 15]]) """ if data_cube.ndim != 3: raise ValueError('The input data must have 3 dimensions.') if data_cube.shape[0] != np.prod(layout): raise ValueError('The desired layout must match the number of input ' 'data layers.') return np.vstack([np.hstack(data_cube[slice(layout[1] * i, layout[1] * (i + 1))]) for i in range(layout[0])])
[ "def", "cube2map", "(", "data_cube", ",", "layout", ")", ":", "if", "data_cube", ".", "ndim", "!=", "3", ":", "raise", "ValueError", "(", "'The input data must have 3 dimensions.'", ")", "if", "data_cube", ".", "shape", "[", "0", "]", "!=", "np", ".", "pro...
r"""Cube to Map This method transforms the input data from a 3D cube to a 2D map with a specified layout Parameters ---------- data_cube : np.ndarray Input data cube, 3D array of 2D images Layout : tuple 2D layout of 2D images Returns ------- np.ndarray 2D map Raises ------ ValueError For invalid data dimensions ValueError For invalid layout Examples -------- >>> from modopt.base.transform import cube2map >>> a = np.arange(16).reshape((4, 2, 2)) >>> cube2map(a, (2, 2)) array([[ 0, 1, 4, 5], [ 2, 3, 6, 7], [ 8, 9, 12, 13], [10, 11, 14, 15]])
[ "r", "Cube", "to", "Map" ]
python
train
bcbio/bcbio-nextgen
bcbio/variation/vcfutils.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/vcfutils.py#L326-L335
def _check_samples_nodups(fnames): """Ensure a set of input VCFs do not have duplicate samples. """ counts = defaultdict(int) for f in fnames: for s in get_samples(f): counts[s] += 1 duplicates = [s for s, c in counts.items() if c > 1] if duplicates: raise ValueError("Duplicate samples found in inputs %s: %s" % (duplicates, fnames))
[ "def", "_check_samples_nodups", "(", "fnames", ")", ":", "counts", "=", "defaultdict", "(", "int", ")", "for", "f", "in", "fnames", ":", "for", "s", "in", "get_samples", "(", "f", ")", ":", "counts", "[", "s", "]", "+=", "1", "duplicates", "=", "[", ...
Ensure a set of input VCFs do not have duplicate samples.
[ "Ensure", "a", "set", "of", "input", "VCFs", "do", "not", "have", "duplicate", "samples", "." ]
python
train
iotile/coretools
transport_plugins/native_ble/iotile_transport_native_ble/connection_manager.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/native_ble/iotile_transport_native_ble/connection_manager.py#L491-L524
def _force_disconnect_action(self, action): """Forcibly disconnect a device. Args: action (ConnectionAction): the action object describing what we are forcibly disconnecting """ conn_key = action.data['id'] if self._get_connection_state(conn_key) == self.Disconnected: return data = self._get_connection(conn_key) # If there are any operations in progress, cancel them cleanly if data['state'] == self.Connecting: callback = data['action'].data['callback'] callback(data['connection_id'], self.id, False, 'Unexpected disconnection') elif data['state'] == self.Disconnecting: callback = data['action'].data['callback'] callback(data['connection_id'], self.id, True, None) elif data['state'] == self.InProgress: callback = data['action'].data['callback'] if data['microstate'] == 'rpc': callback(False, 'Unexpected disconnection', 0xFF, None) elif data['microstate'] == 'open_interface': callback(False, 'Unexpected disconnection') elif data['microstate'] == 'close_interface': callback(False, 'Unexpected disconnection') connection_id = data['connection_id'] internal_id = data['internal_id'] del self._connections[connection_id] del self._int_connections[internal_id]
[ "def", "_force_disconnect_action", "(", "self", ",", "action", ")", ":", "conn_key", "=", "action", ".", "data", "[", "'id'", "]", "if", "self", ".", "_get_connection_state", "(", "conn_key", ")", "==", "self", ".", "Disconnected", ":", "return", "data", "...
Forcibly disconnect a device. Args: action (ConnectionAction): the action object describing what we are forcibly disconnecting
[ "Forcibly", "disconnect", "a", "device", "." ]
python
train
SoCo/SoCo
dev_tools/analyse_ws.py
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/dev_tools/analyse_ws.py#L434-L489
def __build_option_parser(): """ Build the option parser for this script """ description = """ Tool to analyze Wireshark dumps of Sonos traffic. The files that are input to this script must be in the "Wireshark/tcpdump/...-libpcap" format, which can be exported from Wireshark. To use the open in browser function, a configuration file must be written. It should be in the same directory as this script and have the name "analyse_ws.ini". An example of such a file is given below ({0} indicates the file): [General] browser_command: epiphany {0} The browser command should be any command that opens a new tab in the program you wish to read the Wireshark dumps in. Separating Sonos traffic out from the rest of the network traffic is tricky. Therefore, it will in all likelyhood increase the succes of this tool, if the traffic is filtered in Wireshark to only show traffic to and from the Sonos unit. Still, if the analysis fails, then use the debug mode. This will show you the analysis of the traffic packet by packet and give you packet numbers so you can find and analyze problematic packets in Wireshark. """ description = textwrap.dedent(description).strip() parser = \ argparse.ArgumentParser(description=description, formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('file_', metavar='FILE', type=str, nargs=1, help='the file to analyze') parser.add_argument('-o', '--output-prefix', type=str, help='the output filename prefix to use') parser.add_argument('-f', '--to-file', action='store_const', const=True, help='output xml to files', default=False) parser.add_argument('-d', '--debug-analysis', action='store_const', const=True, help='writes debug information to file.debug', default=False) parser.add_argument('-m', '--disable-color', action='store_const', const=False, help='disable color in interactive mode', default=COLOR, dest='color') parser.add_argument('-c', '--enable-color', action='store_const', const=True, help='disable color in interactive mode', default=COLOR, dest='color') parser.add_argument('-b', '--to-browser', action='store_const', const=True, help='output xml to browser, implies --to-file', default=False) parser.add_argument('-e', '--external-inner-xml', action='store_const', const=True, help='show the internal separately ' 'encoded xml externally instead of re-integrating it', default=False) return parser
[ "def", "__build_option_parser", "(", ")", ":", "description", "=", "\"\"\"\n Tool to analyze Wireshark dumps of Sonos traffic.\n\n The files that are input to this script must be in the\n \"Wireshark/tcpdump/...-libpcap\" format, which can be exported from\n Wireshark.\n\n To use the op...
Build the option parser for this script
[ "Build", "the", "option", "parser", "for", "this", "script" ]
python
train
chaoss/grimoirelab-elk
grimoire_elk/enriched/enrich.py
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/enrich.py#L867-L872
def get_sh_ids(self, identity, backend_name): """ Return the Sorting Hat id and uuid for an identity """ # Convert the dict to tuple so it is hashable identity_tuple = tuple(identity.items()) sh_ids = self.__get_sh_ids_cache(identity_tuple, backend_name) return sh_ids
[ "def", "get_sh_ids", "(", "self", ",", "identity", ",", "backend_name", ")", ":", "# Convert the dict to tuple so it is hashable", "identity_tuple", "=", "tuple", "(", "identity", ".", "items", "(", ")", ")", "sh_ids", "=", "self", ".", "__get_sh_ids_cache", "(", ...
Return the Sorting Hat id and uuid for an identity
[ "Return", "the", "Sorting", "Hat", "id", "and", "uuid", "for", "an", "identity" ]
python
train
ActivisionGameScience/assertpy
assertpy/assertpy.py
https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L653-L663
def matches(self, pattern): """Asserts that val is string and matches regex pattern.""" if not isinstance(self.val, str_types): raise TypeError('val is not a string') if not isinstance(pattern, str_types): raise TypeError('given pattern arg must be a string') if len(pattern) == 0: raise ValueError('given pattern arg must not be empty') if re.search(pattern, self.val) is None: self._err('Expected <%s> to match pattern <%s>, but did not.' % (self.val, pattern)) return self
[ "def", "matches", "(", "self", ",", "pattern", ")", ":", "if", "not", "isinstance", "(", "self", ".", "val", ",", "str_types", ")", ":", "raise", "TypeError", "(", "'val is not a string'", ")", "if", "not", "isinstance", "(", "pattern", ",", "str_types", ...
Asserts that val is string and matches regex pattern.
[ "Asserts", "that", "val", "is", "string", "and", "matches", "regex", "pattern", "." ]
python
valid
NoviceLive/intellicoder
intellicoder/utils.py
https://github.com/NoviceLive/intellicoder/blob/6cac5ebfce65c370dbebe47756a1789b120ef982/intellicoder/utils.py#L181-L186
def read_files(filenames, with_name=False): """Read many files.""" text = [read_file(filename) for filename in filenames] if with_name: return dict(zip(filenames, text)) return text
[ "def", "read_files", "(", "filenames", ",", "with_name", "=", "False", ")", ":", "text", "=", "[", "read_file", "(", "filename", ")", "for", "filename", "in", "filenames", "]", "if", "with_name", ":", "return", "dict", "(", "zip", "(", "filenames", ",", ...
Read many files.
[ "Read", "many", "files", "." ]
python
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/transforms/linear.py
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/transforms/linear.py#L181-L190
def move(self, move): """Change the translation of this transform by the amount given. Parameters ---------- move : array-like The values to be added to the current translation of the transform. """ move = as_vec4(move, default=(0, 0, 0, 0)) self.translate = self.translate + move
[ "def", "move", "(", "self", ",", "move", ")", ":", "move", "=", "as_vec4", "(", "move", ",", "default", "=", "(", "0", ",", "0", ",", "0", ",", "0", ")", ")", "self", ".", "translate", "=", "self", ".", "translate", "+", "move" ]
Change the translation of this transform by the amount given. Parameters ---------- move : array-like The values to be added to the current translation of the transform.
[ "Change", "the", "translation", "of", "this", "transform", "by", "the", "amount", "given", "." ]
python
train
python/core-workflow
blurb/blurb.py
https://github.com/python/core-workflow/blob/b93c76195f6db382cfcefee334380fb4c68d4e21/blurb/blurb.py#L1204-L1584
def split(*, released=False): """ Split the current Misc/NEWS into a zillion little blurb files. Assumes that the newest version section in Misc/NEWS is under development, and splits those entries into the "next" subdirectory. If the current version has actually been released, use the --released flag. Also runs "blurb populate" for you. """ # note: populate also does chdir $python_root/Misc for you populate() if not os.path.isfile("NEWS"): error("You don't have a Misc/NEWS file!") def global_sections(): global sections return sections sections = set(global_sections()) release_date_marker = "Release date:" whats_new_marker = "What's New in Python " blurbs = Blurbs() accumulator = [] bpo = "0" serial_number = 9999 version = None release_date = None section = None see_also = None no_changes = None security = None blurb_count = 0 version_count = 0 def flush_blurb(): nonlocal accumulator nonlocal serial_number nonlocal bpo nonlocal release_date nonlocal see_also nonlocal no_changes nonlocal blurb_count nonlocal security if accumulator: if version: # strip trailing blank lines while accumulator: line = accumulator.pop() if not line.rstrip(): continue accumulator.append(line) break if see_also: fields = [] see_also = see_also.replace(" and ", ",") for field in see_also.split(","): field = field.strip() if not field: continue if field.startswith("and "): field = field[5:].lstrip() if field.lower().startswith("issue"): field = field[5:].strip() if field.startswith("#"): field = field[1:] try: int(field) field = "bpo-" + field except ValueError: pass fields.append(field) see_also = ", ".join(fields) # print("see_also: ", repr(see_also)) accumulator.append(f("(See also: {see_also})")) see_also = None if not accumulator: return if not (section or no_changes): error("No section for line " + str(line_number) + "!") body = "\n".join(accumulator) + "\n" metadata = {} metadata["bpo"] = bpo metadata["date"] = str(serial_number) if section: metadata["section"] = section else: assert no_changes metadata["nonce"] = nonceify(body) if security: # retroactively change section to "Security" assert section metadata["original section"] = metadata["section"] metadata["section"] = "Security" if release_date is not None: assert not len(blurbs) metadata["release date"] = release_date release_date = None if no_changes is not None: assert not len(blurbs) metadata["no changes"] = "True" no_changes = None blurbs.append((metadata, body)) blurb_count += 1 bpo = "0" serial_number -= 1 accumulator.clear() def flush_version(): global git_add_files nonlocal released nonlocal version_count flush_blurb() if version is None: assert not blurbs, "version should only be None initially, we shouldn't have blurbs yet" return assert blurbs, f("No blurbs defined when flushing version {version}!") output = f("NEWS.d/{version}.rst") if released: # saving merged blurb file for version, e.g. Misc/NEWS.d/3.7.0a1.rst blurbs.save(output) git_add_files.append(output) else: # saving a million old-school blurb next files # with serial numbers instead of dates # e.g. Misc/NEWS.d/next/IDLE/094.bpo-25514.882pXa.rst filenames = blurbs.save_split_next() git_add_files.extend(filenames) released = True blurbs.clear() version_count += 1 with open("NEWS", "rt", encoding="utf-8") as file: for line_number, line in enumerate(file): line = line.rstrip() if line.startswith("\ufeff"): line = line[1:] # clean the slightly dirty data: # 1. inconsistent names for sections, etc for old, new in ( ("C-API", "C API"), ("Core and builtins", "Core and Builtins"), ("Tools", "Tools/Demos"), ("Tools / Demos", "Tools/Demos"), ("Misc", "Windows"), # only used twice, both were really Windows ("Mac", "macOS"), ("Mac OS X", "macOS"), ("Extension Modules", "Library"), ("Whats' New in Python 2.7.6?", "What's New in Python 2.7.6?"), ): if line == old: line = new # 2. unusual indenting _line = line.lstrip() if _line.startswith(("- Issue #", "- bpo-")): line = _line if _line == ".characters() and ignorableWhitespace() methods. Original patch by Sebastian": line = " " + line # 3. fix version for What's New if line.startswith(whats_new_marker): flush_version() version = line[len(whats_new_marker):].strip().lower() for old, new in ( ("?", ""), (" alpha ", "a"), (" beta ", "b"), (" release candidate ", "rc"), (" final", ""), ("3.5a", "3.5.0a"), ): version = version.replace(old, new) section = None continue # 3.a. fix specific precious little snowflakes # who can't be bothered to follow our stifling style conventions # and like, did their own *thing*, man. if line.startswith("- Issue #27181 remove statistics.geometric_mean"): line = line.replace(" remove", ": remove") elif line.startswith("* bpo-30357: test_thread: setUp()"): line = line.replace("* bpo-30357", "- bpo-30357") elif line.startswith("- Issue #25262. Added support for BINBYTES8"): line = line.replace("#25262.", "#25262:") elif line.startswith("- Issue #21032. Fixed socket leak if"): line = line.replace("#21032.", "#21032:") elif line.startswith("- Issue ##665194: Update "): line = line.replace("##665194", "#665194") elif line.startswith("- Issue #13449 sched.scheduler.run()"): line = line.replace("#13449 sched", "#13449: sched") elif line.startswith("- Issue #8684 sched.scheduler class"): line = line.replace("#8684 sched", "#8684: sched") elif line.startswith(" bpo-29243: Prevent unnecessary rebuilding"): line = line.replace(" bpo-29243:", "- bpo-29243:") elif line.startswith(( "- Issue #11603 (again): Setting", "- Issue #15801 (again): With string", )): line = line.replace(" (again):", ":") elif line.startswith("- Issue #1665206 (partially): "): line = line.replace(" (partially):", ":") elif line.startswith("- Issue #2885 (partial): The"): line = line.replace(" (partial):", ":") elif line.startswith("- Issue #2885 (partial): The"): line = line.replace(" (partial):", ":") elif line.startswith("- Issue #1797 (partial fix):"): line = line.replace(" (partial fix):", ":") elif line.startswith("- Issue #5828 (Invalid behavior of unicode.lower): Fixed bogus logic in"): line = line.replace(" (Invalid behavior of unicode.lower):", ":") elif line.startswith("- Issue #4512 (part 2): Promote ``ZipImporter._get_filename()`` to be a public"): line = line.replace(" (part 2):", ":") elif line.startswith("- Revert bpo-26293 for zipfile breakage. See also bpo-29094."): line = "- bpo-26293, bpo-29094: Change resulted because of zipfile breakage." elif line.startswith("- Revert a37cc3d926ec (Issue #5322)."): line = "- Issue #5322: Revert a37cc3d926ec." elif line.startswith("- Patch #1970 by Antoine Pitrou: Speedup unicode whitespace and"): line = "- Issue #1970: Speedup unicode whitespace and" elif line.startswith(" linebreak detection"): line = " linebreak detection. (Patch by Antoine Pitrou.)" elif line.startswith("- Patch #1182394 from Shane Holloway: speed up HMAC.hexdigest."): line = "- Issue #1182394: Speed up ``HMAC.hexdigest``. (Patch by Shane Holloway.)" elif line.startswith("- Variant of patch #697613: don't exit the interpreter on a SystemExit"): line = "- Issue #697613: Don't exit the interpreter on a SystemExit" elif line.startswith("- Bugs #1668596/#1720897: distutils now copies data files even if"): line = "- Issue #1668596, #1720897: distutils now copies data files even if" elif line.startswith("- Reverted patch #1504333 to sgmllib because it introduced an infinite"): line = "- Issue #1504333: Reverted change to sgmllib because it introduced an infinite" elif line.startswith("- PEP 465 and Issue #21176: Add the '@' operator for matrix multiplication."): line = "- Issue #21176: PEP 465: Add the '@' operator for matrix multiplication." elif line.startswith("- Issue: #15138: base64.urlsafe_{en,de}code() are now 3-4x faster."): line = "- Issue #15138: base64.urlsafe_{en,de}code() are now 3-4x faster." elif line.startswith("- Issue #9516: Issue #9516: avoid errors in sysconfig when MACOSX_DEPLOYMENT_TARGET"): line = "- Issue #9516 and Issue #9516: avoid errors in sysconfig when MACOSX_DEPLOYMENT_TARGET" elif line.title().startswith(("- Request #", "- Bug #", "- Patch #", "- Patches #")): # print(f("FIXING LINE {line_number}: {line!r}")) line = "- Issue #" + line.partition('#')[2] # print(f("FIXED LINE {line_number}: {line!r}")) # else: # print(f("NOT FIXING LINE {line_number}: {line!r}")) # 4. determine the actual content of the line # 4.1 section declaration if line in sections: flush_blurb() section = line continue # 4.2 heading ReST marker if line.startswith(( "===", "---", "---", "+++", "Python News", "**(For information about older versions, consult the HISTORY file.)**", )): continue # 4.3 version release date declaration if line.startswith(release_date_marker) or ( line.startswith("*") and release_date_marker in line): while line.startswith("*"): line = line[1:] while line.endswith("*"): line = line[:-1] release_date = line[len(release_date_marker):].strip() continue # 4.4 no changes declaration if line.strip() in ( '- No changes since release candidate 2', 'No changes from release candidate 2.', 'There were no code changes between 3.5.3rc1 and 3.5.3 final.', 'There were no changes between 3.4.6rc1 and 3.4.6 final.', ): no_changes = True if line.startswith("- "): line = line[2:] accumulator.append(line) continue # 4.5 start of new blurb if line.startswith("- "): flush_blurb() line = line[2:] security = line.startswith("[Security]") if security: line = line[10:].lstrip() if line.startswith("Issue"): line = line[5:].lstrip() if line.startswith("s"): line = line[1:] line = line.lstrip() if line.startswith("#"): line = line[1:].lstrip() parse_bpo = True elif line.startswith("bpo-"): line = line[4:] parse_bpo = True else: # print(f("[[{line_number:8} no bpo]] {line}")) parse_bpo = False if parse_bpo: # GAAAH if line == "17500, and https://github.com/python/pythondotorg/issues/945: Remove": line = "Remove" bpo = "17500" see_also = "https://github.com/python/pythondotorg/issues/945" else: bpo, colon, line = line.partition(":") line = line.lstrip() bpo, comma, see_also = bpo.partition(",") if comma: see_also = see_also.strip() # if it's just an integer, add bpo- to the front try: int(see_also) see_also = "bpo-" + see_also except ValueError: pass else: # - Issue #21529 (CVE-2014-4616) bpo, space_paren, see_also = bpo.partition(" (") if space_paren: see_also = see_also.rstrip(")") else: # - Issue #19544 and Issue #1180: bpo, space_and, see_also = bpo.partition(" and ") if not space_and: bpo, space_and, see_also = bpo.partition(" & ") if space_and: see_also = see_also.replace("Issue #", "bpo-").strip() else: # - Issue #5258/#10642: if site.py bpo, slash, see_also = bpo.partition("/") if space_and: see_also = see_also.replace("#", "bpo-").strip() try: int(bpo) # this will throw if it's not a legal int except ValueError: sys.exit(f("Couldn't convert bpo number to int on line {line_number}! {bpo!r}")) if see_also == "partially": sys.exit(f("What the hell on line {line_number}! {bpo!r}")) # 4.6.1 continuation of blurb elif line.startswith(" "): line = line[2:] # 4.6.2 continuation of blurb elif line.startswith(" * "): line = line[3:] elif line: sys.exit(f("Didn't recognize line {line_number}! {line!r}")) # only add blank lines if we have an initial line in the accumulator if line or accumulator: accumulator.append(line) flush_version() assert git_add_files flush_git_add_files() git_rm_files.append("NEWS") flush_git_rm_files() print(f("Wrote {blurb_count} news items across {version_count} versions.")) print() print("Ready for commit.")
[ "def", "split", "(", "*", ",", "released", "=", "False", ")", ":", "# note: populate also does chdir $python_root/Misc for you", "populate", "(", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "\"NEWS\"", ")", ":", "error", "(", "\"You don't have a Mis...
Split the current Misc/NEWS into a zillion little blurb files. Assumes that the newest version section in Misc/NEWS is under development, and splits those entries into the "next" subdirectory. If the current version has actually been released, use the --released flag. Also runs "blurb populate" for you.
[ "Split", "the", "current", "Misc", "/", "NEWS", "into", "a", "zillion", "little", "blurb", "files", "." ]
python
train
pandas-dev/pandas
pandas/core/series.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/series.py#L523-L538
def compress(self, condition, *args, **kwargs): """ Return selected slices of an array along given axis as a Series. .. deprecated:: 0.24.0 See Also -------- numpy.ndarray.compress """ msg = ("Series.compress(condition) is deprecated. " "Use 'Series[condition]' or " "'np.asarray(series).compress(condition)' instead.") warnings.warn(msg, FutureWarning, stacklevel=2) nv.validate_compress(args, kwargs) return self[condition]
[ "def", "compress", "(", "self", ",", "condition", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "msg", "=", "(", "\"Series.compress(condition) is deprecated. \"", "\"Use 'Series[condition]' or \"", "\"'np.asarray(series).compress(condition)' instead.\"", ")", "warn...
Return selected slices of an array along given axis as a Series. .. deprecated:: 0.24.0 See Also -------- numpy.ndarray.compress
[ "Return", "selected", "slices", "of", "an", "array", "along", "given", "axis", "as", "a", "Series", "." ]
python
train
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-core/ask_sdk_core/utils/viewport.py
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/utils/viewport.py#L147-L246
def get_viewport_profile(request_envelope): # type: (RequestEnvelope) -> ViewportProfile """Utility method, to get viewport profile. The viewport profile is calculated using the shape, current pixel width and height, along with the dpi. If there is no `viewport` value in `request_envelope.context`, then an `ViewportProfile.UNKNOWN_VIEWPORT_PROFILE` is returned. :param request_envelope: The alexa request envelope object :type request_envelope: ask_sdk_model.request_envelope.RequestEnvelope :return: Calculated Viewport Profile enum :rtype: ViewportProfile """ viewport_state = request_envelope.context.viewport if viewport_state: shape = viewport_state.shape current_pixel_width = int(viewport_state.current_pixel_width) current_pixel_height = int(viewport_state.current_pixel_height) dpi = int(viewport_state.dpi) orientation = get_orientation( width=current_pixel_width, height=current_pixel_height) dpi_group = get_dpi_group(dpi=dpi) pixel_width_size_group = get_size(size=current_pixel_width) pixel_height_size_group = get_size(size=current_pixel_height) if (shape is Shape.ROUND and orientation is Orientation.EQUAL and dpi_group is Density.LOW and pixel_width_size_group is Size.XSMALL and pixel_height_size_group is Size.XSMALL): return ViewportProfile.HUB_ROUND_SMALL elif (shape is Shape.RECTANGLE and orientation is Orientation.LANDSCAPE and dpi_group is Density.LOW and pixel_width_size_group <= Size.MEDIUM and pixel_height_size_group <= Size.SMALL): return ViewportProfile.HUB_LANDSCAPE_MEDIUM elif (shape is Shape.RECTANGLE and orientation is Orientation.LANDSCAPE and dpi_group is Density.LOW and pixel_width_size_group >= Size.LARGE and pixel_height_size_group >= Size.SMALL): return ViewportProfile.HUB_LANDSCAPE_LARGE elif (shape is Shape.RECTANGLE and orientation is Orientation.LANDSCAPE and dpi_group is Density.MEDIUM and pixel_width_size_group >= Size.MEDIUM and pixel_height_size_group >= Size.SMALL): return ViewportProfile.MOBILE_LANDSCAPE_MEDIUM elif (shape is Shape.RECTANGLE and orientation is Orientation.PORTRAIT and dpi_group is Density.MEDIUM and pixel_width_size_group >= Size.SMALL and pixel_height_size_group >= Size.MEDIUM): return ViewportProfile.MOBILE_PORTRAIT_MEDIUM elif (shape is Shape.RECTANGLE and orientation is Orientation.LANDSCAPE and dpi_group is Density.MEDIUM and pixel_width_size_group >= Size.SMALL and pixel_height_size_group >= Size.XSMALL): return ViewportProfile.MOBILE_LANDSCAPE_SMALL elif (shape is Shape.RECTANGLE and orientation is Orientation.PORTRAIT and dpi_group is Density.MEDIUM and pixel_width_size_group >= Size.XSMALL and pixel_height_size_group >= Size.SMALL): return ViewportProfile.MOBILE_PORTRAIT_SMALL elif (shape is Shape.RECTANGLE and orientation is Orientation.LANDSCAPE and dpi_group >= Density.HIGH and pixel_width_size_group >= Size.XLARGE and pixel_height_size_group >= Size.MEDIUM): return ViewportProfile.TV_LANDSCAPE_XLARGE elif (shape is Shape.RECTANGLE and orientation is Orientation.PORTRAIT and dpi_group >= Density.HIGH and pixel_width_size_group is Size.XSMALL and pixel_height_size_group is Size.XLARGE): return ViewportProfile.TV_PORTRAIT_MEDIUM elif (shape is Shape.RECTANGLE and orientation is Orientation.LANDSCAPE and dpi_group >= Density.HIGH and pixel_width_size_group is Size.MEDIUM and pixel_height_size_group is Size.SMALL): return ViewportProfile.TV_LANDSCAPE_MEDIUM return ViewportProfile.UNKNOWN_VIEWPORT_PROFILE
[ "def", "get_viewport_profile", "(", "request_envelope", ")", ":", "# type: (RequestEnvelope) -> ViewportProfile", "viewport_state", "=", "request_envelope", ".", "context", ".", "viewport", "if", "viewport_state", ":", "shape", "=", "viewport_state", ".", "shape", "curren...
Utility method, to get viewport profile. The viewport profile is calculated using the shape, current pixel width and height, along with the dpi. If there is no `viewport` value in `request_envelope.context`, then an `ViewportProfile.UNKNOWN_VIEWPORT_PROFILE` is returned. :param request_envelope: The alexa request envelope object :type request_envelope: ask_sdk_model.request_envelope.RequestEnvelope :return: Calculated Viewport Profile enum :rtype: ViewportProfile
[ "Utility", "method", "to", "get", "viewport", "profile", "." ]
python
train
quantopian/zipline
zipline/pipeline/loaders/earnings_estimates.py
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/earnings_estimates.py#L1294-L1336
def merge_split_adjustments_with_overwrites( self, pre, post, overwrites, requested_split_adjusted_columns ): """ Merge split adjustments with the dict containing overwrites. Parameters ---------- pre : dict[str -> dict[int -> list]] The adjustments that occur before the split-adjusted-asof-date. post : dict[str -> dict[int -> list]] The adjustments that occur after the split-adjusted-asof-date. overwrites : dict[str -> dict[int -> list]] The overwrites across all time. Adjustments will be merged into this dictionary. requested_split_adjusted_columns : list of str List of names of split adjusted columns that are being requested. """ for column_name in requested_split_adjusted_columns: # We can do a merge here because the timestamps in 'pre' and # 'post' are guaranteed to not overlap. if pre: # Either empty or contains all columns. for ts in pre[column_name]: add_new_adjustments( overwrites, pre[column_name][ts], column_name, ts ) if post: # Either empty or contains all columns. for ts in post[column_name]: add_new_adjustments( overwrites, post[column_name][ts], column_name, ts )
[ "def", "merge_split_adjustments_with_overwrites", "(", "self", ",", "pre", ",", "post", ",", "overwrites", ",", "requested_split_adjusted_columns", ")", ":", "for", "column_name", "in", "requested_split_adjusted_columns", ":", "# We can do a merge here because the timestamps in...
Merge split adjustments with the dict containing overwrites. Parameters ---------- pre : dict[str -> dict[int -> list]] The adjustments that occur before the split-adjusted-asof-date. post : dict[str -> dict[int -> list]] The adjustments that occur after the split-adjusted-asof-date. overwrites : dict[str -> dict[int -> list]] The overwrites across all time. Adjustments will be merged into this dictionary. requested_split_adjusted_columns : list of str List of names of split adjusted columns that are being requested.
[ "Merge", "split", "adjustments", "with", "the", "dict", "containing", "overwrites", "." ]
python
train
calmjs/calmjs
src/calmjs/dist.py
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/dist.py#L219-L227
def read_egginfo_json(pkg_name, filename=DEFAULT_JSON, working_set=None): """ Read json from egginfo of a package identified by `pkg_name` that's already installed within the current Python environment. """ working_set = working_set or default_working_set dist = find_pkg_dist(pkg_name, working_set=working_set) return read_dist_egginfo_json(dist, filename)
[ "def", "read_egginfo_json", "(", "pkg_name", ",", "filename", "=", "DEFAULT_JSON", ",", "working_set", "=", "None", ")", ":", "working_set", "=", "working_set", "or", "default_working_set", "dist", "=", "find_pkg_dist", "(", "pkg_name", ",", "working_set", "=", ...
Read json from egginfo of a package identified by `pkg_name` that's already installed within the current Python environment.
[ "Read", "json", "from", "egginfo", "of", "a", "package", "identified", "by", "pkg_name", "that", "s", "already", "installed", "within", "the", "current", "Python", "environment", "." ]
python
train
ECESeniorDesign/lazy_record
lazy_record/repo.py
https://github.com/ECESeniorDesign/lazy_record/blob/929d3cc7c2538b0f792365c0d2b0e0d41084c2dd/lazy_record/repo.py#L93-L99
def _standard_items(self, restrictions): """Generate argument pairs for queries like where(id=2)""" standard_items = self._build_where(restrictions, for_in=False) names = ["{}.{} == ?".format(pair[0], pair[1]) for pair in standard_items] values = [item[2] for item in standard_items] return (names, values)
[ "def", "_standard_items", "(", "self", ",", "restrictions", ")", ":", "standard_items", "=", "self", ".", "_build_where", "(", "restrictions", ",", "for_in", "=", "False", ")", "names", "=", "[", "\"{}.{} == ?\"", ".", "format", "(", "pair", "[", "0", "]",...
Generate argument pairs for queries like where(id=2)
[ "Generate", "argument", "pairs", "for", "queries", "like", "where", "(", "id", "=", "2", ")" ]
python
train
kervi/kervi-core
kervi/displays/__init__.py
https://github.com/kervi/kervi-core/blob/3c1e3c8a17a7b4d085d8a28b99180ff2a96b0e23/kervi/displays/__init__.py#L69-L83
def add_page(self, page, default = True): r""" Add a display page to the display. :param page: Page to be added :type display_id: ``DisplayPage`` :param default: True if this page should be shown upon initialization. :type name: ``bool`` """ self._pages[page.page_id] = page page._add_display(self) if default or not self._active_page: self._active_page = page
[ "def", "add_page", "(", "self", ",", "page", ",", "default", "=", "True", ")", ":", "self", ".", "_pages", "[", "page", ".", "page_id", "]", "=", "page", "page", ".", "_add_display", "(", "self", ")", "if", "default", "or", "not", "self", ".", "_ac...
r""" Add a display page to the display. :param page: Page to be added :type display_id: ``DisplayPage`` :param default: True if this page should be shown upon initialization. :type name: ``bool``
[ "r", "Add", "a", "display", "page", "to", "the", "display", "." ]
python
train
osrg/ryu
ryu/lib/packet/packet_utils.py
https://github.com/osrg/ryu/blob/6f906e72c92e10bd0264c9b91a2f7bb85b97780c/ryu/lib/packet/packet_utils.py#L106-L138
def fletcher_checksum(data, offset): """ Fletcher Checksum -- Refer to RFC1008 calling with offset == _FLETCHER_CHECKSUM_VALIDATE will validate the checksum without modifying the buffer; a valid checksum returns 0. """ c0 = 0 c1 = 0 pos = 0 length = len(data) data = bytearray(data) data[offset:offset + 2] = [0] * 2 while pos < length: tlen = min(length - pos, _MODX) for d in data[pos:pos + tlen]: c0 += d c1 += c0 c0 %= 255 c1 %= 255 pos += tlen x = ((length - offset - 1) * c0 - c1) % 255 if x <= 0: x += 255 y = 510 - c0 - x if y > 255: y -= 255 data[offset] = x data[offset + 1] = y return (x << 8) | (y & 0xff)
[ "def", "fletcher_checksum", "(", "data", ",", "offset", ")", ":", "c0", "=", "0", "c1", "=", "0", "pos", "=", "0", "length", "=", "len", "(", "data", ")", "data", "=", "bytearray", "(", "data", ")", "data", "[", "offset", ":", "offset", "+", "2",...
Fletcher Checksum -- Refer to RFC1008 calling with offset == _FLETCHER_CHECKSUM_VALIDATE will validate the checksum without modifying the buffer; a valid checksum returns 0.
[ "Fletcher", "Checksum", "--", "Refer", "to", "RFC1008" ]
python
train
StackStorm/pybind
pybind/nos/v6_0_2f/rbridge_id/crypto/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v6_0_2f/rbridge_id/crypto/__init__.py#L127-L148
def _set_ca(self, v, load=False): """ Setter method for ca, mapped from YANG variable /rbridge_id/crypto/ca (list) If this variable is read-only (config: false) in the source YANG file, then _set_ca is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_ca() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGListType("trustpoint",ca.ca, yang_name="ca", rest_name="ca", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='trustpoint', extensions={u'tailf-common': {u'info': u'Configure TrustpointCA', u'cli-suppress-list-no': None, u'callpoint': u'crypto_ca_cp', u'cli-full-command': None}}), is_container='list', yang_name="ca", rest_name="ca", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Configure TrustpointCA', u'cli-suppress-list-no': None, u'callpoint': u'crypto_ca_cp', u'cli-full-command': None}}, namespace='urn:brocade.com:mgmt:brocade-crypto', defining_module='brocade-crypto', yang_type='list', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """ca must be of a type compatible with list""", 'defined-type': "list", 'generated-type': """YANGDynClass(base=YANGListType("trustpoint",ca.ca, yang_name="ca", rest_name="ca", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='trustpoint', extensions={u'tailf-common': {u'info': u'Configure TrustpointCA', u'cli-suppress-list-no': None, u'callpoint': u'crypto_ca_cp', u'cli-full-command': None}}), is_container='list', yang_name="ca", rest_name="ca", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Configure TrustpointCA', u'cli-suppress-list-no': None, u'callpoint': u'crypto_ca_cp', u'cli-full-command': None}}, namespace='urn:brocade.com:mgmt:brocade-crypto', defining_module='brocade-crypto', yang_type='list', is_config=True)""", }) self.__ca = t if hasattr(self, '_set'): self._set()
[ "def", "_set_ca", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base", "=...
Setter method for ca, mapped from YANG variable /rbridge_id/crypto/ca (list) If this variable is read-only (config: false) in the source YANG file, then _set_ca is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_ca() directly.
[ "Setter", "method", "for", "ca", "mapped", "from", "YANG", "variable", "/", "rbridge_id", "/", "crypto", "/", "ca", "(", "list", ")", "If", "this", "variable", "is", "read", "-", "only", "(", "config", ":", "false", ")", "in", "the", "source", "YANG", ...
python
train
thespacedoctor/tastic
tastic/tastic.py
https://github.com/thespacedoctor/tastic/blob/a0a16cf329a50057906ac3f696bb60b6fcee25e0/tastic/tastic.py#L1197-L1247
def add_note( self, note): """*Add a note to this taskpaper object* **Key Arguments:** - ``note`` -- the note (string) **Return:** - None **Usage:** To add a note to a document, project or task object: .. code-block:: python newNote = doc.add_note(And another note with a link http://www.thespacedoctor.co.uk") """ self.refresh note = note.strip() newNote = self._get_object( regex=re.compile( r'((?<=\n)|(?<=^))(?P<title>\S(?<!-)((?!(: +@|: *\n|: *$)).)*)\s*?(\n|$)(?P<tagString>&&&)?(?P<content>&&&)?', re.UNICODE), objectType="note", content=note ) # ADD DIRECTLY TO CONTENT IF THE PROJECT IS BEING ADDED SPECIFICALLY TO # THIS OBJECT oldContent = self.to_string(indentLevel=1) newContent = self.to_string( indentLevel=1) if self.parent: self.parent._update_document_tree( oldContent=oldContent, newContent=newContent ) self.notes = newNote + self.notes self.content = self.content.replace(self.to_string(indentLevel=0, title=False), self.to_string( indentLevel=0, title=False)) doc = self while doc.parent: doc = doc.parent doc.refresh return newNote[0]
[ "def", "add_note", "(", "self", ",", "note", ")", ":", "self", ".", "refresh", "note", "=", "note", ".", "strip", "(", ")", "newNote", "=", "self", ".", "_get_object", "(", "regex", "=", "re", ".", "compile", "(", "r'((?<=\\n)|(?<=^))(?P<title>\\S(?<!-)((?...
*Add a note to this taskpaper object* **Key Arguments:** - ``note`` -- the note (string) **Return:** - None **Usage:** To add a note to a document, project or task object: .. code-block:: python newNote = doc.add_note(And another note with a link http://www.thespacedoctor.co.uk")
[ "*", "Add", "a", "note", "to", "this", "taskpaper", "object", "*" ]
python
train
ivbeg/qddate
qddate/qdparser.py
https://github.com/ivbeg/qddate/blob/f7730610611f2509ab264bc8d77a902742daf08c/qddate/qdparser.py#L79-L122
def match(self, text, noprefix=False): """Matches date/datetime string against date patterns and returns pattern and parsed date if matched. It's not indeded for common usage, since if successful it returns date as array of numbers and pattern that matched this date :param text: Any human readable string :type date_string: str|unicode :param noprefix: If set True than doesn't use prefix based date patterns filtering settings :type noprefix: bool :return: Returns dicts with `values` as array of representing parsed date and 'pattern' with info about matched pattern if successful, else returns None :rtype: :class:`dict`.""" n = len(text) if self.cachedpats is not None: pats = self.cachedpats else: pats = self.patterns if n > 5 and not noprefix: basekeys = self.__matchPrefix(text[:6]) else: basekeys = [] for p in pats: if n < p['length']['min'] or n > p['length']['max']: continue if p['right'] and len(basekeys) > 0 and p['basekey'] not in basekeys: continue try: r = p['pattern'].parseString(text) # Do sanity check d = r.asDict() if 'month' in d: val = int(d['month']) if val > 12 or val < 1: continue if 'day' in d: val = int(d['day']) if val > 31 or val < 1: continue return {'values' : r, 'pattern' : p} except ParseException as e: # print p['key'], text.encode('utf-8'), e pass return None
[ "def", "match", "(", "self", ",", "text", ",", "noprefix", "=", "False", ")", ":", "n", "=", "len", "(", "text", ")", "if", "self", ".", "cachedpats", "is", "not", "None", ":", "pats", "=", "self", ".", "cachedpats", "else", ":", "pats", "=", "se...
Matches date/datetime string against date patterns and returns pattern and parsed date if matched. It's not indeded for common usage, since if successful it returns date as array of numbers and pattern that matched this date :param text: Any human readable string :type date_string: str|unicode :param noprefix: If set True than doesn't use prefix based date patterns filtering settings :type noprefix: bool :return: Returns dicts with `values` as array of representing parsed date and 'pattern' with info about matched pattern if successful, else returns None :rtype: :class:`dict`.
[ "Matches", "date", "/", "datetime", "string", "against", "date", "patterns", "and", "returns", "pattern", "and", "parsed", "date", "if", "matched", ".", "It", "s", "not", "indeded", "for", "common", "usage", "since", "if", "successful", "it", "returns", "dat...
python
train
CGATOxford/UMI-tools
umi_tools/sam_methods.py
https://github.com/CGATOxford/UMI-tools/blob/c4b5d84aac391d59916d294f8f4f8f5378abcfbe/umi_tools/sam_methods.py#L520-L558
def get_gene_count_tab(infile, bc_getter=None): ''' Yields the counts per umi for each gene bc_getter: method to get umi (plus optionally, cell barcode) from read, e.g get_umi_read_id or get_umi_tag TODO: ADD FOLLOWING OPTION skip_regex: skip genes matching this regex. Useful to ignore unassigned reads (as per get_bundles class above) ''' gene = None counts = collections.Counter() for line in infile: values = line.strip().split("\t") assert len(values) == 2, "line: %s does not contain 2 columns" % line read_id, assigned_gene = values if assigned_gene != gene: if gene: yield gene, counts gene = assigned_gene counts = collections.defaultdict(collections.Counter) cell, umi = bc_getter(read_id) counts[cell][umi] += 1 # yield final values yield gene, counts
[ "def", "get_gene_count_tab", "(", "infile", ",", "bc_getter", "=", "None", ")", ":", "gene", "=", "None", "counts", "=", "collections", ".", "Counter", "(", ")", "for", "line", "in", "infile", ":", "values", "=", "line", ".", "strip", "(", ")", ".", ...
Yields the counts per umi for each gene bc_getter: method to get umi (plus optionally, cell barcode) from read, e.g get_umi_read_id or get_umi_tag TODO: ADD FOLLOWING OPTION skip_regex: skip genes matching this regex. Useful to ignore unassigned reads (as per get_bundles class above)
[ "Yields", "the", "counts", "per", "umi", "for", "each", "gene" ]
python
train
GoogleCloudPlatform/datastore-ndb-python
ndb/context.py
https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/context.py#L908-L928
def call_on_commit(self, callback): """Call a callback upon successful commit of a transaction. If not in a transaction, the callback is called immediately. In a transaction, multiple callbacks may be registered and will be called once the transaction commits, in the order in which they were registered. If the transaction fails, the callbacks will not be called. If the callback raises an exception, it bubbles up normally. This means: If the callback is called immediately, any exception it raises will bubble up immediately. If the call is postponed until commit, remaining callbacks will be skipped and the exception will bubble up through the transaction() call. (However, the transaction is already committed at that point.) """ if not self.in_transaction(): callback() else: self._on_commit_queue.append(callback)
[ "def", "call_on_commit", "(", "self", ",", "callback", ")", ":", "if", "not", "self", ".", "in_transaction", "(", ")", ":", "callback", "(", ")", "else", ":", "self", ".", "_on_commit_queue", ".", "append", "(", "callback", ")" ]
Call a callback upon successful commit of a transaction. If not in a transaction, the callback is called immediately. In a transaction, multiple callbacks may be registered and will be called once the transaction commits, in the order in which they were registered. If the transaction fails, the callbacks will not be called. If the callback raises an exception, it bubbles up normally. This means: If the callback is called immediately, any exception it raises will bubble up immediately. If the call is postponed until commit, remaining callbacks will be skipped and the exception will bubble up through the transaction() call. (However, the transaction is already committed at that point.)
[ "Call", "a", "callback", "upon", "successful", "commit", "of", "a", "transaction", "." ]
python
train
click-contrib/click-repl
click_repl/__init__.py
https://github.com/click-contrib/click-repl/blob/2d78dc520eb0bb5b813bad3b72344edbd22a7f4e/click_repl/__init__.py#L146-L165
def bootstrap_prompt(prompt_kwargs, group): """ Bootstrap prompt_toolkit kwargs or use user defined values. :param prompt_kwargs: The user specified prompt kwargs. """ prompt_kwargs = prompt_kwargs or {} defaults = { "history": InMemoryHistory(), "completer": ClickCompleter(group), "message": u"> ", } for key in defaults: default_value = defaults[key] if key not in prompt_kwargs: prompt_kwargs[key] = default_value return prompt_kwargs
[ "def", "bootstrap_prompt", "(", "prompt_kwargs", ",", "group", ")", ":", "prompt_kwargs", "=", "prompt_kwargs", "or", "{", "}", "defaults", "=", "{", "\"history\"", ":", "InMemoryHistory", "(", ")", ",", "\"completer\"", ":", "ClickCompleter", "(", "group", ")...
Bootstrap prompt_toolkit kwargs or use user defined values. :param prompt_kwargs: The user specified prompt kwargs.
[ "Bootstrap", "prompt_toolkit", "kwargs", "or", "use", "user", "defined", "values", "." ]
python
train
titusjan/argos
argos/repo/baserti.py
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/baserti.py#L60-L66
def createFromFileName(cls, fileName): """ Creates a BaseRti (or descendant), given a file name. """ # See https://julien.danjou.info/blog/2013/guide-python-static-class-abstract-methods #logger.debug("Trying to create object of class: {!r}".format(cls)) basename = os.path.basename(os.path.realpath(fileName)) # strips trailing slashes return cls(nodeName=basename, fileName=fileName)
[ "def", "createFromFileName", "(", "cls", ",", "fileName", ")", ":", "# See https://julien.danjou.info/blog/2013/guide-python-static-class-abstract-methods", "#logger.debug(\"Trying to create object of class: {!r}\".format(cls))", "basename", "=", "os", ".", "path", ".", "basename", ...
Creates a BaseRti (or descendant), given a file name.
[ "Creates", "a", "BaseRti", "(", "or", "descendant", ")", "given", "a", "file", "name", "." ]
python
train
saltstack/salt
salt/modules/openbsdpkg.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/openbsdpkg.py#L57-L98
def list_pkgs(versions_as_list=False, **kwargs): ''' List the packages currently installed as a dict:: {'<package_name>': '<version>'} CLI Example: .. code-block:: bash salt '*' pkg.list_pkgs ''' versions_as_list = salt.utils.data.is_true(versions_as_list) # not yet implemented or not applicable if any([salt.utils.data.is_true(kwargs.get(x)) for x in ('removed', 'purge_desired')]): return {} if 'pkg.list_pkgs' in __context__: if versions_as_list: return __context__['pkg.list_pkgs'] else: ret = copy.deepcopy(__context__['pkg.list_pkgs']) __salt__['pkg_resource.stringify'](ret) return ret ret = {} cmd = 'pkg_info -q -a' out = __salt__['cmd.run_stdout'](cmd, output_loglevel='trace') for line in out.splitlines(): try: pkgname, pkgver, flavor = __PKG_RE.match(line).groups() except AttributeError: continue pkgname += '--{0}'.format(flavor) if flavor else '' __salt__['pkg_resource.add_pkg'](ret, pkgname, pkgver) __salt__['pkg_resource.sort_pkglist'](ret) __context__['pkg.list_pkgs'] = copy.deepcopy(ret) if not versions_as_list: __salt__['pkg_resource.stringify'](ret) return ret
[ "def", "list_pkgs", "(", "versions_as_list", "=", "False", ",", "*", "*", "kwargs", ")", ":", "versions_as_list", "=", "salt", ".", "utils", ".", "data", ".", "is_true", "(", "versions_as_list", ")", "# not yet implemented or not applicable", "if", "any", "(", ...
List the packages currently installed as a dict:: {'<package_name>': '<version>'} CLI Example: .. code-block:: bash salt '*' pkg.list_pkgs
[ "List", "the", "packages", "currently", "installed", "as", "a", "dict", "::" ]
python
train
bohea/sanic-limiter
sanic_limiter/extension.py
https://github.com/bohea/sanic-limiter/blob/54c9fc4a3a3f1a9bb69367262637d07701ae5694/sanic_limiter/extension.py#L116-L147
def init_app(self, app): """ :param app: :class:`sanic.Sanic` instance to rate limit. """ self.enabled = app.config.setdefault(C.ENABLED, True) self._swallow_errors = app.config.setdefault( C.SWALLOW_ERRORS, self._swallow_errors ) self._storage_options.update( app.config.get(C.STORAGE_OPTIONS, {}) ) self._storage = storage_from_string( self._storage_uri or app.config.setdefault(C.STORAGE_URL, 'memory://'), **self._storage_options ) strategy = ( self._strategy or app.config.setdefault(C.STRATEGY, 'fixed-window') ) if strategy not in STRATEGIES: raise ConfigurationError("Invalid rate limiting strategy %s" % strategy) self._limiter = STRATEGIES[strategy](self._storage) conf_limits = app.config.get(C.GLOBAL_LIMITS, None) if not self._global_limits and conf_limits: self._global_limits = [ ExtLimit( limit, self._key_func, None, False, None, None, None ) for limit in parse_many(conf_limits) ] app.request_middleware.append(self.__check_request_limit)
[ "def", "init_app", "(", "self", ",", "app", ")", ":", "self", ".", "enabled", "=", "app", ".", "config", ".", "setdefault", "(", "C", ".", "ENABLED", ",", "True", ")", "self", ".", "_swallow_errors", "=", "app", ".", "config", ".", "setdefault", "(",...
:param app: :class:`sanic.Sanic` instance to rate limit.
[ ":", "param", "app", ":", ":", "class", ":", "sanic", ".", "Sanic", "instance", "to", "rate", "limit", "." ]
python
train
HPENetworking/PYHPEIMC
pyhpeimc/plat/alarms.py
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/alarms.py#L102-L138
def get_alarms(username, auth, url): """Takes in no param as input to fetch RealTime Alarms from HP IMC RESTFUL API :param username OpeatorName, String type. Required. Default Value "admin". Checks the operator has the privileges to view the Real-Time Alarms. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return:list of dictionaries where each element of the list represents a single alarm as pulled from the the current list of browse alarms in the HPE IMC Platform :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.alarms import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> all_alarms = get_alarms('admin', auth.creds, auth.url) >>> assert (type(all_alarms)) is list >>> assert 'ackStatus' in all_alarms[0] """ f_url = url + "/imcrs/fault/alarm?operatorName=" + username + \ "&recStatus=0&ackStatus=0&timeRange=0&size=50&desc=true" response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: alarm_list = (json.loads(response.text)) return alarm_list['alarm'] except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' get_alarms: An Error has occured'
[ "def", "get_alarms", "(", "username", ",", "auth", ",", "url", ")", ":", "f_url", "=", "url", "+", "\"/imcrs/fault/alarm?operatorName=\"", "+", "username", "+", "\"&recStatus=0&ackStatus=0&timeRange=0&size=50&desc=true\"", "response", "=", "requests", ".", "get", "(",...
Takes in no param as input to fetch RealTime Alarms from HP IMC RESTFUL API :param username OpeatorName, String type. Required. Default Value "admin". Checks the operator has the privileges to view the Real-Time Alarms. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return:list of dictionaries where each element of the list represents a single alarm as pulled from the the current list of browse alarms in the HPE IMC Platform :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.alarms import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> all_alarms = get_alarms('admin', auth.creds, auth.url) >>> assert (type(all_alarms)) is list >>> assert 'ackStatus' in all_alarms[0]
[ "Takes", "in", "no", "param", "as", "input", "to", "fetch", "RealTime", "Alarms", "from", "HP", "IMC", "RESTFUL", "API" ]
python
train
materialsproject/pymatgen
pymatgen/optimization/linear_assignment_numpy.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/optimization/linear_assignment_numpy.py#L187-L244
def _build_tree(self): """ Builds the tree finding an augmenting path. Alternates along matched and unmatched edges between X and Y. The paths are stored in _pred (new predecessor of nodes in Y), and self._x and self._y """ #find unassigned i* istar = np.argmin(self._x) #compute distances self._d = self.c[istar] - self._v _pred = np.zeros(self.n, dtype=np.int) + istar #initialize sets #READY: set of nodes visited and in the path (whose price gets #updated in augment) #SCAN: set of nodes at the bottom of the tree, which we need to #look at #T0DO: unvisited nodes _ready = np.zeros(self.n, dtype=np.bool) _scan = np.zeros(self.n, dtype=np.bool) _todo = np.zeros(self.n, dtype=np.bool) + True while True: #populate scan with minimum reduced distances if True not in _scan: mu = np.min(self._d[_todo]) _scan[self._d == mu] = True _todo[_scan] = False j = np.argmin(self._y * _scan) if self._y[j] == -1 and _scan[j]: return _pred, _ready, istar, j, mu #pick jstar from scan (scan always has at least 1) _jstar = np.argmax(_scan) #pick i associated with jstar i = self._y[_jstar] _scan[_jstar] = False _ready[_jstar] = True #find shorter distances newdists = mu + self.cred[i, :] shorter = np.logical_and(newdists < self._d, _todo) #update distances self._d[shorter] = newdists[shorter] #update predecessors _pred[shorter] = i for j in np.nonzero(np.logical_and(self._d == mu, _todo))[0]: if self._y[j] == -1: return _pred, _ready, istar, j, mu _scan[j] = True _todo[j] = False
[ "def", "_build_tree", "(", "self", ")", ":", "#find unassigned i*", "istar", "=", "np", ".", "argmin", "(", "self", ".", "_x", ")", "#compute distances", "self", ".", "_d", "=", "self", ".", "c", "[", "istar", "]", "-", "self", ".", "_v", "_pred", "=...
Builds the tree finding an augmenting path. Alternates along matched and unmatched edges between X and Y. The paths are stored in _pred (new predecessor of nodes in Y), and self._x and self._y
[ "Builds", "the", "tree", "finding", "an", "augmenting", "path", ".", "Alternates", "along", "matched", "and", "unmatched", "edges", "between", "X", "and", "Y", ".", "The", "paths", "are", "stored", "in", "_pred", "(", "new", "predecessor", "of", "nodes", "...
python
train
kata198/python-subprocess2
subprocess2/__init__.py
https://github.com/kata198/python-subprocess2/blob/8544b0b651d8e14de9fdd597baa704182e248b01/subprocess2/__init__.py#L63-L85
def waitUpTo(self, timeoutSeconds, pollInterval=DEFAULT_POLL_INTERVAL): ''' Popen.waitUpTo - Wait up to a certain number of seconds for the process to end. @param timeoutSeconds <float> - Number of seconds to wait @param pollInterval <float> (default .05) - Number of seconds in between each poll @return - Returncode of application, or None if did not terminate. ''' i = 0 numWaits = timeoutSeconds / float(pollInterval) ret = self.poll() if ret is None: while i < numWaits: time.sleep(pollInterval) ret = self.poll() if ret is not None: break i += 1 return ret
[ "def", "waitUpTo", "(", "self", ",", "timeoutSeconds", ",", "pollInterval", "=", "DEFAULT_POLL_INTERVAL", ")", ":", "i", "=", "0", "numWaits", "=", "timeoutSeconds", "/", "float", "(", "pollInterval", ")", "ret", "=", "self", ".", "poll", "(", ")", "if", ...
Popen.waitUpTo - Wait up to a certain number of seconds for the process to end. @param timeoutSeconds <float> - Number of seconds to wait @param pollInterval <float> (default .05) - Number of seconds in between each poll @return - Returncode of application, or None if did not terminate.
[ "Popen", ".", "waitUpTo", "-", "Wait", "up", "to", "a", "certain", "number", "of", "seconds", "for", "the", "process", "to", "end", "." ]
python
train
Azure/azure-storage-python
azure-storage-queue/azure/storage/queue/queueservice.py
https://github.com/Azure/azure-storage-python/blob/52327354b192cbcf6b7905118ec6b5d57fa46275/azure-storage-queue/azure/storage/queue/queueservice.py#L894-L929
def delete_message(self, queue_name, message_id, pop_receipt, timeout=None): ''' Deletes the specified message. Normally after a client retrieves a message with the get_messages operation, the client is expected to process and delete the message. To delete the message, you must have two items of data: id and pop_receipt. The id is returned from the previous get_messages operation. The pop_receipt is returned from the most recent :func:`~get_messages` or :func:`~update_message` operation. In order for the delete_message operation to succeed, the pop_receipt specified on the request must match the pop_receipt returned from the :func:`~get_messages` or :func:`~update_message` operation. :param str queue_name: The name of the queue from which to delete the message. :param str message_id: The message id identifying the message to delete. :param str pop_receipt: A valid pop receipt value returned from an earlier call to the :func:`~get_messages` or :func:`~update_message`. :param int timeout: The server timeout, expressed in seconds. ''' _validate_not_none('queue_name', queue_name) _validate_not_none('message_id', message_id) _validate_not_none('pop_receipt', pop_receipt) request = HTTPRequest() request.method = 'DELETE' request.host_locations = self._get_host_locations() request.path = _get_path(queue_name, True, message_id) request.query = { 'popreceipt': _to_str(pop_receipt), 'timeout': _int_to_str(timeout) } self._perform_request(request)
[ "def", "delete_message", "(", "self", ",", "queue_name", ",", "message_id", ",", "pop_receipt", ",", "timeout", "=", "None", ")", ":", "_validate_not_none", "(", "'queue_name'", ",", "queue_name", ")", "_validate_not_none", "(", "'message_id'", ",", "message_id", ...
Deletes the specified message. Normally after a client retrieves a message with the get_messages operation, the client is expected to process and delete the message. To delete the message, you must have two items of data: id and pop_receipt. The id is returned from the previous get_messages operation. The pop_receipt is returned from the most recent :func:`~get_messages` or :func:`~update_message` operation. In order for the delete_message operation to succeed, the pop_receipt specified on the request must match the pop_receipt returned from the :func:`~get_messages` or :func:`~update_message` operation. :param str queue_name: The name of the queue from which to delete the message. :param str message_id: The message id identifying the message to delete. :param str pop_receipt: A valid pop receipt value returned from an earlier call to the :func:`~get_messages` or :func:`~update_message`. :param int timeout: The server timeout, expressed in seconds.
[ "Deletes", "the", "specified", "message", "." ]
python
train
houtianze/bypy
bypy/bypy.py
https://github.com/houtianze/bypy/blob/c59b6183e2fca45f11138bbcdec6247449b2eaad/bypy/bypy.py#L2922-L2937
def cleancache(self): ''' Usage: cleancache - remove invalid entries from hash cache file''' if os.path.exists(self.__hashcachepath): try: # backup first backup = self.__hashcachepath + '.lastclean' shutil.copy(self.__hashcachepath, backup) self.pd("Hash Cache file '{}' backed up as '{}".format( self.__hashcachepath, backup)) cached.cleancache() return const.ENoError except Exception as ex: perr(formatex(ex)) return const.EException else: return const.EFileNotFound
[ "def", "cleancache", "(", "self", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "__hashcachepath", ")", ":", "try", ":", "# backup first", "backup", "=", "self", ".", "__hashcachepath", "+", "'.lastclean'", "shutil", ".", "copy", "(...
Usage: cleancache - remove invalid entries from hash cache file
[ "Usage", ":", "cleancache", "-", "remove", "invalid", "entries", "from", "hash", "cache", "file" ]
python
train
klmitch/bark
bark/format.py
https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/format.py#L381-L393
def append_text(self, text): """ Append static text to the Format. :param text: The text to append. """ if (self.conversions and isinstance(self.conversions[-1], conversions.StringConversion)): self.conversions[-1].append(text) else: self.conversions.append(conversions.StringConversion(text))
[ "def", "append_text", "(", "self", ",", "text", ")", ":", "if", "(", "self", ".", "conversions", "and", "isinstance", "(", "self", ".", "conversions", "[", "-", "1", "]", ",", "conversions", ".", "StringConversion", ")", ")", ":", "self", ".", "convers...
Append static text to the Format. :param text: The text to append.
[ "Append", "static", "text", "to", "the", "Format", "." ]
python
train
inveniosoftware-attic/invenio-utils
invenio_utils/filedownload.py
https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/filedownload.py#L253-L295
def download_local_file(filename, download_to_file): """ Copies a local file to Invenio's temporary directory. @param filename: the name of the file to copy @type filename: string @param download_to_file: the path to save the file to @type download_to_file: string @return: the path of the temporary file created @rtype: string @raise StandardError: if something went wrong """ # Try to copy. try: path = urllib2.urlparse.urlsplit(urllib.unquote(filename))[2] if os.path.abspath(path) != path: msg = "%s is not a normalized path (would be %s)." \ % (path, os.path.normpath(path)) raise InvenioFileCopyError(msg) allowed_path_list = current_app.config.get( 'CFG_BIBUPLOAD_FFT_ALLOWED_LOCAL_PATHS', [] ) allowed_path_list.append(current_app.config['CFG_TMPSHAREDDIR']) for allowed_path in allowed_path_list: if path.startswith(allowed_path): shutil.copy(path, download_to_file) if os.path.getsize(download_to_file) == 0: os.remove(download_to_file) msg = "%s seems to be empty" % (filename,) raise InvenioFileCopyError(msg) break else: msg = "%s is not in one of the allowed paths." % (path,) raise InvenioFileCopyError() except Exception as e: msg = "Impossible to copy the local file '%s' to %s: %s" % \ (filename, download_to_file, str(e)) raise InvenioFileCopyError(msg) return download_to_file
[ "def", "download_local_file", "(", "filename", ",", "download_to_file", ")", ":", "# Try to copy.", "try", ":", "path", "=", "urllib2", ".", "urlparse", ".", "urlsplit", "(", "urllib", ".", "unquote", "(", "filename", ")", ")", "[", "2", "]", "if", "os", ...
Copies a local file to Invenio's temporary directory. @param filename: the name of the file to copy @type filename: string @param download_to_file: the path to save the file to @type download_to_file: string @return: the path of the temporary file created @rtype: string @raise StandardError: if something went wrong
[ "Copies", "a", "local", "file", "to", "Invenio", "s", "temporary", "directory", "." ]
python
train
pip-services3-python/pip-services3-components-python
pip_services3_components/log/CachedLogger.py
https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/log/CachedLogger.py#L55-L77
def _write(self, level, correlation_id, ex, message): """ Writes a log message to the logger destination. :param level: a log level. :param correlation_id: (optional) transaction id to trace execution through call chain. :param ex: an error object associated with this message. :param message: a human-readable message to log. """ error = ErrorDescriptionFactory.create(ex) if ex != None else None source = socket.gethostname() # Todo: add process/module name log_message = LogMessage(level, source, correlation_id, error, message) self._lock.acquire() try: self._cache.append(log_message) finally: self._lock.release() self._update()
[ "def", "_write", "(", "self", ",", "level", ",", "correlation_id", ",", "ex", ",", "message", ")", ":", "error", "=", "ErrorDescriptionFactory", ".", "create", "(", "ex", ")", "if", "ex", "!=", "None", "else", "None", "source", "=", "socket", ".", "get...
Writes a log message to the logger destination. :param level: a log level. :param correlation_id: (optional) transaction id to trace execution through call chain. :param ex: an error object associated with this message. :param message: a human-readable message to log.
[ "Writes", "a", "log", "message", "to", "the", "logger", "destination", "." ]
python
train
SKA-ScienceDataProcessor/integration-prototype
sip/execution_control/docker_api/sip_docker_swarm/docker_swarm_client.py
https://github.com/SKA-ScienceDataProcessor/integration-prototype/blob/8c8006de6ad71dcd44114b0338780738079c87d4/sip/execution_control/docker_api/sip_docker_swarm/docker_swarm_client.py#L310-L330
def get_node_list(self) -> list: """Get a list of nodes. Only the manager nodes can retrieve all the nodes Returns: list, all the ids of the nodes in swarm """ # Initialising empty list nodes = [] # Raise an exception if we are not a manager if not self._manager: raise RuntimeError('Only the Swarm manager node ' 'can retrieve all the nodes.') node_list = self._client.nodes.list() for n_list in node_list: nodes.append(n_list.id) return nodes
[ "def", "get_node_list", "(", "self", ")", "->", "list", ":", "# Initialising empty list", "nodes", "=", "[", "]", "# Raise an exception if we are not a manager", "if", "not", "self", ".", "_manager", ":", "raise", "RuntimeError", "(", "'Only the Swarm manager node '", ...
Get a list of nodes. Only the manager nodes can retrieve all the nodes Returns: list, all the ids of the nodes in swarm
[ "Get", "a", "list", "of", "nodes", "." ]
python
train
expfactory/expfactory
expfactory/database/filesystem.py
https://github.com/expfactory/expfactory/blob/27ce6cc93e17231df8a8024f18e631336afd3501/expfactory/database/filesystem.py#L188-L199
def validate_token(self, token): '''retrieve a subject based on a token. Valid means we return a participant invalid means we return None ''' # A token that is finished or revoked is not valid subid = None if not token.endswith(('finished','revoked')): subid = self.generate_subid(token=token) data_base = "%s/%s" %(self.data_base, subid) if not os.path.exists(data_base): subid = None return subid
[ "def", "validate_token", "(", "self", ",", "token", ")", ":", "# A token that is finished or revoked is not valid", "subid", "=", "None", "if", "not", "token", ".", "endswith", "(", "(", "'finished'", ",", "'revoked'", ")", ")", ":", "subid", "=", "self", ".",...
retrieve a subject based on a token. Valid means we return a participant invalid means we return None
[ "retrieve", "a", "subject", "based", "on", "a", "token", ".", "Valid", "means", "we", "return", "a", "participant", "invalid", "means", "we", "return", "None" ]
python
train
klen/starter
starter/core.py
https://github.com/klen/starter/blob/24a65c10d4ac5a9ca8fc1d8b3d54b3fb13603f5f/starter/core.py#L42-L50
def make_directory(path): """ Create directory if that not exists. """ try: makedirs(path) logging.debug('Directory created: {0}'.format(path)) except OSError as e: if e.errno != errno.EEXIST: raise
[ "def", "make_directory", "(", "path", ")", ":", "try", ":", "makedirs", "(", "path", ")", "logging", ".", "debug", "(", "'Directory created: {0}'", ".", "format", "(", "path", ")", ")", "except", "OSError", "as", "e", ":", "if", "e", ".", "errno", "!="...
Create directory if that not exists.
[ "Create", "directory", "if", "that", "not", "exists", "." ]
python
train
scheibler/khard
khard/khard.py
https://github.com/scheibler/khard/blob/0f69430c2680f1ff5f073a977a3c5b753b96cc17/khard/khard.py#L921-L982
def phone_subcommand(search_terms, vcard_list, parsable): """Print a phone application friendly contact table. :param search_terms: used as search term to filter the contacts before printing :type search_terms: str :param vcard_list: the vcards to search for matching entries which should be printed :type vcard_list: list of carddav_object.CarddavObject :param parsable: machine readable output: columns devided by tabulator (\t) :type parsable: bool :returns: None :rtype: None """ all_phone_numbers_list = [] matching_phone_number_list = [] for vcard in vcard_list: for type, number_list in sorted(vcard.get_phone_numbers().items(), key=lambda k: k[0].lower()): for number in sorted(number_list): if config.display_by_name() == "first_name": name = vcard.get_first_name_last_name() else: name = vcard.get_last_name_first_name() # create output lines line_formatted = "\t".join([name, type, number]) line_parsable = "\t".join([number, name, type]) if parsable: # parsable option: start with phone number phone_number_line = line_parsable else: # else: start with name phone_number_line = line_formatted if re.search(search_terms, "%s\n%s" % (line_formatted, line_parsable), re.IGNORECASE | re.DOTALL): matching_phone_number_list.append(phone_number_line) elif len(re.sub("\D", "", search_terms)) >= 3: # The user likely searches for a phone number cause the # search string contains at least three digits. So we # remove all non-digit chars from the phone number field # and match against that. if re.search(re.sub("\D", "", search_terms), re.sub("\D", "", number), re.IGNORECASE): matching_phone_number_list.append(phone_number_line) # collect all phone numbers in a different list as fallback all_phone_numbers_list.append(phone_number_line) if matching_phone_number_list: if parsable: print('\n'.join(matching_phone_number_list)) else: list_phone_numbers(matching_phone_number_list) elif all_phone_numbers_list: if parsable: print('\n'.join(all_phone_numbers_list)) else: list_phone_numbers(all_phone_numbers_list) else: if not parsable: print("Found no phone numbers") sys.exit(1)
[ "def", "phone_subcommand", "(", "search_terms", ",", "vcard_list", ",", "parsable", ")", ":", "all_phone_numbers_list", "=", "[", "]", "matching_phone_number_list", "=", "[", "]", "for", "vcard", "in", "vcard_list", ":", "for", "type", ",", "number_list", "in", ...
Print a phone application friendly contact table. :param search_terms: used as search term to filter the contacts before printing :type search_terms: str :param vcard_list: the vcards to search for matching entries which should be printed :type vcard_list: list of carddav_object.CarddavObject :param parsable: machine readable output: columns devided by tabulator (\t) :type parsable: bool :returns: None :rtype: None
[ "Print", "a", "phone", "application", "friendly", "contact", "table", "." ]
python
test
streamlink/streamlink
src/streamlink_cli/main.py
https://github.com/streamlink/streamlink/blob/c8ed1daff14ac03195870238b9b900c1109dd5c1/src/streamlink_cli/main.py#L504-L534
def format_valid_streams(plugin, streams): """Formats a dict of streams. Filters out synonyms and displays them next to the stream they point to. Streams are sorted according to their quality (based on plugin.stream_weight). """ delimiter = ", " validstreams = [] for name, stream in sorted(streams.items(), key=lambda stream: plugin.stream_weight(stream[0])): if name in STREAM_SYNONYMS: continue def synonymfilter(n): return stream is streams[n] and n is not name synonyms = list(filter(synonymfilter, streams.keys())) if len(synonyms) > 0: joined = delimiter.join(synonyms) name = "{0} ({1})".format(name, joined) validstreams.append(name) return delimiter.join(validstreams)
[ "def", "format_valid_streams", "(", "plugin", ",", "streams", ")", ":", "delimiter", "=", "\", \"", "validstreams", "=", "[", "]", "for", "name", ",", "stream", "in", "sorted", "(", "streams", ".", "items", "(", ")", ",", "key", "=", "lambda", "stream", ...
Formats a dict of streams. Filters out synonyms and displays them next to the stream they point to. Streams are sorted according to their quality (based on plugin.stream_weight).
[ "Formats", "a", "dict", "of", "streams", "." ]
python
test
DarkEnergySurvey/ugali
ugali/isochrone/model.py
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/isochrone/model.py#L389-L444
def absolute_magnitude_martin(self, richness=1, steps=1e4, n_trials=1000, mag_bright=None, mag_faint=23., alpha=0.32, seed=None): """ Calculate the absolute magnitude (Mv) of the isochrone using the prescription of Martin et al. 2008. ADW: Seems like the faint and bright limits should depend on the survey maglim? Parameters: ----------- richness : Isochrone nomalization factor steps : Number of steps for sampling the isochrone. n_trials : Number of bootstrap samples mag_bright : Bright magnitude limit [SDSS g-band] for luminosity calculation mag_faint : Faint magnitude limit [SDSS g-band] for luminosity calculation alpha : Output confidence interval (1-alpha) seed : Random seed Returns: -------- med,lo,hi : Total absolute magnitude interval """ # ADW: This function is not quite right. It should restrict # the catalog to the obsevable space using the mask in each # pixel. This becomes even more complicated when we transform # the isochrone into SDSS g,r... if seed is not None: np.random.seed(seed) # Create a copy of the isochrone in the SDSS system params = {k:v.value for k,v in self._params.items()} params.update(band_1='g',band_2='r',survey='sdss') iso = self.__class__(**params) # Analytic part (below detection threshold) # g, r are absolute magnitudes mass_init, mass_pdf, mass_act, sdss_g, sdss_r = iso.sample(mass_steps = steps) V = jester_mag_v(sdss_g, sdss_r) cut = ( (sdss_g + iso.distance_modulus) > mag_faint) mag_unobs = sum_mags(V[cut], weights = richness * mass_pdf[cut]) # Stochastic part (above detection threshold) abs_mag_v = np.zeros(n_trials) for i in range(n_trials): if i%100==0: logger.debug('%i absolute magnitude trials'%i) # g,r are apparent magnitudes sdss_g, sdss_r = iso.simulate(richness * iso.stellar_mass()) cut = (sdss_g < mag_faint) # V is absolute magnitude V = jester_mag_v(sdss_g[cut]-iso.distance_modulus, sdss_r[cut]-iso.distance_modulus) mag_obs = sum_mags(V) abs_mag_v[i] = sum_mags([mag_obs,mag_unobs]) # ADW: Careful, fainter abs mag is larger (less negative) number q = [100*alpha/2., 50, 100*(1-alpha/2.)] hi,med,lo = np.percentile(abs_mag_v,q) return ugali.utils.stats.interval(med,lo,hi)
[ "def", "absolute_magnitude_martin", "(", "self", ",", "richness", "=", "1", ",", "steps", "=", "1e4", ",", "n_trials", "=", "1000", ",", "mag_bright", "=", "None", ",", "mag_faint", "=", "23.", ",", "alpha", "=", "0.32", ",", "seed", "=", "None", ")", ...
Calculate the absolute magnitude (Mv) of the isochrone using the prescription of Martin et al. 2008. ADW: Seems like the faint and bright limits should depend on the survey maglim? Parameters: ----------- richness : Isochrone nomalization factor steps : Number of steps for sampling the isochrone. n_trials : Number of bootstrap samples mag_bright : Bright magnitude limit [SDSS g-band] for luminosity calculation mag_faint : Faint magnitude limit [SDSS g-band] for luminosity calculation alpha : Output confidence interval (1-alpha) seed : Random seed Returns: -------- med,lo,hi : Total absolute magnitude interval
[ "Calculate", "the", "absolute", "magnitude", "(", "Mv", ")", "of", "the", "isochrone", "using", "the", "prescription", "of", "Martin", "et", "al", ".", "2008", ".", "ADW", ":", "Seems", "like", "the", "faint", "and", "bright", "limits", "should", "depend",...
python
train
ambitioninc/rabbitmq-admin
rabbitmq_admin/api.py
https://github.com/ambitioninc/rabbitmq-admin/blob/ff65054115f19991da153f0e4f4e45e526545fea/rabbitmq_admin/api.py#L476-L488
def get_policy_for_vhost(self, vhost, name): """ Get a specific policy for a vhost. :param vhost: The virtual host the policy is for :type vhost: str :param name: The name of the policy :type name: str """ return self._api_get('/api/policies/{0}/{1}'.format( urllib.parse.quote_plus(vhost), urllib.parse.quote_plus(name), ))
[ "def", "get_policy_for_vhost", "(", "self", ",", "vhost", ",", "name", ")", ":", "return", "self", ".", "_api_get", "(", "'/api/policies/{0}/{1}'", ".", "format", "(", "urllib", ".", "parse", ".", "quote_plus", "(", "vhost", ")", ",", "urllib", ".", "parse...
Get a specific policy for a vhost. :param vhost: The virtual host the policy is for :type vhost: str :param name: The name of the policy :type name: str
[ "Get", "a", "specific", "policy", "for", "a", "vhost", "." ]
python
train
senaite/senaite.core
bika/lims/browser/analysisservice.py
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/analysisservice.py#L131-L140
def analysis_log_view(self): """Get the log view of the requested analysis """ service = self.get_analysis_or_service() if not self.can_view_logs_of(service): return None view = api.get_view("auditlog", context=service, request=self.request) view.update() view.before_render() return view
[ "def", "analysis_log_view", "(", "self", ")", ":", "service", "=", "self", ".", "get_analysis_or_service", "(", ")", "if", "not", "self", ".", "can_view_logs_of", "(", "service", ")", ":", "return", "None", "view", "=", "api", ".", "get_view", "(", "\"audi...
Get the log view of the requested analysis
[ "Get", "the", "log", "view", "of", "the", "requested", "analysis" ]
python
train
alimanfoo/csvvalidator
csvvalidator.py
https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/csvvalidator.py#L591-L629
def _apply_value_predicates(self, i, r, summarize=False, report_unexpected_exceptions=True, context=None): """Apply value predicates on the given record `r`.""" for field_name, predicate, code, message, modulus in self._value_predicates: if i % modulus == 0: # support sampling fi = self._field_names.index(field_name) if fi < len(r): # only apply predicate if there is a value value = r[fi] try: valid = predicate(value) if not valid: p = {'code': code} if not summarize: p['message'] = message p['row'] = i + 1 p['column'] = fi + 1 p['field'] = field_name p['value'] = value p['record'] = r if context is not None: p['context'] = context yield p except Exception as e: if report_unexpected_exceptions: p = {'code': UNEXPECTED_EXCEPTION} if not summarize: p['message'] = MESSAGES[UNEXPECTED_EXCEPTION] % (e.__class__.__name__, e) p['row'] = i + 1 p['column'] = fi + 1 p['field'] = field_name p['value'] = value p['record'] = r p['exception'] = e p['function'] = '%s: %s' % (predicate.__name__, predicate.__doc__) if context is not None: p['context'] = context yield p
[ "def", "_apply_value_predicates", "(", "self", ",", "i", ",", "r", ",", "summarize", "=", "False", ",", "report_unexpected_exceptions", "=", "True", ",", "context", "=", "None", ")", ":", "for", "field_name", ",", "predicate", ",", "code", ",", "message", ...
Apply value predicates on the given record `r`.
[ "Apply", "value", "predicates", "on", "the", "given", "record", "r", "." ]
python
valid