repo
stringlengths
7
55
path
stringlengths
4
223
url
stringlengths
87
315
code
stringlengths
75
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
avg_line_len
float64
7.91
980
UCBerkeleySETI/blimpy
blimpy/file_wrapper.py
https://github.com/UCBerkeleySETI/blimpy/blob/b8822d3e3e911944370d84371a91fa0c29e9772e/blimpy/file_wrapper.py#L282-L291
def isheavy(self): """ Check if the current selection is too large. """ selection_size_bytes = self._calc_selection_size() if selection_size_bytes > self.MAX_DATA_ARRAY_SIZE: return True else: return False
[ "def", "isheavy", "(", "self", ")", ":", "selection_size_bytes", "=", "self", ".", "_calc_selection_size", "(", ")", "if", "selection_size_bytes", ">", "self", ".", "MAX_DATA_ARRAY_SIZE", ":", "return", "True", "else", ":", "return", "False" ]
Check if the current selection is too large.
[ "Check", "if", "the", "current", "selection", "is", "too", "large", "." ]
python
test
26.2
carlosp420/primer-designer
primer_designer/utils.py
https://github.com/carlosp420/primer-designer/blob/586cb7fecf41fedbffe6563c8b79a3156c6066ae/primer_designer/utils.py#L4-L15
def is_fasta(filename): """Check if filename is FASTA based on extension Return: Boolean """ if re.search("\.fa*s[ta]*$", filename, flags=re.I): return True elif re.search("\.fa$", filename, flags=re.I): return True else: return False
[ "def", "is_fasta", "(", "filename", ")", ":", "if", "re", ".", "search", "(", "\"\\.fa*s[ta]*$\"", ",", "filename", ",", "flags", "=", "re", ".", "I", ")", ":", "return", "True", "elif", "re", ".", "search", "(", "\"\\.fa$\"", ",", "filename", ",", "...
Check if filename is FASTA based on extension Return: Boolean
[ "Check", "if", "filename", "is", "FASTA", "based", "on", "extension" ]
python
train
23.25
SBRG/ssbio
ssbio/core/protein.py
https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/core/protein.py#L1917-L2175
def set_representative_structure(self, seq_outdir=None, struct_outdir=None, pdb_file_type=None, engine='needle', always_use_homology=False, rez_cutoff=0.0, seq_ident_cutoff=0.5, allow_missing_on_termini=0.2, allow_mutants=True, allow_deletions=False, allow_insertions=False, allow_unresolved=True, clean=True, keep_chemicals=None, skip_large_structures=False, force_rerun=False): """Set a representative structure from a structure in the structures attribute. Each gene can have a combination of the following, which will be analyzed to set a representative structure. * Homology model(s) * Ranked PDBs * BLASTed PDBs If the ``always_use_homology`` flag is true, homology models are always set as representative when they exist. If there are multiple homology models, we rank by the percent sequence coverage. Args: seq_outdir (str): Path to output directory of sequence alignment files, must be set if Protein directory was not created initially struct_outdir (str): Path to output directory of structure files, must be set if Protein directory was not created initially pdb_file_type (str): ``pdb``, ``mmCif``, ``xml``, ``mmtf`` - file type for files downloaded from the PDB engine (str): ``biopython`` or ``needle`` - which pairwise alignment program to use. ``needle`` is the standard EMBOSS tool to run pairwise alignments. ``biopython`` is Biopython's implementation of needle. Results can differ! always_use_homology (bool): If homology models should always be set as the representative structure rez_cutoff (float): Resolution cutoff, in Angstroms (only if experimental structure) seq_ident_cutoff (float): Percent sequence identity cutoff, in decimal form allow_missing_on_termini (float): Percentage of the total length of the reference sequence which will be ignored when checking for modifications. Example: if 0.1, and reference sequence is 100 AA, then only residues 5 to 95 will be checked for modifications. allow_mutants (bool): If mutations should be allowed or checked for allow_deletions (bool): If deletions should be allowed or checked for allow_insertions (bool): If insertions should be allowed or checked for allow_unresolved (bool): If unresolved residues should be allowed or checked for clean (bool): If structure should be cleaned keep_chemicals (str, list): Keep specified chemical names if structure is to be cleaned skip_large_structures (bool): Default False -- currently, large structures can't be saved as a PDB file even if you just want to save a single chain, so Biopython will throw an error when trying to do so. As an alternative, if a large structure is selected as representative, the pipeline will currently point to it and not clean it. If you don't want this to happen, set this to true. force_rerun (bool): If sequence to structure alignment should be rerun Returns: StructProp: Representative structure from the list of structures. This is a not a map to the original structure, it is copied and optionally cleaned from the original one. Todo: - Remedy large structure representative setting """ log.debug('{}: setting representative structure'.format(self.id)) if len(self.structures) == 0: log.debug('{}: no structures available'.format(self.id)) return None if not self.representative_sequence: log.error('{}: no representative sequence to compare structures to'.format(self.id)) return None if self.representative_structure and not force_rerun: log.debug('{}: representative structure already set'.format(self.id)) return self.representative_structure if self.representative_structure and force_rerun: log.debug('{}: representative structure previously set, unsetting'.format(self.id)) self.representative_structure = None if not pdb_file_type: pdb_file_type = self.pdb_file_type if not seq_outdir: seq_outdir = self.sequence_dir if not seq_outdir: raise ValueError('Sequence output directory must be specified') if not struct_outdir: struct_outdir = self.structure_dir if not struct_outdir: raise ValueError('Structure output directory must be specified') has_homology = False has_pdb = False use_homology = False use_pdb = False if self.num_structures_homology > 0: has_homology = True if self.num_structures_experimental > 0: has_pdb = True # If we mark to always use homology, use it if it exists if always_use_homology: if has_homology: use_homology = True elif has_pdb: use_pdb = True # If we don't always want to use homology, use PDB if it exists else: if has_homology and has_pdb: use_pdb = True use_homology = True elif has_homology and not has_pdb: use_homology = True elif has_pdb and not has_homology: use_pdb = True if use_pdb: # Put PDBs through QC/QA all_pdbs = self.get_experimental_structures() log.debug('{}: checking quality of {} experimental structures'.format(self.id, len(all_pdbs))) for pdb in all_pdbs: # Download the structure and parse it # This will add all chains to the mapped_chains attribute if there are none try: pdb.download_structure_file(outdir=struct_outdir, file_type=pdb_file_type, force_rerun=force_rerun, load_header_metadata=True) except (requests.exceptions.HTTPError, URLError): log.error('{}: structure file could not be downloaded in {} format'.format(pdb, pdb_file_type)) continue # TODO: add try/except to download cif file as fallback like below? if rez_cutoff and pdb.resolution: if pdb.resolution > rez_cutoff: log.debug('{}: structure does not meet experimental resolution cutoff'.format(pdb, pdb_file_type)) continue # TODO: clean up these try/except things try: self.align_seqprop_to_structprop(seqprop=self.representative_sequence, structprop=pdb, outdir=seq_outdir, engine=engine, parse=True, force_rerun=force_rerun) except (PDBConstructionException, ExtraData, KeyError) as e: log.error('Protein {}, PDB {}: unable to parse structure file as {}. Falling back to mmCIF format.'.format(self.id, pdb, pdb_file_type)) print(e) # Fall back to using mmCIF file if structure cannot be parsed try: pdb.download_structure_file(outdir=struct_outdir, file_type='mmCif', force_rerun=force_rerun, load_header_metadata=True) except (requests.exceptions.HTTPError, URLError): log.error('Protein {}, PDB {}: structure file could not be downloaded'.format(self.id, pdb)) continue try: self.align_seqprop_to_structprop(seqprop=self.representative_sequence, structprop=pdb, outdir=seq_outdir, engine=engine, parse=True, force_rerun=force_rerun) except (PDBConstructionException, KeyError) as e: log.error('Protein {}, PDB {}: unable to parse structure file as {}.'.format(self.id, pdb, 'mmCif')) print(e) continue best_chain = self.find_representative_chain(seqprop=self.representative_sequence, structprop=pdb, seq_ident_cutoff=seq_ident_cutoff, allow_missing_on_termini=allow_missing_on_termini, allow_mutants=allow_mutants, allow_deletions=allow_deletions, allow_insertions=allow_insertions, allow_unresolved=allow_unresolved) if best_chain: try: self._representative_structure_setter(structprop=pdb, clean=clean, out_suffix='-{}_clean'.format(best_chain), keep_chain=best_chain, keep_chemicals=keep_chemicals, outdir=struct_outdir, force_rerun=force_rerun) except TypeError: if skip_large_structures == True: log.warning("{}: unable to save large PDB {}-{} in PDB file format, trying next " "structure.".format(self.id, pdb.id, best_chain)) continue else: log.warning("{}: unable to save large PDB {}-{} in PDB file format, setting original " "structure as representative. Set skip_large_structures=True if you don't " "want this to happen".format(self.id, pdb.id, best_chain)) self.representative_structure = pdb except Exception as e: # Try force rerunning first if there exists a corrupt clean PDB file try: log.debug('{}: unknown error with {}, trying force_rerun first'.format(self.id, pdb.id)) self._representative_structure_setter(structprop=pdb, clean=clean, out_suffix='-{}_clean'.format(best_chain), keep_chain=best_chain, keep_chemicals=keep_chemicals, outdir=struct_outdir, force_rerun=True) except Exception as e: # TODO: inspect causes of these errors - most common is Biopython PDBParser error logging.exception("{}: unknown error with PDB ID {}".format(self.id, pdb.id)) print(e) continue log.debug('{}-{}: set as representative structure'.format(pdb.id, best_chain)) pdb.reset_chain_seq_records() return self.representative_structure else: pdb.reset_chain_seq_records() else: log.debug('{}: no experimental structures meet cutoffs'.format(self.id)) # If we are to use homology, save its information in the representative structure field if use_homology: log.debug('{}: checking quality of homology models'.format(self.id)) all_models = self.get_homology_models() # TODO: homology models are not ordered in any other way other than how they are loaded, # rethink this for multiple homology models for homology in all_models: if not homology.structure_file: log.debug('{}: no homology structure file'.format(self.id)) continue self.align_seqprop_to_structprop(seqprop=self.representative_sequence, structprop=homology, outdir=seq_outdir, engine=engine, parse=True, force_rerun=force_rerun) best_chain = self.find_representative_chain(seqprop=self.representative_sequence, structprop=homology, seq_ident_cutoff=seq_ident_cutoff, allow_missing_on_termini=allow_missing_on_termini, allow_mutants=allow_mutants, allow_deletions=allow_deletions, allow_insertions=allow_insertions, allow_unresolved=allow_unresolved) if best_chain: # If chain ID is empty (some homology models are like that), use ID "X" if not best_chain.strip(): best_chain = 'X' try: self._representative_structure_setter(structprop=homology, # new_id='{}-{}'.format(homology.id, best_chain), # 170906 Deprecated use of new_id clean=True, out_suffix='-{}_clean'.format(best_chain), keep_chain=best_chain, outdir=struct_outdir, force_rerun=force_rerun) except: # TODO: inspect causes of these errors - most common is Biopython PDBParser error logging.exception("Unknown error with homology model {}".format(homology.id)) continue log.debug('{}-{}: set as representative structure'.format(homology.id, best_chain)) homology.reset_chain_seq_records() return self.representative_structure else: homology.reset_chain_seq_records() log.warning('{}: no structures meet quality checks'.format(self.id)) return None
[ "def", "set_representative_structure", "(", "self", ",", "seq_outdir", "=", "None", ",", "struct_outdir", "=", "None", ",", "pdb_file_type", "=", "None", ",", "engine", "=", "'needle'", ",", "always_use_homology", "=", "False", ",", "rez_cutoff", "=", "0.0", "...
Set a representative structure from a structure in the structures attribute. Each gene can have a combination of the following, which will be analyzed to set a representative structure. * Homology model(s) * Ranked PDBs * BLASTed PDBs If the ``always_use_homology`` flag is true, homology models are always set as representative when they exist. If there are multiple homology models, we rank by the percent sequence coverage. Args: seq_outdir (str): Path to output directory of sequence alignment files, must be set if Protein directory was not created initially struct_outdir (str): Path to output directory of structure files, must be set if Protein directory was not created initially pdb_file_type (str): ``pdb``, ``mmCif``, ``xml``, ``mmtf`` - file type for files downloaded from the PDB engine (str): ``biopython`` or ``needle`` - which pairwise alignment program to use. ``needle`` is the standard EMBOSS tool to run pairwise alignments. ``biopython`` is Biopython's implementation of needle. Results can differ! always_use_homology (bool): If homology models should always be set as the representative structure rez_cutoff (float): Resolution cutoff, in Angstroms (only if experimental structure) seq_ident_cutoff (float): Percent sequence identity cutoff, in decimal form allow_missing_on_termini (float): Percentage of the total length of the reference sequence which will be ignored when checking for modifications. Example: if 0.1, and reference sequence is 100 AA, then only residues 5 to 95 will be checked for modifications. allow_mutants (bool): If mutations should be allowed or checked for allow_deletions (bool): If deletions should be allowed or checked for allow_insertions (bool): If insertions should be allowed or checked for allow_unresolved (bool): If unresolved residues should be allowed or checked for clean (bool): If structure should be cleaned keep_chemicals (str, list): Keep specified chemical names if structure is to be cleaned skip_large_structures (bool): Default False -- currently, large structures can't be saved as a PDB file even if you just want to save a single chain, so Biopython will throw an error when trying to do so. As an alternative, if a large structure is selected as representative, the pipeline will currently point to it and not clean it. If you don't want this to happen, set this to true. force_rerun (bool): If sequence to structure alignment should be rerun Returns: StructProp: Representative structure from the list of structures. This is a not a map to the original structure, it is copied and optionally cleaned from the original one. Todo: - Remedy large structure representative setting
[ "Set", "a", "representative", "structure", "from", "a", "structure", "in", "the", "structures", "attribute", "." ]
python
train
60.903475
standage/tag
tag/select.py
https://github.com/standage/tag/blob/94686adf57115cea1c5235e99299e691f80ba10b/tag/select.py#L13-L37
def features(entrystream, type=None, traverse=False): """ Pull features out of the specified entry stream. :param entrystream: a stream of entries :param type: retrieve only features of the specified type; set to :code:`None` to retrieve all features :param traverse: by default, only top-level features are selected; set to :code:`True` to search each feature graph for the specified feature type """ for feature in entry_type_filter(entrystream, tag.Feature): if traverse: if type is None: message = 'cannot traverse without a specific feature type' raise ValueError(message) if type == feature.type: yield feature else: for subfeature in feature: if type == subfeature.type: yield subfeature else: if not type or type == feature.type: yield feature
[ "def", "features", "(", "entrystream", ",", "type", "=", "None", ",", "traverse", "=", "False", ")", ":", "for", "feature", "in", "entry_type_filter", "(", "entrystream", ",", "tag", ".", "Feature", ")", ":", "if", "traverse", ":", "if", "type", "is", ...
Pull features out of the specified entry stream. :param entrystream: a stream of entries :param type: retrieve only features of the specified type; set to :code:`None` to retrieve all features :param traverse: by default, only top-level features are selected; set to :code:`True` to search each feature graph for the specified feature type
[ "Pull", "features", "out", "of", "the", "specified", "entry", "stream", "." ]
python
train
40.12
saltstack/salt
salt/_compat.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/_compat.py#L90-L103
def native_(s, encoding='latin-1', errors='strict'): ''' Python 3: If ``s`` is an instance of ``text_type``, return ``s``, otherwise return ``str(s, encoding, errors)`` Python 2: If ``s`` is an instance of ``text_type``, return ``s.encode(encoding, errors)``, otherwise return ``str(s)`` ''' if PY3: out = s if isinstance(s, text_type) else str(s, encoding, errors) else: out = s.encode(encoding, errors) if isinstance(s, text_type) else str(s) return out
[ "def", "native_", "(", "s", ",", "encoding", "=", "'latin-1'", ",", "errors", "=", "'strict'", ")", ":", "if", "PY3", ":", "out", "=", "s", "if", "isinstance", "(", "s", ",", "text_type", ")", "else", "str", "(", "s", ",", "encoding", ",", "errors"...
Python 3: If ``s`` is an instance of ``text_type``, return ``s``, otherwise return ``str(s, encoding, errors)`` Python 2: If ``s`` is an instance of ``text_type``, return ``s.encode(encoding, errors)``, otherwise return ``str(s)``
[ "Python", "3", ":", "If", "s", "is", "an", "instance", "of", "text_type", "return", "s", "otherwise", "return", "str", "(", "s", "encoding", "errors", ")" ]
python
train
35.428571
GNS3/gns3-server
gns3server/controller/gns3vm/virtualbox_gns3_vm.py
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/virtualbox_gns3_vm.py#L304-L312
def set_ram(self, ram): """ Set the RAM amount for the GNS3 VM. :param ram: amount of memory """ yield from self._execute("modifyvm", [self._vmname, "--memory", str(ram)], timeout=3) log.info("GNS3 VM RAM amount set to {}".format(ram))
[ "def", "set_ram", "(", "self", ",", "ram", ")", ":", "yield", "from", "self", ".", "_execute", "(", "\"modifyvm\"", ",", "[", "self", ".", "_vmname", ",", "\"--memory\"", ",", "str", "(", "ram", ")", "]", ",", "timeout", "=", "3", ")", "log", ".", ...
Set the RAM amount for the GNS3 VM. :param ram: amount of memory
[ "Set", "the", "RAM", "amount", "for", "the", "GNS3", "VM", "." ]
python
train
30.777778
drj11/pypng
code/iccp.py
https://github.com/drj11/pypng/blob/b8220ca9f58e4c5bc1d507e713744fcb8c049225/code/iccp.py#L147-L157
def write(self, out): """Write ICC Profile to the file.""" if not self.rawtagtable: self.rawtagtable = self.rawtagdict.items() tags = tagblock(self.rawtagtable) self.writeHeader(out, 128 + len(tags)) out.write(tags) out.flush() return self
[ "def", "write", "(", "self", ",", "out", ")", ":", "if", "not", "self", ".", "rawtagtable", ":", "self", ".", "rawtagtable", "=", "self", ".", "rawtagdict", ".", "items", "(", ")", "tags", "=", "tagblock", "(", "self", ".", "rawtagtable", ")", "self"...
Write ICC Profile to the file.
[ "Write", "ICC", "Profile", "to", "the", "file", "." ]
python
train
27.181818
ChrisBeaumont/smother
smother/cli.py
https://github.com/ChrisBeaumont/smother/blob/65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb/smother/cli.py#L48-L53
def lookup(ctx, path): """ Determine which tests intersect a source interval. """ regions = parse_intervals(path, as_context=ctx.obj['semantic']) _report_from_regions(regions, ctx.obj)
[ "def", "lookup", "(", "ctx", ",", "path", ")", ":", "regions", "=", "parse_intervals", "(", "path", ",", "as_context", "=", "ctx", ".", "obj", "[", "'semantic'", "]", ")", "_report_from_regions", "(", "regions", ",", "ctx", ".", "obj", ")" ]
Determine which tests intersect a source interval.
[ "Determine", "which", "tests", "intersect", "a", "source", "interval", "." ]
python
train
33.166667
pantsbuild/pants
src/python/pants/util/contextutil.py
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/contextutil.py#L194-L206
def temporary_file_path(root_dir=None, cleanup=True, suffix='', permissions=None): """ A with-context that creates a temporary file and returns its path. :API: public You may specify the following keyword args: :param str root_dir: The parent directory to create the temporary file. :param bool cleanup: Whether or not to clean up the temporary file. """ with temporary_file(root_dir, cleanup=cleanup, suffix=suffix, permissions=permissions) as fd: fd.close() yield fd.name
[ "def", "temporary_file_path", "(", "root_dir", "=", "None", ",", "cleanup", "=", "True", ",", "suffix", "=", "''", ",", "permissions", "=", "None", ")", ":", "with", "temporary_file", "(", "root_dir", ",", "cleanup", "=", "cleanup", ",", "suffix", "=", "...
A with-context that creates a temporary file and returns its path. :API: public You may specify the following keyword args: :param str root_dir: The parent directory to create the temporary file. :param bool cleanup: Whether or not to clean up the temporary file.
[ "A", "with", "-", "context", "that", "creates", "a", "temporary", "file", "and", "returns", "its", "path", "." ]
python
train
38.230769
quintusdias/glymur
glymur/codestream.py
https://github.com/quintusdias/glymur/blob/8b8fb091130fff00f1028dc82219e69e3f9baf6d/glymur/codestream.py#L367-L406
def _parse_cod_segment(cls, fptr): """Parse the COD segment. Parameters ---------- fptr : file Open file object. Returns ------- CODSegment The current COD segment. """ offset = fptr.tell() - 2 read_buffer = fptr.read(2) length, = struct.unpack('>H', read_buffer) read_buffer = fptr.read(length - 2) lst = struct.unpack_from('>BBHBBBBBB', read_buffer, offset=0) scod, prog, nlayers, mct, nr, xcb, ycb, cstyle, xform = lst if len(read_buffer) > 10: precinct_size = _parse_precinct_size(read_buffer[10:]) else: precinct_size = None sop = (scod & 2) > 0 eph = (scod & 4) > 0 if sop or eph: cls._parse_tpart_flag = True else: cls._parse_tpart_flag = False pargs = (scod, prog, nlayers, mct, nr, xcb, ycb, cstyle, xform, precinct_size) return CODsegment(*pargs, length=length, offset=offset)
[ "def", "_parse_cod_segment", "(", "cls", ",", "fptr", ")", ":", "offset", "=", "fptr", ".", "tell", "(", ")", "-", "2", "read_buffer", "=", "fptr", ".", "read", "(", "2", ")", "length", ",", "=", "struct", ".", "unpack", "(", "'>H'", ",", "read_buf...
Parse the COD segment. Parameters ---------- fptr : file Open file object. Returns ------- CODSegment The current COD segment.
[ "Parse", "the", "COD", "segment", "." ]
python
train
25.55
ansible/tower-cli
tower_cli/cli/resource.py
https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/cli/resource.py#L59-L95
def _auto_help_text(self, help_text): """Given a method with a docstring, convert the docstring to more CLI appropriate wording, and also disambiguate the word "object" on the base class docstrings. """ # Delete API docs if there are any. api_doc_delimiter = '=====API DOCS=====' begin_api_doc = help_text.find(api_doc_delimiter) if begin_api_doc >= 0: end_api_doc = help_text.rfind(api_doc_delimiter) + len(api_doc_delimiter) help_text = help_text[:begin_api_doc] + help_text[end_api_doc:] # Convert the word "object" to the appropriate type of # object being modified (e.g. user, organization). an_prefix = ('a', 'e', 'i', 'o') if not self.resource_name.lower().startswith(an_prefix): help_text = help_text.replace('an object', 'a %s' % self.resource_name) if self.resource_name.lower().endswith('y'): help_text = help_text.replace( 'objects', '%sies' % self.resource_name[:-1], ) help_text = help_text.replace('object', self.resource_name) # Convert some common Python terms to their CLI equivalents. help_text = help_text.replace('keyword argument', 'option') help_text = help_text.replace('raise an exception', 'abort with an error') # Convert keyword arguments specified in docstrings enclosed # by backticks to switches. for match in re.findall(r'`([\w_]+)`', help_text): option = '--%s' % match.replace('_', '-') help_text = help_text.replace('`%s`' % match, option) # Done; return the new help text. return help_text
[ "def", "_auto_help_text", "(", "self", ",", "help_text", ")", ":", "# Delete API docs if there are any.", "api_doc_delimiter", "=", "'=====API DOCS====='", "begin_api_doc", "=", "help_text", ".", "find", "(", "api_doc_delimiter", ")", "if", "begin_api_doc", ">=", "0", ...
Given a method with a docstring, convert the docstring to more CLI appropriate wording, and also disambiguate the word "object" on the base class docstrings.
[ "Given", "a", "method", "with", "a", "docstring", "convert", "the", "docstring", "to", "more", "CLI", "appropriate", "wording", "and", "also", "disambiguate", "the", "word", "object", "on", "the", "base", "class", "docstrings", "." ]
python
valid
47.675676
hcpl/xkbgroup
xkbgroup/core.py
https://github.com/hcpl/xkbgroup/blob/fcf4709a3c8221e0cdf62c09e5cccda232b0104c/xkbgroup/core.py#L228-L239
def groups_data(self): """All data about all groups (get-only). :getter: Returns all data about all groups :type: list of GroupData """ return _ListProxy(GroupData(num, name, symbol, variant) for (num, name, symbol, variant) in zip(range(self.groups_count), self.groups_names, self.groups_symbols, self.groups_variants))
[ "def", "groups_data", "(", "self", ")", ":", "return", "_ListProxy", "(", "GroupData", "(", "num", ",", "name", ",", "symbol", ",", "variant", ")", "for", "(", "num", ",", "name", ",", "symbol", ",", "variant", ")", "in", "zip", "(", "range", "(", ...
All data about all groups (get-only). :getter: Returns all data about all groups :type: list of GroupData
[ "All", "data", "about", "all", "groups", "(", "get", "-", "only", ")", "." ]
python
train
41.75
PMEAL/OpenPNM
openpnm/algorithms/GenericTransport.py
https://github.com/PMEAL/OpenPNM/blob/0547b5724ffedc0a593aae48639d36fe10e0baed/openpnm/algorithms/GenericTransport.py#L244-L298
def _set_BC(self, pores, bctype, bcvalues=None, mode='merge'): r""" Apply boundary conditions to specified pores Parameters ---------- pores : array_like The pores where the boundary conditions should be applied bctype : string Specifies the type or the name of boundary condition to apply. The types can be one one of the following: - *'value'* : Specify the value of the quantity in each location - *'rate'* : Specify the flow rate into each location bcvalues : int or array_like The boundary value to apply, such as concentration or rate. If a single value is given, it's assumed to apply to all locations. Different values can be applied to all pores in the form of an array of the same length as ``pores``. mode : string, optional Controls how the conditions are applied. Options are: *'merge'*: (Default) Adds supplied boundary conditions to already existing conditions. *'overwrite'*: Deletes all boundary condition on object then add the given ones Notes ----- It is not possible to have multiple boundary conditions for a specified location in one algorithm. Use ``remove_BCs`` to clear existing BCs before applying new ones or ``mode='overwrite'`` which removes all existing BC's before applying the new ones. """ # Hijack the parse_mode function to verify bctype argument bctype = self._parse_mode(bctype, allowed=['value', 'rate'], single=True) mode = self._parse_mode(mode, allowed=['merge', 'overwrite', 'remove'], single=True) pores = self._parse_indices(pores) values = np.array(bcvalues) if values.size > 1 and values.size != pores.size: raise Exception('The number of boundary values must match the ' + 'number of locations') # Store boundary values if ('pore.bc_'+bctype not in self.keys()) or (mode == 'overwrite'): self['pore.bc_'+bctype] = np.nan self['pore.bc_'+bctype][pores] = values
[ "def", "_set_BC", "(", "self", ",", "pores", ",", "bctype", ",", "bcvalues", "=", "None", ",", "mode", "=", "'merge'", ")", ":", "# Hijack the parse_mode function to verify bctype argument", "bctype", "=", "self", ".", "_parse_mode", "(", "bctype", ",", "allowed...
r""" Apply boundary conditions to specified pores Parameters ---------- pores : array_like The pores where the boundary conditions should be applied bctype : string Specifies the type or the name of boundary condition to apply. The types can be one one of the following: - *'value'* : Specify the value of the quantity in each location - *'rate'* : Specify the flow rate into each location bcvalues : int or array_like The boundary value to apply, such as concentration or rate. If a single value is given, it's assumed to apply to all locations. Different values can be applied to all pores in the form of an array of the same length as ``pores``. mode : string, optional Controls how the conditions are applied. Options are: *'merge'*: (Default) Adds supplied boundary conditions to already existing conditions. *'overwrite'*: Deletes all boundary condition on object then add the given ones Notes ----- It is not possible to have multiple boundary conditions for a specified location in one algorithm. Use ``remove_BCs`` to clear existing BCs before applying new ones or ``mode='overwrite'`` which removes all existing BC's before applying the new ones.
[ "r", "Apply", "boundary", "conditions", "to", "specified", "pores" ]
python
train
40.818182
inasafe/inasafe
safe/messaging/item/abstract_list.py
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/messaging/item/abstract_list.py#L50-L71
def add(self, item): """add a Text MessageElement to the existing Text Strings can be passed and are automatically converted in to item.Text() :param item: Text text, an element to add to the text """ if self._is_stringable(item) or self._is_qstring(item): self.items.append(PlainText(item)) elif isinstance(item, MessageElement): self.items.append(item) elif item is None or (hasattr(item, 'isNull') and item.isNull()): self.items.append(PlainText( tr('Null (None) found from the data.'))) elif isinstance(item, tuple) or isinstance(item, list): for i in item: # Recursive call self.add(i) else: raise InvalidMessageItemError(item, item.__class__)
[ "def", "add", "(", "self", ",", "item", ")", ":", "if", "self", ".", "_is_stringable", "(", "item", ")", "or", "self", ".", "_is_qstring", "(", "item", ")", ":", "self", ".", "items", ".", "append", "(", "PlainText", "(", "item", ")", ")", "elif", ...
add a Text MessageElement to the existing Text Strings can be passed and are automatically converted in to item.Text() :param item: Text text, an element to add to the text
[ "add", "a", "Text", "MessageElement", "to", "the", "existing", "Text" ]
python
train
37.181818
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_mac_address_table.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_mac_address_table.py#L265-L279
def get_mac_address_table_input_request_type_get_next_request_last_mac_address_details_last_mac_address(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_mac_address_table = ET.Element("get_mac_address_table") config = get_mac_address_table input = ET.SubElement(get_mac_address_table, "input") request_type = ET.SubElement(input, "request-type") get_next_request = ET.SubElement(request_type, "get-next-request") last_mac_address_details = ET.SubElement(get_next_request, "last-mac-address-details") last_mac_address = ET.SubElement(last_mac_address_details, "last-mac-address") last_mac_address.text = kwargs.pop('last_mac_address') callback = kwargs.pop('callback', self._callback) return callback(config)
[ "def", "get_mac_address_table_input_request_type_get_next_request_last_mac_address_details_last_mac_address", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_mac_address_table", "=", "ET", ".", "Element", ...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
55.133333
pantsbuild/pants
src/python/pants/scm/git.py
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/scm/git.py#L207-L209
def merge_base(self, left='master', right='HEAD'): """Returns the merge-base of master and HEAD in bash: `git merge-base left right`""" return self._check_output(['merge-base', left, right], raise_type=Scm.LocalException)
[ "def", "merge_base", "(", "self", ",", "left", "=", "'master'", ",", "right", "=", "'HEAD'", ")", ":", "return", "self", ".", "_check_output", "(", "[", "'merge-base'", ",", "left", ",", "right", "]", ",", "raise_type", "=", "Scm", ".", "LocalException",...
Returns the merge-base of master and HEAD in bash: `git merge-base left right`
[ "Returns", "the", "merge", "-", "base", "of", "master", "and", "HEAD", "in", "bash", ":", "git", "merge", "-", "base", "left", "right" ]
python
train
75.666667
uw-it-aca/uw-restclients
restclients/grad/committee.py
https://github.com/uw-it-aca/uw-restclients/blob/e12dcd32bf5296b6ebdf71798031594afb7852cb/restclients/grad/committee.py#L31-L68
def _process_json(data): """ return a list of GradCommittee objects. """ requests = [] for item in data: committee = GradCommittee() committee.status = item.get('status') committee.committee_type = item.get('committeeType') committee.dept = item.get('dept') committee.degree_title = item.get('degreeTitle') committee.degree_type = item.get('degreeType') committee.major_full_name = item.get('majorFullName') committee.start_date = datetime_from_string(item.get('startDate')) committee.end_date = datetime_from_string(item.get('endDate')) for member in item.get('members'): if member.get('status') == "inactive": continue com_mem = GradCommitteeMember() com_mem.first_name = member.get('nameFirst') com_mem.last_name = member.get('nameLast') if member.get('memberType') is not None and\ len(member.get('memberType')) > 0: com_mem.member_type = member.get('memberType').lower() if member.get('readingType') is not None and\ len(member.get('readingType')) > 0: com_mem.reading_type = member.get('readingType').lower() com_mem.dept = member.get('dept') com_mem.email = member.get('email') com_mem.status = member.get('status') committee.members.append(com_mem) requests.append(committee) return requests
[ "def", "_process_json", "(", "data", ")", ":", "requests", "=", "[", "]", "for", "item", "in", "data", ":", "committee", "=", "GradCommittee", "(", ")", "committee", ".", "status", "=", "item", ".", "get", "(", "'status'", ")", "committee", ".", "commi...
return a list of GradCommittee objects.
[ "return", "a", "list", "of", "GradCommittee", "objects", "." ]
python
train
39.131579
DataDog/integrations-core
sqlserver/datadog_checks/sqlserver/sqlserver.py
https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/sqlserver/datadog_checks/sqlserver/sqlserver.py#L365-L389
def _conn_string_odbc(self, db_key, instance=None, conn_key=None, db_name=None): ''' Return a connection string to use with odbc ''' if instance: dsn, host, username, password, database, driver = self._get_access_info(instance, db_key, db_name) elif conn_key: dsn, host, username, password, database, driver = conn_key.split(":") conn_str = '' if dsn: conn_str = 'DSN={};'.format(dsn) if driver: conn_str += 'DRIVER={};'.format(driver) if host: conn_str += 'Server={};'.format(host) if database: conn_str += 'Database={};'.format(database) if username: conn_str += 'UID={};'.format(username) self.log.debug("Connection string (before password) {}".format(conn_str)) if password: conn_str += 'PWD={};'.format(password) return conn_str
[ "def", "_conn_string_odbc", "(", "self", ",", "db_key", ",", "instance", "=", "None", ",", "conn_key", "=", "None", ",", "db_name", "=", "None", ")", ":", "if", "instance", ":", "dsn", ",", "host", ",", "username", ",", "password", ",", "database", ","...
Return a connection string to use with odbc
[ "Return", "a", "connection", "string", "to", "use", "with", "odbc" ]
python
train
36.48
jpweiser/cuts
cuts/main.py
https://github.com/jpweiser/cuts/blob/5baf7f2e145045942ee8dcaccbc47f8f821fcb56/cuts/main.py#L34-L60
def _parse_args(args): """Setup argparser to process arguments and generate help""" # parser uses custom usage string, with 'usage: ' removed, as it is # added automatically via argparser. parser = argparse.ArgumentParser(description="Remove and/or rearrange " + "sections from each line of a file(s).", usage=_usage()[len('usage: '):]) parser.add_argument('-b', "--bytes", action='store', type=lst, default=[], help="Bytes to select") parser.add_argument('-c', "--chars", action='store', type=lst, default=[], help="Character to select") parser.add_argument('-f', "--fields", action='store', type=lst, default=[], help="Fields to select") parser.add_argument('-d', "--delimiter", action='store', default="\t", help="Sets field delimiter(default is TAB)") parser.add_argument('-e', "--regex", action='store_true', help='Enable regular expressions to be used as input '+ 'delimiter') parser.add_argument('-s', '--skip', action='store_true', help="Skip lines that do not contain input delimiter.") parser.add_argument('-S', "--separator", action='store', default="\t", help="Sets field separator for output.") parser.add_argument('file', nargs='*', default="-", help="File(s) to cut") return parser.parse_args(args)
[ "def", "_parse_args", "(", "args", ")", ":", "# parser uses custom usage string, with 'usage: ' removed, as it is", "# added automatically via argparser.", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Remove and/or rearrange \"", "+", "\"sections ...
Setup argparser to process arguments and generate help
[ "Setup", "argparser", "to", "process", "arguments", "and", "generate", "help" ]
python
valid
56.703704
juju/charm-helpers
charmhelpers/contrib/openstack/cert_utils.py
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/cert_utils.py#L244-L263
def get_requests_for_local_unit(relation_name=None): """Extract any certificates data targeted at this unit down relation_name. :param relation_name: str Name of relation to check for data. :returns: List of bundles of certificates. :rtype: List of dicts """ local_name = local_unit().replace('/', '_') raw_certs_key = '{}.processed_requests'.format(local_name) relation_name = relation_name or 'certificates' bundles = [] for rid in relation_ids(relation_name): for unit in related_units(rid): data = relation_get(rid=rid, unit=unit) if data.get(raw_certs_key): bundles.append({ 'ca': data['ca'], 'chain': data.get('chain'), 'certs': json.loads(data[raw_certs_key])}) return bundles
[ "def", "get_requests_for_local_unit", "(", "relation_name", "=", "None", ")", ":", "local_name", "=", "local_unit", "(", ")", ".", "replace", "(", "'/'", ",", "'_'", ")", "raw_certs_key", "=", "'{}.processed_requests'", ".", "format", "(", "local_name", ")", "...
Extract any certificates data targeted at this unit down relation_name. :param relation_name: str Name of relation to check for data. :returns: List of bundles of certificates. :rtype: List of dicts
[ "Extract", "any", "certificates", "data", "targeted", "at", "this", "unit", "down", "relation_name", "." ]
python
train
40.85
proteanhq/protean
src/protean/services/email/utils.py
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/services/email/utils.py#L8-L15
def get_connection(backend=None, fail_silently=False, **kwargs): """Load an email backend and return an instance of it. If backend is None (default), use settings.EMAIL_BACKEND. Both fail_silently and other keyword arguments are used in the constructor of the backend. """ klass = perform_import(backend or active_config.EMAIL_BACKEND) return klass(fail_silently=fail_silently, **kwargs)
[ "def", "get_connection", "(", "backend", "=", "None", ",", "fail_silently", "=", "False", ",", "*", "*", "kwargs", ")", ":", "klass", "=", "perform_import", "(", "backend", "or", "active_config", ".", "EMAIL_BACKEND", ")", "return", "klass", "(", "fail_silen...
Load an email backend and return an instance of it. If backend is None (default), use settings.EMAIL_BACKEND. Both fail_silently and other keyword arguments are used in the constructor of the backend.
[ "Load", "an", "email", "backend", "and", "return", "an", "instance", "of", "it", ".", "If", "backend", "is", "None", "(", "default", ")", "use", "settings", ".", "EMAIL_BACKEND", ".", "Both", "fail_silently", "and", "other", "keyword", "arguments", "are", ...
python
train
51
Morrolan/surrealism
surrealism.py
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L814-L841
def __check_spaces(sentence): """ Here we check to see that we have the correct number of spaces in the correct locations. :param _sentence: :return: """ # We have to run the process multiple times: # Once to search for all spaces, and check if there are adjoining spaces; # The second time to check for 2 spaces after sentence-ending characters such as . and ! and ? if sentence is not None: words = sentence.split() new_sentence = '' for (i, word) in enumerate(words): if word[-1] in set('.!?'): word += ' ' new_word = ''.join(word) new_sentence += ' ' + new_word # remove any trailing whitespace new_sentence = new_sentence.strip() return new_sentence
[ "def", "__check_spaces", "(", "sentence", ")", ":", "# We have to run the process multiple times:", "# Once to search for all spaces, and check if there are adjoining spaces;", "# The second time to check for 2 spaces after sentence-ending characters such as . and ! and ?", "if", "sentence",...
Here we check to see that we have the correct number of spaces in the correct locations. :param _sentence: :return:
[ "Here", "we", "check", "to", "see", "that", "we", "have", "the", "correct", "number", "of", "spaces", "in", "the", "correct", "locations", "." ]
python
train
27.535714
numenta/htmresearch
htmresearch/support/union_temporal_pooler_monitor_mixin.py
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/union_temporal_pooler_monitor_mixin.py#L291-L308
def mmGetPlotStability(self, title="Stability", showReset=False, resetShading=0.25): """ Returns plot of the overlap metric between union SDRs within a sequence. @param title an optional title for the figure @return (Plot) plot """ plot = Plot(self, title) self._mmComputeSequenceRepresentationData() data = self._mmData["stabilityConfusion"] plot.addGraph(sorted(data, reverse=True), position=211, xlabel="Time steps", ylabel="Overlap") plot.addHistogram(data, position=212, bins=100, xlabel="Overlap", ylabel="# time steps") return plot
[ "def", "mmGetPlotStability", "(", "self", ",", "title", "=", "\"Stability\"", ",", "showReset", "=", "False", ",", "resetShading", "=", "0.25", ")", ":", "plot", "=", "Plot", "(", "self", ",", "title", ")", "self", ".", "_mmComputeSequenceRepresentationData", ...
Returns plot of the overlap metric between union SDRs within a sequence. @param title an optional title for the figure @return (Plot) plot
[ "Returns", "plot", "of", "the", "overlap", "metric", "between", "union", "SDRs", "within", "a", "sequence", "." ]
python
train
38.444444
YeoLab/anchor
anchor/infotheory.py
https://github.com/YeoLab/anchor/blob/1f9c9d6d30235b1e77b945e6ef01db5a0e55d53a/anchor/infotheory.py#L190-L215
def binify_and_jsd(df1, df2, bins, pair=None): """Binify and calculate jensen-shannon divergence between two dataframes Parameters ---------- df1, df2 : pandas.DataFrames Dataframes to calculate JSD between columns of. Must have overlapping column names bins : array-like Bins to use for transforming df{1,2} into probability distributions pair : str, optional Name of the pair to save as the name of the series Returns ------- divergence : pandas.Series The Jensen-Shannon divergence between columns of df1, df2 """ binned1 = binify(df1, bins=bins).dropna(how='all', axis=1) binned2 = binify(df2, bins=bins).dropna(how='all', axis=1) binned1, binned2 = binned1.align(binned2, axis=1, join='inner') series = np.sqrt(jsd(binned1, binned2)) series.name = pair return series
[ "def", "binify_and_jsd", "(", "df1", ",", "df2", ",", "bins", ",", "pair", "=", "None", ")", ":", "binned1", "=", "binify", "(", "df1", ",", "bins", "=", "bins", ")", ".", "dropna", "(", "how", "=", "'all'", ",", "axis", "=", "1", ")", "binned2",...
Binify and calculate jensen-shannon divergence between two dataframes Parameters ---------- df1, df2 : pandas.DataFrames Dataframes to calculate JSD between columns of. Must have overlapping column names bins : array-like Bins to use for transforming df{1,2} into probability distributions pair : str, optional Name of the pair to save as the name of the series Returns ------- divergence : pandas.Series The Jensen-Shannon divergence between columns of df1, df2
[ "Binify", "and", "calculate", "jensen", "-", "shannon", "divergence", "between", "two", "dataframes" ]
python
train
32.846154
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_aaa.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_aaa.py#L631-L642
def rule_action(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") rule = ET.SubElement(config, "rule", xmlns="urn:brocade.com:mgmt:brocade-aaa") index_key = ET.SubElement(rule, "index") index_key.text = kwargs.pop('index') action = ET.SubElement(rule, "action") action.text = kwargs.pop('action') callback = kwargs.pop('callback', self._callback) return callback(config)
[ "def", "rule_action", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "rule", "=", "ET", ".", "SubElement", "(", "config", ",", "\"rule\"", ",", "xmlns", "=", "\"urn:brocade.com:mgmt:brocade-aaa\...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
38.666667
zhanglab/psamm
psamm/balancecheck.py
https://github.com/zhanglab/psamm/blob/dc427848c4f9d109ca590f0afa024c63b685b3f4/psamm/balancecheck.py#L91-L117
def formula_balance(model): """Calculate formula compositions for each reaction. Call :func:`reaction_formula` for each reaction. Yield (reaction, result) pairs, where result has two formula compositions or `None`. Args: model: :class:`psamm.datasource.native.NativeModel`. """ # Mapping from compound id to formula compound_formula = {} for compound in model.compounds: if compound.formula is not None: try: f = Formula.parse(compound.formula).flattened() compound_formula[compound.id] = f except ParseError as e: msg = 'Error parsing formula for compound {}:\n{}\n{}'.format( compound.id, e, compound.formula) if e.indicator is not None: msg += '\n{}'.format(e.indicator) logger.warning(msg) for reaction in model.reactions: yield reaction, reaction_formula(reaction.equation, compound_formula)
[ "def", "formula_balance", "(", "model", ")", ":", "# Mapping from compound id to formula", "compound_formula", "=", "{", "}", "for", "compound", "in", "model", ".", "compounds", ":", "if", "compound", ".", "formula", "is", "not", "None", ":", "try", ":", "f", ...
Calculate formula compositions for each reaction. Call :func:`reaction_formula` for each reaction. Yield (reaction, result) pairs, where result has two formula compositions or `None`. Args: model: :class:`psamm.datasource.native.NativeModel`.
[ "Calculate", "formula", "compositions", "for", "each", "reaction", "." ]
python
train
36.37037
jf-parent/brome
brome/runner/local_runner.py
https://github.com/jf-parent/brome/blob/784f45d96b83b703dd2181cb59ca8ea777c2510e/brome/runner/local_runner.py#L43-L78
def run(self): """Run the test batch """ self.info_log("The test batch is ready.") self.executed_tests = [] for test in self.tests: localhost_instance = LocalhostInstance( runner=self, browser_config=self.browser_config, test_name=test.Test.name ) localhost_instance.startup() with DbSessionContext(BROME_CONFIG['database']['mongo_database_name']) as session: # noqa test_batch = session.query(Testbatch)\ .filter(Testbatch.mongo_id == self.test_batch_id).one() test_batch.total_executing_tests = 1 session.save(test_batch, safe=True) test_ = test.Test( runner=self, browser_config=self.browser_config, name=test.Test.name, test_batch_id=self.test_batch_id, localhost_instance=localhost_instance, index=1 ) test_.execute() self.executed_tests.append(test_) localhost_instance.tear_down()
[ "def", "run", "(", "self", ")", ":", "self", ".", "info_log", "(", "\"The test batch is ready.\"", ")", "self", ".", "executed_tests", "=", "[", "]", "for", "test", "in", "self", ".", "tests", ":", "localhost_instance", "=", "LocalhostInstance", "(", "runner...
Run the test batch
[ "Run", "the", "test", "batch" ]
python
train
31.138889
danilobellini/audiolazy
examples/play_bach_choral.py
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/examples/play_bach_choral.py#L33-L40
def ks_synth(freq): """ Synthesize the given frequency into a Stream by using a model based on Karplus-Strong. """ ks_mem = (sum(lz.sinusoid(x * freq) for x in [1, 3, 9]) + lz.white_noise() + lz.Stream(-1, 1)) / 5 return lz.karplus_strong(freq, memory=ks_mem)
[ "def", "ks_synth", "(", "freq", ")", ":", "ks_mem", "=", "(", "sum", "(", "lz", ".", "sinusoid", "(", "x", "*", "freq", ")", "for", "x", "in", "[", "1", ",", "3", ",", "9", "]", ")", "+", "lz", ".", "white_noise", "(", ")", "+", "lz", ".", ...
Synthesize the given frequency into a Stream by using a model based on Karplus-Strong.
[ "Synthesize", "the", "given", "frequency", "into", "a", "Stream", "by", "using", "a", "model", "based", "on", "Karplus", "-", "Strong", "." ]
python
train
34.5
gem/oq-engine
openquake/hazardlib/gsim/abrahamson_2014.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_2014.py#L231-L283
def _get_hanging_wall_term(self, C, dists, rup): """ Compute and return hanging wall model term, see page 1038. """ if rup.dip == 90.0: return np.zeros_like(dists.rx) else: Fhw = np.zeros_like(dists.rx) Fhw[dists.rx > 0] = 1. # Compute taper t1 T1 = np.ones_like(dists.rx) T1 *= 60./45. if rup.dip <= 30. else (90.-rup.dip)/45.0 # Compute taper t2 (eq 12 at page 1039) - a2hw set to 0.2 as # indicated at page 1041 T2 = np.zeros_like(dists.rx) a2hw = 0.2 if rup.mag > 6.5: T2 += (1. + a2hw * (rup.mag - 6.5)) elif rup.mag > 5.5: T2 += (1. + a2hw * (rup.mag - 6.5) - (1. - a2hw) * (rup.mag - 6.5)**2) else: T2 *= 0. # Compute taper t3 (eq. 13 at page 1039) - r1 and r2 specified at # page 1040 T3 = np.zeros_like(dists.rx) r1 = rup.width * np.cos(np.radians(rup.dip)) r2 = 3. * r1 # idx = dists.rx < r1 T3[idx] = (np.ones_like(dists.rx)[idx] * self.CONSTS['h1'] + self.CONSTS['h2'] * (dists.rx[idx] / r1) + self.CONSTS['h3'] * (dists.rx[idx] / r1)**2) # idx = ((dists.rx >= r1) & (dists.rx <= r2)) T3[idx] = 1. - (dists.rx[idx] - r1) / (r2 - r1) # Compute taper t4 (eq. 14 at page 1040) T4 = np.zeros_like(dists.rx) # if rup.ztor <= 10.: T4 += (1. - rup.ztor**2. / 100.) # Compute T5 (eq 15a at page 1040) - ry1 computed according to # suggestions provided at page 1040 T5 = np.zeros_like(dists.rx) ry1 = dists.rx * np.tan(np.radians(20.)) # idx = (dists.ry0 - ry1) <= 0.0 T5[idx] = 1. # idx = (((dists.ry0 - ry1) > 0.0) & ((dists.ry0 - ry1) < 5.0)) T5[idx] = 1. - (dists.ry0[idx] - ry1[idx]) / 5.0 # Finally, compute the hanging wall term return Fhw*C['a13']*T1*T2*T3*T4*T5
[ "def", "_get_hanging_wall_term", "(", "self", ",", "C", ",", "dists", ",", "rup", ")", ":", "if", "rup", ".", "dip", "==", "90.0", ":", "return", "np", ".", "zeros_like", "(", "dists", ".", "rx", ")", "else", ":", "Fhw", "=", "np", ".", "zeros_like...
Compute and return hanging wall model term, see page 1038.
[ "Compute", "and", "return", "hanging", "wall", "model", "term", "see", "page", "1038", "." ]
python
train
41.018868
arne-cl/discoursegraphs
src/discoursegraphs/readwrite/conll.py
https://github.com/arne-cl/discoursegraphs/blob/842f0068a3190be2c75905754521b176b25a54fb/src/discoursegraphs/readwrite/conll.py#L201-L224
def __add_sentence_root_node(self, sent_number): """ adds the root node of a sentence to the graph and the list of sentences (``self.sentences``). the node has a ``tokens` attribute, which contains a list of the tokens (token node IDs) of this sentence. Parameters ---------- sent_number : int the index of the sentence within the document Results ------- sent_id : str the ID of the sentence """ sent_id = 's{}'.format(sent_number) self.add_node(sent_id, layers={self.ns, self.ns+':sentence'}, tokens=[]) self.add_edge(self.root, sent_id, layers={self.ns, self.ns+':sentence'}, edge_type=EdgeTypes.dominance_relation) self.sentences.append(sent_id) return sent_id
[ "def", "__add_sentence_root_node", "(", "self", ",", "sent_number", ")", ":", "sent_id", "=", "'s{}'", ".", "format", "(", "sent_number", ")", "self", ".", "add_node", "(", "sent_id", ",", "layers", "=", "{", "self", ".", "ns", ",", "self", ".", "ns", ...
adds the root node of a sentence to the graph and the list of sentences (``self.sentences``). the node has a ``tokens` attribute, which contains a list of the tokens (token node IDs) of this sentence. Parameters ---------- sent_number : int the index of the sentence within the document Results ------- sent_id : str the ID of the sentence
[ "adds", "the", "root", "node", "of", "a", "sentence", "to", "the", "graph", "and", "the", "list", "of", "sentences", "(", "self", ".", "sentences", ")", ".", "the", "node", "has", "a", "tokens", "attribute", "which", "contains", "a", "list", "of", "the...
python
train
35.875
bitlabstudio/django-calendarium
calendarium/utils.py
https://github.com/bitlabstudio/django-calendarium/blob/cabe69eff965dff80893012fb4dfe724e995807a/calendarium/utils.py#L57-L64
def get_occurrence(self, occ): """ Return a persisted occurrences matching the occ and remove it from lookup since it has already been matched """ return self.lookup.pop( (occ.event, occ.original_start, occ.original_end), occ)
[ "def", "get_occurrence", "(", "self", ",", "occ", ")", ":", "return", "self", ".", "lookup", ".", "pop", "(", "(", "occ", ".", "event", ",", "occ", ".", "original_start", ",", "occ", ".", "original_end", ")", ",", "occ", ")" ]
Return a persisted occurrences matching the occ and remove it from lookup since it has already been matched
[ "Return", "a", "persisted", "occurrences", "matching", "the", "occ", "and", "remove", "it", "from", "lookup", "since", "it", "has", "already", "been", "matched" ]
python
train
35.375
pyviz/holoviews
holoviews/plotting/bokeh/sankey.py
https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/plotting/bokeh/sankey.py#L117-L178
def _compute_labels(self, element, data, mapping): """ Computes labels for the nodes and adds it to the data. """ if element.vdims: edges = Dataset(element)[element[element.vdims[0].name]>0] nodes = list(np.unique([edges.dimension_values(i) for i in range(2)])) nodes = element.nodes.select(**{element.nodes.kdims[2].name: nodes}) else: nodes = element label_dim = nodes.get_dimension(self.label_index) labels = self.labels if label_dim and labels: if self.label_index not in [2, None]: self.param.warning( "Cannot declare style mapping for 'labels' option " "and declare a label_index; ignoring the label_index.") elif label_dim: labels = label_dim if isinstance(labels, basestring): labels = element.nodes.get_dimension(labels) if labels is None: text = [] if isinstance(labels, dim): text = labels.apply(element, flat=True) else: text = element.nodes.dimension_values(labels) text = [labels.pprint_value(v) for v in text] value_dim = element.vdims[0] text_labels = [] for i, node in enumerate(element._sankey['nodes']): if len(text): label = text[i] else: label = '' if self.show_values: value = value_dim.pprint_value(node['value']) if label: label = '%s - %s' % (label, value) else: label = value if value_dim.unit: label += ' %s' % value_dim.unit if label: text_labels.append(label) ys = nodes.dimension_values(1) nodes = element._sankey['nodes'] if nodes: offset = (nodes[0]['x1']-nodes[0]['x0'])/4. else: offset = 0 if self.label_position == 'right': xs = np.array([node['x1'] for node in nodes])+offset else: xs = np.array([node['x0'] for node in nodes])-offset data['text_1'] = dict(x=xs, y=ys, text=[str(l) for l in text_labels]) align = 'left' if self.label_position == 'right' else 'right' mapping['text_1'] = dict(text='text', x='x', y='y', text_baseline='middle', text_align=align)
[ "def", "_compute_labels", "(", "self", ",", "element", ",", "data", ",", "mapping", ")", ":", "if", "element", ".", "vdims", ":", "edges", "=", "Dataset", "(", "element", ")", "[", "element", "[", "element", ".", "vdims", "[", "0", "]", ".", "name", ...
Computes labels for the nodes and adds it to the data.
[ "Computes", "labels", "for", "the", "nodes", "and", "adds", "it", "to", "the", "data", "." ]
python
train
38.5
redhat-cip/python-dciclient
dciclient/v1/shell_commands/topic.py
https://github.com/redhat-cip/python-dciclient/blob/a4aa5899062802bbe4c30a075d8447f8d222d214/dciclient/v1/shell_commands/topic.py#L57-L76
def create(context, name, component_types, active, product_id, data): """create(context, name, component_types, active, product_id, data) Create a topic. >>> dcictl topic-create [OPTIONS] :param string name: Name of the topic [required] :param string component_types: list of component types separated by commas :param boolean active: Set the topic in the (in)active state :param string product_id: The product the topic belongs to :param string data: JSON data of the topic """ if component_types: component_types = component_types.split(',') state = utils.active_string(active) result = topic.create(context, name=name, component_types=component_types, state=state, product_id=product_id, data=data) utils.format_output(result, context.format)
[ "def", "create", "(", "context", ",", "name", ",", "component_types", ",", "active", ",", "product_id", ",", "data", ")", ":", "if", "component_types", ":", "component_types", "=", "component_types", ".", "split", "(", "','", ")", "state", "=", "utils", "....
create(context, name, component_types, active, product_id, data) Create a topic. >>> dcictl topic-create [OPTIONS] :param string name: Name of the topic [required] :param string component_types: list of component types separated by commas :param boolean active: Set the topic in the (in)active state :param string product_id: The product the topic belongs to :param string data: JSON data of the topic
[ "create", "(", "context", "name", "component_types", "active", "product_id", "data", ")" ]
python
train
40.8
apache/incubator-mxnet
python/mxnet/contrib/onnx/mx2onnx/export_onnx.py
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/mx2onnx/export_onnx.py#L86-L92
def convert_layer(node, **kwargs): """Convert MXNet layer to ONNX""" op = str(node["op"]) if op not in MXNetGraph.registry_: raise AttributeError("No conversion function registered for op type %s yet." % op) convert_func = MXNetGraph.registry_[op] return convert_func(node, **kwargs)
[ "def", "convert_layer", "(", "node", ",", "*", "*", "kwargs", ")", ":", "op", "=", "str", "(", "node", "[", "\"op\"", "]", ")", "if", "op", "not", "in", "MXNetGraph", ".", "registry_", ":", "raise", "AttributeError", "(", "\"No conversion function register...
Convert MXNet layer to ONNX
[ "Convert", "MXNet", "layer", "to", "ONNX" ]
python
train
47
onicagroup/runway
runway/module/terraform.py
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/module/terraform.py#L58-L64
def get_backend_init_list(backend_vals): """Turn backend config dict into command line items.""" cmd_list = [] for (key, val) in backend_vals.items(): cmd_list.append('-backend-config') cmd_list.append(key + '=' + val) return cmd_list
[ "def", "get_backend_init_list", "(", "backend_vals", ")", ":", "cmd_list", "=", "[", "]", "for", "(", "key", ",", "val", ")", "in", "backend_vals", ".", "items", "(", ")", ":", "cmd_list", ".", "append", "(", "'-backend-config'", ")", "cmd_list", ".", "a...
Turn backend config dict into command line items.
[ "Turn", "backend", "config", "dict", "into", "command", "line", "items", "." ]
python
train
37.142857
Hackerfleet/hfos
hfos/tool/user.py
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/tool/user.py#L207-L225
def add_role(ctx, role): """Grant a role to an existing user""" if role is None: log('Specify the role with --role') return if ctx.obj['username'] is None: log('Specify the username with --username') return change_user = ctx.obj['db'].objectmodels['user'].find_one({ 'name': ctx.obj['username'] }) if role not in change_user.roles: change_user.roles.append(role) change_user.save() log('Done') else: log('User already has that role!', lvl=warn)
[ "def", "add_role", "(", "ctx", ",", "role", ")", ":", "if", "role", "is", "None", ":", "log", "(", "'Specify the role with --role'", ")", "return", "if", "ctx", ".", "obj", "[", "'username'", "]", "is", "None", ":", "log", "(", "'Specify the username with ...
Grant a role to an existing user
[ "Grant", "a", "role", "to", "an", "existing", "user" ]
python
train
27.789474
PmagPy/PmagPy
dialogs/magic_grid2.py
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/magic_grid2.py#L276-L297
def remove_row(self, row_num=None): """ Remove a row from the grid """ #DeleteRows(self, pos, numRows, updateLabel if not row_num and row_num != 0: row_num = self.GetNumberRows() - 1 label = self.GetCellValue(row_num, 0) self.DeleteRows(pos=row_num, numRows=1, updateLabels=True) # remove label from row_labels try: self.row_labels.remove(label) except ValueError: # if label name hasn't been saved yet, simply truncate row_labels self.row_labels = self.row_labels[:-1] self.row_items.pop(row_num) if not self.changes: self.changes = set() self.changes.add(-1) # fix #s for rows edited: self.update_changes_after_row_delete(row_num)
[ "def", "remove_row", "(", "self", ",", "row_num", "=", "None", ")", ":", "#DeleteRows(self, pos, numRows, updateLabel", "if", "not", "row_num", "and", "row_num", "!=", "0", ":", "row_num", "=", "self", ".", "GetNumberRows", "(", ")", "-", "1", "label", "=", ...
Remove a row from the grid
[ "Remove", "a", "row", "from", "the", "grid" ]
python
train
36
matthewdeanmartin/jiggle_version
jiggle_version/find_version_by_package.py
https://github.com/matthewdeanmartin/jiggle_version/blob/963656a0a47b7162780a5f6c8f4b8bbbebc148f5/jiggle_version/find_version_by_package.py#L58-L74
def guess_version_by_running_live_package( pkg_key, default="?" ): # type: (str,str) -> Any """Guess the version of a pkg when pip doesn't provide it. :param str pkg_key: key of the package :param str default: default version to return if unable to find :returns: version :rtype: string """ try: m = import_module(pkg_key) except ImportError: return default else: return getattr(m, "__version__", default)
[ "def", "guess_version_by_running_live_package", "(", "pkg_key", ",", "default", "=", "\"?\"", ")", ":", "# type: (str,str) -> Any", "try", ":", "m", "=", "import_module", "(", "pkg_key", ")", "except", "ImportError", ":", "return", "default", "else", ":", "return"...
Guess the version of a pkg when pip doesn't provide it. :param str pkg_key: key of the package :param str default: default version to return if unable to find :returns: version :rtype: string
[ "Guess", "the", "version", "of", "a", "pkg", "when", "pip", "doesn", "t", "provide", "it", "." ]
python
train
26.823529
dims/etcd3-gateway
etcd3gw/lease.py
https://github.com/dims/etcd3-gateway/blob/ad566c29cbde135aee20cfd32e0a4815ca3b5ee6/etcd3gw/lease.py#L66-L75
def keys(self): """Get the keys associated with this lease. :return: """ result = self.client.post(self.client.get_url("/kv/lease/timetolive"), json={"ID": self.id, "keys": True}) keys = result['keys'] if 'keys' in result else [] return [_decode(key) for key in keys]
[ "def", "keys", "(", "self", ")", ":", "result", "=", "self", ".", "client", ".", "post", "(", "self", ".", "client", ".", "get_url", "(", "\"/kv/lease/timetolive\"", ")", ",", "json", "=", "{", "\"ID\"", ":", "self", ".", "id", ",", "\"keys\"", ":", ...
Get the keys associated with this lease. :return:
[ "Get", "the", "keys", "associated", "with", "this", "lease", "." ]
python
train
38.1
googledatalab/pydatalab
google/datalab/storage/_object.py
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_object.py#L69-L72
def updated_on(self): """The updated timestamp of the object as a datetime.datetime.""" s = self._info.get('updated', None) return dateutil.parser.parse(s) if s else None
[ "def", "updated_on", "(", "self", ")", ":", "s", "=", "self", ".", "_info", ".", "get", "(", "'updated'", ",", "None", ")", "return", "dateutil", ".", "parser", ".", "parse", "(", "s", ")", "if", "s", "else", "None" ]
The updated timestamp of the object as a datetime.datetime.
[ "The", "updated", "timestamp", "of", "the", "object", "as", "a", "datetime", ".", "datetime", "." ]
python
train
44.75
brocade/pynos
pynos/versions/ver_7/ver_7_1_0/yang/brocade_tunnels.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_tunnels.py#L258-L271
def overlay_gateway_map_vlan_vni_auto(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns="urn:brocade.com:mgmt:brocade-tunnels") name_key = ET.SubElement(overlay_gateway, "name") name_key.text = kwargs.pop('name') map = ET.SubElement(overlay_gateway, "map") vlan = ET.SubElement(map, "vlan") vni = ET.SubElement(vlan, "vni") auto = ET.SubElement(vni, "auto") callback = kwargs.pop('callback', self._callback) return callback(config)
[ "def", "overlay_gateway_map_vlan_vni_auto", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "overlay_gateway", "=", "ET", ".", "SubElement", "(", "config", ",", "\"overlay-gateway\"", ",", "xmlns", ...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
43.142857
funkybob/knights-templater
knights/tags.py
https://github.com/funkybob/knights-templater/blob/b15cdbaae7d824d02f7f03ca04599ae94bb759dd/knights/tags.py#L225-L245
def use(parser, token): ''' Counterpart to `macro`, lets you render any block/macro in place. ''' args, kwargs = parser.parse_args(token) assert isinstance(args[0], ast.Str), \ 'First argument to "include" tag must be a string' name = args[0].s action = ast.YieldFrom( value=_a.Call(_a.Attribute(_a.Name('self'), name), [ _a.Name('context'), ]) ) if kwargs: kwargs = _wrap_kwargs(kwargs) return _create_with_scope([ast.Expr(value=action)], kwargs) return action
[ "def", "use", "(", "parser", ",", "token", ")", ":", "args", ",", "kwargs", "=", "parser", ".", "parse_args", "(", "token", ")", "assert", "isinstance", "(", "args", "[", "0", "]", ",", "ast", ".", "Str", ")", ",", "'First argument to \"include\" tag mus...
Counterpart to `macro`, lets you render any block/macro in place.
[ "Counterpart", "to", "macro", "lets", "you", "render", "any", "block", "/", "macro", "in", "place", "." ]
python
train
25.571429
SoCo/SoCo
soco/plugins/wimp.py
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/plugins/wimp.py#L452-L482
def _base_body(self): """Return the base XML body, which has the following form: .. code :: xml <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> <s:Header> <credentials xmlns="http://www.sonos.com/Services/1.1"> <sessionId>self._session_id</sessionId> <deviceId>self._serial_number</deviceId> <deviceProvider>Sonos</deviceProvider> </credentials> </s:Header> </s:Envelope> """ item_attrib = { 'xmlns:s': 'http://schemas.xmlsoap.org/soap/envelope/', } xml = XML.Element('s:Envelope', item_attrib) # Add the Header part XML.SubElement(xml, 's:Header') item_attrib = { 'xmlns': 'http://www.sonos.com/Services/1.1' } credentials = XML.SubElement(xml[0], 'credentials', item_attrib) XML.SubElement(credentials, 'sessionId').text = self._session_id XML.SubElement(credentials, 'deviceId').text = self._serial_number XML.SubElement(credentials, 'deviceProvider').text = 'Sonos' return xml
[ "def", "_base_body", "(", "self", ")", ":", "item_attrib", "=", "{", "'xmlns:s'", ":", "'http://schemas.xmlsoap.org/soap/envelope/'", ",", "}", "xml", "=", "XML", ".", "Element", "(", "'s:Envelope'", ",", "item_attrib", ")", "# Add the Header part", "XML", ".", ...
Return the base XML body, which has the following form: .. code :: xml <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> <s:Header> <credentials xmlns="http://www.sonos.com/Services/1.1"> <sessionId>self._session_id</sessionId> <deviceId>self._serial_number</deviceId> <deviceProvider>Sonos</deviceProvider> </credentials> </s:Header> </s:Envelope>
[ "Return", "the", "base", "XML", "body", "which", "has", "the", "following", "form", ":" ]
python
train
36.322581
pauleveritt/kaybee
kaybee/plugins/references/base_reference.py
https://github.com/pauleveritt/kaybee/blob/a00a718aaaa23b2d12db30dfacb6b2b6ec84459c/kaybee/plugins/references/base_reference.py#L23-L33
def get_sources(self, resources): """ Filter resources based on which have this reference """ rtype = self.rtype # E.g. category label = self.props.label # E.g. category1 result = [ resource for resource in resources.values() if is_reference_target(resource, rtype, label) ] return result
[ "def", "get_sources", "(", "self", ",", "resources", ")", ":", "rtype", "=", "self", ".", "rtype", "# E.g. category", "label", "=", "self", ".", "props", ".", "label", "# E.g. category1", "result", "=", "[", "resource", "for", "resource", "in", "resources", ...
Filter resources based on which have this reference
[ "Filter", "resources", "based", "on", "which", "have", "this", "reference" ]
python
train
33.181818
phoebe-project/phoebe2
phoebe/parameters/constraint.py
https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/constraint.py#L126-L130
def roche_requiv_contact_L1(q, sma, compno=1): """ TODO: add documentation """ return ConstraintParameter(q._bundle, "requiv_contact_L1(%s, %d)" % (", ".join(["{%s}" % (param.uniquetwig if hasattr(param, 'uniquetwig') else param.expr) for param in (q, sma)]), compno))
[ "def", "roche_requiv_contact_L1", "(", "q", ",", "sma", ",", "compno", "=", "1", ")", ":", "return", "ConstraintParameter", "(", "q", ".", "_bundle", ",", "\"requiv_contact_L1(%s, %d)\"", "%", "(", "\", \"", ".", "join", "(", "[", "\"{%s}\"", "%", "(", "pa...
TODO: add documentation
[ "TODO", ":", "add", "documentation" ]
python
train
56
tsroten/dragonmapper
dragonmapper/transcriptions.py
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L417-L435
def to_pinyin(s, accented=True): """Convert *s* to Pinyin. If *accented* is ``True``, diacritics are added to the Pinyin syllables. If it's ``False``, numbers are used to indicate tone. """ identity = identify(s) if identity == PINYIN: if _has_accented_vowels(s): return s if accented else accented_to_numbered(s) else: return numbered_to_accented(s) if accented else s elif identity == ZHUYIN: return zhuyin_to_pinyin(s, accented=accented) elif identity == IPA: return ipa_to_pinyin(s, accented=accented) else: raise ValueError("String is not a valid Chinese transcription.")
[ "def", "to_pinyin", "(", "s", ",", "accented", "=", "True", ")", ":", "identity", "=", "identify", "(", "s", ")", "if", "identity", "==", "PINYIN", ":", "if", "_has_accented_vowels", "(", "s", ")", ":", "return", "s", "if", "accented", "else", "accente...
Convert *s* to Pinyin. If *accented* is ``True``, diacritics are added to the Pinyin syllables. If it's ``False``, numbers are used to indicate tone.
[ "Convert", "*", "s", "*", "to", "Pinyin", "." ]
python
train
34.736842
KvasirSecurity/kvasirapi-python
KvasirAPI/jsonrpc/services.py
https://github.com/KvasirSecurity/kvasirapi-python/blob/ec8c5818bd5913f3afd150f25eaec6e7cc732f4c/KvasirAPI/jsonrpc/services.py#L89-L99
def report_list(self, service_id=None, service_port=None, hostfilter=None): """ Returns a list of ports with IPs, banners and vulnerabilities (warning, slow!) :param service_id: t_services.id :param service_port: Port (tcp/#, udp/#, info/#) :param hostfilter: Valid hostfilter or None :return: { 'port': [t_hosts.f_ipaddr, t_services.f_banner, (t_vulndata.f_vulnid, t_vulndata.f_title, t_vulndata.f_severity, t_vulndata.f_cvss_score), ...} """ return self.send.service_report_list(service_id, service_port, hostfilter)
[ "def", "report_list", "(", "self", ",", "service_id", "=", "None", ",", "service_port", "=", "None", ",", "hostfilter", "=", "None", ")", ":", "return", "self", ".", "send", ".", "service_report_list", "(", "service_id", ",", "service_port", ",", "hostfilter...
Returns a list of ports with IPs, banners and vulnerabilities (warning, slow!) :param service_id: t_services.id :param service_port: Port (tcp/#, udp/#, info/#) :param hostfilter: Valid hostfilter or None :return: { 'port': [t_hosts.f_ipaddr, t_services.f_banner, (t_vulndata.f_vulnid, t_vulndata.f_title, t_vulndata.f_severity, t_vulndata.f_cvss_score), ...}
[ "Returns", "a", "list", "of", "ports", "with", "IPs", "banners", "and", "vulnerabilities", "(", "warning", "slow!", ")" ]
python
train
53.181818
materialsproject/pymatgen
pymatgen/analysis/magnetism/analyzer.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/magnetism/analyzer.py#L1170-L1207
def magnetic_deformation(structure_A, structure_B): """ Calculates 'magnetic deformation proxy', a measure of deformation (norm of finite strain) between 'non-magnetic' (non-spin-polarized) and ferromagnetic structures. Adapted from Bocarsly et al. 2017, doi: 10.1021/acs.chemmater.6b04729 :param structure_A: Structure :param structure_B: Structure :return: """ # retrieve orderings of both input structures ordering_a = CollinearMagneticStructureAnalyzer( structure_A, overwrite_magmom_mode="none" ).ordering ordering_b = CollinearMagneticStructureAnalyzer( structure_B, overwrite_magmom_mode="none" ).ordering # get a type string, this is either 'NM-FM' for between non-magnetic # and ferromagnetic, as in Bocarsly paper, or e.g. 'FM-AFM' type_str = "{}-{}".format(ordering_a.value, ordering_b.value) lattice_a = structure_A.lattice.matrix.T lattice_b = structure_B.lattice.matrix.T lattice_a_inv = np.linalg.inv(lattice_a) p = np.dot(lattice_a_inv, lattice_b) eta = 0.5 * (np.dot(p.T, p) - np.identity(3)) w, v = np.linalg.eig(eta) deformation = 100 * (1.0 / 3.0) * np.sqrt(w[0] ** 2 + w[1] ** 2 + w[2] ** 2) MagneticDeformation = namedtuple("MagneticDeformation", "type deformation") return MagneticDeformation(deformation=deformation, type=type_str)
[ "def", "magnetic_deformation", "(", "structure_A", ",", "structure_B", ")", ":", "# retrieve orderings of both input structures", "ordering_a", "=", "CollinearMagneticStructureAnalyzer", "(", "structure_A", ",", "overwrite_magmom_mode", "=", "\"none\"", ")", ".", "ordering", ...
Calculates 'magnetic deformation proxy', a measure of deformation (norm of finite strain) between 'non-magnetic' (non-spin-polarized) and ferromagnetic structures. Adapted from Bocarsly et al. 2017, doi: 10.1021/acs.chemmater.6b04729 :param structure_A: Structure :param structure_B: Structure :return:
[ "Calculates", "magnetic", "deformation", "proxy", "a", "measure", "of", "deformation", "(", "norm", "of", "finite", "strain", ")", "between", "non", "-", "magnetic", "(", "non", "-", "spin", "-", "polarized", ")", "and", "ferromagnetic", "structures", "." ]
python
train
35.605263
pgmpy/pgmpy
pgmpy/readwrite/PomdpX.py
https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/readwrite/PomdpX.py#L314-L328
def get_parameter_tbl(self, parameter): """ This method returns parameters as list of dict in case of table type parameter """ par = [] for entry in parameter.findall('Entry'): instance = defaultdict(list) instance['Instance'] = entry.find('Instance').text.split() if entry.find('ProbTable') is None: instance['ValueTable'] = entry.find('ValueTable').text.split() else: instance['ProbTable'] = entry.find('ProbTable').text.split() par.append(instance) return par
[ "def", "get_parameter_tbl", "(", "self", ",", "parameter", ")", ":", "par", "=", "[", "]", "for", "entry", "in", "parameter", ".", "findall", "(", "'Entry'", ")", ":", "instance", "=", "defaultdict", "(", "list", ")", "instance", "[", "'Instance'", "]", ...
This method returns parameters as list of dict in case of table type parameter
[ "This", "method", "returns", "parameters", "as", "list", "of", "dict", "in", "case", "of", "table", "type", "parameter" ]
python
train
39.733333
squeaky-pl/japronto
misc/cpu.py
https://github.com/squeaky-pl/japronto/blob/a526277a2f59100388c9f39d4ca22bfb4909955b/misc/cpu.py#L105-L151
def dump(): """ dump function """ try: sensors = subprocess.check_output('sensors').decode('utf-8') except (FileNotFoundError, subprocess.CalledProcessError): print("Couldn't read CPU temp") else: cores = [] for line in sensors.splitlines(): if line.startswith('Core '): core, rest = line.split(':') temp = rest.strip().split()[0] cores.append((core, temp)) for core, temp in cores: print(core + ':', temp) cpu_number = 0 while True: try: _file = open( CPU_PREFIX + 'cpu{}/cpufreq/scaling_governor'.format(cpu_number)) except: break print('Core ' + str(cpu_number) + ':', _file.read().strip(), end=', ') _file.close() try: _file = open( CPU_PREFIX + 'cpu{}/cpufreq/scaling_cur_freq'.format(cpu_number)) except: break freq = round(int(_file.read()) / 10 ** 6, 2) print(freq, 'GHz') cpu_number += 1
[ "def", "dump", "(", ")", ":", "try", ":", "sensors", "=", "subprocess", ".", "check_output", "(", "'sensors'", ")", ".", "decode", "(", "'utf-8'", ")", "except", "(", "FileNotFoundError", ",", "subprocess", ".", "CalledProcessError", ")", ":", "print", "("...
dump function
[ "dump", "function" ]
python
train
22.531915
saltstack/salt
salt/modules/pkg_resource.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pkg_resource.py#L180-L214
def version(*names, **kwargs): ''' Common interface for obtaining the version of installed packages. CLI Example: .. code-block:: bash salt '*' pkg_resource.version vim salt '*' pkg_resource.version foo bar baz salt '*' pkg_resource.version 'python*' ''' ret = {} versions_as_list = \ salt.utils.data.is_true(kwargs.pop('versions_as_list', False)) pkg_glob = False if names: pkgs = __salt__['pkg.list_pkgs'](versions_as_list=True, **kwargs) for name in names: if '*' in name: pkg_glob = True for match in fnmatch.filter(pkgs, name): ret[match] = pkgs.get(match, []) else: ret[name] = pkgs.get(name, []) if not versions_as_list: __salt__['pkg_resource.stringify'](ret) # Return a string if no globbing is used, and there is one item in the # return dict if len(ret) == 1 and not pkg_glob: try: return next(six.itervalues(ret)) except StopIteration: return '' return ret
[ "def", "version", "(", "*", "names", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "}", "versions_as_list", "=", "salt", ".", "utils", ".", "data", ".", "is_true", "(", "kwargs", ".", "pop", "(", "'versions_as_list'", ",", "False", ")", ")", ...
Common interface for obtaining the version of installed packages. CLI Example: .. code-block:: bash salt '*' pkg_resource.version vim salt '*' pkg_resource.version foo bar baz salt '*' pkg_resource.version 'python*'
[ "Common", "interface", "for", "obtaining", "the", "version", "of", "installed", "packages", "." ]
python
train
30.885714
nvdv/vprof
vprof/memory_profiler.py
https://github.com/nvdv/vprof/blob/4c3ff78f8920ab10cb9c00b14143452aa09ff6bb/vprof/memory_profiler.py#L65-L75
def _format_obj_count(objects): """Formats object count.""" result = [] regex = re.compile(r'<(?P<type>\w+) \'(?P<name>\S+)\'>') for obj_type, obj_count in objects.items(): if obj_count != 0: match = re.findall(regex, repr(obj_type)) if match: obj_type, obj_name = match[0] result.append(("%s %s" % (obj_type, obj_name), obj_count)) return sorted(result, key=operator.itemgetter(1), reverse=True)
[ "def", "_format_obj_count", "(", "objects", ")", ":", "result", "=", "[", "]", "regex", "=", "re", ".", "compile", "(", "r'<(?P<type>\\w+) \\'(?P<name>\\S+)\\'>'", ")", "for", "obj_type", ",", "obj_count", "in", "objects", ".", "items", "(", ")", ":", "if", ...
Formats object count.
[ "Formats", "object", "count", "." ]
python
test
42.727273
njouanin/repool
repool/pool.py
https://github.com/njouanin/repool/blob/27102cf84cb382c0b2d935f8b8651aa7f8c2777e/repool/pool.py#L123-L133
def release_pool(self): """Release pool and all its connection""" if self._current_acquired > 0: raise PoolException("Can't release pool: %d connection(s) still acquired" % self._current_acquired) while not self._pool.empty(): conn = self.acquire() conn.close() if self._cleanup_thread is not None: self._thread_event.set() self._cleanup_thread.join() self._pool = None
[ "def", "release_pool", "(", "self", ")", ":", "if", "self", ".", "_current_acquired", ">", "0", ":", "raise", "PoolException", "(", "\"Can't release pool: %d connection(s) still acquired\"", "%", "self", ".", "_current_acquired", ")", "while", "not", "self", ".", ...
Release pool and all its connection
[ "Release", "pool", "and", "all", "its", "connection" ]
python
train
41.727273
saltstack/salt
salt/modules/git.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L63-L110
def _config_getter(get_opt, key, value_regex=None, cwd=None, user=None, password=None, ignore_retcode=False, output_encoding=None, **kwargs): ''' Common code for config.get_* functions, builds and runs the git CLI command and returns the result dict for the calling function to parse. ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) global_ = kwargs.pop('global', False) if kwargs: salt.utils.args.invalid_kwargs(kwargs) if cwd is None: if not global_: raise SaltInvocationError( '\'cwd\' argument required unless global=True' ) else: cwd = _expand_path(cwd, user) if get_opt == '--get-regexp': if value_regex is not None \ and not isinstance(value_regex, six.string_types): value_regex = six.text_type(value_regex) else: # Ignore value_regex value_regex = None command = ['git', 'config'] command.extend(_which_git_config(global_, cwd, user, password, output_encoding=output_encoding)) command.append(get_opt) command.append(key) if value_regex is not None: command.append(value_regex) return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, failhard=False, output_encoding=output_encoding)
[ "def", "_config_getter", "(", "get_opt", ",", "key", ",", "value_regex", "=", "None", ",", "cwd", "=", "None", ",", "user", "=", "None", ",", "password", "=", "None", ",", "ignore_retcode", "=", "False", ",", "output_encoding", "=", "None", ",", "*", "...
Common code for config.get_* functions, builds and runs the git CLI command and returns the result dict for the calling function to parse.
[ "Common", "code", "for", "config", ".", "get_", "*", "functions", "builds", "and", "runs", "the", "git", "CLI", "command", "and", "returns", "the", "result", "dict", "for", "the", "calling", "function", "to", "parse", "." ]
python
train
33.145833
toumorokoshi/sprinter
sprinter/lib/request.py
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/lib/request.py#L34-L39
def cleaned_request(request_type, *args, **kwargs): """ Perform a cleaned requests request """ s = requests.Session() # this removes netrc checking s.trust_env = False return s.request(request_type, *args, **kwargs)
[ "def", "cleaned_request", "(", "request_type", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "s", "=", "requests", ".", "Session", "(", ")", "# this removes netrc checking", "s", ".", "trust_env", "=", "False", "return", "s", ".", "request", "(", ...
Perform a cleaned requests request
[ "Perform", "a", "cleaned", "requests", "request" ]
python
train
38.333333
praekeltfoundation/molo
molo/core/api/endpoints.py
https://github.com/praekeltfoundation/molo/blob/57702fda4fab261d67591415f7d46bc98fa38525/molo/core/api/endpoints.py#L84-L90
def get_queryset(self): ''' Only serve site-specific languages ''' request = self.request return (Languages.for_site(request.site) .languages.filter().order_by('pk'))
[ "def", "get_queryset", "(", "self", ")", ":", "request", "=", "self", ".", "request", "return", "(", "Languages", ".", "for_site", "(", "request", ".", "site", ")", ".", "languages", ".", "filter", "(", ")", ".", "order_by", "(", "'pk'", ")", ")" ]
Only serve site-specific languages
[ "Only", "serve", "site", "-", "specific", "languages" ]
python
train
32.142857
sdispater/pendulum
pendulum/helpers.py
https://github.com/sdispater/pendulum/blob/94d28b0d3cb524ae02361bd1ed7ea03e2e655e4e/pendulum/helpers.py#L46-L122
def add_duration( dt, # type: Union[datetime, date] years=0, # type: int months=0, # type: int weeks=0, # type: int days=0, # type: int hours=0, # type: int minutes=0, # type: int seconds=0, # type: int microseconds=0, ): # type: (...) -> Union[datetime, date] """ Adds a duration to a date/datetime instance. """ days += weeks * 7 if ( isinstance(dt, date) and not isinstance(dt, datetime) and any([hours, minutes, seconds, microseconds]) ): raise RuntimeError("Time elements cannot be added to a date instance.") # Normalizing if abs(microseconds) > 999999: s = _sign(microseconds) div, mod = divmod(microseconds * s, 1000000) microseconds = mod * s seconds += div * s if abs(seconds) > 59: s = _sign(seconds) div, mod = divmod(seconds * s, 60) seconds = mod * s minutes += div * s if abs(minutes) > 59: s = _sign(minutes) div, mod = divmod(minutes * s, 60) minutes = mod * s hours += div * s if abs(hours) > 23: s = _sign(hours) div, mod = divmod(hours * s, 24) hours = mod * s days += div * s if abs(months) > 11: s = _sign(months) div, mod = divmod(months * s, 12) months = mod * s years += div * s year = dt.year + years month = dt.month if months: month += months if month > 12: year += 1 month -= 12 elif month < 1: year -= 1 month += 12 day = min(DAYS_PER_MONTHS[int(is_leap(year))][month], dt.day) dt = dt.replace(year=year, month=month, day=day) return dt + timedelta( days=days, hours=hours, minutes=minutes, seconds=seconds, microseconds=microseconds, )
[ "def", "add_duration", "(", "dt", ",", "# type: Union[datetime, date]", "years", "=", "0", ",", "# type: int", "months", "=", "0", ",", "# type: int", "weeks", "=", "0", ",", "# type: int", "days", "=", "0", ",", "# type: int", "hours", "=", "0", ",", "# ...
Adds a duration to a date/datetime instance.
[ "Adds", "a", "duration", "to", "a", "date", "/", "datetime", "instance", "." ]
python
train
23.727273
intuition-io/intuition
intuition/api/context.py
https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/api/context.py#L86-L103
def _normalize_data_types(self, strategy): ''' some contexts only retrieves strings, giving back right type ''' for k, v in strategy.iteritems(): if not isinstance(v, str): # There is probably nothing to do continue if v == 'true': strategy[k] = True elif v == 'false' or v is None: strategy[k] = False else: try: if v.find('.') > 0: strategy[k] = float(v) else: strategy[k] = int(v) except ValueError: pass
[ "def", "_normalize_data_types", "(", "self", ",", "strategy", ")", ":", "for", "k", ",", "v", "in", "strategy", ".", "iteritems", "(", ")", ":", "if", "not", "isinstance", "(", "v", ",", "str", ")", ":", "# There is probably nothing to do", "continue", "if...
some contexts only retrieves strings, giving back right type
[ "some", "contexts", "only", "retrieves", "strings", "giving", "back", "right", "type" ]
python
train
36.555556
ejeschke/ginga
ginga/canvas/transform.py
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/canvas/transform.py#L219-L241
def from_(self, win_pts): """Reverse of :meth:`to_`.""" # make relative to center pixel to convert from window # graphics space to standard X/Y coordinate space win_pts = np.asarray(win_pts, dtype=np.float) has_z = (win_pts.shape[-1] > 2) ctr_pt = list(self.viewer.get_center()) if has_z: ctr_pt.append(0.0) mpy_pt = [1.0, -1.0] if has_z: mpy_pt.append(1.0) # off_x = win_x - ctr_x # = win_x + -ctr_x # off_y = ctr_y - win_y # = -win_y + ctr_y ctr_pt[0] = -ctr_pt[0] off_pts = np.add(np.multiply(win_pts, mpy_pt), ctr_pt) return off_pts
[ "def", "from_", "(", "self", ",", "win_pts", ")", ":", "# make relative to center pixel to convert from window", "# graphics space to standard X/Y coordinate space", "win_pts", "=", "np", ".", "asarray", "(", "win_pts", ",", "dtype", "=", "np", ".", "float", ")", "has...
Reverse of :meth:`to_`.
[ "Reverse", "of", ":", "meth", ":", "to_", "." ]
python
train
29.652174
johnnoone/json-spec
src/jsonspec/validators/draft04.py
https://github.com/johnnoone/json-spec/blob/f91981724cea0c366bd42a6670eb07bbe31c0e0c/src/jsonspec/validators/draft04.py#L32-L251
def compile(schema, pointer, context, scope=None): """ Compiles schema with `JSON Schema`_ draft-04. :param schema: obj to compile :type schema: Mapping :param pointer: uri of the schema :type pointer: Pointer, str :param context: context of this schema :type context: Context .. _`JSON Schema`: http://json-schema.org """ schm = deepcopy(schema) scope = urljoin(scope or str(pointer), schm.pop('id', None)) if '$ref' in schema: return ReferenceValidator(urljoin(scope, schema['$ref']), context) attrs = {} if 'additionalItems' in schm: subpointer = pointer_join(pointer, 'additionalItems') attrs['additional_items'] = schm.pop('additionalItems') if isinstance(attrs['additional_items'], dict): compiled = compile(attrs['additional_items'], subpointer, context, scope) attrs['additional_items'] = compiled elif not isinstance(attrs['additional_items'], bool): raise CompilationError('wrong type for {}'.format('additional_items'), schema) # noqa if 'additionalProperties' in schm: subpointer = pointer_join(pointer, 'additionalProperties') attrs['additional_properties'] = schm.pop('additionalProperties') if isinstance(attrs['additional_properties'], dict): compiled = compile(attrs['additional_properties'], subpointer, context, scope) attrs['additional_properties'] = compiled elif not isinstance(attrs['additional_properties'], bool): raise CompilationError('wrong type for {}'.format('additional_properties'), schema) # noqa if 'allOf' in schm: subpointer = pointer_join(pointer, 'allOf') attrs['all_of'] = schm.pop('allOf') if isinstance(attrs['all_of'], (list, tuple)): attrs['all_of'] = [compile(element, subpointer, context, scope) for element in attrs['all_of']] # noqa else: # should be a boolean raise CompilationError('wrong type for {}'.format('allOf'), schema) # noqa if 'anyOf' in schm: subpointer = pointer_join(pointer, 'anyOf') attrs['any_of'] = schm.pop('anyOf') if isinstance(attrs['any_of'], (list, tuple)): attrs['any_of'] = [compile(element, subpointer, context, scope) for element in attrs['any_of']] # noqa else: # should be a boolean raise CompilationError('wrong type for {}'.format('anyOf'), schema) # noqa if 'default' in schm: attrs['default'] = schm.pop('default') if 'dependencies' in schm: attrs['dependencies'] = schm.pop('dependencies') if not isinstance(attrs['dependencies'], dict): raise CompilationError('dependencies must be an object', schema) for key, value in attrs['dependencies'].items(): if isinstance(value, dict): subpointer = pointer_join(pointer, 'dependencies', key) attrs['dependencies'][key] = compile(value, subpointer, context, scope) elif not isinstance(value, sequence_types): raise CompilationError('dependencies must be an array or object', schema) # noqa if 'enum' in schm: attrs['enum'] = schm.pop('enum') if not isinstance(attrs['enum'], sequence_types): raise CompilationError('enum must be a sequence', schema) if 'exclusiveMaximum' in schm: attrs['exclusive_maximum'] = schm.pop('exclusiveMaximum') if not isinstance(attrs['exclusive_maximum'], bool): raise CompilationError('exclusiveMaximum must be a boolean', schema) # noqa if 'exclusiveMinimum' in schm: attrs['exclusive_minimum'] = schm.pop('exclusiveMinimum') if not isinstance(attrs['exclusive_minimum'], bool): raise CompilationError('exclusiveMinimum must be a boolean', schema) # noqa if 'format' in schm: attrs['format'] = schm.pop('format') if not isinstance(attrs['format'], string_types): raise CompilationError('format must be a string', schema) if 'items' in schm: subpointer = pointer_join(pointer, 'items') attrs['items'] = schm.pop('items') if isinstance(attrs['items'], (list, tuple)): # each value must be a json schema attrs['items'] = [compile(element, subpointer, context, scope) for element in attrs['items']] # noqa elif isinstance(attrs['items'], dict): # value must be a json schema attrs['items'] = compile(attrs['items'], subpointer, context, scope) # noqa else: # should be a boolean raise CompilationError('wrong type for {}'.format('items'), schema) # noqa if 'maximum' in schm: attrs['maximum'] = schm.pop('maximum') if not isinstance(attrs['maximum'], number_types): raise CompilationError('maximum must be a number', schema) if 'maxItems' in schm: attrs['max_items'] = schm.pop('maxItems') if not isinstance(attrs['max_items'], integer_types): raise CompilationError('maxItems must be integer', schema) if 'maxLength' in schm: attrs['max_length'] = schm.pop('maxLength') if not isinstance(attrs['max_length'], integer_types): raise CompilationError('maxLength must be integer', schema) if 'maxProperties' in schm: attrs['max_properties'] = schm.pop('maxProperties') if not isinstance(attrs['max_properties'], integer_types): raise CompilationError('maxProperties must be integer', schema) if 'minimum' in schm: attrs['minimum'] = schm.pop('minimum') if not isinstance(attrs['minimum'], number_types): raise CompilationError('minimum must be a number', schema) if 'minItems' in schm: attrs['min_items'] = schm.pop('minItems') if not isinstance(attrs['min_items'], integer_types): raise CompilationError('minItems must be integer', schema) if 'minLength' in schm: attrs['min_length'] = schm.pop('minLength') if not isinstance(attrs['min_length'], integer_types): raise CompilationError('minLength must be integer', schema) if 'minProperties' in schm: attrs['min_properties'] = schm.pop('minProperties') if not isinstance(attrs['min_properties'], integer_types): raise CompilationError('minProperties must be integer', schema) if 'multipleOf' in schm: attrs['multiple_of'] = schm.pop('multipleOf') if not isinstance(attrs['multiple_of'], number_types): raise CompilationError('multipleOf must be a number', schema) if 'not' in schm: attrs['not'] = schm.pop('not') if not isinstance(attrs['not'], dict): raise CompilationError('not must be an object', schema) subpointer = pointer_join(pointer, 'not') attrs['not'] = compile(attrs['not'], subpointer, context, scope) if 'oneOf' in schm: subpointer = pointer_join(pointer, 'oneOf') attrs['one_of'] = schm.pop('oneOf') if isinstance(attrs['one_of'], (list, tuple)): # each value must be a json schema attrs['one_of'] = [compile(element, subpointer, context, scope) for element in attrs['one_of']] # noqa else: # should be a boolean raise CompilationError('wrong type for {}'.format('oneOf'), schema) if 'pattern' in schm: attrs['pattern'] = schm.pop('pattern') if not isinstance(attrs['pattern'], string_types): raise CompilationError('pattern must be a string', schema) if 'properties' in schm: attrs['properties'] = schm.pop('properties') if not isinstance(attrs['properties'], dict): raise CompilationError('properties must be an object', schema) for subname, subschema in attrs['properties'].items(): subpointer = pointer_join(pointer, subname) compiled = compile(subschema, subpointer, context, scope) attrs['properties'][subname] = compiled if 'patternProperties' in schm: attrs['pattern_properties'] = schm.pop('patternProperties') if not isinstance(attrs['pattern_properties'], dict): raise CompilationError('patternProperties must be an object', schema) # noqa for subname, subschema in attrs['pattern_properties'].items(): subpointer = pointer_join(pointer, 'patternProperties', subname) compiled = compile(subschema, subpointer, context, scope) attrs['pattern_properties'][subname] = compiled if 'required' in schm: attrs['required'] = schm.pop('required') if not isinstance(attrs['required'], list): raise CompilationError('required must be a list', schema) if len(attrs['required']) < 1: raise CompilationError('required cannot be empty', schema) if 'type' in schm: attrs['type'] = schm.pop('type') if isinstance(attrs['type'], string_types): attrs['type'] = [attrs['type']] elif not isinstance(attrs['type'], sequence_types): raise CompilationError('type must be string or sequence', schema) if 'uniqueItems' in schm: attrs['unique_items'] = schm.pop('uniqueItems') if not isinstance(attrs['unique_items'], bool): raise CompilationError('type must be boolean', schema) return Draft04Validator(attrs, str(pointer), context.formats)
[ "def", "compile", "(", "schema", ",", "pointer", ",", "context", ",", "scope", "=", "None", ")", ":", "schm", "=", "deepcopy", "(", "schema", ")", "scope", "=", "urljoin", "(", "scope", "or", "str", "(", "pointer", ")", ",", "schm", ".", "pop", "("...
Compiles schema with `JSON Schema`_ draft-04. :param schema: obj to compile :type schema: Mapping :param pointer: uri of the schema :type pointer: Pointer, str :param context: context of this schema :type context: Context .. _`JSON Schema`: http://json-schema.org
[ "Compiles", "schema", "with", "JSON", "Schema", "_", "draft", "-", "04", "." ]
python
train
44
olt/scriptine
scriptine/command.py
https://github.com/olt/scriptine/blob/f4cfea939f2f3ad352b24c5f6410f79e78723d0e/scriptine/command.py#L241-L274
def parse_rst_params(doc): """ Parse a reStructuredText docstring and return a dictionary with parameter names and descriptions. >>> doc = ''' ... :param foo: foo parameter ... foo parameter ... ... :param bar: bar parameter ... :param baz: baz parameter ... baz parameter ... baz parameter ... Some text. ... ''' >>> params = parse_rst_params(doc) >>> params['foo'] 'foo parameter foo parameter' >>> params['bar'] 'bar parameter' >>> params['baz'] 'baz parameter baz parameter baz parameter' """ param_re = re.compile(r"""^([ \t]*):param\ (?P<param>\w+):\ (?P<body>.*\n(\1[ \t]+\w.*\n)*)""", re.MULTILINE|re.VERBOSE) params = {} for match in param_re.finditer(doc): parts = match.groupdict() body_lines = parts['body'].strip().split('\n') params[parts['param']] = ' '.join(s.strip() for s in body_lines) return params
[ "def", "parse_rst_params", "(", "doc", ")", ":", "param_re", "=", "re", ".", "compile", "(", "r\"\"\"^([ \\t]*):param\\ \n (?P<param>\\w+):\\ \n (?P<body>.*\\n(\\1[ \\t]+\\w.*\\n)*)\"\"\"", ",", "re", ".", "MULTILINE", "|", ...
Parse a reStructuredText docstring and return a dictionary with parameter names and descriptions. >>> doc = ''' ... :param foo: foo parameter ... foo parameter ... ... :param bar: bar parameter ... :param baz: baz parameter ... baz parameter ... baz parameter ... Some text. ... ''' >>> params = parse_rst_params(doc) >>> params['foo'] 'foo parameter foo parameter' >>> params['bar'] 'bar parameter' >>> params['baz'] 'baz parameter baz parameter baz parameter'
[ "Parse", "a", "reStructuredText", "docstring", "and", "return", "a", "dictionary", "with", "parameter", "names", "and", "descriptions", ".", ">>>", "doc", "=", "...", ":", "param", "foo", ":", "foo", "parameter", "...", "foo", "parameter", "...", "...", ":",...
python
train
30.235294
pandas-dev/pandas
pandas/io/html.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/html.py#L498-L518
def _handle_hidden_tables(self, tbl_list, attr_name): """ Return list of tables, potentially removing hidden elements Parameters ---------- tbl_list : list of node-like Type of list elements will vary depending upon parser used attr_name : str Name of the accessor for retrieving HTML attributes Returns ------- list of node-like Return type matches `tbl_list` """ if not self.displayed_only: return tbl_list return [x for x in tbl_list if "display:none" not in getattr(x, attr_name).get('style', '').replace(" ", "")]
[ "def", "_handle_hidden_tables", "(", "self", ",", "tbl_list", ",", "attr_name", ")", ":", "if", "not", "self", ".", "displayed_only", ":", "return", "tbl_list", "return", "[", "x", "for", "x", "in", "tbl_list", "if", "\"display:none\"", "not", "in", "getattr...
Return list of tables, potentially removing hidden elements Parameters ---------- tbl_list : list of node-like Type of list elements will vary depending upon parser used attr_name : str Name of the accessor for retrieving HTML attributes Returns ------- list of node-like Return type matches `tbl_list`
[ "Return", "list", "of", "tables", "potentially", "removing", "hidden", "elements" ]
python
train
31.47619
dj-stripe/dj-stripe
djstripe/models/payment_methods.py
https://github.com/dj-stripe/dj-stripe/blob/a5308a3808cd6e2baba49482f7a699f3a8992518/djstripe/models/payment_methods.py#L442-L461
def detach(self): """ Detach the source from its customer. """ # First, wipe default source on all customers that use this. Customer.objects.filter(default_source=self.id).update(default_source=None) try: # TODO - we could use the return value of sync_from_stripe_data # or call its internals - self._sync/_attach_objects_hook etc here # to update `self` at this point? self.sync_from_stripe_data(self.api_retrieve().detach()) return True except (InvalidRequestError, NotImplementedError): # The source was already detached. Resyncing. # NotImplementedError is an artifact of stripe-python<2.0 # https://github.com/stripe/stripe-python/issues/376 self.sync_from_stripe_data(self.api_retrieve()) return False
[ "def", "detach", "(", "self", ")", ":", "# First, wipe default source on all customers that use this.", "Customer", ".", "objects", ".", "filter", "(", "default_source", "=", "self", ".", "id", ")", ".", "update", "(", "default_source", "=", "None", ")", "try", ...
Detach the source from its customer.
[ "Detach", "the", "source", "from", "its", "customer", "." ]
python
train
36.8
tensorforce/tensorforce
docs/mistune.py
https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/docs/mistune.py#L817-L823
def codespan(self, text): """Rendering inline `code` text. :param text: text content for inline code. """ text = escape(text.rstrip(), smart_amp=False) return '<code>%s</code>' % text
[ "def", "codespan", "(", "self", ",", "text", ")", ":", "text", "=", "escape", "(", "text", ".", "rstrip", "(", ")", ",", "smart_amp", "=", "False", ")", "return", "'<code>%s</code>'", "%", "text" ]
Rendering inline `code` text. :param text: text content for inline code.
[ "Rendering", "inline", "code", "text", "." ]
python
valid
31.142857
numenta/nupic
scripts/profiling/tm_profile.py
https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/scripts/profiling/tm_profile.py#L31-L54
def profileTM(tmClass, tmDim, nRuns): """ profiling performance of TemporalMemory (TM) using the python cProfile module and ordered by cumulative time, see how to run on command-line above. @param tmClass implementation of TM (cpp, py, ..) @param tmDim number of columns in TM @param nRuns number of calls of the profiled code (epochs) """ # create TM instance to measure tm = tmClass(numberOfCols=tmDim) # generate input data data = numpy.random.randint(0, 2, [tmDim, nRuns]).astype('float32') for i in xrange(nRuns): # new data every time, this is the worst case performance # real performance would be better, as the input data would not be completely random d = data[:,i] # the actual function to profile! tm.compute(d, True)
[ "def", "profileTM", "(", "tmClass", ",", "tmDim", ",", "nRuns", ")", ":", "# create TM instance to measure", "tm", "=", "tmClass", "(", "numberOfCols", "=", "tmDim", ")", "# generate input data", "data", "=", "numpy", ".", "random", ".", "randint", "(", "0", ...
profiling performance of TemporalMemory (TM) using the python cProfile module and ordered by cumulative time, see how to run on command-line above. @param tmClass implementation of TM (cpp, py, ..) @param tmDim number of columns in TM @param nRuns number of calls of the profiled code (epochs)
[ "profiling", "performance", "of", "TemporalMemory", "(", "TM", ")", "using", "the", "python", "cProfile", "module", "and", "ordered", "by", "cumulative", "time", "see", "how", "to", "run", "on", "command", "-", "line", "above", "." ]
python
valid
31.541667
saltstack/salt
salt/modules/mac_system.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_system.py#L362-L387
def set_subnet_name(name): ''' Set the local subnet name :param str name: The new local subnet name .. note:: Spaces are changed to dashes. Other special characters are removed. :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash The following will be set as 'Mikes-Mac' salt '*' system.set_subnet_name "Mike's Mac" ''' cmd = 'systemsetup -setlocalsubnetname "{0}"'.format(name) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( name, get_subnet_name, )
[ "def", "set_subnet_name", "(", "name", ")", ":", "cmd", "=", "'systemsetup -setlocalsubnetname \"{0}\"'", ".", "format", "(", "name", ")", "__utils__", "[", "'mac_utils.execute_return_success'", "]", "(", "cmd", ")", "return", "__utils__", "[", "'mac_utils.confirm_upd...
Set the local subnet name :param str name: The new local subnet name .. note:: Spaces are changed to dashes. Other special characters are removed. :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash The following will be set as 'Mikes-Mac' salt '*' system.set_subnet_name "Mike's Mac"
[ "Set", "the", "local", "subnet", "name" ]
python
train
23.5
kalefranz/auxlib
auxlib/collection.py
https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/collection.py#L87-L117
def first(seq, key=lambda x: bool(x), default=None, apply=lambda x: x): """Give the first value that satisfies the key test. Args: seq (iterable): key (callable): test for each element of iterable default: returned when all elements fail test apply (callable): applied to element before return, but not to default value Returns: first element in seq that passes key, mutated with optional apply Examples: >>> first([0, False, None, [], (), 42]) 42 >>> first([0, False, None, [], ()]) is None True >>> first([0, False, None, [], ()], default='ohai') 'ohai' >>> import re >>> m = first(re.match(regex, 'abc') for regex in ['b.*', 'a(.*)']) >>> m.group(1) 'bc' The optional `key` argument specifies a one-argument predicate function like that used for `filter()`. The `key` argument, if supplied, must be in keyword form. For example: >>> first([1, 1, 3, 4, 5], key=lambda x: x % 2 == 0) 4 """ return next((apply(x) for x in seq if key(x)), default() if callable(default) else default)
[ "def", "first", "(", "seq", ",", "key", "=", "lambda", "x", ":", "bool", "(", "x", ")", ",", "default", "=", "None", ",", "apply", "=", "lambda", "x", ":", "x", ")", ":", "return", "next", "(", "(", "apply", "(", "x", ")", "for", "x", "in", ...
Give the first value that satisfies the key test. Args: seq (iterable): key (callable): test for each element of iterable default: returned when all elements fail test apply (callable): applied to element before return, but not to default value Returns: first element in seq that passes key, mutated with optional apply Examples: >>> first([0, False, None, [], (), 42]) 42 >>> first([0, False, None, [], ()]) is None True >>> first([0, False, None, [], ()], default='ohai') 'ohai' >>> import re >>> m = first(re.match(regex, 'abc') for regex in ['b.*', 'a(.*)']) >>> m.group(1) 'bc' The optional `key` argument specifies a one-argument predicate function like that used for `filter()`. The `key` argument, if supplied, must be in keyword form. For example: >>> first([1, 1, 3, 4, 5], key=lambda x: x % 2 == 0) 4
[ "Give", "the", "first", "value", "that", "satisfies", "the", "key", "test", "." ]
python
train
36.612903
tkf/rash
rash/init.py
https://github.com/tkf/rash/blob/585da418ec37dd138f1a4277718b6f507e9536a2/rash/init.py#L37-L77
def init_run(shell, no_daemon, daemon_options, daemon_outfile): """ Configure your shell. Add the following line in your shell RC file and then you are ready to go:: eval $(%(prog)s) To check if your shell is supported, simply run:: %(prog)s --no-daemon If you want to specify shell other than $SHELL, you can give --shell option:: eval $(%(prog)s --shell zsh) By default, this command also starts daemon in background to automatically index shell history records. To not start daemon, use --no-daemon option like this:: eval $(%(prog)s --no-daemon) To see the other methods to launch the daemon process, see ``rash daemon --help``. """ import sys from .__init__ import __version__ init_file = find_init(shell) if os.path.exists(init_file): sys.stdout.write(INIT_TEMPLATE.format( file=init_file, version=__version__)) else: raise RuntimeError( "Shell '{0}' is not supported.".format(shell_name(shell))) if not no_daemon: from .daemon import start_daemon_in_subprocess start_daemon_in_subprocess(daemon_options, daemon_outfile)
[ "def", "init_run", "(", "shell", ",", "no_daemon", ",", "daemon_options", ",", "daemon_outfile", ")", ":", "import", "sys", "from", ".", "__init__", "import", "__version__", "init_file", "=", "find_init", "(", "shell", ")", "if", "os", ".", "path", ".", "e...
Configure your shell. Add the following line in your shell RC file and then you are ready to go:: eval $(%(prog)s) To check if your shell is supported, simply run:: %(prog)s --no-daemon If you want to specify shell other than $SHELL, you can give --shell option:: eval $(%(prog)s --shell zsh) By default, this command also starts daemon in background to automatically index shell history records. To not start daemon, use --no-daemon option like this:: eval $(%(prog)s --no-daemon) To see the other methods to launch the daemon process, see ``rash daemon --help``.
[ "Configure", "your", "shell", "." ]
python
train
28.146341
openstack/networking-hyperv
networking_hyperv/neutron/agent/layer2.py
https://github.com/openstack/networking-hyperv/blob/7a89306ab0586c95b99debb44d898f70834508b9/networking_hyperv/neutron/agent/layer2.py#L389-L392
def _treat_devices_removed(self): """Process the removed devices.""" for device in self._removed_ports.copy(): eventlet.spawn_n(self._process_removed_port, device)
[ "def", "_treat_devices_removed", "(", "self", ")", ":", "for", "device", "in", "self", ".", "_removed_ports", ".", "copy", "(", ")", ":", "eventlet", ".", "spawn_n", "(", "self", ".", "_process_removed_port", ",", "device", ")" ]
Process the removed devices.
[ "Process", "the", "removed", "devices", "." ]
python
train
47
log2timeline/plaso
plaso/preprocessors/macos.py
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/preprocessors/macos.py#L267-L311
def _ParseFileEntry(self, knowledge_base, file_entry): """Parses artifact file system data for a preprocessing attribute. Args: knowledge_base (KnowledgeBase): to fill with preprocessing information. file_entry (dfvfs.FileEntry): file entry that contains the artifact value data. Raises: errors.PreProcessFail: if the preprocessing fails. """ root_key = self._GetPlistRootKey(file_entry) if not root_key: location = getattr(file_entry.path_spec, 'location', '') raise errors.PreProcessFail(( 'Unable to read: {0:s} plist: {1:s} with error: missing root ' 'key.').format(self.ARTIFACT_DEFINITION_NAME, location)) try: match = self._GetKeysDefaultEmpty(root_key, self._KEYS) except KeyError as exception: location = getattr(file_entry.path_spec, 'location', '') raise errors.PreProcessFail( 'Unable to read: {0:s} plist: {1:s} with error: {2!s}'.format( self.ARTIFACT_DEFINITION_NAME, location, exception)) name = match.get('name', [None])[0] uid = match.get('uid', [None])[0] if not name or not uid: # TODO: add and store preprocessing errors. return user_account = artifacts.UserAccountArtifact( identifier=uid, username=name) user_account.group_identifier = match.get('gid', [None])[0] user_account.full_name = match.get('realname', [None])[0] user_account.shell = match.get('shell', [None])[0] user_account.user_directory = match.get('home', [None])[0] try: knowledge_base.AddUserAccount(user_account) except KeyError: # TODO: add and store preprocessing errors. pass
[ "def", "_ParseFileEntry", "(", "self", ",", "knowledge_base", ",", "file_entry", ")", ":", "root_key", "=", "self", ".", "_GetPlistRootKey", "(", "file_entry", ")", "if", "not", "root_key", ":", "location", "=", "getattr", "(", "file_entry", ".", "path_spec", ...
Parses artifact file system data for a preprocessing attribute. Args: knowledge_base (KnowledgeBase): to fill with preprocessing information. file_entry (dfvfs.FileEntry): file entry that contains the artifact value data. Raises: errors.PreProcessFail: if the preprocessing fails.
[ "Parses", "artifact", "file", "system", "data", "for", "a", "preprocessing", "attribute", "." ]
python
train
36.533333
saltstack/salt
salt/modules/win_groupadd.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_groupadd.py#L70-L82
def _get_all_groups(): ''' A helper function that gets a list of group objects for all groups on the machine Returns: iter: A list of objects for all groups on the machine ''' with salt.utils.winapi.Com(): nt = win32com.client.Dispatch('AdsNameSpaces') results = nt.GetObject('', 'WinNT://.') results.Filter = ['group'] return results
[ "def", "_get_all_groups", "(", ")", ":", "with", "salt", ".", "utils", ".", "winapi", ".", "Com", "(", ")", ":", "nt", "=", "win32com", ".", "client", ".", "Dispatch", "(", "'AdsNameSpaces'", ")", "results", "=", "nt", ".", "GetObject", "(", "''", ",...
A helper function that gets a list of group objects for all groups on the machine Returns: iter: A list of objects for all groups on the machine
[ "A", "helper", "function", "that", "gets", "a", "list", "of", "group", "objects", "for", "all", "groups", "on", "the", "machine" ]
python
train
28.846154
biolink/ontobio
ontobio/util/go_utils.py
https://github.com/biolink/ontobio/blob/4e512a7831cfe6bc1b32f2c3be2ba41bc5cf7345/ontobio/util/go_utils.py#L68-L81
def go_aspect(self, go_term): """ For GO terms, returns F, C, or P corresponding to its aspect """ if not go_term.startswith("GO:"): return None else: # Check ancestors for root terms if self.is_molecular_function(go_term): return 'F' elif self.is_cellular_component(go_term): return 'C' elif self.is_biological_process(go_term): return 'P'
[ "def", "go_aspect", "(", "self", ",", "go_term", ")", ":", "if", "not", "go_term", ".", "startswith", "(", "\"GO:\"", ")", ":", "return", "None", "else", ":", "# Check ancestors for root terms", "if", "self", ".", "is_molecular_function", "(", "go_term", ")", ...
For GO terms, returns F, C, or P corresponding to its aspect
[ "For", "GO", "terms", "returns", "F", "C", "or", "P", "corresponding", "to", "its", "aspect" ]
python
train
33.928571
PGower/PyCanvas
pycanvas/apis/content_migrations.py
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/content_migrations.py#L293-L321
def update_migration_issue_users(self, id, user_id, workflow_state, content_migration_id): """ Update a migration issue. Update the workflow_state of a migration issue """ path = {} data = {} params = {} # REQUIRED - PATH - user_id """ID""" path["user_id"] = user_id # REQUIRED - PATH - content_migration_id """ID""" path["content_migration_id"] = content_migration_id # REQUIRED - PATH - id """ID""" path["id"] = id # REQUIRED - workflow_state """Set the workflow_state of the issue.""" self._validate_enum(workflow_state, ["active", "resolved"]) data["workflow_state"] = workflow_state self.logger.debug("PUT /api/v1/users/{user_id}/content_migrations/{content_migration_id}/migration_issues/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/users/{user_id}/content_migrations/{content_migration_id}/migration_issues/{id}".format(**path), data=data, params=params, single_item=True)
[ "def", "update_migration_issue_users", "(", "self", ",", "id", ",", "user_id", ",", "workflow_state", ",", "content_migration_id", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - user_id\r", "\"\"\"ID\"\"\"",...
Update a migration issue. Update the workflow_state of a migration issue
[ "Update", "a", "migration", "issue", ".", "Update", "the", "workflow_state", "of", "a", "migration", "issue" ]
python
train
39.931034
dereneaton/ipyrad
ipyrad/assemble/cluster_within.py
https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/cluster_within.py#L1429-L1508
def run(data, samples, noreverse, maxindels, force, ipyclient): """ run the major functions for clustering within samples """ ## list of samples to submit to queue subsamples = [] ## if sample is already done skip for sample in samples: ## If sample not in state 2 don't try to cluster it. if sample.stats.state < 2: print("""\ Sample not ready for clustering. First run step2 on sample: {}""".\ format(sample.name)) continue if not force: if sample.stats.state >= 3: print("""\ Skipping {}; aleady clustered. Use force to re-cluster""".\ format(sample.name)) else: if sample.stats.reads_passed_filter: subsamples.append(sample) else: ## force to overwrite if sample.stats.reads_passed_filter: subsamples.append(sample) ## run subsamples if not subsamples: print(" No Samples ready to be clustered. First run step2().") else: ## arguments to apply_jobs, inst catches exceptions try: ## make dirs that are needed including tmpdir setup_dirs(data) ## if refmapping make filehandles that will be persistent if not data.paramsdict["assembly_method"] == "denovo": for sample in subsamples: refmap_init(data, sample, force) ## set thread-count to 2 for paired-data nthreads = 2 ## set thread-count to 1 for single-end data else: nthreads = 1 ## overwrite nthreads if value in _ipcluster dict if "threads" in data._ipcluster.keys(): nthreads = int(data._ipcluster["threads"]) ## if more CPUs than there are samples then increase threads _ncpus = len(ipyclient) if _ncpus > 2*len(data.samples): nthreads *= 2 ## submit jobs to be run on cluster args = [data, subsamples, ipyclient, nthreads, maxindels, force] new_apply_jobs(*args) finally: ## this can fail if jobs were not stopped properly and are still ## writing to tmpdir. don't cleanup if debug is on. try: log_level = logging.getLevelName(LOGGER.getEffectiveLevel()) if not log_level == "DEBUG": if os.path.exists(data.tmpdir): shutil.rmtree(data.tmpdir) ## get all refmap_derep.fastqs rdereps = glob.glob(os.path.join(data.dirs.edits, "*-refmap_derep.fastq")) ## Remove the unmapped fastq files for rmfile in rdereps: os.remove(rmfile) except Exception as _: LOGGER.warning("failed to cleanup files/dirs")
[ "def", "run", "(", "data", ",", "samples", ",", "noreverse", ",", "maxindels", ",", "force", ",", "ipyclient", ")", ":", "## list of samples to submit to queue", "subsamples", "=", "[", "]", "## if sample is already done skip", "for", "sample", "in", "samples", ":...
run the major functions for clustering within samples
[ "run", "the", "major", "functions", "for", "clustering", "within", "samples" ]
python
valid
36.3125
Carbonara-Project/Guanciale
guanciale/idblib.py
https://github.com/Carbonara-Project/Guanciale/blob/c239ffac6fb481d09c4071d1de1a09f60dc584ab/guanciale/idblib.py#L1002-L1014
def name(self, id): """ resolves a name, both short and long names. """ data = self.bytes(id, 'N') if not data: print("%x has no name" % id) return if data[:1] == b'\x00': nameid, = struct.unpack_from(">" + self.fmt, data, 1) nameblob = self.blob(self.nodebase, 'S', nameid * 256, nameid * 256 + 32) return nameblob.rstrip(b"\x00").decode('utf-8') return data.rstrip(b"\x00").decode('utf-8')
[ "def", "name", "(", "self", ",", "id", ")", ":", "data", "=", "self", ".", "bytes", "(", "id", ",", "'N'", ")", "if", "not", "data", ":", "print", "(", "\"%x has no name\"", "%", "id", ")", "return", "if", "data", "[", ":", "1", "]", "==", "b'\...
resolves a name, both short and long names.
[ "resolves", "a", "name", "both", "short", "and", "long", "names", "." ]
python
train
39
jpscaletti/solution
solution/fields/splitted_datetime.py
https://github.com/jpscaletti/solution/blob/eabafd8e695bbb0209242e002dbcc05ffb327f43/solution/fields/splitted_datetime.py#L69-L74
def _to_timezone(self, dt): """Takes a naive timezone with an utc value and return it formatted as a local timezone.""" tz = self._get_tz() utc_dt = pytz.utc.localize(dt) return utc_dt.astimezone(tz)
[ "def", "_to_timezone", "(", "self", ",", "dt", ")", ":", "tz", "=", "self", ".", "_get_tz", "(", ")", "utc_dt", "=", "pytz", ".", "utc", ".", "localize", "(", "dt", ")", "return", "utc_dt", ".", "astimezone", "(", "tz", ")" ]
Takes a naive timezone with an utc value and return it formatted as a local timezone.
[ "Takes", "a", "naive", "timezone", "with", "an", "utc", "value", "and", "return", "it", "formatted", "as", "a", "local", "timezone", "." ]
python
train
39
boriel/zxbasic
arch/zx48k/backend/__32bit.py
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__32bit.py#L725-L733
def _abs32(ins): """ Absolute value of top of the stack (32 bits in DEHL) """ output = _32bit_oper(ins.quad[2]) output.append('call __ABS32') output.append('push de') output.append('push hl') REQUIRES.add('abs32.asm') return output
[ "def", "_abs32", "(", "ins", ")", ":", "output", "=", "_32bit_oper", "(", "ins", ".", "quad", "[", "2", "]", ")", "output", ".", "append", "(", "'call __ABS32'", ")", "output", ".", "append", "(", "'push de'", ")", "output", ".", "append", "(", "'pus...
Absolute value of top of the stack (32 bits in DEHL)
[ "Absolute", "value", "of", "top", "of", "the", "stack", "(", "32", "bits", "in", "DEHL", ")" ]
python
train
28.333333
pyviz/holoviews
holoviews/core/util.py
https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/util.py#L1190-L1212
def dimension_sort(odict, kdims, vdims, key_index): """ Sorts data by key using usual Python tuple sorting semantics or sorts in categorical order for any categorical Dimensions. """ sortkws = {} ndims = len(kdims) dimensions = kdims+vdims indexes = [(dimensions[i], int(i not in range(ndims)), i if i in range(ndims) else i-ndims) for i in key_index] cached_values = {d.name: [None]+list(d.values) for d in dimensions} if len(set(key_index)) != len(key_index): raise ValueError("Cannot sort on duplicated dimensions") else: sortkws['key'] = lambda x: tuple(cached_values[dim.name].index(x[t][d]) if dim.values else x[t][d] for i, (dim, t, d) in enumerate(indexes)) if sys.version_info.major == 3: return python2sort(odict.items(), **sortkws) else: return sorted(odict.items(), **sortkws)
[ "def", "dimension_sort", "(", "odict", ",", "kdims", ",", "vdims", ",", "key_index", ")", ":", "sortkws", "=", "{", "}", "ndims", "=", "len", "(", "kdims", ")", "dimensions", "=", "kdims", "+", "vdims", "indexes", "=", "[", "(", "dimensions", "[", "i...
Sorts data by key using usual Python tuple sorting semantics or sorts in categorical order for any categorical Dimensions.
[ "Sorts", "data", "by", "key", "using", "usual", "Python", "tuple", "sorting", "semantics", "or", "sorts", "in", "categorical", "order", "for", "any", "categorical", "Dimensions", "." ]
python
train
42
Othernet-Project/hwd
hwd/storage.py
https://github.com/Othernet-Project/hwd/blob/7f4445bac61aa2305806aa80338e2ce5baa1093c/hwd/storage.py#L114-L122
def partitions(self): """ Iterable containing disk's partition objects. Objects in the iterable are :py:class:`~hwd.storage.Partition` instances. """ if not self._partitions: self._partitions = [Partition(d, self) for d in self.device.children] return self._partitions
[ "def", "partitions", "(", "self", ")", ":", "if", "not", "self", ".", "_partitions", ":", "self", ".", "_partitions", "=", "[", "Partition", "(", "d", ",", "self", ")", "for", "d", "in", "self", ".", "device", ".", "children", "]", "return", "self", ...
Iterable containing disk's partition objects. Objects in the iterable are :py:class:`~hwd.storage.Partition` instances.
[ "Iterable", "containing", "disk", "s", "partition", "objects", ".", "Objects", "in", "the", "iterable", "are", ":", "py", ":", "class", ":", "~hwd", ".", "storage", ".", "Partition", "instances", "." ]
python
train
39.111111
artefactual-labs/agentarchives
agentarchives/atom/client.py
https://github.com/artefactual-labs/agentarchives/blob/af19ade56a90c64069cf46b50972fe72b6f10a45/agentarchives/atom/client.py#L692-L747
def add_child( self, parent_slug=None, title="", level="", start_date=None, end_date=None, date_expression=None, notes=[], ): """ Adds a new resource component parented within `parent`. :param str parent_slug: The parent's slug. :param str title: A title for the record. :param str level: The level of description. :return: The ID of the newly-created record. """ new_object = {"title": title, "level_of_description": level} if parent_slug is not None: new_object["parent_slug"] = parent_slug # Optionally add date specification new_date = {} if start_date is not None: new_date["start_date"] = start_date if end_date is not None: new_date["end_date"] = end_date if date_expression is not None: new_date["date"] = date_expression if new_date != {}: new_object["dates"] = [new_date] # Optionally add notes new_object["notes"] = [] for note in notes: note_type = note.get("type", "General note") # If there is a note, but it's an empty string, skip this; content = note.get("content") if not content: continue new_note = {"content": content, "type": note_type} new_object["notes"].append(new_note) return self._post( urljoin(self.base_url, "informationobjects"), data=json.dumps(new_object), expected_response=201, ).json()["slug"]
[ "def", "add_child", "(", "self", ",", "parent_slug", "=", "None", ",", "title", "=", "\"\"", ",", "level", "=", "\"\"", ",", "start_date", "=", "None", ",", "end_date", "=", "None", ",", "date_expression", "=", "None", ",", "notes", "=", "[", "]", ",...
Adds a new resource component parented within `parent`. :param str parent_slug: The parent's slug. :param str title: A title for the record. :param str level: The level of description. :return: The ID of the newly-created record.
[ "Adds", "a", "new", "resource", "component", "parented", "within", "parent", "." ]
python
train
28.517857
MSchnei/pyprf_feature
pyprf_feature/analysis/load_config.py
https://github.com/MSchnei/pyprf_feature/blob/49004ede7ae1ddee07a30afe9ce3e2776750805c/pyprf_feature/analysis/load_config.py#L12-L277
def load_config(strCsvCnfg, lgcTest=False, lgcPrint=True): """ Load py_pRF_mapping config file. Parameters ---------- strCsvCnfg : string Absolute file path of config file. lgcTest : Boolean Whether this is a test (pytest). If yes, absolute path of this function will be prepended to config file paths. lgcPrint : Boolean Print config parameters? Returns ------- dicCnfg : dict Dictionary containing parameter names (as keys) and parameter values (as values). For example, `dicCnfg['varTr']` contains a float, such as `2.94`. """ # Dictionary with config information: dicCnfg = {} # Open file with parameter configuration: # fleConfig = open(strCsvCnfg, 'r') with open(strCsvCnfg, 'r') as fleConfig: # Read file with ROI information: csvIn = csv.reader(fleConfig, delimiter='\n', skipinitialspace=True) # Loop through csv object to fill list with csv data: for lstTmp in csvIn: # Skip comments (i.e. lines starting with '#') and empty lines. # Note: Indexing the list (i.e. lstTmp[0][0]) does not work for # empty lines. However, if the first condition is no fullfilled # (i.e. line is empty and 'if lstTmp' evaluates to false), the # second logical test (after the 'and') is not actually carried # out. if lstTmp and not (lstTmp[0][0] == '#'): # Name of current parameter (e.g. 'varTr'): strParamKey = lstTmp[0].split(' = ')[0] # print(strParamKey) # Current parameter value (e.g. '2.94'): strParamVlu = lstTmp[0].split(' = ')[1] # print(strParamVlu) # Put paramter name (key) and value (item) into dictionary: dicCnfg[strParamKey] = strParamVlu # Are model parameters in cartesian or polar coordinates? # set either pol (polar) or crt (cartesian) dicCnfg['strKwCrd'] = ast.literal_eval(dicCnfg['strKwCrd']) if lgcPrint: print('---Model coordinates are in: ' + str(dicCnfg['strKwCrd'])) # Number of x- or radial positions to model: dicCnfg['varNum1'] = int(dicCnfg['varNum1']) # Number of y- or angular positions to model: dicCnfg['varNum2'] = int(dicCnfg['varNum2']) if lgcPrint: if dicCnfg['strKwCrd'] == 'crt': print('---Number of x-positions to model: ' + str(dicCnfg['varNum1'])) print('---Number of y-positions to model: ' + str(dicCnfg['varNum2'])) elif dicCnfg['strKwCrd'] == 'pol': print('---Number of radial positions to model: ' + str(dicCnfg['varNum1'])) print('---Number of angular positions to model: ' + str(dicCnfg['varNum2'])) # Number of pRF sizes to model: dicCnfg['varNumPrfSizes'] = int(dicCnfg['varNumPrfSizes']) if lgcPrint: print('---Number of pRF sizes to model: ' + str(dicCnfg['varNumPrfSizes'])) # Extent of visual space from centre of the screen in negative x-direction # (i.e. from the fixation point to the left end of the screen) in degrees # of visual angle. dicCnfg['varExtXmin'] = float(dicCnfg['varExtXmin']) if lgcPrint: print('---Extent of visual space in negative x-direction: ' + str(dicCnfg['varExtXmin'])) # Extent of visual space from centre of the screen in positive x-direction # (i.e. from the fixation point to the right end of the screen) in degrees # of visual angle. dicCnfg['varExtXmax'] = float(dicCnfg['varExtXmax']) if lgcPrint: print('---Extent of visual space in positive x-direction: ' + str(dicCnfg['varExtXmax'])) # Extent of visual space from centre of the screen in negative y-direction # (i.e. from the fixation point to the lower end of the screen) in degrees # of visual angle. dicCnfg['varExtYmin'] = float(dicCnfg['varExtYmin']) if lgcPrint: print('---Extent of visual space in negative y-direction: ' + str(dicCnfg['varExtYmin'])) # Extent of visual space from centre of the screen in positive y-direction # (i.e. from the fixation point to the upper end of the screen) in degrees # of visual angle. dicCnfg['varExtYmax'] = float(dicCnfg['varExtYmax']) if lgcPrint: print('---Extent of visual space in positive y-direction: ' + str(dicCnfg['varExtYmax'])) # Minimum pRF model size (standard deviation of 2D Gaussian) [degrees of # visual angle]: dicCnfg['varPrfStdMin'] = float(dicCnfg['varPrfStdMin']) if lgcPrint: print('---Minimum pRF model size: ' + str(dicCnfg['varPrfStdMin'])) # Maximum pRF model size (standard deviation of 2D Gaussian) [degrees of # visual angle]: dicCnfg['varPrfStdMax'] = float(dicCnfg['varPrfStdMax']) if lgcPrint: print('---Maximum pRF model size: ' + str(dicCnfg['varPrfStdMax'])) # Volume TR of input data [s]: dicCnfg['varTr'] = float(dicCnfg['varTr']) if lgcPrint: print('---Volume TR of input data [s]: ' + str(dicCnfg['varTr'])) # Voxel resolution of fMRI data [mm]: dicCnfg['varVoxRes'] = float(dicCnfg['varVoxRes']) if lgcPrint: print('---Voxel resolution of fMRI data [mm]: ' + str(dicCnfg['varVoxRes'])) # Number of fMRI volumes and png files to load: dicCnfg['varNumVol'] = int(dicCnfg['varNumVol']) if lgcPrint: print('---Total number of fMRI volumes and png files: ' + str(dicCnfg['varNumVol'])) # Extent of temporal smoothing for fMRI data and pRF time course models # [standard deviation of the Gaussian kernel, in seconds]: # same temporal smoothing will be applied to pRF model time courses dicCnfg['varSdSmthTmp'] = float(dicCnfg['varSdSmthTmp']) if lgcPrint: print('---Extent of temporal smoothing (Gaussian SD in [s]): ' + str(dicCnfg['varSdSmthTmp'])) # Number of processes to run in parallel: dicCnfg['varPar'] = int(dicCnfg['varPar']) if lgcPrint: print('---Number of processes to run in parallel: ' + str(dicCnfg['varPar'])) # Size of space model in which the pRF models are # created (x- and y-dimension). dicCnfg['tplVslSpcSze'] = tuple([int(dicCnfg['varVslSpcSzeX']), int(dicCnfg['varVslSpcSzeY'])]) if lgcPrint: print('---Size of visual space model (x & y): ' + str(dicCnfg['tplVslSpcSze'])) # Path(s) of functional data: dicCnfg['lstPathNiiFunc'] = ast.literal_eval(dicCnfg['lstPathNiiFunc']) if lgcPrint: print('---Path(s) of functional data:') for strTmp in dicCnfg['lstPathNiiFunc']: print(' ' + str(strTmp)) # Path of mask (to restrict pRF model finding): dicCnfg['strPathNiiMask'] = ast.literal_eval(dicCnfg['strPathNiiMask']) if lgcPrint: print('---Path of mask (to restrict pRF model finding):') print(' ' + str(dicCnfg['strPathNiiMask'])) # Output basename: dicCnfg['strPathOut'] = ast.literal_eval(dicCnfg['strPathOut']) if lgcPrint: print('---Output basename:') print(' ' + str(dicCnfg['strPathOut'])) # Which version to use for pRF finding. 'numpy' or 'cython' for pRF finding # on CPU, 'gpu' for using GPU. dicCnfg['strVersion'] = ast.literal_eval(dicCnfg['strVersion']) if lgcPrint: print('---Version (numpy, cython, or gpu): ' + str(dicCnfg['strVersion'])) # Create pRF time course models? dicCnfg['lgcCrteMdl'] = (dicCnfg['lgcCrteMdl'] == 'True') if lgcPrint: print('---Create pRF time course models: ' + str(dicCnfg['lgcCrteMdl'])) # Path to npy file with pRF time course models (to save or laod). Without # file extension. dicCnfg['strPathMdl'] = ast.literal_eval(dicCnfg['strPathMdl']) if lgcPrint: print('---Path to npy file with pRF time course models (to save ' + 'or load):') print(' ' + str(dicCnfg['strPathMdl'])) # switch to determine which hrf functions should be used # 1: canonical, 2: can and temp derivative, 3: can, temp and spat deriv dicCnfg['switchHrfSet'] = ast.literal_eval(dicCnfg['switchHrfSet']) if lgcPrint: print('---Switch to determine which hrf functions should be used: ' + str(dicCnfg['switchHrfSet'])) # should model fitting be based on k-fold cross-validation? # if not, set to 1 dicCnfg['varNumXval'] = ast.literal_eval(dicCnfg['varNumXval']) if lgcPrint: print('---Model fitting will have this number of folds for xval: ' + str(dicCnfg['varNumXval'])) # If we create new pRF time course models, the following parameters have to # be provided: if dicCnfg['lgcCrteMdl']: # Name of the npy that holds spatial info about conditions dicCnfg['strSptExpInf'] = ast.literal_eval(dicCnfg['strSptExpInf']) if lgcPrint: print('---Path to npy file with spatial condition info: ') print(' ' + str(dicCnfg['strSptExpInf'])) # Name of the npy that holds temporal info about conditions dicCnfg['strTmpExpInf'] = ast.literal_eval(dicCnfg['strTmpExpInf']) if lgcPrint: print('---Path to npy file with temporal condition info: ') print(' ' + str(dicCnfg['strTmpExpInf'])) # Factor by which time courses and HRF will be upsampled for the # convolutions dicCnfg['varTmpOvsmpl'] = ast.literal_eval(dicCnfg['varTmpOvsmpl']) if lgcPrint: print('---Factor by which time courses and HRF will be upsampled: ' + str(dicCnfg['varTmpOvsmpl'])) # Is this a test? if lgcTest: # Prepend absolute path of this file to config file paths: dicCnfg['strPathNiiMask'] = (strDir + dicCnfg['strPathNiiMask']) dicCnfg['strPathOut'] = (strDir + dicCnfg['strPathOut']) dicCnfg['strPathMdl'] = (strDir + dicCnfg['strPathMdl']) dicCnfg['strSptExpInf'] = (strDir + dicCnfg['strSptExpInf']) dicCnfg['strTmpExpInf'] = (strDir + dicCnfg['strTmpExpInf']) # Loop through functional runs: varNumRun = len(dicCnfg['lstPathNiiFunc']) for idxRun in range(varNumRun): dicCnfg['lstPathNiiFunc'][idxRun] = ( strDir + dicCnfg['lstPathNiiFunc'][idxRun] ) return dicCnfg
[ "def", "load_config", "(", "strCsvCnfg", ",", "lgcTest", "=", "False", ",", "lgcPrint", "=", "True", ")", ":", "# Dictionary with config information:", "dicCnfg", "=", "{", "}", "# Open file with parameter configuration:", "# fleConfig = open(strCsvCnfg, 'r')", "with", "o...
Load py_pRF_mapping config file. Parameters ---------- strCsvCnfg : string Absolute file path of config file. lgcTest : Boolean Whether this is a test (pytest). If yes, absolute path of this function will be prepended to config file paths. lgcPrint : Boolean Print config parameters? Returns ------- dicCnfg : dict Dictionary containing parameter names (as keys) and parameter values (as values). For example, `dicCnfg['varTr']` contains a float, such as `2.94`.
[ "Load", "py_pRF_mapping", "config", "file", "." ]
python
train
39.349624
StackStorm/pybind
pybind/nos/v7_2_0/interface/hundredgigabitethernet/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v7_2_0/interface/hundredgigabitethernet/__init__.py#L1672-L1693
def _set_bpdu_drop(self, v, load=False): """ Setter method for bpdu_drop, mapped from YANG variable /interface/hundredgigabitethernet/bpdu_drop (container) If this variable is read-only (config: false) in the source YANG file, then _set_bpdu_drop is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_bpdu_drop() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=bpdu_drop.bpdu_drop, is_container='container', presence=False, yang_name="bpdu-drop", rest_name="bpdu-drop", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Drop received BPDUs', u'callpoint': u'phy-stp-config', u'sort-priority': u'105', u'cli-compact-syntax': None, u'cli-sequence-commands': None, u'cli-incomplete-no': None, u'display-when': u'/vcsmode/vcs-mode = "true"'}}, namespace='urn:brocade.com:mgmt:brocade-xstp', defining_module='brocade-xstp', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """bpdu_drop must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=bpdu_drop.bpdu_drop, is_container='container', presence=False, yang_name="bpdu-drop", rest_name="bpdu-drop", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Drop received BPDUs', u'callpoint': u'phy-stp-config', u'sort-priority': u'105', u'cli-compact-syntax': None, u'cli-sequence-commands': None, u'cli-incomplete-no': None, u'display-when': u'/vcsmode/vcs-mode = "true"'}}, namespace='urn:brocade.com:mgmt:brocade-xstp', defining_module='brocade-xstp', yang_type='container', is_config=True)""", }) self.__bpdu_drop = t if hasattr(self, '_set'): self._set()
[ "def", "_set_bpdu_drop", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base...
Setter method for bpdu_drop, mapped from YANG variable /interface/hundredgigabitethernet/bpdu_drop (container) If this variable is read-only (config: false) in the source YANG file, then _set_bpdu_drop is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_bpdu_drop() directly.
[ "Setter", "method", "for", "bpdu_drop", "mapped", "from", "YANG", "variable", "/", "interface", "/", "hundredgigabitethernet", "/", "bpdu_drop", "(", "container", ")", "If", "this", "variable", "is", "read", "-", "only", "(", "config", ":", "false", ")", "in...
python
train
89.727273
qiniu/python-sdk
qiniu/services/compute/qcos_api.py
https://github.com/qiniu/python-sdk/blob/a69fbef4e3e6ea1ebe09f4610a5b18bb2c17de59/qiniu/services/compute/qcos_api.py#L623-L638
def disable_ap_port(self, apid, port): """临时关闭接入点端口 临时关闭接入点端口,仅对公网域名,公网ip有效。 Args: - apid: 接入点ID - port: 要设置的端口号 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回空dict{},失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息 """ url = '{0}/v3/aps/{1}/{2}/disable'.format(self.host, apid, port) return self.__post(url)
[ "def", "disable_ap_port", "(", "self", ",", "apid", ",", "port", ")", ":", "url", "=", "'{0}/v3/aps/{1}/{2}/disable'", ".", "format", "(", "self", ".", "host", ",", "apid", ",", "port", ")", "return", "self", ".", "__post", "(", "url", ")" ]
临时关闭接入点端口 临时关闭接入点端口,仅对公网域名,公网ip有效。 Args: - apid: 接入点ID - port: 要设置的端口号 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回空dict{},失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
[ "临时关闭接入点端口" ]
python
train
28.5
ladybug-tools/ladybug
ladybug/datatype/mass.py
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datatype/mass.py#L59-L66
def to_si(self, values, from_unit): """Return values in SI and the units to which the values have been converted.""" if from_unit in self.si_units: return values, from_unit elif from_unit == 'ton': return self.to_unit(values, 'tonne', from_unit), 'tonne' else: return self.to_unit(values, 'kg', from_unit), 'kg'
[ "def", "to_si", "(", "self", ",", "values", ",", "from_unit", ")", ":", "if", "from_unit", "in", "self", ".", "si_units", ":", "return", "values", ",", "from_unit", "elif", "from_unit", "==", "'ton'", ":", "return", "self", ".", "to_unit", "(", "values",...
Return values in SI and the units to which the values have been converted.
[ "Return", "values", "in", "SI", "and", "the", "units", "to", "which", "the", "values", "have", "been", "converted", "." ]
python
train
46.5
dmlc/gluon-nlp
src/gluonnlp/model/sampled_block.py
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/sampled_block.py#L52-L95
def hybrid_forward(self, F, x, sampled_values, label, w_all, b_all): """Forward computation.""" sampled_candidates, expected_count_sampled, expected_count_true = sampled_values # (num_sampled, in_unit) w_sampled = w_all.slice(begin=(0, 0), end=(self._num_sampled, None)) w_true = w_all.slice(begin=(self._num_sampled, 0), end=(None, None)) b_sampled = b_all.slice(begin=(0,), end=(self._num_sampled,)) b_true = b_all.slice(begin=(self._num_sampled,), end=(None,)) # true pred # (batch_size, 1) x = x.reshape((-1, self._in_unit)) pred_true = (w_true * x).sum(axis=1) + b_true # samples pred # (batch_size, num_sampled) b_sampled = F.reshape(b_sampled, (-1,)) pred_sampled = F.FullyConnected(x, weight=w_sampled, bias=b_sampled, num_hidden=self._num_sampled) # remove accidental hits if self._remove_accidental_hits: label_vec = F.reshape(label, (-1, 1)) sample_vec = F.reshape(sampled_candidates, (1, -1)) mask = F.broadcast_equal(label_vec, sample_vec) * -1e37 pred_sampled = pred_sampled + mask # subtract log(q) expected_count_sampled = F.reshape(expected_count_sampled, shape=(1, self._num_sampled)) expected_count_true = expected_count_true.reshape((-1,)) pred_true = pred_true - F.log(expected_count_true) pred_true = pred_true.reshape((-1, 1)) pred_sampled = F.broadcast_sub(pred_sampled, F.log(expected_count_sampled)) # pred and new_labels # (batch_size, 1+num_sampled) pred = F.concat(pred_true, pred_sampled, dim=1) if self._sparse_label: new_label = F.zeros_like(label) else: label_vec = F.reshape(label, (-1, 1)) new_label_true = F.ones_like(label_vec) new_label_sampled = F.zeros_like(pred_sampled) new_label = F.Concat(new_label_true, new_label_sampled, dim=1) return pred, new_label
[ "def", "hybrid_forward", "(", "self", ",", "F", ",", "x", ",", "sampled_values", ",", "label", ",", "w_all", ",", "b_all", ")", ":", "sampled_candidates", ",", "expected_count_sampled", ",", "expected_count_true", "=", "sampled_values", "# (num_sampled, in_unit)", ...
Forward computation.
[ "Forward", "computation", "." ]
python
train
47.272727
etingof/pyasn1
pyasn1/type/namedtype.py
https://github.com/etingof/pyasn1/blob/25cf116ef8d11bb0e08454c0f3635c9f4002c2d6/pyasn1/type/namedtype.py#L406-L437
def getPositionNearType(self, tagSet, idx): """Return the closest field position where given ASN.1 type is allowed. Some ASN.1 serialisation allow for skipping optional and defaulted fields. Some constructed ASN.1 types allow reordering of the fields. When recovering such objects it may be important to know at which field position, in field set, given *tagSet* is allowed at or past *idx* position. Parameters ---------- tagSet: :class:`~pyasn1.type.tag.TagSet` ASN.1 type which field position to look up idx: :py:class:`int` Field position at or past which to perform ASN.1 type look up Returns ------- : :py:class:`int` Field position in fields set Raises ------ : :class:`~pyasn1.error.PyAsn1Error` If *tagSet* is not present or not unique within callee *NamedTypes* or *idx* is out of fields range """ try: return idx + self.__ambiguousTypes[idx].getPositionByType(tagSet) except KeyError: raise error.PyAsn1Error('Type position out of range')
[ "def", "getPositionNearType", "(", "self", ",", "tagSet", ",", "idx", ")", ":", "try", ":", "return", "idx", "+", "self", ".", "__ambiguousTypes", "[", "idx", "]", ".", "getPositionByType", "(", "tagSet", ")", "except", "KeyError", ":", "raise", "error", ...
Return the closest field position where given ASN.1 type is allowed. Some ASN.1 serialisation allow for skipping optional and defaulted fields. Some constructed ASN.1 types allow reordering of the fields. When recovering such objects it may be important to know at which field position, in field set, given *tagSet* is allowed at or past *idx* position. Parameters ---------- tagSet: :class:`~pyasn1.type.tag.TagSet` ASN.1 type which field position to look up idx: :py:class:`int` Field position at or past which to perform ASN.1 type look up Returns ------- : :py:class:`int` Field position in fields set Raises ------ : :class:`~pyasn1.error.PyAsn1Error` If *tagSet* is not present or not unique within callee *NamedTypes* or *idx* is out of fields range
[ "Return", "the", "closest", "field", "position", "where", "given", "ASN", ".", "1", "type", "is", "allowed", "." ]
python
train
35.96875
PythonSanSebastian/docstamp
docstamp/file_utils.py
https://github.com/PythonSanSebastian/docstamp/blob/b43808f2e15351b0b2f0b7eade9c7ef319c9e646/docstamp/file_utils.py#L138-L170
def csv_to_json(csv_filepath, json_filepath, fieldnames, ignore_first_line=True): """ Convert a CSV file in `csv_filepath` into a JSON file in `json_filepath`. Parameters ---------- csv_filepath: str Path to the input CSV file. json_filepath: str Path to the output JSON file. Will be overwritten if exists. fieldnames: List[str] Names of the fields in the CSV file. ignore_first_line: bool """ import csv import json csvfile = open(csv_filepath, 'r') jsonfile = open(json_filepath, 'w') reader = csv.DictReader(csvfile, fieldnames) rows = [] if ignore_first_line: next(reader) for row in reader: rows.append(row) json.dump(rows, jsonfile) jsonfile.close() csvfile.close()
[ "def", "csv_to_json", "(", "csv_filepath", ",", "json_filepath", ",", "fieldnames", ",", "ignore_first_line", "=", "True", ")", ":", "import", "csv", "import", "json", "csvfile", "=", "open", "(", "csv_filepath", ",", "'r'", ")", "jsonfile", "=", "open", "("...
Convert a CSV file in `csv_filepath` into a JSON file in `json_filepath`. Parameters ---------- csv_filepath: str Path to the input CSV file. json_filepath: str Path to the output JSON file. Will be overwritten if exists. fieldnames: List[str] Names of the fields in the CSV file. ignore_first_line: bool
[ "Convert", "a", "CSV", "file", "in", "csv_filepath", "into", "a", "JSON", "file", "in", "json_filepath", "." ]
python
test
23.151515
ThomasChiroux/attowiki
src/attowiki/rst_directives.py
https://github.com/ThomasChiroux/attowiki/blob/6c93c420305490d324fdc95a7b40b2283a222183/src/attowiki/rst_directives.py#L30-L49
def add_node(node, **kwds): """add_node from Sphinx """ nodes._add_node_class_names([node.__name__]) for key, val in kwds.iteritems(): try: visit, depart = val except ValueError: raise ValueError('Value for key %r must be a ' '(visit, depart) function tuple' % key) if key == 'html': from docutils.writers.html4css1 import HTMLTranslator as translator elif key == 'latex': from docutils.writers.latex2e import LaTeXTranslator as translator else: # ignore invalid keys for compatibility continue setattr(translator, 'visit_'+node.__name__, visit) if depart: setattr(translator, 'depart_'+node.__name__, depart)
[ "def", "add_node", "(", "node", ",", "*", "*", "kwds", ")", ":", "nodes", ".", "_add_node_class_names", "(", "[", "node", ".", "__name__", "]", ")", "for", "key", ",", "val", "in", "kwds", ".", "iteritems", "(", ")", ":", "try", ":", "visit", ",", ...
add_node from Sphinx
[ "add_node", "from", "Sphinx" ]
python
train
38.95
tango-controls/pytango
tango/asyncio_executor.py
https://github.com/tango-controls/pytango/blob/9cf78c517c9cdc1081ff6d080a9646a740cc1d36/tango/asyncio_executor.py#L88-L94
def execute(self, fn, *args, **kwargs): """Execute an operation and return the result.""" if self.in_executor_context(): corofn = asyncio.coroutine(lambda: fn(*args, **kwargs)) return corofn() future = self.submit(fn, *args, **kwargs) return future.result()
[ "def", "execute", "(", "self", ",", "fn", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "in_executor_context", "(", ")", ":", "corofn", "=", "asyncio", ".", "coroutine", "(", "lambda", ":", "fn", "(", "*", "args", ",", "...
Execute an operation and return the result.
[ "Execute", "an", "operation", "and", "return", "the", "result", "." ]
python
train
43.857143
boriel/zxbasic
arch/zx48k/optimizer.py
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L641-L653
def rl(self, r): """ Like the above, bus uses carry """ if self.C is None or not is_number(self.regs[r]): self.set(r, None) self.set_flag(None) return self.rlc(r) tmp = self.C v_ = self.getv(self.regs[r]) self.C = v_ & 1 self.regs[r] = str((v_ & 0xFE) | tmp)
[ "def", "rl", "(", "self", ",", "r", ")", ":", "if", "self", ".", "C", "is", "None", "or", "not", "is_number", "(", "self", ".", "regs", "[", "r", "]", ")", ":", "self", ".", "set", "(", "r", ",", "None", ")", "self", ".", "set_flag", "(", "...
Like the above, bus uses carry
[ "Like", "the", "above", "bus", "uses", "carry" ]
python
train
26.692308
selenol/selenol-python
selenol_python/params.py
https://github.com/selenol/selenol-python/blob/53775fdfc95161f4aca350305cb3459e6f2f808d/selenol_python/params.py#L40-L51
def _get_value(data_structure, key): """Return the value of a data_structure given a path. :param data_structure: Dictionary, list or subscriptable object. :param key: Array with the defined path ordered. """ if len(key) == 0: raise KeyError() value = data_structure[key[0]] if len(key) > 1: return _get_value(value, key[1:]) return value
[ "def", "_get_value", "(", "data_structure", ",", "key", ")", ":", "if", "len", "(", "key", ")", "==", "0", ":", "raise", "KeyError", "(", ")", "value", "=", "data_structure", "[", "key", "[", "0", "]", "]", "if", "len", "(", "key", ")", ">", "1",...
Return the value of a data_structure given a path. :param data_structure: Dictionary, list or subscriptable object. :param key: Array with the defined path ordered.
[ "Return", "the", "value", "of", "a", "data_structure", "given", "a", "path", "." ]
python
train
31.333333
madprime/vcf2clinvar
vcf2clinvar/clinvar.py
https://github.com/madprime/vcf2clinvar/blob/d5bbf6df2902c6cabe9ef1894cfac527e90fa32a/vcf2clinvar/clinvar.py#L91-L122
def _parse_allele_data(self): """Parse alleles for ClinVar VCF, overrides parent method.""" # Get allele frequencies if they exist. pref_freq, frequencies = self._parse_frequencies() info_clnvar_single_tags = ['ALLELEID', 'CLNSIG', 'CLNHGVS'] cln_data = {x.lower(): self.info[x] if x in self.info else None for x in info_clnvar_single_tags} cln_data.update( {'clndisdb': [x.split(',') for x in self.info['CLNDISDB'].split('|')] if 'CLNDISDB' in self.info else []}) cln_data.update({'clndn': self.info['CLNDN'].split('|') if 'CLNDN' in self.info else []}) cln_data.update({'clnvi': self.info['CLNVI'].split(',') if 'CLNVI' in self.info else []}) try: sequence = self.alt_alleles[0] except IndexError: sequence = self.ref_allele allele = ClinVarAllele(frequency=pref_freq, sequence=sequence, **cln_data) # A few ClinVar variants are only reported as a combination with # other variants, and no single-variant effect is proposed. Skip these. if not cln_data['clnsig']: return [] return [allele]
[ "def", "_parse_allele_data", "(", "self", ")", ":", "# Get allele frequencies if they exist.", "pref_freq", ",", "frequencies", "=", "self", ".", "_parse_frequencies", "(", ")", "info_clnvar_single_tags", "=", "[", "'ALLELEID'", ",", "'CLNSIG'", ",", "'CLNHGVS'", "]",...
Parse alleles for ClinVar VCF, overrides parent method.
[ "Parse", "alleles", "for", "ClinVar", "VCF", "overrides", "parent", "method", "." ]
python
valid
39.78125
ynop/audiomate
audiomate/corpus/subset/selection.py
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/subset/selection.py#L107-L141
def random_subsets(self, relative_sizes, by_duration=False, balance_labels=False, label_list_ids=None): """ Create a bunch of subsets with the given sizes relative to the size or duration of the full corpus. Basically the same as calling ``random_subset`` or ``random_subset_by_duration`` multiple times with different values. But this method makes sure that every subset contains only utterances, that are also contained in the next bigger subset. Args: relative_sizes (list): A list of numbers between 0 and 1 indicating the sizes of the desired subsets, relative to the full corpus. by_duration (bool): If True the size measure is the duration of all utterances in a subset/corpus. balance_labels (bool): If True the labels contained in a subset are chosen to be balanced as far as possible. label_list_ids (list): List of label-list ids. If none is given, all label-lists are considered for balancing. Otherwise only the ones that are in the list are considered. Returns: dict : A dictionary containing all subsets with the relative size as key. """ resulting_sets = {} next_bigger_subset = self.corpus for relative_size in reversed(relative_sizes): generator = SubsetGenerator(next_bigger_subset, random_seed=self.random_seed) if by_duration: sv = generator.random_subset_by_duration(relative_size, balance_labels=balance_labels, label_list_ids=label_list_ids) else: sv = generator.random_subset(relative_size, balance_labels=balance_labels, label_list_ids=label_list_ids) resulting_sets[relative_size] = sv return resulting_sets
[ "def", "random_subsets", "(", "self", ",", "relative_sizes", ",", "by_duration", "=", "False", ",", "balance_labels", "=", "False", ",", "label_list_ids", "=", "None", ")", ":", "resulting_sets", "=", "{", "}", "next_bigger_subset", "=", "self", ".", "corpus",...
Create a bunch of subsets with the given sizes relative to the size or duration of the full corpus. Basically the same as calling ``random_subset`` or ``random_subset_by_duration`` multiple times with different values. But this method makes sure that every subset contains only utterances, that are also contained in the next bigger subset. Args: relative_sizes (list): A list of numbers between 0 and 1 indicating the sizes of the desired subsets, relative to the full corpus. by_duration (bool): If True the size measure is the duration of all utterances in a subset/corpus. balance_labels (bool): If True the labels contained in a subset are chosen to be balanced as far as possible. label_list_ids (list): List of label-list ids. If none is given, all label-lists are considered for balancing. Otherwise only the ones that are in the list are considered. Returns: dict : A dictionary containing all subsets with the relative size as key.
[ "Create", "a", "bunch", "of", "subsets", "with", "the", "given", "sizes", "relative", "to", "the", "size", "or", "duration", "of", "the", "full", "corpus", ".", "Basically", "the", "same", "as", "calling", "random_subset", "or", "random_subset_by_duration", "m...
python
train
55.685714
edx/edx-enterprise
enterprise/utils.py
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/utils.py#L414-L443
def get_course_track_selection_url(course_run, query_parameters): """ Return track selection url for the given course. Arguments: course_run (dict): A dictionary containing course run metadata. query_parameters (dict): A dictionary containing query parameters to be added to course selection url. Raises: (KeyError): Raised when course run dict does not have 'key' key. Returns: (str): Course track selection url. """ try: course_root = reverse('course_modes_choose', kwargs={'course_id': course_run['key']}) except KeyError: LOGGER.exception( "KeyError while parsing course run data.\nCourse Run: \n[%s]", course_run, ) raise url = '{}{}'.format( settings.LMS_ROOT_URL, course_root ) course_run_url = update_query_parameters(url, query_parameters) return course_run_url
[ "def", "get_course_track_selection_url", "(", "course_run", ",", "query_parameters", ")", ":", "try", ":", "course_root", "=", "reverse", "(", "'course_modes_choose'", ",", "kwargs", "=", "{", "'course_id'", ":", "course_run", "[", "'key'", "]", "}", ")", "excep...
Return track selection url for the given course. Arguments: course_run (dict): A dictionary containing course run metadata. query_parameters (dict): A dictionary containing query parameters to be added to course selection url. Raises: (KeyError): Raised when course run dict does not have 'key' key. Returns: (str): Course track selection url.
[ "Return", "track", "selection", "url", "for", "the", "given", "course", "." ]
python
valid
29.566667
UpCloudLtd/upcloud-python-api
upcloud_api/server.py
https://github.com/UpCloudLtd/upcloud-python-api/blob/954b0ad7c4b932b2be31a95d88975f6b0eeac8ed/upcloud_api/server.py#L272-L278
def remove_tags(self, tags): """ Add tags to a server. Accepts tags as strings or Tag objects. """ if self.cloud_manager.remove_tags(self, tags): new_tags = [tag for tag in self.tags if tag not in tags] object.__setattr__(self, 'tags', new_tags)
[ "def", "remove_tags", "(", "self", ",", "tags", ")", ":", "if", "self", ".", "cloud_manager", ".", "remove_tags", "(", "self", ",", "tags", ")", ":", "new_tags", "=", "[", "tag", "for", "tag", "in", "self", ".", "tags", "if", "tag", "not", "in", "t...
Add tags to a server. Accepts tags as strings or Tag objects.
[ "Add", "tags", "to", "a", "server", ".", "Accepts", "tags", "as", "strings", "or", "Tag", "objects", "." ]
python
train
42.142857
astropy/pyregion
pyregion/region_to_filter.py
https://github.com/astropy/pyregion/blob/913af7ea4917855cb2e43d5086d1c8dd99c31363/pyregion/region_to_filter.py#L6-L117
def as_region_filter(shape_list, origin=1): """ Often, the regions files implicitly assume the lower-left corner of the image as a coordinate (1,1). However, the python convetion is that the array index starts from 0. By default (origin = 1), coordinates of the returned mpl artists have coordinate shifted by (1, 1). If you do not want this shift, use origin=0. """ filter_list = [] for shape in shape_list: if shape.name == "composite": continue if shape.name == "polygon": xy = np.array(shape.coord_list) - origin f = region_filter.Polygon(xy[::2], xy[1::2]) elif shape.name == "rotbox" or shape.name == "box": xc, yc, w, h, rot = shape.coord_list # -1 for change origin to 0,0 xc, yc = xc - origin, yc - origin f = region_filter.Rotated(region_filter.Box(xc, yc, w, h), rot, xc, yc) elif shape.name == "ellipse": xc, yc = shape.coord_list[:2] # -1 for change origin to 0,0 xc, yc = xc - origin, yc - origin angle = shape.coord_list[-1] maj_list, min_list = shape.coord_list[2:-1:2], shape.coord_list[3:-1:2] if len(maj_list) > 1: w1, h1 = max(maj_list), max(min_list) w2, h2 = min(maj_list), min(min_list) f1 = region_filter.Ellipse(xc, yc, w1, h1) \ & ~region_filter.Ellipse(xc, yc, w2, h2) f = region_filter.Rotated(f1, angle, xc, yc) else: w, h = maj_list[0], min_list[0] f = region_filter.Rotated(region_filter.Ellipse(xc, yc, w, h), angle, xc, yc) elif shape.name == "annulus": xc, yc = shape.coord_list[:2] # -1 for change origin to 0,0 xc, yc = xc - origin, yc - origin r_list = shape.coord_list[2:] r1 = max(r_list) r2 = min(r_list) f = region_filter.Circle(xc, yc, r1) & ~region_filter.Circle(xc, yc, r2) elif shape.name == "circle": xc, yc, r = shape.coord_list # -1 for change origin to 0,0 xc, yc = xc - origin, yc - origin f = region_filter.Circle(xc, yc, r) elif shape.name == "panda": xc, yc, a1, a2, an, r1, r2, rn = shape.coord_list # -1 for change origin to 0,0 xc, yc = xc - origin, yc - origin f1 = region_filter.Circle(xc, yc, r2) & ~region_filter.Circle(xc, yc, r1) f = f1 & region_filter.AngleRange(xc, yc, a1, a2) elif shape.name == "pie": xc, yc, r1, r2, a1, a2 = shape.coord_list # -1 for change origin to 0,0 xc, yc = xc - origin, yc - origin f1 = region_filter.Circle(xc, yc, r2) & ~region_filter.Circle(xc, yc, r1) f = f1 & region_filter.AngleRange(xc, yc, a1, a2) elif shape.name == "epanda": xc, yc, a1, a2, an, r11, r12, r21, r22, rn, angle = shape.coord_list # -1 for change origin to 0,0 xc, yc = xc - origin, yc - origin f1 = region_filter.Ellipse(xc, yc, r21, r22) & ~region_filter.Ellipse(xc, yc, r11, r12) f2 = f1 & region_filter.AngleRange(xc, yc, a1, a2) f = region_filter.Rotated(f2, angle, xc, yc) # f = f2 & region_filter.AngleRange(xc, yc, a1, a2) elif shape.name == "bpanda": xc, yc, a1, a2, an, r11, r12, r21, r22, rn, angle = shape.coord_list # -1 for change origin to 0,0 xc, yc = xc - origin, yc - origin f1 = region_filter.Box(xc, yc, r21, r22) & ~region_filter.Box(xc, yc, r11, r12) f2 = f1 & region_filter.AngleRange(xc, yc, a1, a2) f = region_filter.Rotated(f2, angle, xc, yc) # f = f2 & region_filter.AngleRange(xc, yc, a1, a2) else: warnings.warn("'as_region_filter' does not know how to convert {0}" " to a region filter.".format(shape.name)) continue if shape.exclude: filter_list = [region_filter.RegionOrList(*filter_list) & ~f] else: filter_list.append(f) return region_filter.RegionOrList(*filter_list)
[ "def", "as_region_filter", "(", "shape_list", ",", "origin", "=", "1", ")", ":", "filter_list", "=", "[", "]", "for", "shape", "in", "shape_list", ":", "if", "shape", ".", "name", "==", "\"composite\"", ":", "continue", "if", "shape", ".", "name", "==", ...
Often, the regions files implicitly assume the lower-left corner of the image as a coordinate (1,1). However, the python convetion is that the array index starts from 0. By default (origin = 1), coordinates of the returned mpl artists have coordinate shifted by (1, 1). If you do not want this shift, use origin=0.
[ "Often", "the", "regions", "files", "implicitly", "assume", "the", "lower", "-", "left", "corner", "of", "the", "image", "as", "a", "coordinate", "(", "1", "1", ")", ".", "However", "the", "python", "convetion", "is", "that", "the", "array", "index", "st...
python
train
38.25
rstoneback/pysat
pysat/instruments/cosmic2013_gps.py
https://github.com/rstoneback/pysat/blob/4ae1afd80e15e4449397d39dce8c3e969c32c422/pysat/instruments/cosmic2013_gps.py#L172-L224
def load_files(files, tag=None, sat_id=None, altitude_bin=None): '''Loads a list of COSMIC data files, supplied by user. Returns a list of dicts, a dict for each file. ''' output = [None]*len(files) drop_idx = [] for (i,file) in enumerate(files): try: #data = netCDF4.Dataset(file) data = netcdf_file(file, mode='r', mmap=False) # build up dictionary will all ncattrs new = {} # get list of file attributes #ncattrsList = data.ncattrs() ncattrsList = data._attributes.keys() for d in ncattrsList: new[d] = data._attributes[d] #data.getncattr(d) # load all of the variables in the netCDF loadedVars={} keys = data.variables.keys() for key in keys: if data.variables[key][:].dtype.byteorder != '=': loadedVars[key] = data.variables[key][:].byteswap().newbyteorder() else: loadedVars[key] = data.variables[key][:] new['profiles'] = pysat.DataFrame(loadedVars) output[i] = new data.close() except RuntimeError: # some of the files have zero bytes, which causes a read error # this stores the index of these zero byte files so I can drop # the Nones the gappy file leaves behind drop_idx.append(i) # drop anything that came from the zero byte files drop_idx.reverse() for i in drop_idx: del output[i] if tag == 'ionprf': if altitude_bin is not None: for out in output: out['profiles'].index = (out['profiles']['MSL_alt']/altitude_bin).round().values*altitude_bin out['profiles'] = out['profiles'].groupby(out['profiles'].index.values).mean() else: for out in output: out['profiles'].index = out['profiles']['MSL_alt'] return output
[ "def", "load_files", "(", "files", ",", "tag", "=", "None", ",", "sat_id", "=", "None", ",", "altitude_bin", "=", "None", ")", ":", "output", "=", "[", "None", "]", "*", "len", "(", "files", ")", "drop_idx", "=", "[", "]", "for", "(", "i", ",", ...
Loads a list of COSMIC data files, supplied by user. Returns a list of dicts, a dict for each file.
[ "Loads", "a", "list", "of", "COSMIC", "data", "files", "supplied", "by", "user", ".", "Returns", "a", "list", "of", "dicts", "a", "dict", "for", "each", "file", "." ]
python
train
38.056604
uuazed/numerapi
numerapi/numerapi.py
https://github.com/uuazed/numerapi/blob/fc9dcc53b32ede95bfda1ceeb62aec1d67d26697/numerapi/numerapi.py#L412-L435
def get_nmr_prize_pool(self, round_num=0, tournament=1): """Get NMR prize pool for the given round and tournament. Args: round_num (int, optional): The round you are interested in, defaults to current round. tournament (int, optional): ID of the tournament, defaults to 1 Returns: decimal.Decimal: prize pool in NMR Raises: Value Error: in case of invalid round number """ tournaments = self.get_competitions(tournament) tournaments.sort(key=lambda t: t['number']) if round_num == 0: t = tournaments[-1] else: tournaments = [t for t in tournaments if t['number'] == round_num] if len(tournaments) == 0: raise ValueError("invalid round number") t = tournaments[0] return t['prizePoolNmr']
[ "def", "get_nmr_prize_pool", "(", "self", ",", "round_num", "=", "0", ",", "tournament", "=", "1", ")", ":", "tournaments", "=", "self", ".", "get_competitions", "(", "tournament", ")", "tournaments", ".", "sort", "(", "key", "=", "lambda", "t", ":", "t"...
Get NMR prize pool for the given round and tournament. Args: round_num (int, optional): The round you are interested in, defaults to current round. tournament (int, optional): ID of the tournament, defaults to 1 Returns: decimal.Decimal: prize pool in NMR Raises: Value Error: in case of invalid round number
[ "Get", "NMR", "prize", "pool", "for", "the", "given", "round", "and", "tournament", "." ]
python
train
36.458333
JarryShaw/DictDumper
src/json.py
https://github.com/JarryShaw/DictDumper/blob/430efcfdff18bb2421c3f27059ff94c93e621483/src/json.py#L237-L253
def _append_bytes(self, value, _file): # pylint: disable=no-self-use """Call this function to write bytes contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file """ # binascii.b2a_base64(value) -> plistlib.Data # binascii.a2b_base64(Data) -> value(bytes) _text = ' '.join(textwrap.wrap(value.hex(), 2)) # _data = [H for H in iter( # functools.partial(io.StringIO(value.hex()).read, 2), '') # ] # to split bytes string into length-2 hex string list _labs = ' "{text}"'.format(text=_text) _file.write(_labs)
[ "def", "_append_bytes", "(", "self", ",", "value", ",", "_file", ")", ":", "# pylint: disable=no-self-use", "# binascii.b2a_base64(value) -> plistlib.Data", "# binascii.a2b_base64(Data) -> value(bytes)", "_text", "=", "' '", ".", "join", "(", "textwrap", ".", "wrap", "(",...
Call this function to write bytes contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file
[ "Call", "this", "function", "to", "write", "bytes", "contents", "." ]
python
train
39
jplusplus/statscraper
statscraper/base_scraper.py
https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/base_scraper.py#L493-L497
def shape(self): """Compute the shape of the dataset as (rows, cols).""" if not self.data: return (0, 0) return (len(self.data), len(self.dimensions))
[ "def", "shape", "(", "self", ")", ":", "if", "not", "self", ".", "data", ":", "return", "(", "0", ",", "0", ")", "return", "(", "len", "(", "self", ".", "data", ")", ",", "len", "(", "self", ".", "dimensions", ")", ")" ]
Compute the shape of the dataset as (rows, cols).
[ "Compute", "the", "shape", "of", "the", "dataset", "as", "(", "rows", "cols", ")", "." ]
python
train
36.4