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
LEMS/pylems
lems/parser/LEMS.py
https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/parser/LEMS.py#L525-L550
def parse_component_reference(self, node): """ Parses <ComponentReference> @param node: Node containing the <ComponentTypeRef> element @type node: xml.etree.Element """ if 'name' in node.lattrib: name = node.lattrib['name'] else: self.rai...
[ "def", "parse_component_reference", "(", "self", ",", "node", ")", ":", "if", "'name'", "in", "node", ".", "lattrib", ":", "name", "=", "node", ".", "lattrib", "[", "'name'", "]", "else", ":", "self", ".", "raise_error", "(", "'<ComponentReference> must spec...
Parses <ComponentReference> @param node: Node containing the <ComponentTypeRef> element @type node: xml.etree.Element
[ "Parses", "<ComponentReference", ">" ]
python
train
33.269231
RedHatInsights/insights-core
insights/util/__init__.py
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/util/__init__.py#L22-L29
def parse_bool(s, default=False): """ Return the boolean value of an English string or default if it can't be determined. """ if s is None: return default return TRUTH.get(s.lower(), default)
[ "def", "parse_bool", "(", "s", ",", "default", "=", "False", ")", ":", "if", "s", "is", "None", ":", "return", "default", "return", "TRUTH", ".", "get", "(", "s", ".", "lower", "(", ")", ",", "default", ")" ]
Return the boolean value of an English string or default if it can't be determined.
[ "Return", "the", "boolean", "value", "of", "an", "English", "string", "or", "default", "if", "it", "can", "t", "be", "determined", "." ]
python
train
27
gr33ndata/dysl
dysl/langid.py
https://github.com/gr33ndata/dysl/blob/649c1d6a1761f47d49a9842e7389f6df52039155/dysl/langid.py#L90-L97
def add_training_sample(self, text=u'', lang=''): """ Initial step for adding new sample to training data. You need to call `save_training_samples()` afterwards. :param text: Sample text to be added. :param lang: Language label for the input text. """ self.tr...
[ "def", "add_training_sample", "(", "self", ",", "text", "=", "u''", ",", "lang", "=", "''", ")", ":", "self", ".", "trainer", ".", "add", "(", "text", "=", "text", ",", "lang", "=", "lang", ")" ]
Initial step for adding new sample to training data. You need to call `save_training_samples()` afterwards. :param text: Sample text to be added. :param lang: Language label for the input text.
[ "Initial", "step", "for", "adding", "new", "sample", "to", "training", "data", ".", "You", "need", "to", "call", "save_training_samples", "()", "afterwards", "." ]
python
train
43
gc3-uzh-ch/elasticluster
elasticluster/utils.py
https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/utils.py#L95-L134
def expand_ssh_proxy_command(command, user, addr, port=22): """ Expand spacial digraphs ``%h``, ``%p``, and ``%r``. Return a copy of `command` with the following string substitutions applied: * ``%h`` is replaced by *addr* * ``%p`` is replaced by *port* * ``%r`` is replaced by *user* *...
[ "def", "expand_ssh_proxy_command", "(", "command", ",", "user", ",", "addr", ",", "port", "=", "22", ")", ":", "translated", "=", "[", "]", "subst", "=", "{", "'h'", ":", "list", "(", "str", "(", "addr", ")", ")", ",", "'p'", ":", "list", "(", "s...
Expand spacial digraphs ``%h``, ``%p``, and ``%r``. Return a copy of `command` with the following string substitutions applied: * ``%h`` is replaced by *addr* * ``%p`` is replaced by *port* * ``%r`` is replaced by *user* * ``%%`` is replaced by ``%``. See also: man page ``ssh_config``, se...
[ "Expand", "spacial", "digraphs", "%h", "%p", "and", "%r", "." ]
python
train
27.05
PyCQA/pylint
pylint/pyreverse/diadefslib.py
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/diadefslib.py#L171-L175
def visit_importfrom(self, node): """visit astroid.ImportFrom and catch modules for package diagram """ if self.pkgdiagram: self.pkgdiagram.add_from_depend(node, node.modname)
[ "def", "visit_importfrom", "(", "self", ",", "node", ")", ":", "if", "self", ".", "pkgdiagram", ":", "self", ".", "pkgdiagram", ".", "add_from_depend", "(", "node", ",", "node", ".", "modname", ")" ]
visit astroid.ImportFrom and catch modules for package diagram
[ "visit", "astroid", ".", "ImportFrom", "and", "catch", "modules", "for", "package", "diagram" ]
python
test
41.6
Alignak-monitoring/alignak
alignak/property.py
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/property.py#L324-L342
def pythonize(self, val): """Convert value into a list:: * split value (or each element if value is a list) on coma char * strip split values :param val: value to convert :type val: str :return: list corresponding to value :rtype: list """ if isi...
[ "def", "pythonize", "(", "self", ",", "val", ")", ":", "if", "isinstance", "(", "val", ",", "list", ")", ":", "return", "[", "s", ".", "strip", "(", ")", "if", "hasattr", "(", "s", ",", "\"strip\"", ")", "else", "s", "for", "s", "in", "list_split...
Convert value into a list:: * split value (or each element if value is a list) on coma char * strip split values :param val: value to convert :type val: str :return: list corresponding to value :rtype: list
[ "Convert", "value", "into", "a", "list", "::" ]
python
train
38.210526
PyHDI/Pyverilog
pyverilog/vparser/parser.py
https://github.com/PyHDI/Pyverilog/blob/b852cc5ed6a7a2712e33639f9d9782d0d1587a53/pyverilog/vparser/parser.py#L1985-L1988
def p_systemcall(self, p): 'systemcall : DOLLER ID LPAREN sysargs RPAREN' p[0] = SystemCall(p[2], p[4], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
[ "def", "p_systemcall", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "SystemCall", "(", "p", "[", "2", "]", ",", "p", "[", "4", "]", ",", "lineno", "=", "p", ".", "lineno", "(", "1", ")", ")", "p", ".", "set_lineno", "(", "0", ...
systemcall : DOLLER ID LPAREN sysargs RPAREN
[ "systemcall", ":", "DOLLER", "ID", "LPAREN", "sysargs", "RPAREN" ]
python
train
43.25
SUSE-Enceladus/ipa
ipa/ipa_ec2.py
https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_ec2.py#L186-L198
def _get_instance(self): """Retrieve instance matching instance_id.""" resource = self._connect() try: instance = resource.Instance(self.running_instance_id) except Exception: raise EC2CloudException( 'Instance with ID: {instance_id} not found.'.f...
[ "def", "_get_instance", "(", "self", ")", ":", "resource", "=", "self", ".", "_connect", "(", ")", "try", ":", "instance", "=", "resource", ".", "Instance", "(", "self", ".", "running_instance_id", ")", "except", "Exception", ":", "raise", "EC2CloudException...
Retrieve instance matching instance_id.
[ "Retrieve", "instance", "matching", "instance_id", "." ]
python
train
32.846154
numenta/htmresearch
htmresearch/regions/ApicalTMPairRegion.py
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/regions/ApicalTMPairRegion.py#L39-L310
def getSpec(cls): """ Return the Spec for ApicalTMPairRegion """ spec = { "description": ApicalTMPairRegion.__doc__, "singleNodeOnly": True, "inputs": { "activeColumns": { "description": ("An array of 0's and 1's representing the active " "m...
[ "def", "getSpec", "(", "cls", ")", ":", "spec", "=", "{", "\"description\"", ":", "ApicalTMPairRegion", ".", "__doc__", ",", "\"singleNodeOnly\"", ":", "True", ",", "\"inputs\"", ":", "{", "\"activeColumns\"", ":", "{", "\"description\"", ":", "(", "\"An array...
Return the Spec for ApicalTMPairRegion
[ "Return", "the", "Spec", "for", "ApicalTMPairRegion" ]
python
train
34.113971
dshean/pygeotools
pygeotools/lib/iolib.py
https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/iolib.py#L506-L515
def cpu_count(logical=True): """Return system CPU count """ if logical: from multiprocessing import cpu_count ncpu=cpu_count() else: import psutil ncpu=psutil.cpu_count(logical=False) return ncpu
[ "def", "cpu_count", "(", "logical", "=", "True", ")", ":", "if", "logical", ":", "from", "multiprocessing", "import", "cpu_count", "ncpu", "=", "cpu_count", "(", ")", "else", ":", "import", "psutil", "ncpu", "=", "psutil", ".", "cpu_count", "(", "logical",...
Return system CPU count
[ "Return", "system", "CPU", "count" ]
python
train
23.8
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/dataframeeditor.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/dataframeeditor.py#L297-L307
def get_value(self, row, column): """Return the value of the DataFrame.""" # To increase the performance iat is used but that requires error # handling, so fallback uses iloc try: value = self.df.iat[row, column] except OutOfBoundsDatetime: value = ...
[ "def", "get_value", "(", "self", ",", "row", ",", "column", ")", ":", "# To increase the performance iat is used but that requires error\r", "# handling, so fallback uses iloc\r", "try", ":", "value", "=", "self", ".", "df", ".", "iat", "[", "row", ",", "column", "]...
Return the value of the DataFrame.
[ "Return", "the", "value", "of", "the", "DataFrame", "." ]
python
train
40
marcomusy/vtkplotter
vtkplotter/actors.py
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L2555-L2577
def threshold(self, vmin=None, vmax=None, replaceWith=None): """ Binary or continuous volume thresholding. """ th = vtk.vtkImageThreshold() th.SetInputData(self.image) if vmin is not None and vmax is not None: th.ThresholdBetween(vmin, vmax) e...
[ "def", "threshold", "(", "self", ",", "vmin", "=", "None", ",", "vmax", "=", "None", ",", "replaceWith", "=", "None", ")", ":", "th", "=", "vtk", ".", "vtkImageThreshold", "(", ")", "th", ".", "SetInputData", "(", "self", ".", "image", ")", "if", "...
Binary or continuous volume thresholding.
[ "Binary", "or", "continuous", "volume", "thresholding", "." ]
python
train
29.956522
TeamHG-Memex/eli5
eli5/base_utils.py
https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/base_utils.py#L11-L36
def attrs(class_): """ Like attr.s with slots=True, but with attributes extracted from __init__ method signature. slots=True ensures that signature matches what really happens (we can't define different attributes on self). It is useful if we still want __init__ for proper type-checking and do n...
[ "def", "attrs", "(", "class_", ")", ":", "attrs_kwargs", "=", "{", "}", "for", "method", ",", "kw_name", "in", "[", "(", "'__repr__'", ",", "'repr'", ")", ",", "(", "'__eq__'", ",", "'cmp'", ")", ",", "(", "'__hash__'", ",", "'hash'", ")", ",", "]"...
Like attr.s with slots=True, but with attributes extracted from __init__ method signature. slots=True ensures that signature matches what really happens (we can't define different attributes on self). It is useful if we still want __init__ for proper type-checking and do not want to repeat attribute...
[ "Like", "attr", ".", "s", "with", "slots", "=", "True", "but", "with", "attributes", "extracted", "from", "__init__", "method", "signature", ".", "slots", "=", "True", "ensures", "that", "signature", "matches", "what", "really", "happens", "(", "we", "can", ...
python
train
44
sveetch/boussole
boussole/conf/base_backend.py
https://github.com/sveetch/boussole/blob/22cc644e9d633f41ebfc167d427a71c1726cee21/boussole/conf/base_backend.py#L83-L106
def check_filepath(self, path, filename): """ Check and return the final filepath to settings Args: path (str): Directory path where to search for settings file. filename (str): Filename to use to search for settings file. Raises: boussole.exceptions...
[ "def", "check_filepath", "(", "self", ",", "path", ",", "filename", ")", ":", "settings_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "filename", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "settings_path", ")", "or", "no...
Check and return the final filepath to settings Args: path (str): Directory path where to search for settings file. filename (str): Filename to use to search for settings file. Raises: boussole.exceptions.SettingsBackendError: If determined filepath ...
[ "Check", "and", "return", "the", "final", "filepath", "to", "settings" ]
python
train
33.166667
apache/incubator-superset
superset/utils/core.py
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/utils/core.py#L932-L1005
def get_since_until(time_range: Optional[str] = None, since: Optional[str] = None, until: Optional[str] = None, time_shift: Optional[str] = None, relative_end: Optional[str] = None) -> Tuple[datetime, datetime]: """Return `since` and `u...
[ "def", "get_since_until", "(", "time_range", ":", "Optional", "[", "str", "]", "=", "None", ",", "since", ":", "Optional", "[", "str", "]", "=", "None", ",", "until", ":", "Optional", "[", "str", "]", "=", "None", ",", "time_shift", ":", "Optional", ...
Return `since` and `until` date time tuple from string representations of time_range, since, until and time_shift. This functiom supports both reading the keys separately (from `since` and `until`), as well as the new `time_range` key. Valid formats are: - ISO 8601 - X days/years/hours/day...
[ "Return", "since", "and", "until", "date", "time", "tuple", "from", "string", "representations", "of", "time_range", "since", "until", "and", "time_shift", "." ]
python
train
41.581081
alimanfoo/vcfnp
vcfnp/array.py
https://github.com/alimanfoo/vcfnp/blob/c3f63fb11ada56d4a88076c61c81f99b8ee78b8f/vcfnp/array.py#L527-L535
def _fromiter(it, dtype, count, progress, log): """Utility function to load an array from an iterator.""" if progress > 0: it = _iter_withprogress(it, progress, log) if count is not None: a = np.fromiter(it, dtype=dtype, count=count) else: a = np.fromiter(it, dtype=dtype) ret...
[ "def", "_fromiter", "(", "it", ",", "dtype", ",", "count", ",", "progress", ",", "log", ")", ":", "if", "progress", ">", "0", ":", "it", "=", "_iter_withprogress", "(", "it", ",", "progress", ",", "log", ")", "if", "count", "is", "not", "None", ":"...
Utility function to load an array from an iterator.
[ "Utility", "function", "to", "load", "an", "array", "from", "an", "iterator", "." ]
python
train
35.222222
twilio/twilio-python
twilio/twiml/voice_response.py
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/twiml/voice_response.py#L486-L496
def ssml_emphasis(self, words, level=None, **kwargs): """ Create a <Emphasis> element :param words: Words to emphasize :param level: Specify the degree of emphasis :param kwargs: additional attributes :returns: <Emphasis> element """ return self.nest(Ssm...
[ "def", "ssml_emphasis", "(", "self", ",", "words", ",", "level", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "nest", "(", "SsmlEmphasis", "(", "words", ",", "level", "=", "level", ",", "*", "*", "kwargs", ")", ")" ]
Create a <Emphasis> element :param words: Words to emphasize :param level: Specify the degree of emphasis :param kwargs: additional attributes :returns: <Emphasis> element
[ "Create", "a", "<Emphasis", ">", "element" ]
python
train
31.818182
Qiskit/qiskit-terra
qiskit/circuit/decorators.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/decorators.py#L53-L73
def _to_bits(nqbits, ncbits=0, func=None): """Convert gate arguments to [qu|cl]bits from integers, slices, ranges, etc. For example circuit.h(0) -> circuit.h(QuantumRegister(2)[0]) """ if func is None: return functools.partial(_to_bits, nqbits, ncbits) @functools.wraps(func) def wrapper(sel...
[ "def", "_to_bits", "(", "nqbits", ",", "ncbits", "=", "0", ",", "func", "=", "None", ")", ":", "if", "func", "is", "None", ":", "return", "functools", ".", "partial", "(", "_to_bits", ",", "nqbits", ",", "ncbits", ")", "@", "functools", ".", "wraps",...
Convert gate arguments to [qu|cl]bits from integers, slices, ranges, etc. For example circuit.h(0) -> circuit.h(QuantumRegister(2)[0])
[ "Convert", "gate", "arguments", "to", "[", "qu|cl", "]", "bits", "from", "integers", "slices", "ranges", "etc", ".", "For", "example", "circuit", ".", "h", "(", "0", ")", "-", ">", "circuit", ".", "h", "(", "QuantumRegister", "(", "2", ")", "[", "0",...
python
test
33
desbma/sacad
sacad/sources/google_images.py
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/sources/google_images.py#L50-L98
async def parseResults(self, api_data): """ See CoverSource.parseResults. """ results = [] # parse HTML and get results parser = lxml.etree.HTMLParser() html = lxml.etree.XML(api_data.decode("latin-1"), parser) for rank, result in enumerate(__class__.RESULTS_SELECTOR(html), 1): # extract...
[ "async", "def", "parseResults", "(", "self", ",", "api_data", ")", ":", "results", "=", "[", "]", "# parse HTML and get results", "parser", "=", "lxml", ".", "etree", ".", "HTMLParser", "(", ")", "html", "=", "lxml", ".", "etree", ".", "XML", "(", "api_d...
See CoverSource.parseResults.
[ "See", "CoverSource", ".", "parseResults", "." ]
python
train
37.632653
scivision/histutils
histutils/camclass.py
https://github.com/scivision/histutils/blob/859a91d3894cb57faed34881c6ea16130b90571e/histutils/camclass.py#L333-L382
def doorient(self): """ NOTE: we need to retrieve values in case no modifications are done. (since we'd get a closed h5py handle) """ assert self.cal1Dfn.is_file( ), 'please specify filename for each camera under [cam]/cal1Dname: in .ini file {}'.format(self.cal1Dfn) ...
[ "def", "doorient", "(", "self", ")", ":", "assert", "self", ".", "cal1Dfn", ".", "is_file", "(", ")", ",", "'please specify filename for each camera under [cam]/cal1Dname: in .ini file {}'", ".", "format", "(", "self", ".", "cal1Dfn", ")", "with", "h5py", ".", "F...
NOTE: we need to retrieve values in case no modifications are done. (since we'd get a closed h5py handle)
[ "NOTE", ":", "we", "need", "to", "retrieve", "values", "in", "case", "no", "modifications", "are", "done", ".", "(", "since", "we", "d", "get", "a", "closed", "h5py", "handle", ")" ]
python
train
32.9
log2timeline/plaso
plaso/parsers/mac_keychain.py
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/parsers/mac_keychain.py#L735-L757
def _ParseBinaryDataAsString(self, parser_mediator, binary_data_value): """Parses a binary data value as string Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. binary_data_value (bytes): binary data value ...
[ "def", "_ParseBinaryDataAsString", "(", "self", ",", "parser_mediator", ",", "binary_data_value", ")", ":", "if", "not", "binary_data_value", ":", "return", "None", "try", ":", "return", "binary_data_value", ".", "decode", "(", "'utf-8'", ")", "except", "UnicodeDe...
Parses a binary data value as string Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. binary_data_value (bytes): binary data value (CSSM_DB_ATTRIBUTE_FORMAT_BLOB) Returns: str: binary data value...
[ "Parses", "a", "binary", "data", "value", "as", "string" ]
python
train
34.608696
iamteem/redisco
redisco/containers.py
https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/containers.py#L124-L129
def union(self, key, *others): """Return a new set with elements from the set and all others.""" if not isinstance(key, str): raise ValueError("String expected.") self.db.sunionstore(key, [self.key] + [o.key for o in others]) return Set(key)
[ "def", "union", "(", "self", ",", "key", ",", "*", "others", ")", ":", "if", "not", "isinstance", "(", "key", ",", "str", ")", ":", "raise", "ValueError", "(", "\"String expected.\"", ")", "self", ".", "db", ".", "sunionstore", "(", "key", ",", "[", ...
Return a new set with elements from the set and all others.
[ "Return", "a", "new", "set", "with", "elements", "from", "the", "set", "and", "all", "others", "." ]
python
train
46.666667
openego/ding0
ding0/grid/mv_grid/util/data_input.py
https://github.com/openego/ding0/blob/e2d6528f96255e4bb22ba15514a4f1883564ed5d/ding0/grid/mv_grid/util/data_input.py#L108-L148
def _parse_nodes_section(f, current_section, nodes): """Parse TSPLIB NODE_COORD_SECTION or DEMAND_SECTION from file descript f Returns a dict containing the node as key """ section = {} dimensions = None if current_section == 'NODE_COORD_SECTION': dimensions = 3 # i: (i, j) elif cu...
[ "def", "_parse_nodes_section", "(", "f", ",", "current_section", ",", "nodes", ")", ":", "section", "=", "{", "}", "dimensions", "=", "None", "if", "current_section", "==", "'NODE_COORD_SECTION'", ":", "dimensions", "=", "3", "# i: (i, j)", "elif", "current_sect...
Parse TSPLIB NODE_COORD_SECTION or DEMAND_SECTION from file descript f Returns a dict containing the node as key
[ "Parse", "TSPLIB", "NODE_COORD_SECTION", "or", "DEMAND_SECTION", "from", "file", "descript", "f" ]
python
train
27.97561
seung-lab/cloud-volume
cloudvolume/skeletonservice.py
https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/skeletonservice.py#L79-L103
def simple_merge(kls, skeletons): """ Simple concatenation of skeletons into one object without adding edges between them. """ if len(skeletons) == 0: return PrecomputedSkeleton() if type(skeletons[0]) is np.ndarray: skeletons = [ skeletons ] ct = 0 edges = [] for skel...
[ "def", "simple_merge", "(", "kls", ",", "skeletons", ")", ":", "if", "len", "(", "skeletons", ")", "==", "0", ":", "return", "PrecomputedSkeleton", "(", ")", "if", "type", "(", "skeletons", "[", "0", "]", ")", "is", "np", ".", "ndarray", ":", "skelet...
Simple concatenation of skeletons into one object without adding edges between them.
[ "Simple", "concatenation", "of", "skeletons", "into", "one", "object", "without", "adding", "edges", "between", "them", "." ]
python
train
30.08
great-expectations/great_expectations
examples/integrations/airflow/operators/expectation_operator.py
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/examples/integrations/airflow/operators/expectation_operator.py#L120-L136
def _get_dataframe(self): """ Load dataframe based on specified connection :return: """ if self.source_conn is None: # Use local file return ge.read_csv(self.dataset_name, **self.dataset_params) if isinstance(self.source_conn, S3Hook): hook = Exp...
[ "def", "_get_dataframe", "(", "self", ")", ":", "if", "self", ".", "source_conn", "is", "None", ":", "# Use local file", "return", "ge", ".", "read_csv", "(", "self", ".", "dataset_name", ",", "*", "*", "self", ".", "dataset_params", ")", "if", "isinstance...
Load dataframe based on specified connection :return:
[ "Load", "dataframe", "based", "on", "specified", "connection", ":", "return", ":" ]
python
train
38.882353
hydpy-dev/hydpy
hydpy/auxs/xmltools.py
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/auxs/xmltools.py#L1947-L1999
def get_nodesitemtypeinsertion(cls, itemgroup, indent) -> str: """Return a string defining the required types for the given combination of an exchange item group and |Node| objects. >>> from hydpy.auxs.xmltools import XSDWriter >>> print(XSDWriter.get_nodesitemtypeinsertion( ......
[ "def", "get_nodesitemtypeinsertion", "(", "cls", ",", "itemgroup", ",", "indent", ")", "->", "str", ":", "blanks", "=", "' '", "*", "(", "indent", "*", "4", ")", "subs", "=", "[", "f'{blanks}<complexType name=\"nodes_{itemgroup}Type\">'", ",", "f'{blanks} <sequ...
Return a string defining the required types for the given combination of an exchange item group and |Node| objects. >>> from hydpy.auxs.xmltools import XSDWriter >>> print(XSDWriter.get_nodesitemtypeinsertion( ... 'setitems', 1)) # doctest: +ELLIPSIS <complexType name...
[ "Return", "a", "string", "defining", "the", "required", "types", "for", "the", "given", "combination", "of", "an", "exchange", "item", "group", "and", "|Node|", "objects", "." ]
python
train
45.320755
numba/llvmlite
llvmlite/ir/builder.py
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/builder.py#L545-L558
def fcmp_ordered(self, cmpop, lhs, rhs, name='', flags=[]): """ Floating-point ordered comparison: name = lhs <cmpop> rhs where cmpop can be '==', '!=', '<', '<=', '>', '>=', 'ord', 'uno' """ if cmpop in _CMP_MAP: op = 'o' + _CMP_MAP[cmpop] else: ...
[ "def", "fcmp_ordered", "(", "self", ",", "cmpop", ",", "lhs", ",", "rhs", ",", "name", "=", "''", ",", "flags", "=", "[", "]", ")", ":", "if", "cmpop", "in", "_CMP_MAP", ":", "op", "=", "'o'", "+", "_CMP_MAP", "[", "cmpop", "]", "else", ":", "o...
Floating-point ordered comparison: name = lhs <cmpop> rhs where cmpop can be '==', '!=', '<', '<=', '>', '>=', 'ord', 'uno'
[ "Floating", "-", "point", "ordered", "comparison", ":", "name", "=", "lhs", "<cmpop", ">", "rhs" ]
python
train
33.357143
tilezen/mapbox-vector-tile
mapbox_vector_tile/optimise.py
https://github.com/tilezen/mapbox-vector-tile/blob/7327b8cff0aa2de1d5233e556bf00429ba2126a0/mapbox_vector_tile/optimise.py#L149-L182
def _reorder_lines(lines): """ Reorder lines so that the distance from the end of one to the beginning of the next is minimised. """ x = 0 y = 0 new_lines = [] # treat the list of lines as a stack, off which we keep popping the best # one to add next. while lines: # loo...
[ "def", "_reorder_lines", "(", "lines", ")", ":", "x", "=", "0", "y", "=", "0", "new_lines", "=", "[", "]", "# treat the list of lines as a stack, off which we keep popping the best", "# one to add next.", "while", "lines", ":", "# looping over all the lines like this isn't ...
Reorder lines so that the distance from the end of one to the beginning of the next is minimised.
[ "Reorder", "lines", "so", "that", "the", "distance", "from", "the", "end", "of", "one", "to", "the", "beginning", "of", "the", "next", "is", "minimised", "." ]
python
train
26.941176
aws/aws-encryption-sdk-python
decrypt_oracle/src/aws_encryption_sdk_decrypt_oracle/key_providers/counting.py
https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/decrypt_oracle/src/aws_encryption_sdk_decrypt_oracle/key_providers/counting.py#L53-L63
def _generate_data_key(self, algorithm: AlgorithmSuite, encryption_context: Dict[Text, Text]) -> DataKey: """Perform the provider-specific data key generation task. :param algorithm: Algorithm on which to base data key :type algorithm: aws_encryption_sdk.identifiers.Algorithm :param dic...
[ "def", "_generate_data_key", "(", "self", ",", "algorithm", ":", "AlgorithmSuite", ",", "encryption_context", ":", "Dict", "[", "Text", ",", "Text", "]", ")", "->", "DataKey", ":", "data_key", "=", "b\"\"", ".", "join", "(", "[", "chr", "(", "i", ")", ...
Perform the provider-specific data key generation task. :param algorithm: Algorithm on which to base data key :type algorithm: aws_encryption_sdk.identifiers.Algorithm :param dict encryption_context: Encryption context to use in encryption :returns: Generated data key :rtype: aw...
[ "Perform", "the", "provider", "-", "specific", "data", "key", "generation", "task", "." ]
python
train
63
twosigma/marbles
marbles/mixins/marbles/mixins/mixins.py
https://github.com/twosigma/marbles/blob/f0c668be8344c70d4d63bc57e82c6f2da43c6925/marbles/mixins/marbles/mixins/mixins.py#L815-L840
def assertFileEncodingNotEqual(self, filename, encoding, msg=None): '''Fail if ``filename`` is encoded with the given ``encoding`` as determined by the '!=' operator. Parameters ---------- filename : str, bytes, file-like encoding : str, bytes msg : str ...
[ "def", "assertFileEncodingNotEqual", "(", "self", ",", "filename", ",", "encoding", ",", "msg", "=", "None", ")", ":", "fencoding", "=", "self", ".", "_get_file_encoding", "(", "filename", ")", "fname", "=", "self", ".", "_get_file_name", "(", "filename", ")...
Fail if ``filename`` is encoded with the given ``encoding`` as determined by the '!=' operator. Parameters ---------- filename : str, bytes, file-like encoding : str, bytes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` st...
[ "Fail", "if", "filename", "is", "encoded", "with", "the", "given", "encoding", "as", "determined", "by", "the", "!", "=", "operator", "." ]
python
train
33.730769
paylogic/halogen
halogen/types.py
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/types.py#L205-L225
def amount_object_to_dict(self, amount): """Return the dictionary representation of an Amount object. Amount object must have amount and currency properties and as_tuple method which will return (currency, amount) and as_quantized method to quantize amount property. :param amount: inst...
[ "def", "amount_object_to_dict", "(", "self", ",", "amount", ")", ":", "currency", ",", "amount", "=", "(", "amount", ".", "as_quantized", "(", "digits", "=", "2", ")", ".", "as_tuple", "(", ")", "if", "not", "isinstance", "(", "amount", ",", "dict", ")...
Return the dictionary representation of an Amount object. Amount object must have amount and currency properties and as_tuple method which will return (currency, amount) and as_quantized method to quantize amount property. :param amount: instance of Amount object :return: dict with am...
[ "Return", "the", "dictionary", "representation", "of", "an", "Amount", "object", "." ]
python
train
38.380952
edx/i18n-tools
i18n/segment.py
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/segment.py#L119-L133
def get_parser(parser): """ Grabs the parser. args: parser: The parser """ parser.description = textwrap.dedent(""" Segment the .po files in LOCALE(s) based on the segmenting rules in config.yaml. Note that segmenting is *not* idempotent: it modifies the input file,...
[ "def", "get_parser", "(", "parser", ")", ":", "parser", ".", "description", "=", "textwrap", ".", "dedent", "(", "\"\"\"\n Segment the .po files in LOCALE(s) based on the segmenting rules in\n config.yaml.\n\n Note that segmenting is *not* idempotent: it modifies the...
Grabs the parser. args: parser: The parser
[ "Grabs", "the", "parser", "." ]
python
train
30.933333
aaugustin/websockets
src/websockets/client.py
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/client.py#L188-L221
def process_subprotocol( headers: Headers, available_subprotocols: Optional[Sequence[Subprotocol]] ) -> Optional[Subprotocol]: """ Handle the Sec-WebSocket-Protocol HTTP response header. Check that it contains exactly one supported subprotocol. Return the selected subprotoc...
[ "def", "process_subprotocol", "(", "headers", ":", "Headers", ",", "available_subprotocols", ":", "Optional", "[", "Sequence", "[", "Subprotocol", "]", "]", ")", "->", "Optional", "[", "Subprotocol", "]", ":", "subprotocol", ":", "Optional", "[", "Subprotocol", ...
Handle the Sec-WebSocket-Protocol HTTP response header. Check that it contains exactly one supported subprotocol. Return the selected subprotocol.
[ "Handle", "the", "Sec", "-", "WebSocket", "-", "Protocol", "HTTP", "response", "header", "." ]
python
train
33.529412
jaraco/keyring
keyring/core.py
https://github.com/jaraco/keyring/blob/71c798378e365286b7cc03c06e4d7d24c7de8fc4/keyring/core.py#L177-L183
def _load_keyring_path(config): "load the keyring-path option (if present)" try: path = config.get("backend", "keyring-path").strip() sys.path.insert(0, path) except (configparser.NoOptionError, configparser.NoSectionError): pass
[ "def", "_load_keyring_path", "(", "config", ")", ":", "try", ":", "path", "=", "config", ".", "get", "(", "\"backend\"", ",", "\"keyring-path\"", ")", ".", "strip", "(", ")", "sys", ".", "path", ".", "insert", "(", "0", ",", "path", ")", "except", "(...
load the keyring-path option (if present)
[ "load", "the", "keyring", "-", "path", "option", "(", "if", "present", ")" ]
python
valid
37
SKA-ScienceDataProcessor/integration-prototype
sip/examples/flask_processing_controller/app/old.db/mock/client.py
https://github.com/SKA-ScienceDataProcessor/integration-prototype/blob/8c8006de6ad71dcd44114b0338780738079c87d4/sip/examples/flask_processing_controller/app/old.db/mock/client.py#L151-L160
def get_processing_block(block_id): """Return the Processing Block Configuration for the specified ID""" identifiers = block_id.split(':') scheduling_block_id = identifiers[0] scheduling_block_config = get_scheduling_block(scheduling_block_id) for processing_block in scheduling_block_config['process...
[ "def", "get_processing_block", "(", "block_id", ")", ":", "identifiers", "=", "block_id", ".", "split", "(", "':'", ")", "scheduling_block_id", "=", "identifiers", "[", "0", "]", "scheduling_block_config", "=", "get_scheduling_block", "(", "scheduling_block_id", ")"...
Return the Processing Block Configuration for the specified ID
[ "Return", "the", "Processing", "Block", "Configuration", "for", "the", "specified", "ID" ]
python
train
52
wtsi-hgi/python-common
hgicommon/managers.py
https://github.com/wtsi-hgi/python-common/blob/0376a6b574ff46e82e509e90b6cb3693a3dbb577/hgicommon/managers.py#L43-L52
def create_temp_directory(self, **mkdtemp_kwargs) -> str: """ Creates a temp directory. :param mkdtemp_kwargs: named arguments to be passed to `tempfile.mkdtemp` :return: the location of the temp directory """ kwargs = {**self.default_mkdtemp_kwargs, **mkdtemp_kwargs} ...
[ "def", "create_temp_directory", "(", "self", ",", "*", "*", "mkdtemp_kwargs", ")", "->", "str", ":", "kwargs", "=", "{", "*", "*", "self", ".", "default_mkdtemp_kwargs", ",", "*", "*", "mkdtemp_kwargs", "}", "location", "=", "tempfile", ".", "mkdtemp", "("...
Creates a temp directory. :param mkdtemp_kwargs: named arguments to be passed to `tempfile.mkdtemp` :return: the location of the temp directory
[ "Creates", "a", "temp", "directory", ".", ":", "param", "mkdtemp_kwargs", ":", "named", "arguments", "to", "be", "passed", "to", "tempfile", ".", "mkdtemp", ":", "return", ":", "the", "location", "of", "the", "temp", "directory" ]
python
valid
42.2
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/reftrackwidget.py
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/reftrackwidget.py#L216-L229
def disable_restricted(self, ): """Disable the restricted buttons :returns: None :rtype: None :raises: None """ todisable = [(self.reftrack.duplicate, self.duplicate_tb), (self.reftrack.delete, self.delete_tb), (self.reftrack.ref...
[ "def", "disable_restricted", "(", "self", ",", ")", ":", "todisable", "=", "[", "(", "self", ".", "reftrack", ".", "duplicate", ",", "self", ".", "duplicate_tb", ")", ",", "(", "self", ".", "reftrack", ".", "delete", ",", "self", ".", "delete_tb", ")",...
Disable the restricted buttons :returns: None :rtype: None :raises: None
[ "Disable", "the", "restricted", "buttons" ]
python
train
37.357143
GPflow/GPflow
gpflow/expectations.py
https://github.com/GPflow/GPflow/blob/549394f0b1b0696c7b521a065e49bdae6e7acf27/gpflow/expectations.py#L764-L779
def _expectation(p, mean1, none1, mean2, none2, nghp=None): """ Compute the expectation: expectation[n] = <m1(x_n)^T m2(x_n)>_p(x_n) - m1(.) :: Linear mean function - m2(.) :: Identity mean function :return: NxQxD """ with params_as_tensors_for(mean1): N = tf.shape(p.mu)...
[ "def", "_expectation", "(", "p", ",", "mean1", ",", "none1", ",", "mean2", ",", "none2", ",", "nghp", "=", "None", ")", ":", "with", "params_as_tensors_for", "(", "mean1", ")", ":", "N", "=", "tf", ".", "shape", "(", "p", ".", "mu", ")", "[", "0"...
Compute the expectation: expectation[n] = <m1(x_n)^T m2(x_n)>_p(x_n) - m1(.) :: Linear mean function - m2(.) :: Identity mean function :return: NxQxD
[ "Compute", "the", "expectation", ":", "expectation", "[", "n", "]", "=", "<m1", "(", "x_n", ")", "^T", "m2", "(", "x_n", ")", ">", "_p", "(", "x_n", ")", "-", "m1", "(", ".", ")", "::", "Linear", "mean", "function", "-", "m2", "(", ".", ")", ...
python
train
36.375
rootpy/rootpy
rootpy/tree/treemodel.py
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/tree/treemodel.py#L53-L82
def checkattr(metacls, attr, value): """ Only allow class attributes that are instances of rootpy.types.Column, ROOT.TObject, or ROOT.ObjectProxy """ if not isinstance(value, ( types.MethodType, types.FunctionType, classmethod, ...
[ "def", "checkattr", "(", "metacls", ",", "attr", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "(", "types", ".", "MethodType", ",", "types", ".", "FunctionType", ",", "classmethod", ",", "staticmethod", ",", "property", ")", ")",...
Only allow class attributes that are instances of rootpy.types.Column, ROOT.TObject, or ROOT.ObjectProxy
[ "Only", "allow", "class", "attributes", "that", "are", "instances", "of", "rootpy", ".", "types", ".", "Column", "ROOT", ".", "TObject", "or", "ROOT", ".", "ObjectProxy" ]
python
train
42.033333
iotile/coretools
iotilecore/iotile/core/utilities/schema_verify/int_verify.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/schema_verify/int_verify.py#L15-L31
def verify(self, obj): """Verify that the object conforms to this verifier's schema Args: obj (object): A python object to verify Raises: ValidationError: If there is a problem verifying the dictionary, a ValidationError is thrown with at least the reaso...
[ "def", "verify", "(", "self", ",", "obj", ")", ":", "if", "not", "isinstance", "(", "obj", ",", "int", ")", ":", "raise", "ValidationError", "(", "\"Object is not a int\"", ",", "reason", "=", "'object is not a int'", ",", "object", "=", "obj", ",", "type"...
Verify that the object conforms to this verifier's schema Args: obj (object): A python object to verify Raises: ValidationError: If there is a problem verifying the dictionary, a ValidationError is thrown with at least the reason key set indicating ...
[ "Verify", "that", "the", "object", "conforms", "to", "this", "verifier", "s", "schema" ]
python
train
36
thespacedoctor/sherlock
sherlock/transient_classifier.py
https://github.com/thespacedoctor/sherlock/blob/2c80fb6fa31b04e7820e6928e3d437a21e692dd3/sherlock/transient_classifier.py#L542-L621
def _remove_previous_ned_queries( self, coordinateList): """iterate through the transient locations to see if we have recent local NED coverage of that area already **Key Arguments:** - ``coordinateList`` -- set of coordinate to check for previous queries **...
[ "def", "_remove_previous_ned_queries", "(", "self", ",", "coordinateList", ")", ":", "self", ".", "log", ".", "debug", "(", "'starting the ``_remove_previous_ned_queries`` method'", ")", "# 1 DEGREE QUERY RADIUS", "radius", "=", "60.", "*", "60.", "updatedCoordinateList",...
iterate through the transient locations to see if we have recent local NED coverage of that area already **Key Arguments:** - ``coordinateList`` -- set of coordinate to check for previous queries **Return:** - ``updatedCoordinateList`` -- coordinate list with previous queries r...
[ "iterate", "through", "the", "transient", "locations", "to", "see", "if", "we", "have", "recent", "local", "NED", "coverage", "of", "that", "area", "already" ]
python
train
35.4
sorgerlab/indra
indra/sources/isi/processor.py
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/isi/processor.py#L38-L43
def get_statements(self): """Process reader output to produce INDRA Statements.""" for k, v in self.reader_output.items(): for interaction in v['interactions']: self._process_interaction(k, interaction, v['text'], self.pmid, self.extr...
[ "def", "get_statements", "(", "self", ")", ":", "for", "k", ",", "v", "in", "self", ".", "reader_output", ".", "items", "(", ")", ":", "for", "interaction", "in", "v", "[", "'interactions'", "]", ":", "self", ".", "_process_interaction", "(", "k", ",",...
Process reader output to produce INDRA Statements.
[ "Process", "reader", "output", "to", "produce", "INDRA", "Statements", "." ]
python
train
54.833333
SamLau95/nbinteract
nbinteract/plotting.py
https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/nbinteract/plotting.py#L312-L377
def scatter_drag( x_points: 'Array', y_points: 'Array', *, fig=None, show_eqn=True, options={} ): """ Generates an interactive scatter plot with the best fit line plotted over the points. The points can be dragged by the user and the line will automatically update. Args: ...
[ "def", "scatter_drag", "(", "x_points", ":", "'Array'", ",", "y_points", ":", "'Array'", ",", "*", ",", "fig", "=", "None", ",", "show_eqn", "=", "True", ",", "options", "=", "{", "}", ")", ":", "params", "=", "{", "'marks'", ":", "[", "{", "'x'", ...
Generates an interactive scatter plot with the best fit line plotted over the points. The points can be dragged by the user and the line will automatically update. Args: x_points (Array Number): x-values of points to plot y_points (Array Number): y-values of points to plot Kwargs: ...
[ "Generates", "an", "interactive", "scatter", "plot", "with", "the", "best", "fit", "line", "plotted", "over", "the", "points", ".", "The", "points", "can", "be", "dragged", "by", "the", "user", "and", "the", "line", "will", "automatically", "update", "." ]
python
train
26.409091
ellmetha/django-machina
machina/apps/forum_conversation/abstract_models.py
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/abstract_models.py#L139-L145
def clean(self): """ Validates the topic instance. """ super().clean() if self.forum.is_category or self.forum.is_link: raise ValidationError( _('A topic can not be associated with a category or a link forum') )
[ "def", "clean", "(", "self", ")", ":", "super", "(", ")", ".", "clean", "(", ")", "if", "self", ".", "forum", ".", "is_category", "or", "self", ".", "forum", ".", "is_link", ":", "raise", "ValidationError", "(", "_", "(", "'A topic can not be associated ...
Validates the topic instance.
[ "Validates", "the", "topic", "instance", "." ]
python
train
38.428571
mattjj/pyhsmm
pyhsmm/util/plot.py
https://github.com/mattjj/pyhsmm/blob/a9a39c2bfd539048e35877cb13283552eadc24e2/pyhsmm/util/plot.py#L7-L34
def plot_gaussian_2D(mu, lmbda, color='b', centermarker=True,label='',alpha=1.,ax=None,artists=None): ''' Plots mean and cov ellipsoid into current axes. Must be 2D. lmbda is a covariance matrix. ''' assert len(mu) == 2 ax = ax if ax else plt.gca() # TODO use artists! t = np.hstack([np.ara...
[ "def", "plot_gaussian_2D", "(", "mu", ",", "lmbda", ",", "color", "=", "'b'", ",", "centermarker", "=", "True", ",", "label", "=", "''", ",", "alpha", "=", "1.", ",", "ax", "=", "None", ",", "artists", "=", "None", ")", ":", "assert", "len", "(", ...
Plots mean and cov ellipsoid into current axes. Must be 2D. lmbda is a covariance matrix.
[ "Plots", "mean", "and", "cov", "ellipsoid", "into", "current", "axes", ".", "Must", "be", "2D", ".", "lmbda", "is", "a", "covariance", "matrix", "." ]
python
train
35.857143
seb-m/pyinotify
python3/pyinotify.py
https://github.com/seb-m/pyinotify/blob/0f3f8950d12e4a6534320153eed1a90a778da4ae/python3/pyinotify.py#L1157-L1174
def coalesce_events(self, coalesce=True): """ Coalescing events. Events are usually processed by batchs, their size depend on various factors. Thus, before processing them, events received from inotify are aggregated in a fifo queue. If this coalescing option is enabled events ar...
[ "def", "coalesce_events", "(", "self", ",", "coalesce", "=", "True", ")", ":", "self", ".", "_coalesce", "=", "coalesce", "if", "not", "coalesce", ":", "self", ".", "_eventset", ".", "clear", "(", ")" ]
Coalescing events. Events are usually processed by batchs, their size depend on various factors. Thus, before processing them, events received from inotify are aggregated in a fifo queue. If this coalescing option is enabled events are filtered based on their unicity, only unique events ...
[ "Coalescing", "events", ".", "Events", "are", "usually", "processed", "by", "batchs", "their", "size", "depend", "on", "various", "factors", ".", "Thus", "before", "processing", "them", "events", "received", "from", "inotify", "are", "aggregated", "in", "a", "...
python
train
51.166667
SBRG/ssbio
ssbio/databases/bigg.py
https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/databases/bigg.py#L12-L50
def get_pdbs_for_gene(bigg_model, bigg_gene, cache_dir=tempfile.gettempdir(), force_rerun=False): """Attempt to get a rank-ordered list of available PDB structures for a BiGG Model and its gene. Args: bigg_model: BiGG Model ID bigg_gene: BiGG Gene ID Returns: list: rank-ordered lis...
[ "def", "get_pdbs_for_gene", "(", "bigg_model", ",", "bigg_gene", ",", "cache_dir", "=", "tempfile", ".", "gettempdir", "(", ")", ",", "force_rerun", "=", "False", ")", ":", "my_structures", "=", "[", "]", "# Download gene info", "gene", "=", "ssbio", ".", "u...
Attempt to get a rank-ordered list of available PDB structures for a BiGG Model and its gene. Args: bigg_model: BiGG Model ID bigg_gene: BiGG Gene ID Returns: list: rank-ordered list of tuples of (pdb_id, chain_id)
[ "Attempt", "to", "get", "a", "rank", "-", "ordered", "list", "of", "available", "PDB", "structures", "for", "a", "BiGG", "Model", "and", "its", "gene", "." ]
python
train
42.769231
scikit-hep/root_numpy
root_numpy/_hist.py
https://github.com/scikit-hep/root_numpy/blob/3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8/root_numpy/_hist.py#L22-L78
def fill_hist(hist, array, weights=None, return_indices=False): """Fill a ROOT histogram with a NumPy array. Parameters ---------- hist : ROOT TH1, TH2, or TH3 The ROOT histogram to fill. array : numpy array of shape [n_samples, n_dimensions] The values to fill the histogram with. T...
[ "def", "fill_hist", "(", "hist", ",", "array", ",", "weights", "=", "None", ",", "return_indices", "=", "False", ")", ":", "import", "ROOT", "array", "=", "np", ".", "asarray", "(", "array", ",", "dtype", "=", "np", ".", "double", ")", "if", "weights...
Fill a ROOT histogram with a NumPy array. Parameters ---------- hist : ROOT TH1, TH2, or TH3 The ROOT histogram to fill. array : numpy array of shape [n_samples, n_dimensions] The values to fill the histogram with. The number of columns must match the dimensionality of the histo...
[ "Fill", "a", "ROOT", "histogram", "with", "a", "NumPy", "array", "." ]
python
train
41.210526
arista-eosplus/pyeapi
pyeapi/client.py
https://github.com/arista-eosplus/pyeapi/blob/96a74faef1fe3bd79c4e900aed29c9956a0587d6/pyeapi/client.py#L513-L530
def _get_version_properties(self): """Parses version and model information out of 'show version' output and uses the output to populate class properties. """ # Parse out version info output = self.enable('show version') self._version = str(output[0]['result']['version']) ...
[ "def", "_get_version_properties", "(", "self", ")", ":", "# Parse out version info", "output", "=", "self", ".", "enable", "(", "'show version'", ")", "self", ".", "_version", "=", "str", "(", "output", "[", "0", "]", "[", "'result'", "]", "[", "'version'", ...
Parses version and model information out of 'show version' output and uses the output to populate class properties.
[ "Parses", "version", "and", "model", "information", "out", "of", "show", "version", "output", "and", "uses", "the", "output", "to", "populate", "class", "properties", "." ]
python
train
43.111111
geertj/pyskiplist
pyskiplist/skiplist.py
https://github.com/geertj/pyskiplist/blob/c5f94cf135d42bb277255150d3f570ed807468b2/pyskiplist/skiplist.py#L359-L369
def search(self, key, default=None): """Find the first key-value pair with key *key* and return its value. If the key was not found, return *default*. If no default was provided, return ``None``. This method never raises a ``KeyError``. """ self._find_lt(key) node = self...
[ "def", "search", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "self", ".", "_find_lt", "(", "key", ")", "node", "=", "self", ".", "_path", "[", "0", "]", "[", "2", "]", "if", "node", "is", "self", ".", "_tail", "or", "key", ...
Find the first key-value pair with key *key* and return its value. If the key was not found, return *default*. If no default was provided, return ``None``. This method never raises a ``KeyError``.
[ "Find", "the", "first", "key", "-", "value", "pair", "with", "key", "*", "key", "*", "and", "return", "its", "value", "." ]
python
train
38.181818
abourget/gevent-socketio
socketio/virtsocket.py
https://github.com/abourget/gevent-socketio/blob/1cdb1594a315326987a17ce0924ea448a82fab01/socketio/virtsocket.py#L213-L236
def kill(self, detach=False): """This function must/will be called when a socket is to be completely shut down, closed by connection timeout, connection error or explicit disconnection from the client. It will call all of the Namespace's :meth:`~socketio.namespace.BaseNamespace....
[ "def", "kill", "(", "self", ",", "detach", "=", "False", ")", ":", "# Clear out the callbacks", "self", ".", "ack_callbacks", "=", "{", "}", "if", "self", ".", "connected", ":", "self", ".", "state", "=", "self", ".", "STATE_DISCONNECTING", "self", ".", ...
This function must/will be called when a socket is to be completely shut down, closed by connection timeout, connection error or explicit disconnection from the client. It will call all of the Namespace's :meth:`~socketio.namespace.BaseNamespace.disconnect` methods so that you c...
[ "This", "function", "must", "/", "will", "be", "called", "when", "a", "socket", "is", "to", "be", "completely", "shut", "down", "closed", "by", "connection", "timeout", "connection", "error", "or", "explicit", "disconnection", "from", "the", "client", "." ]
python
valid
34.791667
saltstack/salt
salt/modules/freebsdpkg.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdpkg.py#L138-L184
def _match(names): ''' Since pkg_delete requires the full "pkgname-version" string, this function will attempt to match the package name with its version. Returns a list of partial matches and package names that match the "pkgname-version" string required by pkg_delete, and a list of errors encounte...
[ "def", "_match", "(", "names", ")", ":", "pkgs", "=", "list_pkgs", "(", "versions_as_list", "=", "True", ")", "errors", "=", "[", "]", "# Look for full matches", "full_pkg_strings", "=", "[", "]", "out", "=", "__salt__", "[", "'cmd.run_stdout'", "]", "(", ...
Since pkg_delete requires the full "pkgname-version" string, this function will attempt to match the package name with its version. Returns a list of partial matches and package names that match the "pkgname-version" string required by pkg_delete, and a list of errors encountered.
[ "Since", "pkg_delete", "requires", "the", "full", "pkgname", "-", "version", "string", "this", "function", "will", "attempt", "to", "match", "the", "package", "name", "with", "its", "version", ".", "Returns", "a", "list", "of", "partial", "matches", "and", "...
python
train
36.12766
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_interface_ext.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_interface_ext.py#L1024-L1040
def get_interface_detail_output_interface_configured_line_speed(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_interface_detail = ET.Element("get_interface_detail") config = get_interface_detail output = ET.SubElement(get_interface_detail, "...
[ "def", "get_interface_detail_output_interface_configured_line_speed", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_interface_detail", "=", "ET", ".", "Element", "(", "\"get_interface_detail\"", ")"...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
51.941176
neighbordog/deviantart
deviantart/api.py
https://github.com/neighbordog/deviantart/blob/5612f1d5e2139a48c9d793d7fd19cde7e162d7b1/deviantart/api.py#L1574-L1586
def get_note(self, noteid): """Fetch a single note :param folderid: The UUID of the note """ if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpo...
[ "def", "get_note", "(", "self", ",", "noteid", ")", ":", "if", "self", ".", "standard_grant_type", "is", "not", "\"authorization_code\"", ":", "raise", "DeviantartError", "(", "\"Authentication through Authorization Code (Grant Type) is required in order to connect to this endp...
Fetch a single note :param folderid: The UUID of the note
[ "Fetch", "a", "single", "note" ]
python
train
30.538462
limpyd/redis-limpyd-extensions
limpyd_extensions/dynamic/related.py
https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/related.py#L67-L73
def get_name_for(self, dynamic_part): """ Return the name for the current dynamic field, accepting a limpyd instance for the dynamic part """ dynamic_part = self.from_python(dynamic_part) return super(DynamicRelatedFieldMixin, self).get_name_for(dynamic_part)
[ "def", "get_name_for", "(", "self", ",", "dynamic_part", ")", ":", "dynamic_part", "=", "self", ".", "from_python", "(", "dynamic_part", ")", "return", "super", "(", "DynamicRelatedFieldMixin", ",", "self", ")", ".", "get_name_for", "(", "dynamic_part", ")" ]
Return the name for the current dynamic field, accepting a limpyd instance for the dynamic part
[ "Return", "the", "name", "for", "the", "current", "dynamic", "field", "accepting", "a", "limpyd", "instance", "for", "the", "dynamic", "part" ]
python
train
43
edx/edx-oauth2-provider
edx_oauth2_provider/oidc/core.py
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/oidc/core.py#L39-L56
def encode(self, secret, algorithm='HS256'): """ Encode the set of claims to the JWT (JSON Web Token) format according to the OpenID Connect specification: http://openid.net/specs/openid-connect-basic-1_0.html#IDToken Arguments: claims (dict): A dictionary with the ...
[ "def", "encode", "(", "self", ",", "secret", ",", "algorithm", "=", "'HS256'", ")", ":", "return", "jwt", ".", "encode", "(", "self", ".", "claims", ",", "secret", ",", "algorithm", ")" ]
Encode the set of claims to the JWT (JSON Web Token) format according to the OpenID Connect specification: http://openid.net/specs/openid-connect-basic-1_0.html#IDToken Arguments: claims (dict): A dictionary with the OpenID Connect claims. secret (str): Secret used to e...
[ "Encode", "the", "set", "of", "claims", "to", "the", "JWT", "(", "JSON", "Web", "Token", ")", "format", "according", "to", "the", "OpenID", "Connect", "specification", ":" ]
python
train
33.055556
matthewdeanmartin/jiggle_version
jiggle_version/find_version_class.py
https://github.com/matthewdeanmartin/jiggle_version/blob/963656a0a47b7162780a5f6c8f4b8bbbebc148f5/jiggle_version/find_version_class.py#L499-L524
def execute_setup(self): # type: () -> Dict[str,str] """ for really surprising things like a dict foo in setup(**foo) consider python3 setup.py --version :return: """ ver = execute_get_text("python setup.py --version") if not ver: return None ...
[ "def", "execute_setup", "(", "self", ")", ":", "# type: () -> Dict[str,str]", "ver", "=", "execute_get_text", "(", "\"python setup.py --version\"", ")", "if", "not", "ver", ":", "return", "None", "if", "\"UserWarning\"", "in", "ver", ":", "logger", ".", "warning",...
for really surprising things like a dict foo in setup(**foo) consider python3 setup.py --version :return:
[ "for", "really", "surprising", "things", "like", "a", "dict", "foo", "in", "setup", "(", "**", "foo", ")", "consider", "python3", "setup", ".", "py", "--", "version", ":", "return", ":" ]
python
train
29.846154
maweigert/gputools
gputools/convolve/convolve.py
https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/convolve/convolve.py#L68-L113
def _convolve_buf(data_g, h_g, res_g=None): """ buffer variant """ assert_bufs_type(np.float32, data_g, h_g) prog = OCLProgram(abspath("kernels/convolve.cl")) if res_g is None: res_g = OCLArray.empty(data_g.shape, dtype=np.float32) Nhs = [np.int32(n) for n in h_g.shape] kerne...
[ "def", "_convolve_buf", "(", "data_g", ",", "h_g", ",", "res_g", "=", "None", ")", ":", "assert_bufs_type", "(", "np", ".", "float32", ",", "data_g", ",", "h_g", ")", "prog", "=", "OCLProgram", "(", "abspath", "(", "\"kernels/convolve.cl\"", ")", ")", "i...
buffer variant
[ "buffer", "variant" ]
python
train
29.369565
payu-org/payu
payu/calendar.py
https://github.com/payu-org/payu/blob/1442a9a226012eff248b8097cc1eaabc3e224867/payu/calendar.py#L79-L88
def calculate_leapdays(init_date, final_date): """Currently unsupported, it only works for differences in years.""" leap_days = (final_date.year - 1) // 4 - (init_date.year - 1) // 4 leap_days -= (final_date.year - 1) // 100 - (init_date.year - 1) // 100 leap_days += (final_date.year - 1) // 400 - (ini...
[ "def", "calculate_leapdays", "(", "init_date", ",", "final_date", ")", ":", "leap_days", "=", "(", "final_date", ".", "year", "-", "1", ")", "//", "4", "-", "(", "init_date", ".", "year", "-", "1", ")", "//", "4", "leap_days", "-=", "(", "final_date", ...
Currently unsupported, it only works for differences in years.
[ "Currently", "unsupported", "it", "only", "works", "for", "differences", "in", "years", "." ]
python
train
45.6
Alir3z4/django-databrowse
django_databrowse/sites.py
https://github.com/Alir3z4/django-databrowse/blob/4469495cd47a0da506ddf4e8cc752c2f453e0339/django_databrowse/sites.py#L138-L148
def unregister(self, *model_list): """ Unregisters the given model(s). If a model isn't already registered, this will raise NotRegistered. """ for model in model_list: if model not in self.registry: raise NotRegistered('The model %s is not registered'...
[ "def", "unregister", "(", "self", ",", "*", "model_list", ")", ":", "for", "model", "in", "model_list", ":", "if", "model", "not", "in", "self", ".", "registry", ":", "raise", "NotRegistered", "(", "'The model %s is not registered'", "%", "model", ".", "__na...
Unregisters the given model(s). If a model isn't already registered, this will raise NotRegistered.
[ "Unregisters", "the", "given", "model", "(", "s", ")", "." ]
python
train
36.454545
MechanicalSoup/MechanicalSoup
mechanicalsoup/stateful_browser.py
https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/stateful_browser.py#L156-L175
def refresh(self): """Reload the current page with the same request as originally done. Any change (`select_form`, or any value filled-in in the form) made to the current page before refresh is discarded. :raise ValueError: Raised if no refreshable page is loaded, e.g., when ...
[ "def", "refresh", "(", "self", ")", ":", "old_request", "=", "self", ".", "__state", ".", "request", "if", "old_request", "is", "None", ":", "raise", "ValueError", "(", "'The current page is not refreshable. Either no '", "'page is opened or low-level browser methods '", ...
Reload the current page with the same request as originally done. Any change (`select_form`, or any value filled-in in the form) made to the current page before refresh is discarded. :raise ValueError: Raised if no refreshable page is loaded, e.g., when using the shallow ``Browser``...
[ "Reload", "the", "current", "page", "with", "the", "same", "request", "as", "originally", "done", ".", "Any", "change", "(", "select_form", "or", "any", "value", "filled", "-", "in", "in", "the", "form", ")", "made", "to", "the", "current", "page", "befo...
python
train
45.95
NICTA/revrand
revrand/basis_functions.py
https://github.com/NICTA/revrand/blob/4c1881b6c1772d2b988518e49dde954f165acfb6/revrand/basis_functions.py#L70-L93
def slice_init(func): """ Decorator for adding partial application functionality to a basis object. This will add an "apply_ind" argument to a basis object initialiser that can be used to apply the basis function to only the dimensions specified in apply_ind. E.g., >>> X = np.ones((100, 20)) ...
[ "def", "slice_init", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "new_init", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "apply_ind", "=", "kwargs", ".", "pop", "(", "'apply_ind'", ",", "None", ")", "if", "...
Decorator for adding partial application functionality to a basis object. This will add an "apply_ind" argument to a basis object initialiser that can be used to apply the basis function to only the dimensions specified in apply_ind. E.g., >>> X = np.ones((100, 20)) >>> base = LinearBasis(onescol=...
[ "Decorator", "for", "adding", "partial", "application", "functionality", "to", "a", "basis", "object", "." ]
python
train
28.666667
materialsproject/pymatgen
pymatgen/analysis/phase_diagram.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/phase_diagram.py#L1318-L1376
def pd_plot_data(self): """ Plot data for phase diagram. 2-comp - Full hull with energies 3/4-comp - Projection into 2D or 3D Gibbs triangle. Returns: (lines, stable_entries, unstable_entries): - lines is a list of list of coordinates for lines in the PD....
[ "def", "pd_plot_data", "(", "self", ")", ":", "pd", "=", "self", ".", "_pd", "entries", "=", "pd", ".", "qhull_entries", "data", "=", "np", ".", "array", "(", "pd", ".", "qhull_data", ")", "lines", "=", "[", "]", "stable_entries", "=", "{", "}", "f...
Plot data for phase diagram. 2-comp - Full hull with energies 3/4-comp - Projection into 2D or 3D Gibbs triangle. Returns: (lines, stable_entries, unstable_entries): - lines is a list of list of coordinates for lines in the PD. - stable_entries is a {coordina...
[ "Plot", "data", "for", "phase", "diagram", ".", "2", "-", "comp", "-", "Full", "hull", "with", "energies", "3", "/", "4", "-", "comp", "-", "Projection", "into", "2D", "or", "3D", "Gibbs", "triangle", "." ]
python
train
40.423729
druids/django-chamber
chamber/models/__init__.py
https://github.com/druids/django-chamber/blob/eef4169923557e96877a664fa254e8c0814f3f23/chamber/models/__init__.py#L70-L79
def model_to_dict(instance, fields=None, exclude=None): """ The same implementation as django model_to_dict but editable fields are allowed """ return { field.name: field_to_dict(field, instance) for field in chain(instance._meta.concrete_fields, instance._meta.many_to_many) # pylint: ...
[ "def", "model_to_dict", "(", "instance", ",", "fields", "=", "None", ",", "exclude", "=", "None", ")", ":", "return", "{", "field", ".", "name", ":", "field_to_dict", "(", "field", ",", "instance", ")", "for", "field", "in", "chain", "(", "instance", "...
The same implementation as django model_to_dict but editable fields are allowed
[ "The", "same", "implementation", "as", "django", "model_to_dict", "but", "editable", "fields", "are", "allowed" ]
python
train
39
chimpler/pyhocon
pyhocon/config_parser.py
https://github.com/chimpler/pyhocon/blob/e5b22a8e74e8f88e43cf9e9140cca5f2cd0ab4a3/pyhocon/config_parser.py#L135-L150
def parse_string(cls, content, basedir=None, resolve=True, unresolved_value=DEFAULT_SUBSTITUTION): """Parse URL :param content: content to parse :type content: basestring :param resolve: If true, resolve substitutions :param resolve: if true, resolve substitutions :type ...
[ "def", "parse_string", "(", "cls", ",", "content", ",", "basedir", "=", "None", ",", "resolve", "=", "True", ",", "unresolved_value", "=", "DEFAULT_SUBSTITUTION", ")", ":", "return", "ConfigParser", "(", ")", ".", "parse", "(", "content", ",", "basedir", "...
Parse URL :param content: content to parse :type content: basestring :param resolve: If true, resolve substitutions :param resolve: if true, resolve substitutions :type resolve: boolean :param unresolved_value: assigned value value to unresolved substitution. If ...
[ "Parse", "URL" ]
python
train
51.5625
agile-geoscience/welly
welly/curve.py
https://github.com/agile-geoscience/welly/blob/ed4c991011d6290938fef365553041026ba29f42/welly/curve.py#L253-L259
def get_alias(self, alias): """ Given a mnemonic, get the alias name(s) it falls under. If there aren't any, you get an empty list. """ alias = alias or {} return [k for k, v in alias.items() if self.mnemonic in v]
[ "def", "get_alias", "(", "self", ",", "alias", ")", ":", "alias", "=", "alias", "or", "{", "}", "return", "[", "k", "for", "k", ",", "v", "in", "alias", ".", "items", "(", ")", "if", "self", ".", "mnemonic", "in", "v", "]" ]
Given a mnemonic, get the alias name(s) it falls under. If there aren't any, you get an empty list.
[ "Given", "a", "mnemonic", "get", "the", "alias", "name", "(", "s", ")", "it", "falls", "under", ".", "If", "there", "aren", "t", "any", "you", "get", "an", "empty", "list", "." ]
python
train
36.571429
python-xlib/python-xlib
Xlib/ext/randr.py
https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/ext/randr.py#L267-L282
def set_screen_config(self, size_id, rotation, config_timestamp, rate=0, timestamp=X.CurrentTime): """Sets the screen to the specified size, rate, rotation and reflection. rate can be 0 to have the server select an appropriate rate. """ return SetScreenConfig( display=self.display, opc...
[ "def", "set_screen_config", "(", "self", ",", "size_id", ",", "rotation", ",", "config_timestamp", ",", "rate", "=", "0", ",", "timestamp", "=", "X", ".", "CurrentTime", ")", ":", "return", "SetScreenConfig", "(", "display", "=", "self", ".", "display", ",...
Sets the screen to the specified size, rate, rotation and reflection. rate can be 0 to have the server select an appropriate rate.
[ "Sets", "the", "screen", "to", "the", "specified", "size", "rate", "rotation", "and", "reflection", "." ]
python
train
32.9375
romanvm/python-web-pdb
web_pdb/wsgi_app.py
https://github.com/romanvm/python-web-pdb/blob/f2df2207e870dbf50a4bb30ca12a59cab39a809f/web_pdb/wsgi_app.py#L49-L67
def compress(func): """ Compress route return data with gzip compression """ @wraps(func) def wrapper(*args, **kwargs): result = func(*args, **kwargs) if ('gzip' in bottle.request.headers.get('Accept-Encoding', '') and isinstance(result, string_type) and ...
[ "def", "compress", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "result", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "(", "'gzip'", "in", ...
Compress route return data with gzip compression
[ "Compress", "route", "return", "data", "with", "gzip", "compression" ]
python
train
37
tanghaibao/jcvi
jcvi/utils/brewer2mpl.py
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/utils/brewer2mpl.py#L240-L297
def get_map(name, map_type, number, reverse=False): """ Return a `BrewerMap` representation of the specified color map. Parameters ---------- name : str Name of color map. Use `print_maps` to see available color maps. map_type : {'Sequential', 'Diverging', 'Qualitative'} Select ...
[ "def", "get_map", "(", "name", ",", "map_type", ",", "number", ",", "reverse", "=", "False", ")", ":", "number", "=", "str", "(", "number", ")", "map_type", "=", "map_type", ".", "lower", "(", ")", ".", "capitalize", "(", ")", "# check for valid type", ...
Return a `BrewerMap` representation of the specified color map. Parameters ---------- name : str Name of color map. Use `print_maps` to see available color maps. map_type : {'Sequential', 'Diverging', 'Qualitative'} Select color map type. number : int Number of defined color...
[ "Return", "a", "BrewerMap", "representation", "of", "the", "specified", "color", "map", "." ]
python
train
34.086207
inveniosoftware/invenio-search
invenio_search/cli.py
https://github.com/inveniosoftware/invenio-search/blob/19c073d608d4c811f1c5aecb6622402d39715228/invenio_search/cli.py#L91-L98
def destroy(force): """Destroy all indexes.""" click.secho('Destroying indexes...', fg='red', bold=True, file=sys.stderr) with click.progressbar( current_search.delete(ignore=[400, 404] if force else None), length=current_search.number_of_indexes) as bar: for name, response i...
[ "def", "destroy", "(", "force", ")", ":", "click", ".", "secho", "(", "'Destroying indexes...'", ",", "fg", "=", "'red'", ",", "bold", "=", "True", ",", "file", "=", "sys", ".", "stderr", ")", "with", "click", ".", "progressbar", "(", "current_search", ...
Destroy all indexes.
[ "Destroy", "all", "indexes", "." ]
python
train
43.5
sassoo/goldman
goldman/deserializers/comma_sep.py
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/deserializers/comma_sep.py#L95-L132
def deserialize(self, data=None): """ Invoke the deserializer If the payload is a collection (more than 1 records) then a list will be returned of normalized dict's. If the payload is a single item then the normalized dict will be returned (not a list) :return: list or...
[ "def", "deserialize", "(", "self", ",", "data", "=", "None", ")", ":", "data", "=", "[", "]", "if", "self", ".", "req", ".", "content_type_params", ".", "get", "(", "'header'", ")", "!=", "'present'", ":", "abort", "(", "exceptions", ".", "InvalidReque...
Invoke the deserializer If the payload is a collection (more than 1 records) then a list will be returned of normalized dict's. If the payload is a single item then the normalized dict will be returned (not a list) :return: list or dict
[ "Invoke", "the", "deserializer" ]
python
train
30.894737
hyperledger/sawtooth-core
cli/sawtooth_cli/network_command/compare.py
https://github.com/hyperledger/sawtooth-core/blob/8cf473bc2207e51f02bd182d825158a57d72b098/cli/sawtooth_cli/network_command/compare.py#L491-L500
def print_split(column_to_split, total_columns): """Print a row that splits the given column into two columns while shifting all the following columns.""" out = "" for _ in range(column_to_split): out += "| " out += "|\\" for _ in range(column_to_split + 1, total_columns): out +=...
[ "def", "print_split", "(", "column_to_split", ",", "total_columns", ")", ":", "out", "=", "\"\"", "for", "_", "in", "range", "(", "column_to_split", ")", ":", "out", "+=", "\"| \"", "out", "+=", "\"|\\\\\"", "for", "_", "in", "range", "(", "column_to_split...
Print a row that splits the given column into two columns while shifting all the following columns.
[ "Print", "a", "row", "that", "splits", "the", "given", "column", "into", "two", "columns", "while", "shifting", "all", "the", "following", "columns", "." ]
python
train
33.2
Lucretiel/autocommand
src/autocommand/autoasync.py
https://github.com/Lucretiel/autocommand/blob/bd3c58a210fdfcc943c729cc5579033add68d0b3/src/autocommand/autoasync.py#L23-L51
def _launch_forever_coro(coro, args, kwargs, loop): ''' This helper function launches an async main function that was tagged with forever=True. There are two possibilities: - The function is a normal function, which handles initializing the event loop, which is then run forever - The function...
[ "def", "_launch_forever_coro", "(", "coro", ",", "args", ",", "kwargs", ",", "loop", ")", ":", "# Personal note: I consider this an antipattern, as it relies on the use of", "# unowned resources. The setup function dumps some stuff into the event", "# loop where it just whirls in the eth...
This helper function launches an async main function that was tagged with forever=True. There are two possibilities: - The function is a normal function, which handles initializing the event loop, which is then run forever - The function is a coroutine, which needs to be scheduled in the event ...
[ "This", "helper", "function", "launches", "an", "async", "main", "function", "that", "was", "tagged", "with", "forever", "=", "True", ".", "There", "are", "two", "possibilities", ":" ]
python
train
46.724138
UCSBarchlab/PyRTL
pyrtl/compilesim.py
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/compilesim.py#L110-L122
def inspect(self, w): """Get the latest value of the wire given, if possible.""" if isinstance(w, WireVector): w = w.name try: vals = self.tracer.trace[w] except KeyError: pass else: if not vals: raise PyrtlError('No...
[ "def", "inspect", "(", "self", ",", "w", ")", ":", "if", "isinstance", "(", "w", ",", "WireVector", ")", ":", "w", "=", "w", ".", "name", "try", ":", "vals", "=", "self", ".", "tracer", ".", "trace", "[", "w", "]", "except", "KeyError", ":", "p...
Get the latest value of the wire given, if possible.
[ "Get", "the", "latest", "value", "of", "the", "wire", "given", "if", "possible", "." ]
python
train
37.076923
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/ext/_bundled/png.py
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/png.py#L1474-L1502
def iterboxed(self, rows): """Iterator that yields each scanline in boxed row flat pixel format. `rows` should be an iterator that yields the bytes of each row in turn. """ def asvalues(raw): """Convert a row of raw bytes into a flat row. Result will be...
[ "def", "iterboxed", "(", "self", ",", "rows", ")", ":", "def", "asvalues", "(", "raw", ")", ":", "\"\"\"Convert a row of raw bytes into a flat row. Result will\n be a freshly allocated object, not shared with\n argument.\n \"\"\"", "if", "self", "....
Iterator that yields each scanline in boxed row flat pixel format. `rows` should be an iterator that yields the bytes of each row in turn.
[ "Iterator", "that", "yields", "each", "scanline", "in", "boxed", "row", "flat", "pixel", "format", ".", "rows", "should", "be", "an", "iterator", "that", "yields", "the", "bytes", "of", "each", "row", "in", "turn", "." ]
python
train
35.482759
readbeyond/aeneas
aeneas/globalfunctions.py
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L333-L348
def norm_join(prefix, suffix): """ Join ``prefix`` and ``suffix`` paths and return the resulting path, normalized. :param string prefix: the prefix path :param string suffix: the suffix path :rtype: string """ if (prefix is None) and (suffix is None): return "." if prefix is...
[ "def", "norm_join", "(", "prefix", ",", "suffix", ")", ":", "if", "(", "prefix", "is", "None", ")", "and", "(", "suffix", "is", "None", ")", ":", "return", "\".\"", "if", "prefix", "is", "None", ":", "return", "os", ".", "path", ".", "normpath", "(...
Join ``prefix`` and ``suffix`` paths and return the resulting path, normalized. :param string prefix: the prefix path :param string suffix: the suffix path :rtype: string
[ "Join", "prefix", "and", "suffix", "paths", "and", "return", "the", "resulting", "path", "normalized", "." ]
python
train
29.5
IAMconsortium/pyam
pyam/plotting.py
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/plotting.py#L158-L169
def reshape_line_plot(df, x, y): """Reshape data from long form to "line plot form". Line plot form has x value as the index with one column for each line. Each column has data points as values and all metadata as column headers. """ idx = list(df.columns.drop(y)) if df.duplicated(idx).any(): ...
[ "def", "reshape_line_plot", "(", "df", ",", "x", ",", "y", ")", ":", "idx", "=", "list", "(", "df", ".", "columns", ".", "drop", "(", "y", ")", ")", "if", "df", ".", "duplicated", "(", "idx", ")", ".", "any", "(", ")", ":", "warnings", ".", "...
Reshape data from long form to "line plot form". Line plot form has x value as the index with one column for each line. Each column has data points as values and all metadata as column headers.
[ "Reshape", "data", "from", "long", "form", "to", "line", "plot", "form", "." ]
python
train
38.583333
tensorflow/mesh
mesh_tensorflow/ops.py
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4192-L4213
def _expand_dims(x, input_shape, output_shape): """Expand dimensions and transpose if necessary. Args: x: a tf.Tensor input_shape: a Shape output_shape: a Shape whose dimensions are a superset of those in input_shape Returns: a tf.Tensor """ verify_no_new_dims([output_shape], input_sha...
[ "def", "_expand_dims", "(", "x", ",", "input_shape", ",", "output_shape", ")", ":", "verify_no_new_dims", "(", "[", "output_shape", "]", ",", "input_shape", ")", "if", "input_shape", "==", "output_shape", "or", "input_shape", ".", "ndims", "==", "0", ":", "r...
Expand dimensions and transpose if necessary. Args: x: a tf.Tensor input_shape: a Shape output_shape: a Shape whose dimensions are a superset of those in input_shape Returns: a tf.Tensor
[ "Expand", "dimensions", "and", "transpose", "if", "necessary", "." ]
python
train
28.272727
pybel/pybel
src/pybel/manager/citation_utils.py
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/citation_utils.py#L84-L97
def get_pubmed_citation_response(pubmed_identifiers: Iterable[str]): """Get the response from PubMed E-Utils for a given list of PubMed identifiers. :param pubmed_identifiers: :rtype: dict """ pubmed_identifiers = list(pubmed_identifiers) url = EUTILS_URL_FMT.format(','.join( pubmed_ide...
[ "def", "get_pubmed_citation_response", "(", "pubmed_identifiers", ":", "Iterable", "[", "str", "]", ")", ":", "pubmed_identifiers", "=", "list", "(", "pubmed_identifiers", ")", "url", "=", "EUTILS_URL_FMT", ".", "format", "(", "','", ".", "join", "(", "pubmed_id...
Get the response from PubMed E-Utils for a given list of PubMed identifiers. :param pubmed_identifiers: :rtype: dict
[ "Get", "the", "response", "from", "PubMed", "E", "-", "Utils", "for", "a", "given", "list", "of", "PubMed", "identifiers", "." ]
python
train
33
sawcordwell/pymdptoolbox
src/experimental/mdpsql.py
https://github.com/sawcordwell/pymdptoolbox/blob/7c96789cc80e280437005c12065cf70266c11636/src/experimental/mdpsql.py#L268-L276
def getPolicyValue(self): """Get the policy and value vectors.""" self._cur.execute("SELECT action FROM policy") r = self._cur.fetchall() policy = [x[0] for x in r] self._cur.execute("SELECT value FROM V") r = self._cur.fetchall() value = [x[0] for x in r] ...
[ "def", "getPolicyValue", "(", "self", ")", ":", "self", ".", "_cur", ".", "execute", "(", "\"SELECT action FROM policy\"", ")", "r", "=", "self", ".", "_cur", ".", "fetchall", "(", ")", "policy", "=", "[", "x", "[", "0", "]", "for", "x", "in", "r", ...
Get the policy and value vectors.
[ "Get", "the", "policy", "and", "value", "vectors", "." ]
python
train
37
xu2243051/easyui-menu
easyui/views.py
https://github.com/xu2243051/easyui-menu/blob/4da0b50cf2d3ddb0f1ec7a4da65fd3c4339f8dfb/easyui/views.py#L156-L177
def get_menu_checked(self, request): """ 获取用户或者用户组checked的菜单列表 usermenu_form.html 中定义 usermenu 这两个model的定义类似,比如menus_checked和menus_show groupmenu @return eg. ['1', '8', '9', '10' ] 获取用户或者用户组的check_ids,会给出app_label, model_name, pk eg. /easyui/menulistview/?app_la...
[ "def", "get_menu_checked", "(", "self", ",", "request", ")", ":", "checked_id", "=", "[", "]", "qd", "=", "request", ".", "GET", "query_dict", "=", "dict", "(", "qd", ".", "items", "(", ")", ")", "if", "query_dict", ":", "#object = get_object(**query_dict)...
获取用户或者用户组checked的菜单列表 usermenu_form.html 中定义 usermenu 这两个model的定义类似,比如menus_checked和menus_show groupmenu @return eg. ['1', '8', '9', '10' ] 获取用户或者用户组的check_ids,会给出app_label, model_name, pk eg. /easyui/menulistview/?app_label=easyui&model_name=UserMenu&pk=1
[ "获取用户或者用户组checked的菜单列表", "usermenu_form", ".", "html", "中定义", "usermenu", "这两个model的定义类似,比如menus_checked和menus_show", "groupmenu" ]
python
valid
37.227273
keras-rl/keras-rl
rl/callbacks.py
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L97-L101
def on_action_end(self, action, logs={}): """ Called at end of each action for each callback in callbackList""" for callback in self.callbacks: if callable(getattr(callback, 'on_action_end', None)): callback.on_action_end(action, logs=logs)
[ "def", "on_action_end", "(", "self", ",", "action", ",", "logs", "=", "{", "}", ")", ":", "for", "callback", "in", "self", ".", "callbacks", ":", "if", "callable", "(", "getattr", "(", "callback", ",", "'on_action_end'", ",", "None", ")", ")", ":", "...
Called at end of each action for each callback in callbackList
[ "Called", "at", "end", "of", "each", "action", "for", "each", "callback", "in", "callbackList" ]
python
train
56
SiLab-Bonn/basil
basil/utils/sim/SiLibUsb.py
https://github.com/SiLab-Bonn/basil/blob/99052482d9334dd1f5598eb2d2fb4d5399a32291/basil/utils/sim/SiLibUsb.py#L56-L61
def DownloadXilinx(self, bitfile): """We hijack this call to perform the socket connect""" self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._sock.connect((self.simulation_host, self.simulation_port)) self._iface = PickleInterface(self._sock) return True
[ "def", "DownloadXilinx", "(", "self", ",", "bitfile", ")", ":", "self", ".", "_sock", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "self", ".", "_sock", ".", "connect", "(", "(", "self", ".", "s...
We hijack this call to perform the socket connect
[ "We", "hijack", "this", "call", "to", "perform", "the", "socket", "connect" ]
python
train
51.166667
hobson/aima
aima/mdp.py
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/mdp.py#L118-L131
def policy_iteration(mdp): "Solve an MDP by policy iteration [Fig. 17.7]" U = dict([(s, 0) for s in mdp.states]) pi = dict([(s, random.choice(mdp.actions(s))) for s in mdp.states]) while True: U = policy_evaluation(pi, U, mdp) unchanged = True for s in mdp.states: a =...
[ "def", "policy_iteration", "(", "mdp", ")", ":", "U", "=", "dict", "(", "[", "(", "s", ",", "0", ")", "for", "s", "in", "mdp", ".", "states", "]", ")", "pi", "=", "dict", "(", "[", "(", "s", ",", "random", ".", "choice", "(", "mdp", ".", "a...
Solve an MDP by policy iteration [Fig. 17.7]
[ "Solve", "an", "MDP", "by", "policy", "iteration", "[", "Fig", ".", "17", ".", "7", "]" ]
python
valid
35.714286
aio-libs/aiohttp_admin
aiohttp_admin/admin.py
https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/admin.py#L105-L116
async def index_page(self, request): """ Return index page with initial state for admin """ context = {"initial_state": self.schema.to_json()} return render_template( self.template, request, context, app_key=TEMPLATE_APP_KEY, ...
[ "async", "def", "index_page", "(", "self", ",", "request", ")", ":", "context", "=", "{", "\"initial_state\"", ":", "self", ".", "schema", ".", "to_json", "(", ")", "}", "return", "render_template", "(", "self", ".", "template", ",", "request", ",", "con...
Return index page with initial state for admin
[ "Return", "index", "page", "with", "initial", "state", "for", "admin" ]
python
train
26.083333
apache/airflow
airflow/hooks/presto_hook.py
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/hooks/presto_hook.py#L80-L88
def get_records(self, hql, parameters=None): """ Get a set of records from Presto """ try: return super().get_records( self._strip_sql(hql), parameters) except DatabaseError as e: raise PrestoException(self._get_pretty_exception_message(e))
[ "def", "get_records", "(", "self", ",", "hql", ",", "parameters", "=", "None", ")", ":", "try", ":", "return", "super", "(", ")", ".", "get_records", "(", "self", ".", "_strip_sql", "(", "hql", ")", ",", "parameters", ")", "except", "DatabaseError", "a...
Get a set of records from Presto
[ "Get", "a", "set", "of", "records", "from", "Presto" ]
python
test
34.666667
napalm-automation/napalm-logs
napalm_logs/base.py
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/base.py#L179-L185
def _setup_log(self): ''' Setup the log object. ''' logging_level = CONFIG.LOGGING_LEVEL.get(self.log_level.lower()) logging.basicConfig(format=self.log_format, level=logging_level)
[ "def", "_setup_log", "(", "self", ")", ":", "logging_level", "=", "CONFIG", ".", "LOGGING_LEVEL", ".", "get", "(", "self", ".", "log_level", ".", "lower", "(", ")", ")", "logging", ".", "basicConfig", "(", "format", "=", "self", ".", "log_format", ",", ...
Setup the log object.
[ "Setup", "the", "log", "object", "." ]
python
train
34.714286
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Script/SConscript.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Script/SConscript.py#L462-L477
def EnsureSConsVersion(self, major, minor, revision=0): """Exit abnormally if the SCons version is not late enough.""" # split string to avoid replacement during build process if SCons.__version__ == '__' + 'VERSION__': SCons.Warnings.warn(SCons.Warnings.DevelopmentVersionWarning, ...
[ "def", "EnsureSConsVersion", "(", "self", ",", "major", ",", "minor", ",", "revision", "=", "0", ")", ":", "# split string to avoid replacement during build process", "if", "SCons", ".", "__version__", "==", "'__'", "+", "'VERSION__'", ":", "SCons", ".", "Warnings...
Exit abnormally if the SCons version is not late enough.
[ "Exit", "abnormally", "if", "the", "SCons", "version", "is", "not", "late", "enough", "." ]
python
train
52.875
libtcod/python-tcod
tcod/libtcodpy.py
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1878-L1882
def console_load_asc(con: tcod.console.Console, filename: str) -> bool: """Update a console from a non-delimited ASCII `.asc` file.""" return bool( lib.TCOD_console_load_asc(_console(con), filename.encode("utf-8")) )
[ "def", "console_load_asc", "(", "con", ":", "tcod", ".", "console", ".", "Console", ",", "filename", ":", "str", ")", "->", "bool", ":", "return", "bool", "(", "lib", ".", "TCOD_console_load_asc", "(", "_console", "(", "con", ")", ",", "filename", ".", ...
Update a console from a non-delimited ASCII `.asc` file.
[ "Update", "a", "console", "from", "a", "non", "-", "delimited", "ASCII", ".", "asc", "file", "." ]
python
train
46.4
pybel/pybel
src/pybel/struct/filters/node_selection.py
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/filters/node_selection.py#L24-L26
def get_nodes_by_namespace(graph: BELGraph, namespaces: Strings) -> Set[BaseEntity]: """Get all nodes identified by the given namespace(s).""" return get_nodes(graph, namespace_inclusion_builder(namespaces))
[ "def", "get_nodes_by_namespace", "(", "graph", ":", "BELGraph", ",", "namespaces", ":", "Strings", ")", "->", "Set", "[", "BaseEntity", "]", ":", "return", "get_nodes", "(", "graph", ",", "namespace_inclusion_builder", "(", "namespaces", ")", ")" ]
Get all nodes identified by the given namespace(s).
[ "Get", "all", "nodes", "identified", "by", "the", "given", "namespace", "(", "s", ")", "." ]
python
train
71
apache/incubator-superset
superset/views/core.py
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/core.py#L2901-L2908
def slice_query(self, slice_id): """ This method exposes an API endpoint to get the database query string for this slice """ viz_obj = get_viz(slice_id) security_manager.assert_datasource_permission(viz_obj.datasource) return self.get_query_string_response(viz_obj...
[ "def", "slice_query", "(", "self", ",", "slice_id", ")", ":", "viz_obj", "=", "get_viz", "(", "slice_id", ")", "security_manager", ".", "assert_datasource_permission", "(", "viz_obj", ".", "datasource", ")", "return", "self", ".", "get_query_string_response", "(",...
This method exposes an API endpoint to get the database query string for this slice
[ "This", "method", "exposes", "an", "API", "endpoint", "to", "get", "the", "database", "query", "string", "for", "this", "slice" ]
python
train
39.25
Qiskit/qiskit-terra
qiskit/result/postprocess.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/result/postprocess.py#L107-L125
def format_level_1_memory(memory): """ Format an experiment result memory object for measurement level 1. Args: memory (list): Memory from experiment with `meas_level==1`. `avg` or `single` will be inferred from shape of result memory. Returns: np.ndarray: Measurement level 1 c...
[ "def", "format_level_1_memory", "(", "memory", ")", ":", "formatted_memory", "=", "_list_to_complex_array", "(", "memory", ")", "# infer meas_return from shape of returned data.", "if", "not", "1", "<=", "len", "(", "formatted_memory", ".", "shape", ")", "<=", "2", ...
Format an experiment result memory object for measurement level 1. Args: memory (list): Memory from experiment with `meas_level==1`. `avg` or `single` will be inferred from shape of result memory. Returns: np.ndarray: Measurement level 1 complex numpy array Raises: Qis...
[ "Format", "an", "experiment", "result", "memory", "object", "for", "measurement", "level", "1", "." ]
python
test
37.052632
hubo1016/namedstruct
namedstruct/namedstruct.py
https://github.com/hubo1016/namedstruct/blob/5039026e0df4ce23003d212358918dbe1a6e1d76/namedstruct/namedstruct.py#L1316-L1323
def new(self, inlineparent = None): ''' Compatible to Parser.new() ''' v = list(range(0, self.size)) for i in range(0, self.size): v[i] = self.innerparser.new() return v
[ "def", "new", "(", "self", ",", "inlineparent", "=", "None", ")", ":", "v", "=", "list", "(", "range", "(", "0", ",", "self", ".", "size", ")", ")", "for", "i", "in", "range", "(", "0", ",", "self", ".", "size", ")", ":", "v", "[", "i", "]"...
Compatible to Parser.new()
[ "Compatible", "to", "Parser", ".", "new", "()" ]
python
train
27.75
ejeschke/ginga
ginga/rv/plugins/SaveImage.py
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/SaveImage.py#L372-L393
def _write_header(self, image, hdu): """Write header from image object to given HDU.""" hduhdr = hdu.header # Ginga image header object for the given extension only. # Cannot use get_header() because that might also return PRI hdr. ghdr = image.metadata['header'] for ke...
[ "def", "_write_header", "(", "self", ",", "image", ",", "hdu", ")", ":", "hduhdr", "=", "hdu", ".", "header", "# Ginga image header object for the given extension only.", "# Cannot use get_header() because that might also return PRI hdr.", "ghdr", "=", "image", ".", "metada...
Write header from image object to given HDU.
[ "Write", "header", "from", "image", "object", "to", "given", "HDU", "." ]
python
train
33.681818
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_nameserver.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_nameserver.py#L247-L261
def get_nameserver_detail_output_show_nameserver_nameserver_redirect(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_nameserver_detail = ET.Element("get_nameserver_detail") config = get_nameserver_detail output = ET.SubElement(get_nameserver_...
[ "def", "get_nameserver_detail_output_show_nameserver_nameserver_redirect", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_nameserver_detail", "=", "ET", ".", "Element", "(", "\"get_nameserver_detail\""...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
52.466667
saltstack/salt
salt/modules/augeas_cfg.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/augeas_cfg.py#L105-L124
def _check_load_paths(load_path): ''' Checks the validity of the load_path, returns a sanitized version with invalid paths removed. ''' if load_path is None or not isinstance(load_path, six.string_types): return None _paths = [] for _path in load_path.split(':'): if os.path...
[ "def", "_check_load_paths", "(", "load_path", ")", ":", "if", "load_path", "is", "None", "or", "not", "isinstance", "(", "load_path", ",", "six", ".", "string_types", ")", ":", "return", "None", "_paths", "=", "[", "]", "for", "_path", "in", "load_path", ...
Checks the validity of the load_path, returns a sanitized version with invalid paths removed.
[ "Checks", "the", "validity", "of", "the", "load_path", "returns", "a", "sanitized", "version", "with", "invalid", "paths", "removed", "." ]
python
train
26.7
coleifer/walrus
walrus/search/__init__.py
https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/search/__init__.py#L29-L47
def stem(self, words): """ Use the porter stemmer to generate consistent forms of words, e.g.:: from walrus.search.utils import PorterStemmer stemmer = PorterStemmer() for word in ['faith', 'faiths', 'faithful']: print s.stem(word, 0, len(word...
[ "def", "stem", "(", "self", ",", "words", ")", ":", "stemmer", "=", "PorterStemmer", "(", ")", "_stem", "=", "stemmer", ".", "stem", "for", "word", "in", "words", ":", "yield", "_stem", "(", "word", ",", "0", ",", "len", "(", "word", ")", "-", "1...
Use the porter stemmer to generate consistent forms of words, e.g.:: from walrus.search.utils import PorterStemmer stemmer = PorterStemmer() for word in ['faith', 'faiths', 'faithful']: print s.stem(word, 0, len(word) - 1) # Prints: #...
[ "Use", "the", "porter", "stemmer", "to", "generate", "consistent", "forms", "of", "words", "e", ".", "g", ".", "::" ]
python
train
28.473684
bolt-project/bolt
bolt/spark/array.py
https://github.com/bolt-project/bolt/blob/9cd7104aa085498da3097b72696184b9d3651c51/bolt/spark/array.py#L284-L334
def _stat(self, axis=None, func=None, name=None, keepdims=False): """ Compute a statistic over an axis. Can provide either a function (for use in a reduce) or a name (for use by a stat counter). Parameters ---------- axis : tuple or int, optional, default=None ...
[ "def", "_stat", "(", "self", ",", "axis", "=", "None", ",", "func", "=", "None", ",", "name", "=", "None", ",", "keepdims", "=", "False", ")", ":", "if", "axis", "is", "None", ":", "axis", "=", "list", "(", "range", "(", "len", "(", "self", "."...
Compute a statistic over an axis. Can provide either a function (for use in a reduce) or a name (for use by a stat counter). Parameters ---------- axis : tuple or int, optional, default=None Axis to compute statistic over, if None will compute over all a...
[ "Compute", "a", "statistic", "over", "an", "axis", "." ]
python
test
30.470588
spyder-ide/pywinpty
winpty/ptyprocess.py
https://github.com/spyder-ide/pywinpty/blob/f4461cde9f0c53047e61e9eff7f7ec21ecbc4573/winpty/ptyprocess.py#L138-L156
def close(self, force=False): """This closes the connection with the child application. Note that calling close() more than once is valid. This emulates standard Python behavior with files. Set force to True if you want to make sure that the child is terminated (SIGKILL is sent if the ch...
[ "def", "close", "(", "self", ",", "force", "=", "False", ")", ":", "if", "not", "self", ".", "closed", ":", "self", ".", "pty", ".", "close", "(", ")", "self", ".", "fileobj", ".", "close", "(", ")", "self", ".", "_server", ".", "close", "(", "...
This closes the connection with the child application. Note that calling close() more than once is valid. This emulates standard Python behavior with files. Set force to True if you want to make sure that the child is terminated (SIGKILL is sent if the child ignores SIGINT).
[ "This", "closes", "the", "connection", "with", "the", "child", "application", ".", "Note", "that", "calling", "close", "()", "more", "than", "once", "is", "valid", ".", "This", "emulates", "standard", "Python", "behavior", "with", "files", ".", "Set", "force...
python
train
42.736842
saltstack/salt
salt/modules/bamboohr.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bamboohr.py#L224-L244
def list_meta_fields(): ''' Show all meta data fields for this company. CLI Example: salt myminion bamboohr.list_meta_fields ''' ret = {} status, result = _query(action='meta', command='fields') root = ET.fromstring(result) fields = root.getchildren() for field in fields: ...
[ "def", "list_meta_fields", "(", ")", ":", "ret", "=", "{", "}", "status", ",", "result", "=", "_query", "(", "action", "=", "'meta'", ",", "command", "=", "'fields'", ")", "root", "=", "ET", ".", "fromstring", "(", "result", ")", "fields", "=", "root...
Show all meta data fields for this company. CLI Example: salt myminion bamboohr.list_meta_fields
[ "Show", "all", "meta", "data", "fields", "for", "this", "company", "." ]
python
train
26.428571