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
ggravlingen/pytradfri
pytradfri/group.py
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/group.py#L70-L81
def set_dimmer(self, dimmer, transition_time=None): """Set dimmer value of a group. dimmer: Integer between 0..255 transition_time: Integer representing tenth of a second (default None) """ values = { ATTR_LIGHT_DIMMER: dimmer, } if transition_time is...
[ "def", "set_dimmer", "(", "self", ",", "dimmer", ",", "transition_time", "=", "None", ")", ":", "values", "=", "{", "ATTR_LIGHT_DIMMER", ":", "dimmer", ",", "}", "if", "transition_time", "is", "not", "None", ":", "values", "[", "ATTR_TRANSITION_TIME", "]", ...
Set dimmer value of a group. dimmer: Integer between 0..255 transition_time: Integer representing tenth of a second (default None)
[ "Set", "dimmer", "value", "of", "a", "group", "." ]
python
train
34.75
tensorflow/tensor2tensor
tensor2tensor/models/video/sv2p_params.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/sv2p_params.py#L145-L151
def next_frame_sv2p_cutoff(): """SV2P model with additional cutoff in L2 loss for environments like pong.""" hparams = next_frame_sv2p() hparams.video_modality_loss_cutoff = 0.4 hparams.video_num_input_frames = 4 hparams.video_num_target_frames = 1 return hparams
[ "def", "next_frame_sv2p_cutoff", "(", ")", ":", "hparams", "=", "next_frame_sv2p", "(", ")", "hparams", ".", "video_modality_loss_cutoff", "=", "0.4", "hparams", ".", "video_num_input_frames", "=", "4", "hparams", ".", "video_num_target_frames", "=", "1", "return", ...
SV2P model with additional cutoff in L2 loss for environments like pong.
[ "SV2P", "model", "with", "additional", "cutoff", "in", "L2", "loss", "for", "environments", "like", "pong", "." ]
python
train
38.428571
monarch-initiative/dipper
dipper/sources/KEGG.py
https://github.com/monarch-initiative/dipper/blob/24cc80db355bbe15776edc5c7b41e0886959ba41/dipper/sources/KEGG.py#L354-L423
def _process_ortholog_classes(self, limit=None): """ This method add the KEGG orthology classes to the graph. If there's an embedded enzyme commission number, that is added as an xref. Triples created: <orthology_class_id> is a class <orthology_class_id> has lab...
[ "def", "_process_ortholog_classes", "(", "self", ",", "limit", "=", "None", ")", ":", "LOG", ".", "info", "(", "\"Processing ortholog classes\"", ")", "if", "self", ".", "test_mode", ":", "graph", "=", "self", ".", "testgraph", "else", ":", "graph", "=", "...
This method add the KEGG orthology classes to the graph. If there's an embedded enzyme commission number, that is added as an xref. Triples created: <orthology_class_id> is a class <orthology_class_id> has label <orthology_symbols> <orthology_class_id> has description <...
[ "This", "method", "add", "the", "KEGG", "orthology", "classes", "to", "the", "graph", "." ]
python
train
39.528571
neherlab/treetime
treetime/gtr.py
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/gtr.py#L821-L861
def prob_t_profiles(self, profile_pair, multiplicity, t, return_log=False, ignore_gaps=True): ''' Calculate the probability of observing a node pair at a distance t Parameters ---------- profile_pair: numpy arrays Probability distributions ...
[ "def", "prob_t_profiles", "(", "self", ",", "profile_pair", ",", "multiplicity", ",", "t", ",", "return_log", "=", "False", ",", "ignore_gaps", "=", "True", ")", ":", "if", "t", "<", "0", ":", "logP", "=", "-", "ttconf", ".", "BIG_NUMBER", "else", ":",...
Calculate the probability of observing a node pair at a distance t Parameters ---------- profile_pair: numpy arrays Probability distributions of the nucleotides at either end of the branch. pp[0] = parent, pp[1] = child multiplicity : numpy array ...
[ "Calculate", "the", "probability", "of", "observing", "a", "node", "pair", "at", "a", "distance", "t" ]
python
test
38.219512
artemrizhov/django-mail-templated
mail_templated/message.py
https://github.com/artemrizhov/django-mail-templated/blob/1b428e7b6e02a5cf775bc83d6f5fd8c5f56d7932/mail_templated/message.py#L207-L227
def send(self, *args, **kwargs): """ Send email message, render if it is not rendered yet. Note ---- Any extra arguments are passed to :class:`EmailMultiAlternatives.send() <django.core.mail.EmailMessage>`. Keyword Arguments ----------------- cle...
[ "def", "send", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "clean", "=", "kwargs", ".", "pop", "(", "'clean'", ",", "False", ")", "if", "not", "self", ".", "_is_rendered", ":", "self", ".", "render", "(", ")", "if", "clean",...
Send email message, render if it is not rendered yet. Note ---- Any extra arguments are passed to :class:`EmailMultiAlternatives.send() <django.core.mail.EmailMessage>`. Keyword Arguments ----------------- clean : bool If ``True``, remove any templat...
[ "Send", "email", "message", "render", "if", "it", "is", "not", "rendered", "yet", "." ]
python
train
31.142857
jazzband/django-analytical
analytical/templatetags/snapengage.py
https://github.com/jazzband/django-analytical/blob/5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3/analytical/templatetags/snapengage.py#L56-L66
def snapengage(parser, token): """ SnapEngage set-up template tag. Renders Javascript code to set-up SnapEngage chat. You must supply your widget ID in the ``SNAPENGAGE_WIDGET_ID`` setting. """ bits = token.split_contents() if len(bits) > 1: raise TemplateSyntaxError("'%s' takes no...
[ "def", "snapengage", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", ">", "1", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' takes no arguments\"", "%", "bits", "[", "0", "]...
SnapEngage set-up template tag. Renders Javascript code to set-up SnapEngage chat. You must supply your widget ID in the ``SNAPENGAGE_WIDGET_ID`` setting.
[ "SnapEngage", "set", "-", "up", "template", "tag", "." ]
python
valid
32.727273
okpy/ok-client
client/protocols/unlock.py
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/protocols/unlock.py#L90-L184
def interact(self, unique_id, case_id, question_prompt, answer, choices=None, randomize=True): """Reads student input for unlocking tests until the student answers correctly. PARAMETERS: unique_id -- str; the ID that is recorded with this unlocking attem...
[ "def", "interact", "(", "self", ",", "unique_id", ",", "case_id", ",", "question_prompt", ",", "answer", ",", "choices", "=", "None", ",", "randomize", "=", "True", ")", ":", "if", "randomize", "and", "choices", ":", "choices", "=", "random", ".", "sampl...
Reads student input for unlocking tests until the student answers correctly. PARAMETERS: unique_id -- str; the ID that is recorded with this unlocking attempt. case_id -- str; the ID that is recorded with this unlocking ...
[ "Reads", "student", "input", "for", "unlocking", "tests", "until", "the", "student", "answers", "correctly", "." ]
python
train
40.178947
google/dotty
efilter/protocol.py
https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/protocol.py#L147-L164
def __get_type_args(for_type=None, for_types=None): """Parse the arguments and return a tuple of types to implement for. Raises: ValueError or TypeError as appropriate. """ if for_type: if for_types: raise ValueError("Cannot pass both for_type and...
[ "def", "__get_type_args", "(", "for_type", "=", "None", ",", "for_types", "=", "None", ")", ":", "if", "for_type", ":", "if", "for_types", ":", "raise", "ValueError", "(", "\"Cannot pass both for_type and for_types.\"", ")", "for_types", "=", "(", "for_type", ",...
Parse the arguments and return a tuple of types to implement for. Raises: ValueError or TypeError as appropriate.
[ "Parse", "the", "arguments", "and", "return", "a", "tuple", "of", "types", "to", "implement", "for", "." ]
python
train
36.833333
google/grr
grr/core/grr_response_core/lib/util/compatibility.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/lib/util/compatibility.py#L252-L271
def Environ(variable, default): """A wrapper for `os.environ.get` that works the same way in both Pythons. Args: variable: A name of the variable to get the value of. default: A default value to return in case no value for the given variable is set. Returns: An environment value of the given v...
[ "def", "Environ", "(", "variable", ",", "default", ")", ":", "precondition", ".", "AssertType", "(", "variable", ",", "Text", ")", "value", "=", "os", ".", "environ", ".", "get", "(", "variable", ",", "default", ")", "if", "value", "is", "None", ":", ...
A wrapper for `os.environ.get` that works the same way in both Pythons. Args: variable: A name of the variable to get the value of. default: A default value to return in case no value for the given variable is set. Returns: An environment value of the given variable.
[ "A", "wrapper", "for", "os", ".", "environ", ".", "get", "that", "works", "the", "same", "way", "in", "both", "Pythons", "." ]
python
train
30.15
elastic/elasticsearch-py
elasticsearch/client/ingest.py
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/ingest.py#L5-L14
def get_pipeline(self, id=None, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/plugins/current/ingest.html>`_ :arg id: Comma separated list of pipeline ids. Wildcards supported :arg master_timeout: Explicit operation timeout for connection to master node ...
[ "def", "get_pipeline", "(", "self", ",", "id", "=", "None", ",", "params", "=", "None", ")", ":", "return", "self", ".", "transport", ".", "perform_request", "(", "'GET'", ",", "_make_path", "(", "'_ingest'", ",", "'pipeline'", ",", "id", ")", ",", "pa...
`<https://www.elastic.co/guide/en/elasticsearch/plugins/current/ingest.html>`_ :arg id: Comma separated list of pipeline ids. Wildcards supported :arg master_timeout: Explicit operation timeout for connection to master node
[ "<https", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "plugins", "/", "current", "/", "ingest", ".", "html", ">", "_" ]
python
train
44
lsst-sqre/documenteer
documenteer/sphinxext/utils.py
https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/utils.py#L44-L83
def make_python_xref_nodes(py_typestr, state, hide_namespace=False): """Make docutils nodes containing a cross-reference to a Python object. Parameters ---------- py_typestr : `str` Name of the Python object. For example ``'mypackage.mymodule.MyClass'``. If you have the object itself, o...
[ "def", "make_python_xref_nodes", "(", "py_typestr", ",", "state", ",", "hide_namespace", "=", "False", ")", ":", "if", "hide_namespace", ":", "template", "=", "':py:obj:`~{}`\\n'", "else", ":", "template", "=", "':py:obj:`{}`\\n'", "xref_text", "=", "template", "....
Make docutils nodes containing a cross-reference to a Python object. Parameters ---------- py_typestr : `str` Name of the Python object. For example ``'mypackage.mymodule.MyClass'``. If you have the object itself, or its type, use the `make_python_xref_nodes_for_type` function inste...
[ "Make", "docutils", "nodes", "containing", "a", "cross", "-", "reference", "to", "a", "Python", "object", "." ]
python
train
29.95
rtfd/sphinx-autoapi
autoapi/mappers/python/mapper.py
https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/mappers/python/mapper.py#L24-L69
def _expand_wildcard_placeholder(original_module, originals_map, placeholder): """Expand a wildcard placeholder to a sequence of named placeholders. :param original_module: The data dictionary of the module that the placeholder is imported from. :type original_module: dict :param originals_map:...
[ "def", "_expand_wildcard_placeholder", "(", "original_module", ",", "originals_map", ",", "placeholder", ")", ":", "originals", "=", "originals_map", ".", "values", "(", ")", "if", "original_module", "[", "\"all\"", "]", "is", "not", "None", ":", "originals", "=...
Expand a wildcard placeholder to a sequence of named placeholders. :param original_module: The data dictionary of the module that the placeholder is imported from. :type original_module: dict :param originals_map: A map of the names of children under the module to their data dictionaries. ...
[ "Expand", "a", "wildcard", "placeholder", "to", "a", "sequence", "of", "named", "placeholders", "." ]
python
train
36.152174
pgmpy/pgmpy
pgmpy/readwrite/BIF.py
https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/readwrite/BIF.py#L535-L552
def write_bif(self, filename): """ Writes the BIF data into a file Parameters ---------- filename : Name of the file Example ------- >>> from pgmpy.readwrite import BIFReader, BIFWriter >>> model = BIFReader('dog-problem.bif').get_model() ...
[ "def", "write_bif", "(", "self", ",", "filename", ")", ":", "writer", "=", "self", ".", "__str__", "(", ")", "with", "open", "(", "filename", ",", "'w'", ")", "as", "fout", ":", "fout", ".", "write", "(", "writer", ")" ]
Writes the BIF data into a file Parameters ---------- filename : Name of the file Example ------- >>> from pgmpy.readwrite import BIFReader, BIFWriter >>> model = BIFReader('dog-problem.bif').get_model() >>> writer = BIFWriter(model) >>> writer.w...
[ "Writes", "the", "BIF", "data", "into", "a", "file" ]
python
train
28
gwastro/pycbc
pycbc/events/stat.py
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/stat.py#L416-L426
def coinc(self, s0, s1, slide, step): # pylint:disable=unused-argument """Calculate the final coinc ranking statistic""" # Approximate log likelihood ratio by summing single-ifo negative # log noise likelihoods loglr = - s0 - s1 # add squares of threshold stat values via idealize...
[ "def", "coinc", "(", "self", ",", "s0", ",", "s1", ",", "slide", ",", "step", ")", ":", "# pylint:disable=unused-argument", "# Approximate log likelihood ratio by summing single-ifo negative", "# log noise likelihoods", "loglr", "=", "-", "s0", "-", "s1", "# add squares...
Calculate the final coinc ranking statistic
[ "Calculate", "the", "final", "coinc", "ranking", "statistic" ]
python
train
54
pywbem/pywbem
wbemcli.py
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/wbemcli.py#L2298-L2389
def orip(ip, rc=None, r=None, fl=None, fs=None, ot=None, coe=None, moc=None): # pylint: disable=too-many-arguments, redefined-outer-name, invalid-name """ This function is a wrapper for :meth:`~pywbem.WBEMConnection.OpenReferenceInstancePaths`. Open an enumeration session to retrieve the instance p...
[ "def", "orip", "(", "ip", ",", "rc", "=", "None", ",", "r", "=", "None", ",", "fl", "=", "None", ",", "fs", "=", "None", ",", "ot", "=", "None", ",", "coe", "=", "None", ",", "moc", "=", "None", ")", ":", "# pylint: disable=too-many-arguments, rede...
This function is a wrapper for :meth:`~pywbem.WBEMConnection.OpenReferenceInstancePaths`. Open an enumeration session to retrieve the instance paths of the association instances that reference a source instance. Use the :func:`~wbemcli.pip` function to retrieve the next set of instance paths or th...
[ "This", "function", "is", "a", "wrapper", "for", ":", "meth", ":", "~pywbem", ".", "WBEMConnection", ".", "OpenReferenceInstancePaths", "." ]
python
train
37.434783
nens/turn
turn/core.py
https://github.com/nens/turn/blob/98e806a0749ada0ddfd04b3c29fb04c15bf5ac18/turn/core.py#L159-L184
def bump(self): """ Fix indicator in case of unnanounced departments. """ # read client values = self.client.mget(self.keys.indicator, self.keys.dispenser) indicator, dispenser = map(int, values) # determine active users numbers = range(indicator, dispenser + 1) ...
[ "def", "bump", "(", "self", ")", ":", "# read client", "values", "=", "self", ".", "client", ".", "mget", "(", "self", ".", "keys", ".", "indicator", ",", "self", ".", "keys", ".", "dispenser", ")", "indicator", ",", "dispenser", "=", "map", "(", "in...
Fix indicator in case of unnanounced departments.
[ "Fix", "indicator", "in", "case", "of", "unnanounced", "departments", "." ]
python
train
35.076923
rosenbrockc/fortpy
fortpy/isense/evaluator.py
https://github.com/rosenbrockc/fortpy/blob/1ed0757c52d549e41d9d44bdea68cb89529293a5/fortpy/isense/evaluator.py#L300-L318
def _complete_el(self, symbol, attribute, fullsymbol): """Suggests a list of completions based on the el_* attributes of the user_context.""" if symbol != fullsymbol: #We have a sym%sym%... chain and the completion just needs to #be a member variable or method of the type...
[ "def", "_complete_el", "(", "self", ",", "symbol", ",", "attribute", ",", "fullsymbol", ")", ":", "if", "symbol", "!=", "fullsymbol", ":", "#We have a sym%sym%... chain and the completion just needs to", "#be a member variable or method of the type being referenced.", "return",...
Suggests a list of completions based on the el_* attributes of the user_context.
[ "Suggests", "a", "list", "of", "completions", "based", "on", "the", "el_", "*", "attributes", "of", "the", "user_context", "." ]
python
train
50.210526
neo4j-drivers/neotime
neotime/__init__.py
https://github.com/neo4j-drivers/neotime/blob/9f6c1d782178fee5e27345dbf78ac161b3a95cc7/neotime/__init__.py#L568-L585
def parse(cls, s): """ Parse a string to produce a :class:`.Date`. Accepted formats: 'YYYY-MM-DD' :param s: :return: """ try: numbers = map(int, s.split("-")) except (ValueError, AttributeError): raise ValueError("Date string ...
[ "def", "parse", "(", "cls", ",", "s", ")", ":", "try", ":", "numbers", "=", "map", "(", "int", ",", "s", ".", "split", "(", "\"-\"", ")", ")", "except", "(", "ValueError", ",", "AttributeError", ")", ":", "raise", "ValueError", "(", "\"Date string mu...
Parse a string to produce a :class:`.Date`. Accepted formats: 'YYYY-MM-DD' :param s: :return:
[ "Parse", "a", "string", "to", "produce", "a", ":", "class", ":", ".", "Date", "." ]
python
train
29.277778
tk0miya/tk.phpautodoc
src/phply/phpparse.py
https://github.com/tk0miya/tk.phpautodoc/blob/cf789f64abaf76351485cee231a075227e665fb6/src/phply/phpparse.py#L1165-L1174
def p_scalar_namespace_name(p): '''scalar : namespace_name | NS_SEPARATOR namespace_name | NAMESPACE NS_SEPARATOR namespace_name''' if len(p) == 2: p[0] = ast.Constant(p[1], lineno=p.lineno(1)) elif len(p) == 3: p[0] = ast.Constant(p[1] + p[2], lineno=p.lineno(1))...
[ "def", "p_scalar_namespace_name", "(", "p", ")", ":", "if", "len", "(", "p", ")", "==", "2", ":", "p", "[", "0", "]", "=", "ast", ".", "Constant", "(", "p", "[", "1", "]", ",", "lineno", "=", "p", ".", "lineno", "(", "1", ")", ")", "elif", ...
scalar : namespace_name | NS_SEPARATOR namespace_name | NAMESPACE NS_SEPARATOR namespace_name
[ "scalar", ":", "namespace_name", "|", "NS_SEPARATOR", "namespace_name", "|", "NAMESPACE", "NS_SEPARATOR", "namespace_name" ]
python
train
38.9
tensorflow/mesh
mesh_tensorflow/simd_mesh_impl.py
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/simd_mesh_impl.py#L460-L483
def slicewise(self, fn, *inputs): """Execute a function in parallel on all slices. Args: fn: a function from tf.Tensors to tf.Tensor or a tuple of tf.Tensors. *inputs: a list of inputs. Each input is either a LaidOutTensor or is convertible to a tf.Tensor. Returns: a LaidOutTenso...
[ "def", "slicewise", "(", "self", ",", "fn", ",", "*", "inputs", ")", ":", "if", "fn", "==", "tf", ".", "add", ":", "assert", "len", "(", "inputs", ")", "==", "2", "if", "isinstance", "(", "inputs", "[", "0", "]", ",", "mtf", ".", "LazyAllreduceSu...
Execute a function in parallel on all slices. Args: fn: a function from tf.Tensors to tf.Tensor or a tuple of tf.Tensors. *inputs: a list of inputs. Each input is either a LaidOutTensor or is convertible to a tf.Tensor. Returns: a LaidOutTensor, or a tuple of LaidOutTensors if fn ret...
[ "Execute", "a", "function", "in", "parallel", "on", "all", "slices", "." ]
python
train
38.541667
dadadel/pyment
pyment/docstring.py
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L1601-L1610
def _extract_docs_other(self): """Extract other specific sections""" if self.dst.style['in'] == 'numpydoc': data = '\n'.join([d.rstrip().replace(self.docs['out']['spaces'], '', 1) for d in self.docs['in']['raw'].splitlines()]) lst = self.dst.numpydoc.get_list_key(data, 'also') ...
[ "def", "_extract_docs_other", "(", "self", ")", ":", "if", "self", ".", "dst", ".", "style", "[", "'in'", "]", "==", "'numpydoc'", ":", "data", "=", "'\\n'", ".", "join", "(", "[", "d", ".", "rstrip", "(", ")", ".", "replace", "(", "self", ".", "...
Extract other specific sections
[ "Extract", "other", "specific", "sections" ]
python
train
62.6
azraq27/neural
neural/decon.py
https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/decon.py#L378-L419
def partial(self,start=0,end=None,run=0): '''chops the stimulus by only including time points ``start`` through ``end`` (in reps, inclusive; ``None``=until the end) if using stim_times-style simulus, will change the ``run``'th run. If a column, will just chop the column''' self.read_file() ...
[ "def", "partial", "(", "self", ",", "start", "=", "0", ",", "end", "=", "None", ",", "run", "=", "0", ")", ":", "self", ".", "read_file", "(", ")", "decon_stim", "=", "copy", ".", "copy", "(", "self", ")", "if", "start", "<", "0", ":", "start",...
chops the stimulus by only including time points ``start`` through ``end`` (in reps, inclusive; ``None``=until the end) if using stim_times-style simulus, will change the ``run``'th run. If a column, will just chop the column
[ "chops", "the", "stimulus", "by", "only", "including", "time", "points", "start", "through", "end", "(", "in", "reps", "inclusive", ";", "None", "=", "until", "the", "end", ")", "if", "using", "stim_times", "-", "style", "simulus", "will", "change", "the",...
python
train
45.357143
openstack/networking-arista
networking_arista/common/db_lib.py
https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/common/db_lib.py#L59-L68
def filter_unnecessary_segments(query): """Filter segments are not needed on CVX""" segment_model = segment_models.NetworkSegment network_model = models_v2.Network query = (query .join_if_necessary(network_model) .join_if_necessary(segment_model) .filter(network_mo...
[ "def", "filter_unnecessary_segments", "(", "query", ")", ":", "segment_model", "=", "segment_models", ".", "NetworkSegment", "network_model", "=", "models_v2", ".", "Network", "query", "=", "(", "query", ".", "join_if_necessary", "(", "network_model", ")", ".", "j...
Filter segments are not needed on CVX
[ "Filter", "segments", "are", "not", "needed", "on", "CVX" ]
python
train
38.6
manns/pyspread
pyspread/src/lib/charts.py
https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/lib/charts.py#L113-L126
def fig2x(figure, format): """Returns svg from matplotlib chart""" # Save svg to file like object svg_io io = StringIO() figure.savefig(io, format=format) # Rewind the file like object io.seek(0) data = io.getvalue() io.close() return data
[ "def", "fig2x", "(", "figure", ",", "format", ")", ":", "# Save svg to file like object svg_io", "io", "=", "StringIO", "(", ")", "figure", ".", "savefig", "(", "io", ",", "format", "=", "format", ")", "# Rewind the file like object", "io", ".", "seek", "(", ...
Returns svg from matplotlib chart
[ "Returns", "svg", "from", "matplotlib", "chart" ]
python
train
19
pokerregion/poker
poker/commands.py
https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/commands.py#L59-L95
def twoplustwo_player(username): """Get profile information about a Two plus Two Forum member given the username.""" from .website.twoplustwo import ForumMember, AmbiguousUserNameError, UserNotFoundError try: member = ForumMember(username) except UserNotFoundError: raise click.ClickExc...
[ "def", "twoplustwo_player", "(", "username", ")", ":", "from", ".", "website", ".", "twoplustwo", "import", "ForumMember", ",", "AmbiguousUserNameError", ",", "UserNotFoundError", "try", ":", "member", "=", "ForumMember", "(", "username", ")", "except", "UserNotFo...
Get profile information about a Two plus Two Forum member given the username.
[ "Get", "profile", "information", "about", "a", "Two", "plus", "Two", "Forum", "member", "given", "the", "username", "." ]
python
train
38.702703
fastai/fastai
fastai/vision/transform.py
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L175-L189
def _crop_pad_default(x, size, padding_mode='reflection', row_pct:uniform = 0.5, col_pct:uniform = 0.5): "Crop and pad tfm - `row_pct`,`col_pct` sets focal point." padding_mode = _pad_mode_convert[padding_mode] size = tis2hw(size) if x.shape[1:] == torch.Size(size): return x rows,cols = size row...
[ "def", "_crop_pad_default", "(", "x", ",", "size", ",", "padding_mode", "=", "'reflection'", ",", "row_pct", ":", "uniform", "=", "0.5", ",", "col_pct", ":", "uniform", "=", "0.5", ")", ":", "padding_mode", "=", "_pad_mode_convert", "[", "padding_mode", "]",...
Crop and pad tfm - `row_pct`,`col_pct` sets focal point.
[ "Crop", "and", "pad", "tfm", "-", "row_pct", "col_pct", "sets", "focal", "point", "." ]
python
train
48.266667
stanfordnlp/stanza
stanza/text/vocab.py
https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/text/vocab.py#L93-L108
def add(self, word, count=1): """Add a word to the vocabulary and return its index. :param word: word to add to the dictionary. :param count: how many times to add the word. :return: index of the added word. WARNING: this function assumes that if the Vocab currently has N wor...
[ "def", "add", "(", "self", ",", "word", ",", "count", "=", "1", ")", ":", "if", "word", "not", "in", "self", ":", "super", "(", "Vocab", ",", "self", ")", ".", "__setitem__", "(", "word", ",", "len", "(", "self", ")", ")", "self", ".", "_counts...
Add a word to the vocabulary and return its index. :param word: word to add to the dictionary. :param count: how many times to add the word. :return: index of the added word. WARNING: this function assumes that if the Vocab currently has N words, then there is a perfect bijec...
[ "Add", "a", "word", "to", "the", "vocabulary", "and", "return", "its", "index", "." ]
python
train
35.4375
markovmodel/msmtools
msmtools/analysis/dense/sensitivity.py
https://github.com/markovmodel/msmtools/blob/54dc76dd2113a0e8f3d15d5316abab41402941be/msmtools/analysis/dense/sensitivity.py#L387-L407
def expectation_sensitivity(T, a): r"""Sensitivity of expectation value of observable A=(a_i). Parameters ---------- T : (M, M) ndarray Transition matrix a : (M,) ndarray Observable, a[i] is the value of the observable at state i. Returns ------- S : (M, M) ndarray ...
[ "def", "expectation_sensitivity", "(", "T", ",", "a", ")", ":", "M", "=", "T", ".", "shape", "[", "0", "]", "S", "=", "numpy", ".", "zeros", "(", "(", "M", ",", "M", ")", ")", "for", "i", "in", "range", "(", "M", ")", ":", "S", "+=", "a", ...
r"""Sensitivity of expectation value of observable A=(a_i). Parameters ---------- T : (M, M) ndarray Transition matrix a : (M,) ndarray Observable, a[i] is the value of the observable at state i. Returns ------- S : (M, M) ndarray Sensitivity matrix of the expectati...
[ "r", "Sensitivity", "of", "expectation", "value", "of", "observable", "A", "=", "(", "a_i", ")", "." ]
python
train
23.904762
pandas-dev/pandas
pandas/core/frame.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/frame.py#L3459-L3547
def assign(self, **kwargs): r""" Assign new columns to a DataFrame. Returns a new object with all original columns in addition to new ones. Existing columns that are re-assigned will be overwritten. Parameters ---------- **kwargs : dict of {str: callable or Seri...
[ "def", "assign", "(", "self", ",", "*", "*", "kwargs", ")", ":", "data", "=", "self", ".", "copy", "(", ")", "# >= 3.6 preserve order of kwargs", "if", "PY36", ":", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "data", "[", "k"...
r""" Assign new columns to a DataFrame. Returns a new object with all original columns in addition to new ones. Existing columns that are re-assigned will be overwritten. Parameters ---------- **kwargs : dict of {str: callable or Series} The column names are...
[ "r", "Assign", "new", "columns", "to", "a", "DataFrame", "." ]
python
train
35.483146
KelSolaar/Umbra
umbra/components/factory/script_editor/search_in_files.py
https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/components/factory/script_editor/search_in_files.py#L519-L532
def filters_in_format(self, value): """ Setter for **self.__filters_in_format** attribute. :param value: Attribute value. :type value: unicode """ if value is not None: assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format( ...
[ "def", "filters_in_format", "(", "self", ",", "value", ")", ":", "if", "value", "is", "not", "None", ":", "assert", "type", "(", "value", ")", "is", "unicode", ",", "\"'{0}' attribute: '{1}' type is not 'unicode'!\"", ".", "format", "(", "\"filters_in_format\"", ...
Setter for **self.__filters_in_format** attribute. :param value: Attribute value. :type value: unicode
[ "Setter", "for", "**", "self", ".", "__filters_in_format", "**", "attribute", "." ]
python
train
37.785714
ThreatConnect-Inc/tcex
tcex/tcex_playbook.py
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L909-L928
def create_string_array(self, key, value): """Create method of CRUD operation for string array data. Args: key (string): The variable to write to the DB. value (any): The data to write to the DB. Returns: (string): Result of DB write. """ dat...
[ "def", "create_string_array", "(", "self", ",", "key", ",", "value", ")", ":", "data", "=", "None", "if", "key", "is", "not", "None", "and", "value", "is", "not", "None", ":", "if", "isinstance", "(", "value", ",", "(", "list", ")", ")", ":", "data...
Create method of CRUD operation for string array data. Args: key (string): The variable to write to the DB. value (any): The data to write to the DB. Returns: (string): Result of DB write.
[ "Create", "method", "of", "CRUD", "operation", "for", "string", "array", "data", "." ]
python
train
35.85
SMTG-UCL/sumo
sumo/cli/dosplot.py
https://github.com/SMTG-UCL/sumo/blob/47aec6bbfa033a624435a65bd4edabd18bfb437f/sumo/cli/dosplot.py#L187-L210
def _el_orb(string): """Parse the element and orbital argument strings. The presence of an element without any orbitals means that we want to plot all of its orbitals. Args: string (str): The element and orbitals as a string, in the form ``"C.s.p,O"``. Returns: dict: T...
[ "def", "_el_orb", "(", "string", ")", ":", "el_orbs", "=", "{", "}", "for", "split", "in", "string", ".", "split", "(", "','", ")", ":", "orbs", "=", "split", ".", "split", "(", "'.'", ")", "orbs", "=", "[", "orbs", "[", "0", "]", ",", "'s'", ...
Parse the element and orbital argument strings. The presence of an element without any orbitals means that we want to plot all of its orbitals. Args: string (str): The element and orbitals as a string, in the form ``"C.s.p,O"``. Returns: dict: The elements and orbitals as ...
[ "Parse", "the", "element", "and", "orbital", "argument", "strings", "." ]
python
train
30.833333
cpenv/cpenv
cpenv/utils.py
https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/utils.py#L384-L397
def set_env_from_file(env_file): '''Restore the current environment from an environment stored in a yaml yaml file. :param env_file: Path to environment yaml file. ''' with open(env_file, 'r') as f: env_dict = yaml.load(f.read()) if 'environment' in env_dict: env_dict = env_di...
[ "def", "set_env_from_file", "(", "env_file", ")", ":", "with", "open", "(", "env_file", ",", "'r'", ")", "as", "f", ":", "env_dict", "=", "yaml", ".", "load", "(", "f", ".", "read", "(", ")", ")", "if", "'environment'", "in", "env_dict", ":", "env_di...
Restore the current environment from an environment stored in a yaml yaml file. :param env_file: Path to environment yaml file.
[ "Restore", "the", "current", "environment", "from", "an", "environment", "stored", "in", "a", "yaml", "yaml", "file", "." ]
python
valid
24.785714
bsolomon1124/pyfinance
pyfinance/returns.py
https://github.com/bsolomon1124/pyfinance/blob/c95925209a809b4e648e79cbeaf7711d8e5ff1a6/pyfinance/returns.py#L687-L699
def pct_negative(self, threshold=0.0): """Pct. of periods in which `self` is less than `threshold.` Parameters ---------- threshold : {float, TSeries, pd.Series}, default 0. Returns ------- float """ return np.count_nonzero(self[self < threshold...
[ "def", "pct_negative", "(", "self", ",", "threshold", "=", "0.0", ")", ":", "return", "np", ".", "count_nonzero", "(", "self", "[", "self", "<", "threshold", "]", ")", "/", "self", ".", "count", "(", ")" ]
Pct. of periods in which `self` is less than `threshold.` Parameters ---------- threshold : {float, TSeries, pd.Series}, default 0. Returns ------- float
[ "Pct", ".", "of", "periods", "in", "which", "self", "is", "less", "than", "threshold", "." ]
python
train
25
bfrog/whizzer
whizzer/rpc/service.py
https://github.com/bfrog/whizzer/blob/a1e43084b3ac8c1f3fb4ada081777cdbf791fd77/whizzer/rpc/service.py#L105-L110
def listen_init(self): """Setup the service to listen for clients.""" self.dispatcher = ObjectDispatch(self) self.factory = MsgPackProtocolFactory(self.dispatcher) self.server = UnixServer(self.loop, self.factory, self.path) self.server.start()
[ "def", "listen_init", "(", "self", ")", ":", "self", ".", "dispatcher", "=", "ObjectDispatch", "(", "self", ")", "self", ".", "factory", "=", "MsgPackProtocolFactory", "(", "self", ".", "dispatcher", ")", "self", ".", "server", "=", "UnixServer", "(", "sel...
Setup the service to listen for clients.
[ "Setup", "the", "service", "to", "listen", "for", "clients", "." ]
python
train
46.5
ctuning/ck
ck/kernel.py
https://github.com/ctuning/ck/blob/7e009814e975f8742790d3106340088a46223714/ck/kernel.py#L4192-L4287
def set_lock(i): """ Input: { path - path to be locked (get_lock) - if 'yes', lock this entry (lock_retries) - number of retries to aquire lock (default=11) (lock_retry_delay) - delay in seconds before trying to aquire lock agai...
[ "def", "set_lock", "(", "i", ")", ":", "p", "=", "i", "[", "'path'", "]", "gl", "=", "i", ".", "get", "(", "'get_lock'", ",", "''", ")", "uuid", "=", "i", ".", "get", "(", "'unlock_uid'", ",", "''", ")", "exp", "=", "float", "(", "i", ".", ...
Input: { path - path to be locked (get_lock) - if 'yes', lock this entry (lock_retries) - number of retries to aquire lock (default=11) (lock_retry_delay) - delay in seconds before trying to aquire lock again (default=3) (...
[ "Input", ":", "{", "path", "-", "path", "to", "be", "locked" ]
python
train
30.5625
quiltdata/quilt
compiler/quilt/tools/util.py
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/util.py#L138-L146
def sub_dirs(path, invisible=False): """ Child directories (non-recursive) """ dirs = [x for x in os.listdir(path) if os.path.isdir(os.path.join(path, x))] if not invisible: dirs = [x for x in dirs if not x.startswith('.')] return dirs
[ "def", "sub_dirs", "(", "path", ",", "invisible", "=", "False", ")", ":", "dirs", "=", "[", "x", "for", "x", "in", "os", ".", "listdir", "(", "path", ")", "if", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "join", "(", "path", ...
Child directories (non-recursive)
[ "Child", "directories", "(", "non", "-", "recursive", ")" ]
python
train
28.888889
metacloud/gilt
gilt/util.py
https://github.com/metacloud/gilt/blob/234eec23fe2f8144369d0ec3b35ad2fef508b8d1/gilt/util.py#L62-L70
def build_sh_cmd(cmd, cwd=None): """Build a `sh.Command` from a string. :param cmd: String with the command to convert. :param cwd: Optional path to use as working directory. :return: `sh.Command` """ args = cmd.split() return getattr(sh, args[0]).bake(_cwd=cwd, *args[1:])
[ "def", "build_sh_cmd", "(", "cmd", ",", "cwd", "=", "None", ")", ":", "args", "=", "cmd", ".", "split", "(", ")", "return", "getattr", "(", "sh", ",", "args", "[", "0", "]", ")", ".", "bake", "(", "_cwd", "=", "cwd", ",", "*", "args", "[", "1...
Build a `sh.Command` from a string. :param cmd: String with the command to convert. :param cwd: Optional path to use as working directory. :return: `sh.Command`
[ "Build", "a", "sh", ".", "Command", "from", "a", "string", "." ]
python
train
32.666667
sparklingpandas/sparklingpandas
sparklingpandas/pcontext.py
https://github.com/sparklingpandas/sparklingpandas/blob/7d549df4348c979042b683c355aa778fc6d3a768/sparklingpandas/pcontext.py#L68-L155
def read_csv(self, file_path, use_whole_file=False, names=None, skiprows=0, *args, **kwargs): """Read a CSV file in and parse it into Pandas DataFrames. By default, the first row from the first partition of that data is parsed and used as the column names for the data from. If n...
[ "def", "read_csv", "(", "self", ",", "file_path", ",", "use_whole_file", "=", "False", ",", "names", "=", "None", ",", "skiprows", "=", "0", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "csv_file", "(", "partition_number", ",", "files", ...
Read a CSV file in and parse it into Pandas DataFrames. By default, the first row from the first partition of that data is parsed and used as the column names for the data from. If no 'names' param is provided we parse the first row of the first partition of data and use it for column na...
[ "Read", "a", "CSV", "file", "in", "and", "parse", "it", "into", "Pandas", "DataFrames", ".", "By", "default", "the", "first", "row", "from", "the", "first", "partition", "of", "that", "data", "is", "parsed", "and", "used", "as", "the", "column", "names",...
python
train
41.181818
ossobv/dutree
dutree/dutree.py
https://github.com/ossobv/dutree/blob/adceeeb17f9fd70a7ed9c674850d7015d820eb2a/dutree/dutree.py#L153-L166
def _prune_all_if_small(self, small_size, a_or_u): "Return True and delete children if small enough." if self._nodes is None: return True total_size = (self.app_size() if a_or_u else self.use_size()) if total_size < small_size: if a_or_u: self._se...
[ "def", "_prune_all_if_small", "(", "self", ",", "small_size", ",", "a_or_u", ")", ":", "if", "self", ".", "_nodes", "is", "None", ":", "return", "True", "total_size", "=", "(", "self", ".", "app_size", "(", ")", "if", "a_or_u", "else", "self", ".", "us...
Return True and delete children if small enough.
[ "Return", "True", "and", "delete", "children", "if", "small", "enough", "." ]
python
train
33.285714
numenta/htmresearch
htmresearch/frameworks/layers/l2_l4_inference.py
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/layers/l2_l4_inference.py#L518-L573
def plotInferenceStats(self, fields, plotDir="plots", experimentID=0, onePlot=True): """ Plots and saves the desired inference statistics. Parameters: ---------------------------- @param fields (li...
[ "def", "plotInferenceStats", "(", "self", ",", "fields", ",", "plotDir", "=", "\"plots\"", ",", "experimentID", "=", "0", ",", "onePlot", "=", "True", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "plotDir", ")", ":", "os", ".", "make...
Plots and saves the desired inference statistics. Parameters: ---------------------------- @param fields (list(str)) List of fields to include in the plots @param experimentID (int) ID of the experiment (usually 0 if only one was conducted) @param onePlot (bool) ...
[ "Plots", "and", "saves", "the", "desired", "inference", "statistics", "." ]
python
train
28.464286
EventTeam/beliefs
src/beliefs/beliefstate.py
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/beliefstate.py#L67-L77
def add_deferred_effect(self, effect, pos): """ Pushes an (pos, effect) tuple onto a stack to later be executed if the state reaches the 'pos'.""" if not isinstance(pos, (unicode, str)): raise Exception("Invalid POS tag. Must be string not %d" % (type(pos))) if self['speaker_...
[ "def", "add_deferred_effect", "(", "self", ",", "effect", ",", "pos", ")", ":", "if", "not", "isinstance", "(", "pos", ",", "(", "unicode", ",", "str", ")", ")", ":", "raise", "Exception", "(", "\"Invalid POS tag. Must be string not %d\"", "%", "(", "type", ...
Pushes an (pos, effect) tuple onto a stack to later be executed if the state reaches the 'pos'.
[ "Pushes", "an", "(", "pos", "effect", ")", "tuple", "onto", "a", "stack", "to", "later", "be", "executed", "if", "the", "state", "reaches", "the", "pos", "." ]
python
train
56.909091
LonamiWebs/Telethon
telethon_examples/interactive_telegram_client.py
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_examples/interactive_telegram_client.py#L329-L347
async def download_media_by_id(self, media_id): """Given a message ID, finds the media this message contained and downloads it. """ try: msg = self.found_media[int(media_id)] except (ValueError, KeyError): # ValueError when parsing, KeyError when access...
[ "async", "def", "download_media_by_id", "(", "self", ",", "media_id", ")", ":", "try", ":", "msg", "=", "self", ".", "found_media", "[", "int", "(", "media_id", ")", "]", "except", "(", "ValueError", ",", "KeyError", ")", ":", "# ValueError when parsing, Key...
Given a message ID, finds the media this message contained and downloads it.
[ "Given", "a", "message", "ID", "finds", "the", "media", "this", "message", "contained", "and", "downloads", "it", "." ]
python
train
38.315789
mozilla-releng/scriptworker
scriptworker/cot/verify.py
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/cot/verify.py#L1841-L1862
def check_num_tasks(chain, task_count): """Make sure there are a specific number of specific task types. Currently we only check decision tasks. Args: chain (ChainOfTrust): the chain we're operating on task_count (dict): mapping task type to the number of links. Raises: CoTErr...
[ "def", "check_num_tasks", "(", "chain", ",", "task_count", ")", ":", "errors", "=", "[", "]", "# hardcode for now. If we need a different set of constraints, either", "# go by cot_product settings or by task_count['docker-image'] + 1", "min_decision_tasks", "=", "1", "if", "task...
Make sure there are a specific number of specific task types. Currently we only check decision tasks. Args: chain (ChainOfTrust): the chain we're operating on task_count (dict): mapping task type to the number of links. Raises: CoTError: on failure.
[ "Make", "sure", "there", "are", "a", "specific", "number", "of", "specific", "task", "types", "." ]
python
train
33.363636
Damgaard/PyImgur
pyimgur/__init__.py
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L487-L491
def get_comments(self): """Get a list of the top-level comments.""" url = self._imgur._base_url + "/3/gallery/{0}/comments".format(self.id) resp = self._imgur._send_request(url) return [Comment(com, self._imgur) for com in resp]
[ "def", "get_comments", "(", "self", ")", ":", "url", "=", "self", ".", "_imgur", ".", "_base_url", "+", "\"/3/gallery/{0}/comments\"", ".", "format", "(", "self", ".", "id", ")", "resp", "=", "self", ".", "_imgur", ".", "_send_request", "(", "url", ")", ...
Get a list of the top-level comments.
[ "Get", "a", "list", "of", "the", "top", "-", "level", "comments", "." ]
python
train
51.2
sorgerlab/indra
indra/sources/reach/api.py
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/reach/api.py#L77-L115
def process_pubmed_abstract(pubmed_id, offline=False, output_fname=default_output_fname, **kwargs): """Return a ReachProcessor by processing an abstract with a given Pubmed id. Uses the Pubmed client to get the abstract. If that fails, None is returned. Parameters -----...
[ "def", "process_pubmed_abstract", "(", "pubmed_id", ",", "offline", "=", "False", ",", "output_fname", "=", "default_output_fname", ",", "*", "*", "kwargs", ")", ":", "abs_txt", "=", "pubmed_client", ".", "get_abstract", "(", "pubmed_id", ")", "if", "abs_txt", ...
Return a ReachProcessor by processing an abstract with a given Pubmed id. Uses the Pubmed client to get the abstract. If that fails, None is returned. Parameters ---------- pubmed_id : str The ID of a Pubmed article. The string may start with PMID but passing just the ID also works...
[ "Return", "a", "ReachProcessor", "by", "processing", "an", "abstract", "with", "a", "given", "Pubmed", "id", "." ]
python
train
37.641026
ZELLMECHANIK-DRESDEN/dclab
dclab/rtdc_dataset/core.py
https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/core.py#L273-L351
def get_kde_contour(self, xax="area_um", yax="deform", xacc=None, yacc=None, kde_type="histogram", kde_kwargs={}, xscale="linear", yscale="linear"): """Evaluate the kernel density estimate for contour plots Parameters ---------- xax: str ...
[ "def", "get_kde_contour", "(", "self", ",", "xax", "=", "\"area_um\"", ",", "yax", "=", "\"deform\"", ",", "xacc", "=", "None", ",", "yacc", "=", "None", ",", "kde_type", "=", "\"histogram\"", ",", "kde_kwargs", "=", "{", "}", ",", "xscale", "=", "\"li...
Evaluate the kernel density estimate for contour plots Parameters ---------- xax: str Identifier for X axis (e.g. "area_um", "aspect", "deform") yax: str Identifier for Y axis xacc: float Contour accuracy in x direction yacc: float ...
[ "Evaluate", "the", "kernel", "density", "estimate", "for", "contour", "plots" ]
python
train
33.21519
igorcoding/asynctnt-queue
asynctnt_queue/tube.py
https://github.com/igorcoding/asynctnt-queue/blob/75719b2dd27e8314ae924aea6a7a85be8f48ecc5/asynctnt_queue/tube.py#L190-L201
async def kick(self, count): """ Kick `count` tasks from queue :param count: Tasks count to kick :return: Number of tasks actually kicked """ args = (count,) res = await self.conn.call(self.__funcs['kick'], args) if self.conn.version < (1, 7):...
[ "async", "def", "kick", "(", "self", ",", "count", ")", ":", "args", "=", "(", "count", ",", ")", "res", "=", "await", "self", ".", "conn", ".", "call", "(", "self", ".", "__funcs", "[", "'kick'", "]", ",", "args", ")", "if", "self", ".", "conn...
Kick `count` tasks from queue :param count: Tasks count to kick :return: Number of tasks actually kicked
[ "Kick", "count", "tasks", "from", "queue" ]
python
train
30.833333
aws/sagemaker-containers
src/sagemaker_containers/entry_point.py
https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/entry_point.py#L22-L89
def run(uri, user_entry_point, args, env_vars=None, wait=True, capture_error=False, runner=_runner.ProcessRunnerType, extra_opts=None): # type: (str, str, List[str], Dict[str, str], bool, bool, _runner.RunnerType, Dict[str, str]) -> None """Download, prepa...
[ "def", "run", "(", "uri", ",", "user_entry_point", ",", "args", ",", "env_vars", "=", "None", ",", "wait", "=", "True", ",", "capture_error", "=", "False", ",", "runner", "=", "_runner", ".", "ProcessRunnerType", ",", "extra_opts", "=", "None", ")", ":",...
Download, prepare and executes a compressed tar file from S3 or provided directory as an user entrypoint. Runs the user entry point, passing env_vars as environment variables and args as command arguments. If the entry point is: - A Python package: executes the packages as >>> env_vars python -m mo...
[ "Download", "prepare", "and", "executes", "a", "compressed", "tar", "file", "from", "S3", "or", "provided", "directory", "as", "an", "user", "entrypoint", ".", "Runs", "the", "user", "entry", "point", "passing", "env_vars", "as", "environment", "variables", "a...
python
train
46.044118
OpenKMIP/PyKMIP
kmip/core/objects.py
https://github.com/OpenKMIP/PyKMIP/blob/b51c5b044bd05f8c85a1d65d13a583a4d8fc1b0e/kmip/core/objects.py#L5082-L5260
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_3): """ Read the data encoding the ValidationInformation structure and decode it into its constituent parts. Args: input_buffer (stream): A data stream containing encoded object data, supporti...
[ "def", "read", "(", "self", ",", "input_buffer", ",", "kmip_version", "=", "enums", ".", "KMIPVersion", ".", "KMIP_1_3", ")", ":", "if", "kmip_version", "<", "enums", ".", "KMIPVersion", ".", "KMIP_1_3", ":", "raise", "exceptions", ".", "VersionNotSupported", ...
Read the data encoding the ValidationInformation structure and decode it into its constituent parts. Args: input_buffer (stream): A data stream containing encoded object data, supporting a read method; usually a BytearrayStream object. kmip_versio...
[ "Read", "the", "data", "encoding", "the", "ValidationInformation", "structure", "and", "decode", "it", "into", "its", "constituent", "parts", "." ]
python
test
37.837989
numenta/nupic
src/nupic/swarming/hypersearch/permutation_helpers.py
https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/permutation_helpers.py#L212-L236
def newPosition(self, globalBestPosition, rng): """See comments in base class.""" # First, update the velocity. The new velocity is given as: # v = (inertia * v) + (cogRate * r1 * (localBest-pos)) # + (socRate * r2 * (globalBest-pos)) # # where r1 and r2 are random numbers be...
[ "def", "newPosition", "(", "self", ",", "globalBestPosition", ",", "rng", ")", ":", "# First, update the velocity. The new velocity is given as:", "# v = (inertia * v) + (cogRate * r1 * (localBest-pos))", "# + (socRate * r2 * (globalBest-pos))", "#", "# where r1 and r...
See comments in base class.
[ "See", "comments", "in", "base", "class", "." ]
python
valid
40.24
The-Politico/politico-civic-election-night
electionnight/serializers/election.py
https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/serializers/election.py#L102-L104
def get_images(self, obj): """Object of images serialized by tag name.""" return {str(i.tag): i.image.url for i in obj.images.all()}
[ "def", "get_images", "(", "self", ",", "obj", ")", ":", "return", "{", "str", "(", "i", ".", "tag", ")", ":", "i", ".", "image", ".", "url", "for", "i", "in", "obj", ".", "images", ".", "all", "(", ")", "}" ]
Object of images serialized by tag name.
[ "Object", "of", "images", "serialized", "by", "tag", "name", "." ]
python
train
48.666667
ejeschke/ginga
ginga/rv/plugins/Thumbs.py
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/Thumbs.py#L630-L651
def delete_channel_cb(self, viewer, channel): """Called when a channel is deleted from the main interface. Parameter is channel (a bunch).""" chname_del = channel.name # TODO: delete thumbs for this channel! self.logger.debug("deleting thumbs for channel '%s'" % (chname_del)) ...
[ "def", "delete_channel_cb", "(", "self", ",", "viewer", ",", "channel", ")", ":", "chname_del", "=", "channel", ".", "name", "# TODO: delete thumbs for this channel!", "self", ".", "logger", ".", "debug", "(", "\"deleting thumbs for channel '%s'\"", "%", "(", "chnam...
Called when a channel is deleted from the main interface. Parameter is channel (a bunch).
[ "Called", "when", "a", "channel", "is", "deleted", "from", "the", "main", "interface", ".", "Parameter", "is", "channel", "(", "a", "bunch", ")", "." ]
python
train
41.954545
jrigden/pyPodcastParser
pyPodcastParser/Podcast.py
https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Podcast.py#L394-L401
def set_pubsubhubbub(self): """Parses pubsubhubbub and email then sets value""" self.pubsubhubbub = None atom_links = self.soup.findAll('atom:link') for atom_link in atom_links: rel = atom_link.get('rel') if rel == "hub": self.pubsubhubbub = atom_l...
[ "def", "set_pubsubhubbub", "(", "self", ")", ":", "self", ".", "pubsubhubbub", "=", "None", "atom_links", "=", "self", ".", "soup", ".", "findAll", "(", "'atom:link'", ")", "for", "atom_link", "in", "atom_links", ":", "rel", "=", "atom_link", ".", "get", ...
Parses pubsubhubbub and email then sets value
[ "Parses", "pubsubhubbub", "and", "email", "then", "sets", "value" ]
python
train
41
obulpathi/cdn-fastly-python
fastly/__init__.py
https://github.com/obulpathi/cdn-fastly-python/blob/db2564b047e8af4bce72c3b88d6c27d3d0291425/fastly/__init__.py#L709-L712
def delete_service(self, service_id): """Delete a service.""" content = self._fetch("/service/%s" % service_id, method="DELETE") return self._status(content)
[ "def", "delete_service", "(", "self", ",", "service_id", ")", ":", "content", "=", "self", ".", "_fetch", "(", "\"/service/%s\"", "%", "service_id", ",", "method", "=", "\"DELETE\"", ")", "return", "self", ".", "_status", "(", "content", ")" ]
Delete a service.
[ "Delete", "a", "service", "." ]
python
train
40
treycucco/pyebnf
pyebnf/compiler.py
https://github.com/treycucco/pyebnf/blob/3634ddabbe5d73508bcc20f4a591f86a46634e1d/pyebnf/compiler.py#L324-L346
def _ast_optree_node_to_code(self, node, **kwargs): """Convert an abstract syntax operator tree to python source code.""" opnode = node.opnode if opnode is None: return self._ast_to_code(node.operands[0]) else: operator = opnode.operator if operator is OP_ALTERNATE: return self...
[ "def", "_ast_optree_node_to_code", "(", "self", ",", "node", ",", "*", "*", "kwargs", ")", ":", "opnode", "=", "node", ".", "opnode", "if", "opnode", "is", "None", ":", "return", "self", ".", "_ast_to_code", "(", "node", ".", "operands", "[", "0", "]",...
Convert an abstract syntax operator tree to python source code.
[ "Convert", "an", "abstract", "syntax", "operator", "tree", "to", "python", "source", "code", "." ]
python
test
42.608696
locationlabs/mockredis
mockredis/script.py
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/script.py#L29-L51
def _execute_lua(self, keys, args, client): """ Sets KEYS and ARGV alongwith redis.call() function in lua globals and executes the lua redis script """ lua, lua_globals = Script._import_lua(self.load_dependencies) lua_globals.KEYS = self._python_to_lua(keys) lua_g...
[ "def", "_execute_lua", "(", "self", ",", "keys", ",", "args", ",", "client", ")", ":", "lua", ",", "lua_globals", "=", "Script", ".", "_import_lua", "(", "self", ".", "load_dependencies", ")", "lua_globals", ".", "KEYS", "=", "self", ".", "_python_to_lua",...
Sets KEYS and ARGV alongwith redis.call() function in lua globals and executes the lua redis script
[ "Sets", "KEYS", "and", "ARGV", "alongwith", "redis", ".", "call", "()", "function", "in", "lua", "globals", "and", "executes", "the", "lua", "redis", "script" ]
python
train
43.086957
JensRantil/rewind
rewind/server/eventstores.py
https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/eventstores.py#L981-L997
def add_event(self, key, event): """Add an event and its corresponding key to the store.""" if self.key_exists(key): # This check might actually also be done further up in the chain # (read: SQLiteEventStore). Could potentially be removed if it # requires a lot of pro...
[ "def", "add_event", "(", "self", ",", "key", ",", "event", ")", ":", "if", "self", ".", "key_exists", "(", "key", ")", ":", "# This check might actually also be done further up in the chain", "# (read: SQLiteEventStore). Could potentially be removed if it", "# requires a lot ...
Add an event and its corresponding key to the store.
[ "Add", "an", "event", "and", "its", "corresponding", "key", "to", "the", "store", "." ]
python
train
45.764706
wal-e/wal-e
wal_e/log_help.py
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/log_help.py#L118-L129
def get_syslog_facility(): """Get syslog facility from ENV var""" facil = os.getenv('WALE_SYSLOG_FACILITY', 'user') valid_facility = True try: facility = handlers.SysLogHandler.facility_names[facil.lower()] except KeyError: valid_facility = False facility = handlers.SysLogHa...
[ "def", "get_syslog_facility", "(", ")", ":", "facil", "=", "os", ".", "getenv", "(", "'WALE_SYSLOG_FACILITY'", ",", "'user'", ")", "valid_facility", "=", "True", "try", ":", "facility", "=", "handlers", ".", "SysLogHandler", ".", "facility_names", "[", "facil"...
Get syslog facility from ENV var
[ "Get", "syslog", "facility", "from", "ENV", "var" ]
python
train
30
HEPData/hepdata-converter
hepdata_converter/writers/csv_writer.py
https://github.com/HEPData/hepdata-converter/blob/354271448980efba86f2f3d27b99d818e75fd90d/hepdata_converter/writers/csv_writer.py#L82-L102
def _write_packed_data(self, data_out, table): """This is kind of legacy function - this functionality may be useful for some people, so even though now the default of writing CSV is writing unpacked data (divided by independent variable) this method is still available and accessible if ```pack`...
[ "def", "_write_packed_data", "(", "self", ",", "data_out", ",", "table", ")", ":", "headers", "=", "[", "]", "data", "=", "[", "]", "qualifiers_marks", "=", "[", "]", "qualifiers", "=", "{", "}", "self", ".", "_extract_independent_variables", "(", "table",...
This is kind of legacy function - this functionality may be useful for some people, so even though now the default of writing CSV is writing unpacked data (divided by independent variable) this method is still available and accessible if ```pack``` flag is specified in Writer's options :param o...
[ "This", "is", "kind", "of", "legacy", "function", "-", "this", "functionality", "may", "be", "useful", "for", "some", "people", "so", "even", "though", "now", "the", "default", "of", "writing", "CSV", "is", "writing", "unpacked", "data", "(", "divided", "b...
python
train
47.428571
materialsproject/pymatgen
pymatgen/analysis/graphs.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/graphs.py#L467-L508
def break_edge(self, from_index, to_index, to_jimage=None, allow_reverse=False): """ Remove an edge from the StructureGraph. If no image is given, this method will fail. :param from_index: int :param to_index: int :param to_jimage: tuple :param allow_reverse: If allow_re...
[ "def", "break_edge", "(", "self", ",", "from_index", ",", "to_index", ",", "to_jimage", "=", "None", ",", "allow_reverse", "=", "False", ")", ":", "# ensure that edge exists before attempting to remove it", "existing_edges", "=", "self", ".", "graph", ".", "get_edge...
Remove an edge from the StructureGraph. If no image is given, this method will fail. :param from_index: int :param to_index: int :param to_jimage: tuple :param allow_reverse: If allow_reverse is True, then break_edge will attempt to break both (from_index, to_index) and, failing...
[ "Remove", "an", "edge", "from", "the", "StructureGraph", ".", "If", "no", "image", "is", "given", "this", "method", "will", "fail", "." ]
python
train
39.285714
koszullab/metaTOR
metator/scripts/hicstuff.py
https://github.com/koszullab/metaTOR/blob/0c1203d1dffedfa5ea380c0335b4baa9cfb7e89a/metator/scripts/hicstuff.py#L1514-L1533
def split_matrix(M, contigs): """Split multiple chromosome matrix Split a labeled matrix with multiple chromosomes into unlabeled single-chromosome matrices. Inter chromosomal contacts are discarded. Parameters ---------- M : array_like The multiple chromosome matrix to be split ...
[ "def", "split_matrix", "(", "M", ",", "contigs", ")", ":", "index", "=", "0", "for", "_", ",", "chunk", "in", "itertools", ".", "groubpy", "(", "contigs", ")", ":", "l", "=", "len", "(", "chunk", ")", "yield", "M", "[", "index", ":", "index", "+"...
Split multiple chromosome matrix Split a labeled matrix with multiple chromosomes into unlabeled single-chromosome matrices. Inter chromosomal contacts are discarded. Parameters ---------- M : array_like The multiple chromosome matrix to be split contigs : list or array_like ...
[ "Split", "multiple", "chromosome", "matrix" ]
python
train
26.65
jic-dtool/dtoolcore
dtoolcore/__init__.py
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/__init__.py#L43-L47
def _is_dataset(uri, config_path): """Helper function for determining if a URI is a dataset.""" uri = dtoolcore.utils.sanitise_uri(uri) storage_broker = _get_storage_broker(uri, config_path) return storage_broker.has_admin_metadata()
[ "def", "_is_dataset", "(", "uri", ",", "config_path", ")", ":", "uri", "=", "dtoolcore", ".", "utils", ".", "sanitise_uri", "(", "uri", ")", "storage_broker", "=", "_get_storage_broker", "(", "uri", ",", "config_path", ")", "return", "storage_broker", ".", "...
Helper function for determining if a URI is a dataset.
[ "Helper", "function", "for", "determining", "if", "a", "URI", "is", "a", "dataset", "." ]
python
train
49
craffel/mir_eval
mir_eval/util.py
https://github.com/craffel/mir_eval/blob/f41c8dafaea04b411252a516d1965af43c7d531b/mir_eval/util.py#L758-L780
def validate_intervals(intervals): """Checks that an (n, 2) interval ndarray is well-formed, and raises errors if not. Parameters ---------- intervals : np.ndarray, shape=(n, 2) Array of interval start/end locations. """ # Validate interval shape if intervals.ndim != 2 or inte...
[ "def", "validate_intervals", "(", "intervals", ")", ":", "# Validate interval shape", "if", "intervals", ".", "ndim", "!=", "2", "or", "intervals", ".", "shape", "[", "1", "]", "!=", "2", ":", "raise", "ValueError", "(", "'Intervals should be n-by-2 numpy ndarray,...
Checks that an (n, 2) interval ndarray is well-formed, and raises errors if not. Parameters ---------- intervals : np.ndarray, shape=(n, 2) Array of interval start/end locations.
[ "Checks", "that", "an", "(", "n", "2", ")", "interval", "ndarray", "is", "well", "-", "formed", "and", "raises", "errors", "if", "not", "." ]
python
train
33.521739
IdentityPython/pysaml2
src/saml2/sigver.py
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/sigver.py#L1855-L1870
def pre_encrypt_assertion(response): """ Move the assertion to within a encrypted_assertion :param response: The response with one assertion :return: The response but now with the assertion within an encrypted_assertion. """ assertion = response.assertion response.assertion = None ...
[ "def", "pre_encrypt_assertion", "(", "response", ")", ":", "assertion", "=", "response", ".", "assertion", "response", ".", "assertion", "=", "None", "response", ".", "encrypted_assertion", "=", "EncryptedAssertion", "(", ")", "if", "assertion", "is", "not", "No...
Move the assertion to within a encrypted_assertion :param response: The response with one assertion :return: The response but now with the assertion within an encrypted_assertion.
[ "Move", "the", "assertion", "to", "within", "a", "encrypted_assertion", ":", "param", "response", ":", "The", "response", "with", "one", "assertion", ":", "return", ":", "The", "response", "but", "now", "with", "the", "assertion", "within", "an", "encrypted_as...
python
train
38.1875
mitsei/dlkit
dlkit/json_/commenting/managers.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/commenting/managers.py#L386-L400
def get_comment_book_session(self): """Gets the session for retrieving comment to book mappings. return: (osid.commenting.CommentBookSession) - a ``CommentBookSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_comment_book()...
[ "def", "get_comment_book_session", "(", "self", ")", ":", "if", "not", "self", ".", "supports_comment_book", "(", ")", ":", "raise", "errors", ".", "Unimplemented", "(", ")", "# pylint: disable=no-member", "return", "sessions", ".", "CommentBookSession", "(", "run...
Gets the session for retrieving comment to book mappings. return: (osid.commenting.CommentBookSession) - a ``CommentBookSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_comment_book()`` is ``false`` *compliance: optional -...
[ "Gets", "the", "session", "for", "retrieving", "comment", "to", "book", "mappings", "." ]
python
train
42.666667
OldhamMade/PySO8601
PySO8601/utility.py
https://github.com/OldhamMade/PySO8601/blob/b7d3b3cb3ed3e12eb2a21caa26a3abeab3c96fe4/PySO8601/utility.py#L28-L52
def _timedelta_from_elements(elements): """ Return a timedelta from a dict of date elements. Accepts a dict containing any of the following: - years - months - days - hours - minutes - seconds If years and/or months are provided, it will use a naive calcuation o...
[ "def", "_timedelta_from_elements", "(", "elements", ")", ":", "days", "=", "sum", "(", "(", "elements", "[", "'days'", "]", ",", "_months_to_days", "(", "elements", ".", "get", "(", "'months'", ",", "0", ")", ")", ",", "_years_to_days", "(", "elements", ...
Return a timedelta from a dict of date elements. Accepts a dict containing any of the following: - years - months - days - hours - minutes - seconds If years and/or months are provided, it will use a naive calcuation of 365 days in a year and 30 days in a month.
[ "Return", "a", "timedelta", "from", "a", "dict", "of", "date", "elements", "." ]
python
train
29.4
softlayer/softlayer-python
SoftLayer/managers/user.py
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/user.py#L171-L197
def get_events(self, user_id, start_date=None): """Gets the event log for a specific user, default start_date is 30 days ago :param int id: User id to view :param string start_date: "%Y-%m-%dT%H:%M:%s.0000-06:00" is the full formatted string. The Timezone part ...
[ "def", "get_events", "(", "self", ",", "user_id", ",", "start_date", "=", "None", ")", ":", "if", "start_date", "is", "None", ":", "date_object", "=", "datetime", ".", "datetime", ".", "today", "(", ")", "-", "datetime", ".", "timedelta", "(", "days", ...
Gets the event log for a specific user, default start_date is 30 days ago :param int id: User id to view :param string start_date: "%Y-%m-%dT%H:%M:%s.0000-06:00" is the full formatted string. The Timezone part has to be HH:MM, notice the : there. :returns: http...
[ "Gets", "the", "event", "log", "for", "a", "specific", "user", "default", "start_date", "is", "30", "days", "ago" ]
python
train
39.962963
cloud9ers/gurumate
environment/lib/python2.7/site-packages/IPython/frontend/html/notebook/kernelmanager.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/html/notebook/kernelmanager.py#L329-L332
def create_shell_stream(self, kernel_id): """Create a new shell stream.""" self._check_kernel_id(kernel_id) return super(MappingKernelManager, self).create_shell_stream(kernel_id)
[ "def", "create_shell_stream", "(", "self", ",", "kernel_id", ")", ":", "self", ".", "_check_kernel_id", "(", "kernel_id", ")", "return", "super", "(", "MappingKernelManager", ",", "self", ")", ".", "create_shell_stream", "(", "kernel_id", ")" ]
Create a new shell stream.
[ "Create", "a", "new", "shell", "stream", "." ]
python
test
50
d0c-s4vage/pfp
pfp/bitwrap.py
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/bitwrap.py#L125-L143
def read_bits(self, num): """Read ``num`` number of bits from the stream :num: number of bits to read :returns: a list of ``num`` bits, or an empty list if EOF has been reached """ if num > len(self._bits): needed = num - len(self._bits) num_bytes = int(m...
[ "def", "read_bits", "(", "self", ",", "num", ")", ":", "if", "num", ">", "len", "(", "self", ".", "_bits", ")", ":", "needed", "=", "num", "-", "len", "(", "self", ".", "_bits", ")", "num_bytes", "=", "int", "(", "math", ".", "ceil", "(", "need...
Read ``num`` number of bits from the stream :num: number of bits to read :returns: a list of ``num`` bits, or an empty list if EOF has been reached
[ "Read", "num", "number", "of", "bits", "from", "the", "stream" ]
python
train
31.894737
twisted/mantissa
xmantissa/ampserver.py
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/ampserver.py#L64-L74
def generateOneTimePad(self, userStore): """ Generate a pad which can be used to authenticate via AMP. This pad will expire in L{ONE_TIME_PAD_DURATION} seconds. """ pad = secureRandom(16).encode('hex') self._oneTimePads[pad] = userStore.idInParent def expirePad()...
[ "def", "generateOneTimePad", "(", "self", ",", "userStore", ")", ":", "pad", "=", "secureRandom", "(", "16", ")", ".", "encode", "(", "'hex'", ")", "self", ".", "_oneTimePads", "[", "pad", "]", "=", "userStore", ".", "idInParent", "def", "expirePad", "("...
Generate a pad which can be used to authenticate via AMP. This pad will expire in L{ONE_TIME_PAD_DURATION} seconds.
[ "Generate", "a", "pad", "which", "can", "be", "used", "to", "authenticate", "via", "AMP", ".", "This", "pad", "will", "expire", "in", "L", "{", "ONE_TIME_PAD_DURATION", "}", "seconds", "." ]
python
train
39.727273
mitsei/dlkit
dlkit/json_/repository/sessions.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/repository/sessions.py#L2765-L2786
def get_compositions_by_asset(self, asset_id): """Gets a list of compositions including the given asset. arg: asset_id (osid.id.Id): ``Id`` of the ``Asset`` return: (osid.repository.CompositionList) - the returned ``Composition list`` raise: NotFound - ``asset_id`` i...
[ "def", "get_compositions_by_asset", "(", "self", ",", "asset_id", ")", ":", "# Implemented from template for", "# osid.repository.AssetCompositionSession.get_compositions_by_asset", "collection", "=", "JSONClientValidated", "(", "'repository'", ",", "collection", "=", "'Compositi...
Gets a list of compositions including the given asset. arg: asset_id (osid.id.Id): ``Id`` of the ``Asset`` return: (osid.repository.CompositionList) - the returned ``Composition list`` raise: NotFound - ``asset_id`` is not found raise: NullArgument - ``asset_id`` is...
[ "Gets", "a", "list", "of", "compositions", "including", "the", "given", "asset", "." ]
python
train
49.681818
coinbase/coinbase-python
coinbase/wallet/client.py
https://github.com/coinbase/coinbase-python/blob/497c28158f529e8c7d0228521b4386a890baf088/coinbase/wallet/client.py#L244-L247
def get_time(self, **params): """https://developers.coinbase.com/api/v2#time""" response = self._get('v2', 'time', params=params) return self._make_api_object(response, APIObject)
[ "def", "get_time", "(", "self", ",", "*", "*", "params", ")", ":", "response", "=", "self", ".", "_get", "(", "'v2'", ",", "'time'", ",", "params", "=", "params", ")", "return", "self", ".", "_make_api_object", "(", "response", ",", "APIObject", ")" ]
https://developers.coinbase.com/api/v2#time
[ "https", ":", "//", "developers", ".", "coinbase", ".", "com", "/", "api", "/", "v2#time" ]
python
train
50
StackStorm/pybind
pybind/nos/v6_0_2f/rbridge_id/secpolicy/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v6_0_2f/rbridge_id/secpolicy/__init__.py#L133-L156
def _set_active_policy(self, v, load=False): """ Setter method for active_policy, mapped from YANG variable /rbridge_id/secpolicy/active_policy (container) If this variable is read-only (config: false) in the source YANG file, then _set_active_policy is considered as a private method. Backends looki...
[ "def", "_set_active_policy", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "...
Setter method for active_policy, mapped from YANG variable /rbridge_id/secpolicy/active_policy (container) If this variable is read-only (config: false) in the source YANG file, then _set_active_policy is considered as a private method. Backends looking to populate this variable should do so via calling...
[ "Setter", "method", "for", "active_policy", "mapped", "from", "YANG", "variable", "/", "rbridge_id", "/", "secpolicy", "/", "active_policy", "(", "container", ")", "If", "this", "variable", "is", "read", "-", "only", "(", "config", ":", "false", ")", "in", ...
python
train
74.541667
charnley/rmsd
rmsd/calculate_rmsd.py
https://github.com/charnley/rmsd/blob/cd8af499fb63529a1b5b1f880fdb2dab2731544a/rmsd/calculate_rmsd.py#L222-L247
def quaternion_rotate(X, Y): """ Calculate the rotation Parameters ---------- X : array (N,D) matrix, where N is points and D is dimension. Y: array (N,D) matrix, where N is points and D is dimension. Returns ------- rot : matrix Rotation matrix (D,D) ""...
[ "def", "quaternion_rotate", "(", "X", ",", "Y", ")", ":", "N", "=", "X", ".", "shape", "[", "0", "]", "W", "=", "np", ".", "asarray", "(", "[", "makeW", "(", "*", "Y", "[", "k", "]", ")", "for", "k", "in", "range", "(", "N", ")", "]", ")"...
Calculate the rotation Parameters ---------- X : array (N,D) matrix, where N is points and D is dimension. Y: array (N,D) matrix, where N is points and D is dimension. Returns ------- rot : matrix Rotation matrix (D,D)
[ "Calculate", "the", "rotation" ]
python
train
26.923077
gautammishra/lyft-rides-python-sdk
lyft_rides/request.py
https://github.com/gautammishra/lyft-rides-python-sdk/blob/b6d96a0fceaf7dc3425153c418a8e25c57803431/lyft_rides/request.py#L131-L160
def _build_headers(self, method, auth_session): """Create headers for the request. Parameters method (str) HTTP method (e.g. 'POST'). auth_session (Session) The Session object containing OAuth 2.0 credentials. Returns headers (d...
[ "def", "_build_headers", "(", "self", ",", "method", ",", "auth_session", ")", ":", "token_type", "=", "auth_session", ".", "token_type", "token", "=", "auth_session", ".", "oauth2credential", ".", "access_token", "if", "not", "self", ".", "_authorization_headers_...
Create headers for the request. Parameters method (str) HTTP method (e.g. 'POST'). auth_session (Session) The Session object containing OAuth 2.0 credentials. Returns headers (dict) Dictionary of access headers to attach...
[ "Create", "headers", "for", "the", "request", ".", "Parameters", "method", "(", "str", ")", "HTTP", "method", "(", "e", ".", "g", ".", "POST", ")", ".", "auth_session", "(", "Session", ")", "The", "Session", "object", "containing", "OAuth", "2", ".", "...
python
train
32.033333
NickMonzillo/SmartCloud
SmartCloud/__init__.py
https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/__init__.py#L23-L27
def plot_word(self,position): '''Blits a rendered word on to the main display surface''' posrectangle = pygame.Rect(position,self.word_size) self.used_pos.append(posrectangle) self.cloud.blit(self.rendered_word,position)
[ "def", "plot_word", "(", "self", ",", "position", ")", ":", "posrectangle", "=", "pygame", ".", "Rect", "(", "position", ",", "self", ".", "word_size", ")", "self", ".", "used_pos", ".", "append", "(", "posrectangle", ")", "self", ".", "cloud", ".", "b...
Blits a rendered word on to the main display surface
[ "Blits", "a", "rendered", "word", "on", "to", "the", "main", "display", "surface" ]
python
train
49.6
pymupdf/PyMuPDF
fitz/fitz.py
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L4147-L4154
def rect(self): """rect(self) -> PyObject *""" CheckParent(self) val = _fitz.Link_rect(self) val = Rect(val) return val
[ "def", "rect", "(", "self", ")", ":", "CheckParent", "(", "self", ")", "val", "=", "_fitz", ".", "Link_rect", "(", "self", ")", "val", "=", "Rect", "(", "val", ")", "return", "val" ]
rect(self) -> PyObject *
[ "rect", "(", "self", ")", "-", ">", "PyObject", "*" ]
python
train
19.25
BerkeleyAutomation/perception
perception/image.py
https://github.com/BerkeleyAutomation/perception/blob/03d9b37dd6b66896cdfe173905c9413c8c3c5df6/perception/image.py#L1306-L1346
def segment_kmeans(self, rgb_weight, num_clusters, hue_weight=0.0): """ Segment a color image using KMeans based on spatial and color distances. Black pixels will automatically be assigned to their own 'background' cluster. Parameters ---------- rgb_weight : float ...
[ "def", "segment_kmeans", "(", "self", ",", "rgb_weight", ",", "num_clusters", ",", "hue_weight", "=", "0.0", ")", ":", "# form features array", "label_offset", "=", "1", "nonzero_px", "=", "np", ".", "where", "(", "self", ".", "data", "!=", "0.0", ")", "no...
Segment a color image using KMeans based on spatial and color distances. Black pixels will automatically be assigned to their own 'background' cluster. Parameters ---------- rgb_weight : float weighting of RGB distance relative to spatial and hue distance num_cluster...
[ "Segment", "a", "color", "image", "using", "KMeans", "based", "on", "spatial", "and", "color", "distances", ".", "Black", "pixels", "will", "automatically", "be", "assigned", "to", "their", "own", "background", "cluster", "." ]
python
train
39.463415
eirannejad/Revit-Journal-Maker
rjm/__init__.py
https://github.com/eirannejad/Revit-Journal-Maker/blob/09a4f27da6d183f63a2c93ed99dca8a8590d5241/rjm/__init__.py#L326-L335
def import_family(self, rfa_file): """Append a import family entry to the journal. This instructs Revit to import a family into the opened model. Args: rfa_file (str): full path of the family file """ self._add_entry(templates.IMPORT_FAMILY ...
[ "def", "import_family", "(", "self", ",", "rfa_file", ")", ":", "self", ".", "_add_entry", "(", "templates", ".", "IMPORT_FAMILY", ".", "format", "(", "family_file", "=", "rfa_file", ")", ")" ]
Append a import family entry to the journal. This instructs Revit to import a family into the opened model. Args: rfa_file (str): full path of the family file
[ "Append", "a", "import", "family", "entry", "to", "the", "journal", "." ]
python
train
34.9
naphatkrit/click-extensions
click_extensions/utils.py
https://github.com/naphatkrit/click-extensions/blob/80fc1a70419fdaf00833649677a9031bdbf8c47b/click_extensions/utils.py#L4-L27
def echo_with_markers(text, marker='=', marker_color='blue', text_color=None): """Print a text to the screen with markers surrounding it. The output looks like: ======== text ======== with marker='=' right now. In the event that the terminal window is too small, the text is printed without mar...
[ "def", "echo_with_markers", "(", "text", ",", "marker", "=", "'='", ",", "marker_color", "=", "'blue'", ",", "text_color", "=", "None", ")", ":", "text", "=", "' '", "+", "text", "+", "' '", "width", ",", "_", "=", "click", ".", "get_terminal_size", "(...
Print a text to the screen with markers surrounding it. The output looks like: ======== text ======== with marker='=' right now. In the event that the terminal window is too small, the text is printed without markers. :param str text: the text to echo :param str marker: the marker to surr...
[ "Print", "a", "text", "to", "the", "screen", "with", "markers", "surrounding", "it", "." ]
python
train
43.291667
zhanglab/psamm
psamm/importer.py
https://github.com/zhanglab/psamm/blob/dc427848c4f9d109ca590f0afa024c63b685b3f4/psamm/importer.py#L703-L813
def main_bigg(args=None, urlopen=urlopen): """Entry point for BiGG import program. If the ``args`` are provided, these should be a list of strings that will be used instead of ``sys.argv[1:]``. This is mostly useful for testing. """ parser = argparse.ArgumentParser( description='Import from...
[ "def", "main_bigg", "(", "args", "=", "None", ",", "urlopen", "=", "urlopen", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Import from BiGG database'", ")", "parser", ".", "add_argument", "(", "'--dest'", ",", "metavar...
Entry point for BiGG import program. If the ``args`` are provided, these should be a list of strings that will be used instead of ``sys.argv[1:]``. This is mostly useful for testing.
[ "Entry", "point", "for", "BiGG", "import", "program", "." ]
python
train
40.774775
spacetelescope/stsci.tools
lib/stsci/tools/capable.py
https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/capable.py#L89-L106
def get_dc_owner(raises, mask_if_self): """ Convenience function to return owner of /dev/console. If raises is True, this raises an exception on any error. If not, it returns any error string as the owner name. If owner is self, and if mask_if_self, returns "<self>".""" try: from pwd import ...
[ "def", "get_dc_owner", "(", "raises", ",", "mask_if_self", ")", ":", "try", ":", "from", "pwd", "import", "getpwuid", "owner_uid", "=", "os", ".", "stat", "(", "'/dev/console'", ")", ".", "st_uid", "self_uid", "=", "os", ".", "getuid", "(", ")", "if", ...
Convenience function to return owner of /dev/console. If raises is True, this raises an exception on any error. If not, it returns any error string as the owner name. If owner is self, and if mask_if_self, returns "<self>".
[ "Convenience", "function", "to", "return", "owner", "of", "/", "dev", "/", "console", ".", "If", "raises", "is", "True", "this", "raises", "an", "exception", "on", "any", "error", ".", "If", "not", "it", "returns", "any", "error", "string", "as", "the", ...
python
train
36.333333
BD2KGenomics/toil-scripts
src/toil_scripts/bwa_alignment/old_alignment_script/batch_align.py
https://github.com/BD2KGenomics/toil-scripts/blob/f878d863defcdccaabb7fe06f991451b7a198fb7/src/toil_scripts/bwa_alignment/old_alignment_script/batch_align.py#L164-L177
def spawn_batch_jobs(job, shared_ids, input_args): """ Spawns an alignment job for every sample in the input configuration file """ samples = [] config = input_args['config'] with open(config, 'r') as f_in: for line in f_in: line = line.strip().split(',') uuid = l...
[ "def", "spawn_batch_jobs", "(", "job", ",", "shared_ids", ",", "input_args", ")", ":", "samples", "=", "[", "]", "config", "=", "input_args", "[", "'config'", "]", "with", "open", "(", "config", ",", "'r'", ")", "as", "f_in", ":", "for", "line", "in", ...
Spawns an alignment job for every sample in the input configuration file
[ "Spawns", "an", "alignment", "job", "for", "every", "sample", "in", "the", "input", "configuration", "file" ]
python
train
36.928571
senaite/senaite.core
bika/lims/browser/fields/aranalysesfield.py
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/fields/aranalysesfield.py#L255-L285
def _to_service(self, thing): """Convert to Analysis Service :param thing: UID/Catalog Brain/Object/Something :returns: Analysis Service object or None """ # Convert UIDs to objects if api.is_uid(thing): thing = api.get_object_by_uid(thing, None) # ...
[ "def", "_to_service", "(", "self", ",", "thing", ")", ":", "# Convert UIDs to objects", "if", "api", ".", "is_uid", "(", "thing", ")", ":", "thing", "=", "api", ".", "get_object_by_uid", "(", "thing", ",", "None", ")", "# Bail out if the thing is not a valid obj...
Convert to Analysis Service :param thing: UID/Catalog Brain/Object/Something :returns: Analysis Service object or None
[ "Convert", "to", "Analysis", "Service" ]
python
train
33.387097
decryptus/sonicprobe
sonicprobe/libs/xys.py
https://github.com/decryptus/sonicprobe/blob/72f73f3a40d2982d79ad68686e36aa31d94b76f8/sonicprobe/libs/xys.py#L350-L374
def add_parameterized_validator(param_validator, base_tag, tag_prefix=None): """ Add a parameterized validator for the given tag prefix. If tag_prefix is None, it is automatically constructed as u'!~%s(' % param_validator.__name__ A parametrized validator is a function that accepts a document node ...
[ "def", "add_parameterized_validator", "(", "param_validator", ",", "base_tag", ",", "tag_prefix", "=", "None", ")", ":", "# pylint: disable-msg=C0111,W0621", "if", "not", "tag_prefix", ":", "tag_prefix", "=", "u'!~%s('", "%", "param_validator", ".", "__name__", "def",...
Add a parameterized validator for the given tag prefix. If tag_prefix is None, it is automatically constructed as u'!~%s(' % param_validator.__name__ A parametrized validator is a function that accepts a document node (in the form of a Python object), a schema node (also a Python object), and other ...
[ "Add", "a", "parameterized", "validator", "for", "the", "given", "tag", "prefix", ".", "If", "tag_prefix", "is", "None", "it", "is", "automatically", "constructed", "as", "u", "!~%s", "(", "%", "param_validator", ".", "__name__", "A", "parametrized", "validato...
python
train
51.08
bram85/topydo
topydo/lib/RelativeDate.py
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/RelativeDate.py#L106-L152
def relative_date_to_date(p_date, p_offset=None): """ Transforms a relative date into a date object. The following formats are understood: * [0-9][dwmy] * 'yesterday', 'today' or 'tomorrow' * days of the week (in full or abbreviated) """ result = None p_date = p_date.lower() p_...
[ "def", "relative_date_to_date", "(", "p_date", ",", "p_offset", "=", "None", ")", ":", "result", "=", "None", "p_date", "=", "p_date", ".", "lower", "(", ")", "p_offset", "=", "p_offset", "or", "date", ".", "today", "(", ")", "relative", "=", "re", "."...
Transforms a relative date into a date object. The following formats are understood: * [0-9][dwmy] * 'yesterday', 'today' or 'tomorrow' * days of the week (in full or abbreviated)
[ "Transforms", "a", "relative", "date", "into", "a", "date", "object", "." ]
python
train
27.276596
allanlei/django-argparse-command
argcmd/management/base.py
https://github.com/allanlei/django-argparse-command/blob/27ea77e1dd0cf2f0567223735762a5ebd14fdaef/argcmd/management/base.py#L26-L36
def run_from_argv(self, argv): """ Set up any environment changes requested (e.g., Python path and Django settings), then run this command. """ parser = self.create_parser(argv[0], argv[1]) self.arguments = parser.parse_args(argv[2:]) handle_default_options(self....
[ "def", "run_from_argv", "(", "self", ",", "argv", ")", ":", "parser", "=", "self", ".", "create_parser", "(", "argv", "[", "0", "]", ",", "argv", "[", "1", "]", ")", "self", ".", "arguments", "=", "parser", ".", "parse_args", "(", "argv", "[", "2",...
Set up any environment changes requested (e.g., Python path and Django settings), then run this command.
[ "Set", "up", "any", "environment", "changes", "requested", "(", "e", ".", "g", ".", "Python", "path", "and", "Django", "settings", ")", "then", "run", "this", "command", "." ]
python
test
35.545455
bjmorgan/lattice_mc
lattice_mc/simulation.py
https://github.com/bjmorgan/lattice_mc/blob/7fa7be85f2f23a2d8dfd0830ecdb89d0dbf2bfd5/lattice_mc/simulation.py#L182-L201
def old_tracer_correlation( self ): """ Deprecated tracer correlation factor for this simulation. Args: None Returns: (Float): The tracer correlation factor, f. Notes: This function assumes that the jump distance between sites has ...
[ "def", "old_tracer_correlation", "(", "self", ")", ":", "if", "self", ".", "has_run", ":", "return", "self", ".", "atoms", ".", "sum_dr_squared", "(", ")", "/", "float", "(", "self", ".", "number_of_jumps", ")", "else", ":", "return", "None" ]
Deprecated tracer correlation factor for this simulation. Args: None Returns: (Float): The tracer correlation factor, f. Notes: This function assumes that the jump distance between sites has been normalised to a=1. If the jump distance is...
[ "Deprecated", "tracer", "correlation", "factor", "for", "this", "simulation", ".", "Args", ":", "None" ]
python
train
33.05
brunato/lograptor
lograptor/timedate.py
https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/timedate.py#L181-L203
def strftimegen(start_dt, end_dt): """ Return a generator function for datetime format strings. The generator produce a day-by-day sequence starting from the first datetime to the second datetime argument. """ if start_dt > end_dt: raise ValueError("the start datetime is after the end da...
[ "def", "strftimegen", "(", "start_dt", ",", "end_dt", ")", ":", "if", "start_dt", ">", "end_dt", ":", "raise", "ValueError", "(", "\"the start datetime is after the end datetime: (%r,%r)\"", "%", "(", "start_dt", ",", "end_dt", ")", ")", "def", "iterftime", "(", ...
Return a generator function for datetime format strings. The generator produce a day-by-day sequence starting from the first datetime to the second datetime argument.
[ "Return", "a", "generator", "function", "for", "datetime", "format", "strings", ".", "The", "generator", "produce", "a", "day", "-", "by", "-", "day", "sequence", "starting", "from", "the", "first", "datetime", "to", "the", "second", "datetime", "argument", ...
python
train
35.73913
mitsei/dlkit
dlkit/json_/assessment/sessions.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/assessment/sessions.py#L4804-L4821
def get_assessments_by_banks(self, bank_ids): """Gets the list of ``Assessments`` corresponding to a list of ``Banks``. arg: bank_ids (osid.id.IdList): list of bank ``Ids`` return: (osid.assessment.AssessmentList) - list of assessments raise: NullArgument - ``bank_ids`` is ``null`` ...
[ "def", "get_assessments_by_banks", "(", "self", ",", "bank_ids", ")", ":", "# Implemented from template for", "# osid.resource.ResourceBinSession.get_resources_by_bins", "assessment_list", "=", "[", "]", "for", "bank_id", "in", "bank_ids", ":", "assessment_list", "+=", "lis...
Gets the list of ``Assessments`` corresponding to a list of ``Banks``. arg: bank_ids (osid.id.IdList): list of bank ``Ids`` return: (osid.assessment.AssessmentList) - list of assessments raise: NullArgument - ``bank_ids`` is ``null`` raise: OperationFailed - unable to complete requ...
[ "Gets", "the", "list", "of", "Assessments", "corresponding", "to", "a", "list", "of", "Banks", "." ]
python
train
45.777778
gabstopper/smc-python
smc/core/node.py
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/node.py#L347-L360
def go_standby(self, comment=None): """ Executes a Go-Standby operation on the specified node. To get the status of the current node/s, run :func:`status` :param str comment: optional comment to audit :raises NodeCommandFailed: engine cannot go standby :return: None ...
[ "def", "go_standby", "(", "self", ",", "comment", "=", "None", ")", ":", "self", ".", "make_request", "(", "NodeCommandFailed", ",", "method", "=", "'update'", ",", "resource", "=", "'go_standby'", ",", "params", "=", "{", "'comment'", ":", "comment", "}",...
Executes a Go-Standby operation on the specified node. To get the status of the current node/s, run :func:`status` :param str comment: optional comment to audit :raises NodeCommandFailed: engine cannot go standby :return: None
[ "Executes", "a", "Go", "-", "Standby", "operation", "on", "the", "specified", "node", ".", "To", "get", "the", "status", "of", "the", "current", "node", "/", "s", "run", ":", "func", ":", "status" ]
python
train
34.071429
cloud9ers/gurumate
environment/lib/python2.7/site-packages/IPython/core/history.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/history.py#L203-L228
def get_session_info(self, session=0): """get info about a session Parameters ---------- session : int Session number to retrieve. The current session is 0, and negative numbers count back from current session, so -1 is previous session. Returns ...
[ "def", "get_session_info", "(", "self", ",", "session", "=", "0", ")", ":", "if", "session", "<=", "0", ":", "session", "+=", "self", ".", "session_number", "query", "=", "\"SELECT * from sessions where session == ?\"", "return", "self", ".", "db", ".", "execu...
get info about a session Parameters ---------- session : int Session number to retrieve. The current session is 0, and negative numbers count back from current session, so -1 is previous session. Returns ------- (session_id [int], start [dateti...
[ "get", "info", "about", "a", "session" ]
python
test
27.692308
basecrm/basecrm-python
basecrm/services.py
https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L186-L200
def retrieve(self, id) : """ Retrieve a single contact Returns a single contact available to the user, according to the unique contact ID provided If the specified contact does not exist, the request will return an error :calls: ``get /contacts/{id}`` :param int id: Uni...
[ "def", "retrieve", "(", "self", ",", "id", ")", ":", "_", ",", "_", ",", "contact", "=", "self", ".", "http_client", ".", "get", "(", "\"/contacts/{id}\"", ".", "format", "(", "id", "=", "id", ")", ")", "return", "contact" ]
Retrieve a single contact Returns a single contact available to the user, according to the unique contact ID provided If the specified contact does not exist, the request will return an error :calls: ``get /contacts/{id}`` :param int id: Unique identifier of a Contact. :return:...
[ "Retrieve", "a", "single", "contact" ]
python
train
37.6
PyAr/fades
fades/cache.py
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/fades/cache.py#L148-L163
def _select(self, current_venvs, requirements=None, interpreter='', uuid='', options=None): """Select which venv satisfy the received requirements.""" if uuid: logger.debug("Searching a venv by uuid: %s", uuid) venv = self._match_by_uuid(current_venvs, uuid) else: ...
[ "def", "_select", "(", "self", ",", "current_venvs", ",", "requirements", "=", "None", ",", "interpreter", "=", "''", ",", "uuid", "=", "''", ",", "options", "=", "None", ")", ":", "if", "uuid", ":", "logger", ".", "debug", "(", "\"Searching a venv by uu...
Select which venv satisfy the received requirements.
[ "Select", "which", "venv", "satisfy", "the", "received", "requirements", "." ]
python
train
45.5
scidash/sciunit
sciunit/models/backends.py
https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/models/backends.py#L95-L102
def set_disk_cache(self, results, key=None): """Store result in disk cache with key matching model state.""" if not getattr(self, 'disk_cache_location', False): self.init_disk_cache() disk_cache = shelve.open(self.disk_cache_location) key = self.model.hash if key is None else...
[ "def", "set_disk_cache", "(", "self", ",", "results", ",", "key", "=", "None", ")", ":", "if", "not", "getattr", "(", "self", ",", "'disk_cache_location'", ",", "False", ")", ":", "self", ".", "init_disk_cache", "(", ")", "disk_cache", "=", "shelve", "."...
Store result in disk cache with key matching model state.
[ "Store", "result", "in", "disk", "cache", "with", "key", "matching", "model", "state", "." ]
python
train
47.25
wbond/oscrypto
oscrypto/_openssl/tls.py
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_openssl/tls.py#L1125-L1137
def intermediates(self): """ A list of asn1crypto.x509.Certificate objects that were presented as intermediates by the server """ if self._ssl is None: self._raise_closed() if self._certificate is None: self._read_certificates() return s...
[ "def", "intermediates", "(", "self", ")", ":", "if", "self", ".", "_ssl", "is", "None", ":", "self", ".", "_raise_closed", "(", ")", "if", "self", ".", "_certificate", "is", "None", ":", "self", ".", "_read_certificates", "(", ")", "return", "self", "....
A list of asn1crypto.x509.Certificate objects that were presented as intermediates by the server
[ "A", "list", "of", "asn1crypto", ".", "x509", ".", "Certificate", "objects", "that", "were", "presented", "as", "intermediates", "by", "the", "server" ]
python
valid
25.076923
pacificclimate/cfmeta
cfmeta/cmipfile.py
https://github.com/pacificclimate/cfmeta/blob/a6eef78d0bce523bb44920ba96233f034b60316a/cfmeta/cmipfile.py#L176-L195
def get_var_name(nc): """Guesses the variable_name of an open NetCDF file """ non_variable_names = [ 'lat', 'lat_bnds', 'lon', 'lon_bnds', 'time', 'latitude', 'longitude', 'bnds' ] _vars = set(nc.variables.keys()) _vars.difference...
[ "def", "get_var_name", "(", "nc", ")", ":", "non_variable_names", "=", "[", "'lat'", ",", "'lat_bnds'", ",", "'lon'", ",", "'lon_bnds'", ",", "'time'", ",", "'latitude'", ",", "'longitude'", ",", "'bnds'", "]", "_vars", "=", "set", "(", "nc", ".", "varia...
Guesses the variable_name of an open NetCDF file
[ "Guesses", "the", "variable_name", "of", "an", "open", "NetCDF", "file" ]
python
train
20
timothydmorton/isochrones
isochrones/grid.py
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/grid.py#L101-L122
def _get_df(self): """Returns stellar model grid with desired bandpasses and with standard column names bands must be iterable, and are parsed according to :func:``get_band`` """ grids = {} df = pd.DataFrame() for bnd in self.bands: s,b = self.get_band(bnd, *...
[ "def", "_get_df", "(", "self", ")", ":", "grids", "=", "{", "}", "df", "=", "pd", ".", "DataFrame", "(", ")", "for", "bnd", "in", "self", ".", "bands", ":", "s", ",", "b", "=", "self", ".", "get_band", "(", "bnd", ",", "*", "*", "self", ".", ...
Returns stellar model grid with desired bandpasses and with standard column names bands must be iterable, and are parsed according to :func:``get_band``
[ "Returns", "stellar", "model", "grid", "with", "desired", "bandpasses", "and", "with", "standard", "column", "names" ]
python
train
41.681818
tensorflow/mesh
mesh_tensorflow/optimize.py
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/optimize.py#L286-L312
def adafactor_optimizer_from_hparams(hparams, lr): """Create an Adafactor optimizer based on model hparams. Args: hparams: model hyperparameters lr: learning rate scalar. Returns: an AdafactorOptimizer Raises: ValueError: on illegal values """ if hparams.optimizer_adafactor_decay_type == "A...
[ "def", "adafactor_optimizer_from_hparams", "(", "hparams", ",", "lr", ")", ":", "if", "hparams", ".", "optimizer_adafactor_decay_type", "==", "\"Adam\"", ":", "decay_rate", "=", "adafactor_decay_rate_adam", "(", "hparams", ".", "optimizer_adafactor_beta2", ")", "elif", ...
Create an Adafactor optimizer based on model hparams. Args: hparams: model hyperparameters lr: learning rate scalar. Returns: an AdafactorOptimizer Raises: ValueError: on illegal values
[ "Create", "an", "Adafactor", "optimizer", "based", "on", "model", "hparams", "." ]
python
train
35.851852