repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
jazzband/django-queued-storage | queued_storage/backends.py | https://github.com/jazzband/django-queued-storage/blob/f8225d88a01ef5ca8001aeb3f7f80818a022a12d/queued_storage/backends.py#L162-L172 | def open(self, name, mode='rb'):
"""
Retrieves the specified file from storage.
:param name: file name
:type name: str
:param mode: mode to open the file with
:type mode: str
:rtype: :class:`~django:django.core.files.File`
"""
return self.get_stor... | [
"def",
"open",
"(",
"self",
",",
"name",
",",
"mode",
"=",
"'rb'",
")",
":",
"return",
"self",
".",
"get_storage",
"(",
"name",
")",
".",
"open",
"(",
"name",
",",
"mode",
")"
] | Retrieves the specified file from storage.
:param name: file name
:type name: str
:param mode: mode to open the file with
:type mode: str
:rtype: :class:`~django:django.core.files.File` | [
"Retrieves",
"the",
"specified",
"file",
"from",
"storage",
"."
] | python | train |
michaelpb/omnic | omnic/web/viewer.py | https://github.com/michaelpb/omnic/blob/1111cfd73c9dc1955afe42d9cf2a468c46f83cd6/omnic/web/viewer.py#L20-L28 | def get_assets(self):
'''
Return a flat list of absolute paths to all assets required by this
viewer
'''
return sum([
[self.prefix_asset(viewer, relpath) for relpath in viewer.assets]
for viewer in self.viewers
], []) | [
"def",
"get_assets",
"(",
"self",
")",
":",
"return",
"sum",
"(",
"[",
"[",
"self",
".",
"prefix_asset",
"(",
"viewer",
",",
"relpath",
")",
"for",
"relpath",
"in",
"viewer",
".",
"assets",
"]",
"for",
"viewer",
"in",
"self",
".",
"viewers",
"]",
","... | Return a flat list of absolute paths to all assets required by this
viewer | [
"Return",
"a",
"flat",
"list",
"of",
"absolute",
"paths",
"to",
"all",
"assets",
"required",
"by",
"this",
"viewer"
] | python | train |
apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L3083-L3217 | def split_datetime(self, column_name_prefix = "X", limit=None, timezone=False):
"""
Splits an SArray of datetime type to multiple columns, return a
new SFrame that contains expanded columns. A SArray of datetime will be
split by default into an SFrame of 6 columns, one for each
y... | [
"def",
"split_datetime",
"(",
"self",
",",
"column_name_prefix",
"=",
"\"X\"",
",",
"limit",
"=",
"None",
",",
"timezone",
"=",
"False",
")",
":",
"from",
".",
"sframe",
"import",
"SFrame",
"as",
"_SFrame",
"if",
"self",
".",
"dtype",
"!=",
"datetime",
"... | Splits an SArray of datetime type to multiple columns, return a
new SFrame that contains expanded columns. A SArray of datetime will be
split by default into an SFrame of 6 columns, one for each
year/month/day/hour/minute/second element.
**Column Naming**
When splitting a SArra... | [
"Splits",
"an",
"SArray",
"of",
"datetime",
"type",
"to",
"multiple",
"columns",
"return",
"a",
"new",
"SFrame",
"that",
"contains",
"expanded",
"columns",
".",
"A",
"SArray",
"of",
"datetime",
"will",
"be",
"split",
"by",
"default",
"into",
"an",
"SFrame",
... | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/core/magic.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/magic.py#L543-L610 | def parse_options(self, arg_str, opt_str, *long_opts, **kw):
"""Parse options passed to an argument string.
The interface is similar to that of getopt(), but it returns back a
Struct with the options as keys and the stripped argument string still
as a string.
arg_str is quoted ... | [
"def",
"parse_options",
"(",
"self",
",",
"arg_str",
",",
"opt_str",
",",
"*",
"long_opts",
",",
"*",
"*",
"kw",
")",
":",
"# inject default options at the beginning of the input line",
"caller",
"=",
"sys",
".",
"_getframe",
"(",
"1",
")",
".",
"f_code",
".",... | Parse options passed to an argument string.
The interface is similar to that of getopt(), but it returns back a
Struct with the options as keys and the stripped argument string still
as a string.
arg_str is quoted as a true sys.argv vector by using shlex.split.
This allows us t... | [
"Parse",
"options",
"passed",
"to",
"an",
"argument",
"string",
"."
] | python | test |
fmfn/BayesianOptimization | bayes_opt/target_space.py | https://github.com/fmfn/BayesianOptimization/blob/8ce2292895137477963cf1bafa4e71fa20b2ce49/bayes_opt/target_space.py#L234-L241 | def res(self):
"""Get all target values found and corresponding parametes."""
params = [dict(zip(self.keys, p)) for p in self.params]
return [
{"target": target, "params": param}
for target, param in zip(self.target, params)
] | [
"def",
"res",
"(",
"self",
")",
":",
"params",
"=",
"[",
"dict",
"(",
"zip",
"(",
"self",
".",
"keys",
",",
"p",
")",
")",
"for",
"p",
"in",
"self",
".",
"params",
"]",
"return",
"[",
"{",
"\"target\"",
":",
"target",
",",
"\"params\"",
":",
"p... | Get all target values found and corresponding parametes. | [
"Get",
"all",
"target",
"values",
"found",
"and",
"corresponding",
"parametes",
"."
] | python | train |
danilobellini/audiolazy | audiolazy/lazy_filters.py | https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_filters.py#L1116-L1142 | def comb(delay, tau=inf):
"""
Feedback comb filter for a given time constant (and delay).
``y[n] = x[n] + alpha * y[n - delay]``
Parameters
----------
delay :
Feedback delay (lag), in number of samples.
tau :
Time decay (up to ``1/e``, or -8.686 dB), in number of samples, which
allows find... | [
"def",
"comb",
"(",
"delay",
",",
"tau",
"=",
"inf",
")",
":",
"alpha",
"=",
"e",
"**",
"(",
"-",
"delay",
"/",
"tau",
")",
"return",
"1",
"/",
"(",
"1",
"-",
"alpha",
"*",
"z",
"**",
"-",
"delay",
")"
] | Feedback comb filter for a given time constant (and delay).
``y[n] = x[n] + alpha * y[n - delay]``
Parameters
----------
delay :
Feedback delay (lag), in number of samples.
tau :
Time decay (up to ``1/e``, or -8.686 dB), in number of samples, which
allows finding ``alpha = e ** (-delay / tau)`... | [
"Feedback",
"comb",
"filter",
"for",
"a",
"given",
"time",
"constant",
"(",
"and",
"delay",
")",
"."
] | python | train |
jtauber/sebastian | sebastian/core/elements.py | https://github.com/jtauber/sebastian/blob/4e460c3aeab332b45c74fe78e65e76ec87d5cfa8/sebastian/core/elements.py#L248-L273 | def subseq(self, start_offset=0, end_offset=None):
"""
Return a subset of the sequence
starting at start_offset (defaulting to the beginning)
ending at end_offset (None representing the end, whih is the default)
Raises ValueError if duration_64 is missing on any element
"... | [
"def",
"subseq",
"(",
"self",
",",
"start_offset",
"=",
"0",
",",
"end_offset",
"=",
"None",
")",
":",
"from",
"sebastian",
".",
"core",
"import",
"DURATION_64",
"def",
"subseq_iter",
"(",
"start_offset",
",",
"end_offset",
")",
":",
"cur_offset",
"=",
"0"... | Return a subset of the sequence
starting at start_offset (defaulting to the beginning)
ending at end_offset (None representing the end, whih is the default)
Raises ValueError if duration_64 is missing on any element | [
"Return",
"a",
"subset",
"of",
"the",
"sequence",
"starting",
"at",
"start_offset",
"(",
"defaulting",
"to",
"the",
"beginning",
")",
"ending",
"at",
"end_offset",
"(",
"None",
"representing",
"the",
"end",
"whih",
"is",
"the",
"default",
")",
"Raises",
"Val... | python | train |
hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2689-L2727 | def get_extent(self, filename, locations):
"""Obtain a SourceRange from this translation unit.
The bounds of the SourceRange must ultimately be defined by a start and
end SourceLocation. For the locations argument, you can pass:
- 2 SourceLocation instances in a 2-tuple or list.
... | [
"def",
"get_extent",
"(",
"self",
",",
"filename",
",",
"locations",
")",
":",
"f",
"=",
"self",
".",
"get_file",
"(",
"filename",
")",
"if",
"len",
"(",
"locations",
")",
"<",
"2",
":",
"raise",
"Exception",
"(",
"'Must pass object with at least 2 elements'... | Obtain a SourceRange from this translation unit.
The bounds of the SourceRange must ultimately be defined by a start and
end SourceLocation. For the locations argument, you can pass:
- 2 SourceLocation instances in a 2-tuple or list.
- 2 int file offsets via a 2-tuple or list.
... | [
"Obtain",
"a",
"SourceRange",
"from",
"this",
"translation",
"unit",
"."
] | python | train |
wummel/linkchecker | third_party/dnspython/dns/message.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/third_party/dnspython/dns/message.py#L593-L615 | def _get_question(self, qcount):
"""Read the next I{qcount} records from the wire data and add them to
the question section.
@param qcount: the number of questions in the message
@type qcount: int"""
if self.updating and qcount > 1:
raise dns.exception.FormError
... | [
"def",
"_get_question",
"(",
"self",
",",
"qcount",
")",
":",
"if",
"self",
".",
"updating",
"and",
"qcount",
">",
"1",
":",
"raise",
"dns",
".",
"exception",
".",
"FormError",
"for",
"i",
"in",
"xrange",
"(",
"0",
",",
"qcount",
")",
":",
"(",
"qn... | Read the next I{qcount} records from the wire data and add them to
the question section.
@param qcount: the number of questions in the message
@type qcount: int | [
"Read",
"the",
"next",
"I",
"{",
"qcount",
"}",
"records",
"from",
"the",
"wire",
"data",
"and",
"add",
"them",
"to",
"the",
"question",
"section",
"."
] | python | train |
ray-project/ray | python/ray/serialization.py | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/serialization.py#L16-L55 | def check_serializable(cls):
"""Throws an exception if Ray cannot serialize this class efficiently.
Args:
cls (type): The class to be serialized.
Raises:
Exception: An exception is raised if Ray cannot serialize this class
efficiently.
"""
if is_named_tuple(cls):
... | [
"def",
"check_serializable",
"(",
"cls",
")",
":",
"if",
"is_named_tuple",
"(",
"cls",
")",
":",
"# This case works.",
"return",
"if",
"not",
"hasattr",
"(",
"cls",
",",
"\"__new__\"",
")",
":",
"print",
"(",
"\"The class {} does not have a '__new__' attribute and i... | Throws an exception if Ray cannot serialize this class efficiently.
Args:
cls (type): The class to be serialized.
Raises:
Exception: An exception is raised if Ray cannot serialize this class
efficiently. | [
"Throws",
"an",
"exception",
"if",
"Ray",
"cannot",
"serialize",
"this",
"class",
"efficiently",
"."
] | python | train |
drj11/pypng | code/iccp.py | https://github.com/drj11/pypng/blob/b8220ca9f58e4c5bc1d507e713744fcb8c049225/code/iccp.py#L316-L328 | def encode(tsig, *l):
"""Encode a Python value as an ICC type. `tsig` is the type
signature to (the first 4 bytes of the encoded value, see [ICC 2004]
section 10.
"""
fun = encodefuns()
if tsig not in fun:
raise "No encoder for type %r." % tsig
v = fun[tsig](*l)
# Padd tsig out... | [
"def",
"encode",
"(",
"tsig",
",",
"*",
"l",
")",
":",
"fun",
"=",
"encodefuns",
"(",
")",
"if",
"tsig",
"not",
"in",
"fun",
":",
"raise",
"\"No encoder for type %r.\"",
"%",
"tsig",
"v",
"=",
"fun",
"[",
"tsig",
"]",
"(",
"*",
"l",
")",
"# Padd ts... | Encode a Python value as an ICC type. `tsig` is the type
signature to (the first 4 bytes of the encoded value, see [ICC 2004]
section 10. | [
"Encode",
"a",
"Python",
"value",
"as",
"an",
"ICC",
"type",
".",
"tsig",
"is",
"the",
"type",
"signature",
"to",
"(",
"the",
"first",
"4",
"bytes",
"of",
"the",
"encoded",
"value",
"see",
"[",
"ICC",
"2004",
"]",
"section",
"10",
"."
] | python | train |
openwisp/netjsonconfig | netjsonconfig/backends/openwisp/openwisp.py | https://github.com/openwisp/netjsonconfig/blob/c23ce9732720856e2f6dc54060db71a8182c7d4b/netjsonconfig/backends/openwisp/openwisp.py#L78-L89 | def _add_install(self, context):
"""
generates install.sh and adds it to included files
"""
contents = self._render_template('install.sh', context)
self.config.setdefault('files', []) # file list might be empty
# add install.sh to list of included files
self._add... | [
"def",
"_add_install",
"(",
"self",
",",
"context",
")",
":",
"contents",
"=",
"self",
".",
"_render_template",
"(",
"'install.sh'",
",",
"context",
")",
"self",
".",
"config",
".",
"setdefault",
"(",
"'files'",
",",
"[",
"]",
")",
"# file list might be empt... | generates install.sh and adds it to included files | [
"generates",
"install",
".",
"sh",
"and",
"adds",
"it",
"to",
"included",
"files"
] | python | valid |
sloria/read_env | read_env.py | https://github.com/sloria/read_env/blob/90c5a7b38d70f06cd96b5d9a7e68e422bb5bd605/read_env.py#L16-L46 | def read_env(path=None, environ=None, recurse=True):
"""Reads a .env file into ``environ`` (which defaults to ``os.environ``).
If .env is not found in the directory from which this function is called, recurse
up the directory tree until a .env file is found.
"""
environ = environ if environ is not N... | [
"def",
"read_env",
"(",
"path",
"=",
"None",
",",
"environ",
"=",
"None",
",",
"recurse",
"=",
"True",
")",
":",
"environ",
"=",
"environ",
"if",
"environ",
"is",
"not",
"None",
"else",
"os",
".",
"environ",
"# By default, start search from the same file this ... | Reads a .env file into ``environ`` (which defaults to ``os.environ``).
If .env is not found in the directory from which this function is called, recurse
up the directory tree until a .env file is found. | [
"Reads",
"a",
".",
"env",
"file",
"into",
"environ",
"(",
"which",
"defaults",
"to",
"os",
".",
"environ",
")",
".",
"If",
".",
"env",
"is",
"not",
"found",
"in",
"the",
"directory",
"from",
"which",
"this",
"function",
"is",
"called",
"recurse",
"up",... | python | train |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_web.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_web.py#L349-L355 | def getenv_escaped(key: str, default: str = None) -> Optional[str]:
"""
Returns an environment variable's value, CGI-escaped, or ``None``.
"""
value = os.getenv(key, default)
# noinspection PyDeprecation
return cgi.escape(value) if value is not None else None | [
"def",
"getenv_escaped",
"(",
"key",
":",
"str",
",",
"default",
":",
"str",
"=",
"None",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"value",
"=",
"os",
".",
"getenv",
"(",
"key",
",",
"default",
")",
"# noinspection PyDeprecation",
"return",
"cgi",
... | Returns an environment variable's value, CGI-escaped, or ``None``. | [
"Returns",
"an",
"environment",
"variable",
"s",
"value",
"CGI",
"-",
"escaped",
"or",
"None",
"."
] | python | train |
pyviz/holoviews | setup.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/setup.py#L183-L196 | def walker(top, names):
"""
Walks a directory and records all packages and file extensions.
"""
global packages, extensions
if any(exc in top for exc in excludes):
return
package = top[top.rfind('holoviews'):].replace(os.path.sep, '.')
packages.append(package)
for name in names:
... | [
"def",
"walker",
"(",
"top",
",",
"names",
")",
":",
"global",
"packages",
",",
"extensions",
"if",
"any",
"(",
"exc",
"in",
"top",
"for",
"exc",
"in",
"excludes",
")",
":",
"return",
"package",
"=",
"top",
"[",
"top",
".",
"rfind",
"(",
"'holoviews'... | Walks a directory and records all packages and file extensions. | [
"Walks",
"a",
"directory",
"and",
"records",
"all",
"packages",
"and",
"file",
"extensions",
"."
] | python | train |
spyder-ide/spyder | spyder/plugins/editor/widgets/status.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/status.py#L34-L38 | def update_eol(self, os_name):
"""Update end of line status."""
os_name = to_text_string(os_name)
value = {"nt": "CRLF", "posix": "LF"}.get(os_name, "CR")
self.set_value(value) | [
"def",
"update_eol",
"(",
"self",
",",
"os_name",
")",
":",
"os_name",
"=",
"to_text_string",
"(",
"os_name",
")",
"value",
"=",
"{",
"\"nt\"",
":",
"\"CRLF\"",
",",
"\"posix\"",
":",
"\"LF\"",
"}",
".",
"get",
"(",
"os_name",
",",
"\"CR\"",
")",
"self... | Update end of line status. | [
"Update",
"end",
"of",
"line",
"status",
"."
] | python | train |
mlavin/django-all-access | allaccess/clients.py | https://github.com/mlavin/django-all-access/blob/4b15b6c9dedf8080a7c477e0af1142c609ec5598/allaccess/clients.py#L202-L214 | def parse_raw_token(self, raw_token):
"Parse token and secret from raw token response."
if raw_token is None:
return (None, None)
# Load as json first then parse as query string
try:
token_data = json.loads(raw_token)
except ValueError:
qs = pa... | [
"def",
"parse_raw_token",
"(",
"self",
",",
"raw_token",
")",
":",
"if",
"raw_token",
"is",
"None",
":",
"return",
"(",
"None",
",",
"None",
")",
"# Load as json first then parse as query string",
"try",
":",
"token_data",
"=",
"json",
".",
"loads",
"(",
"raw_... | Parse token and secret from raw token response. | [
"Parse",
"token",
"and",
"secret",
"from",
"raw",
"token",
"response",
"."
] | python | train |
mensi/gittornado | gittornado/iowrapper.py | https://github.com/mensi/gittornado/blob/adf86b5537064337c806cce0e71eacaabc8bb610/gittornado/iowrapper.py#L330-L359 | def _handle_stderr_event(self, fd, events):
"""Eventhandler for stderr"""
assert fd == self.fd_stderr
if events & self.ioloop.READ:
# got data ready
if not self.headers_sent:
payload = self.process.stderr.read()
data = 'HTTP/1.1 500 Inte... | [
"def",
"_handle_stderr_event",
"(",
"self",
",",
"fd",
",",
"events",
")",
":",
"assert",
"fd",
"==",
"self",
".",
"fd_stderr",
"if",
"events",
"&",
"self",
".",
"ioloop",
".",
"READ",
":",
"# got data ready",
"if",
"not",
"self",
".",
"headers_sent",
":... | Eventhandler for stderr | [
"Eventhandler",
"for",
"stderr"
] | python | train |
dask/dask-kubernetes | dask_kubernetes/core.py | https://github.com/dask/dask-kubernetes/blob/8a4883ecd902460b446bb1f43ed97efe398a135e/dask_kubernetes/core.py#L522-L535 | def _namespace_default():
"""
Get current namespace if running in a k8s cluster
If not in a k8s cluster with service accounts enabled, default to
'default'
Taken from https://github.com/jupyterhub/kubespawner/blob/master/kubespawner/spawner.py#L125
"""
ns_path = '/var/run/secrets/kubernete... | [
"def",
"_namespace_default",
"(",
")",
":",
"ns_path",
"=",
"'/var/run/secrets/kubernetes.io/serviceaccount/namespace'",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"ns_path",
")",
":",
"with",
"open",
"(",
"ns_path",
")",
"as",
"f",
":",
"return",
"f",
".",
... | Get current namespace if running in a k8s cluster
If not in a k8s cluster with service accounts enabled, default to
'default'
Taken from https://github.com/jupyterhub/kubespawner/blob/master/kubespawner/spawner.py#L125 | [
"Get",
"current",
"namespace",
"if",
"running",
"in",
"a",
"k8s",
"cluster"
] | python | train |
MaxStrange/AudioSegment | audiosegment.py | https://github.com/MaxStrange/AudioSegment/blob/1daefb8de626ddff3ff7016697c3ad31d262ecd6/audiosegment.py#L409-L450 | def detect_voice(self, prob_detect_voice=0.5):
"""
Returns self as a list of tuples:
[('v', voiced segment), ('u', unvoiced segment), (etc.)]
The overall order of the AudioSegment is preserved.
:param prob_detect_voice: The raw probability that any random 20ms window of the aud... | [
"def",
"detect_voice",
"(",
"self",
",",
"prob_detect_voice",
"=",
"0.5",
")",
":",
"assert",
"self",
".",
"frame_rate",
"in",
"(",
"48000",
",",
"32000",
",",
"16000",
",",
"8000",
")",
",",
"\"Try resampling to one of the allowed frame rates.\"",
"assert",
"se... | Returns self as a list of tuples:
[('v', voiced segment), ('u', unvoiced segment), (etc.)]
The overall order of the AudioSegment is preserved.
:param prob_detect_voice: The raw probability that any random 20ms window of the audio file
contains voice.
:... | [
"Returns",
"self",
"as",
"a",
"list",
"of",
"tuples",
":",
"[",
"(",
"v",
"voiced",
"segment",
")",
"(",
"u",
"unvoiced",
"segment",
")",
"(",
"etc",
".",
")",
"]"
] | python | test |
sxslex/capitalize-name | capitalize_name/__init__.py | https://github.com/sxslex/capitalize-name/blob/98f288a3cffaecdb8aaee5154e783ba46849bccd/capitalize_name/__init__.py#L86-L107 | def deep_unicode(s, encodings=None):
"""decode "DEEP" S using the codec registered for encoding."""
if encodings is None:
encodings = ['utf-8', 'latin-1']
if isinstance(s, (list, tuple)):
return [deep_unicode(i) for i in s]
if isinstance(s, dict):
return dict([
(deep_... | [
"def",
"deep_unicode",
"(",
"s",
",",
"encodings",
"=",
"None",
")",
":",
"if",
"encodings",
"is",
"None",
":",
"encodings",
"=",
"[",
"'utf-8'",
",",
"'latin-1'",
"]",
"if",
"isinstance",
"(",
"s",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"r... | decode "DEEP" S using the codec registered for encoding. | [
"decode",
"DEEP",
"S",
"using",
"the",
"codec",
"registered",
"for",
"encoding",
"."
] | python | train |
google/grumpy | third_party/stdlib/re.py | https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/re.py#L211-L221 | def escape(pattern):
"Escape all non-alphanumeric characters in pattern."
s = list(pattern)
alphanum = _alphanum
for i, c in enumerate(pattern):
if c not in alphanum:
if c == "\000":
s[i] = "\\000"
else:
s[i] = "\\" + c
return pattern[:... | [
"def",
"escape",
"(",
"pattern",
")",
":",
"s",
"=",
"list",
"(",
"pattern",
")",
"alphanum",
"=",
"_alphanum",
"for",
"i",
",",
"c",
"in",
"enumerate",
"(",
"pattern",
")",
":",
"if",
"c",
"not",
"in",
"alphanum",
":",
"if",
"c",
"==",
"\"\\000\""... | Escape all non-alphanumeric characters in pattern. | [
"Escape",
"all",
"non",
"-",
"alphanumeric",
"characters",
"in",
"pattern",
"."
] | python | valid |
datajoint/datajoint-python | datajoint/expression.py | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/expression.py#L291-L339 | def restrict(self, restriction):
"""
In-place restriction. Restricts the result to a specified subset of the input.
rel.restrict(restriction) is equivalent to rel = rel & restriction or rel &= restriction
rel.restrict(Not(restriction)) is equivalent to rel = rel - restriction or ... | [
"def",
"restrict",
"(",
"self",
",",
"restriction",
")",
":",
"assert",
"is_true",
"(",
"restriction",
")",
"or",
"not",
"self",
".",
"heading",
".",
"expressions",
"or",
"isinstance",
"(",
"self",
",",
"GroupBy",
")",
",",
"\"Cannot restrict a projection with... | In-place restriction. Restricts the result to a specified subset of the input.
rel.restrict(restriction) is equivalent to rel = rel & restriction or rel &= restriction
rel.restrict(Not(restriction)) is equivalent to rel = rel - restriction or rel -= restriction
The primary key of the re... | [
"In",
"-",
"place",
"restriction",
".",
"Restricts",
"the",
"result",
"to",
"a",
"specified",
"subset",
"of",
"the",
"input",
".",
"rel",
".",
"restrict",
"(",
"restriction",
")",
"is",
"equivalent",
"to",
"rel",
"=",
"rel",
"&",
"restriction",
"or",
"re... | python | train |
Jajcus/pyxmpp2 | pyxmpp2/ext/legacyauth.py | https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/legacyauth.py#L143-L166 | def auth_in_stage1(self,stanza):
"""Handle the first stage (<iq type='get'/>) of legacy ("plain" or
"digest") authentication.
[server only]"""
self.lock.acquire()
try:
if "plain" not in self.auth_methods and "digest" not in self.auth_methods:
iq=stanz... | [
"def",
"auth_in_stage1",
"(",
"self",
",",
"stanza",
")",
":",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"try",
":",
"if",
"\"plain\"",
"not",
"in",
"self",
".",
"auth_methods",
"and",
"\"digest\"",
"not",
"in",
"self",
".",
"auth_methods",
":",
"... | Handle the first stage (<iq type='get'/>) of legacy ("plain" or
"digest") authentication.
[server only] | [
"Handle",
"the",
"first",
"stage",
"(",
"<iq",
"type",
"=",
"get",
"/",
">",
")",
"of",
"legacy",
"(",
"plain",
"or",
"digest",
")",
"authentication",
"."
] | python | valid |
gbowerman/azurerm | azurerm/amsrp.py | https://github.com/gbowerman/azurerm/blob/79d40431d3b13f8a36aadbff5029888383d72674/azurerm/amsrp.py#L460-L478 | def create_sas_locator(access_token, asset_id, accesspolicy_id):
'''Create Media Service SAS Locator.
Args:
access_token (str): A valid Azure authentication token.
asset_id (str): Media Service Asset ID.
accesspolicy_id (str): Media Service Access Policy ID.
Returns:
HTTP r... | [
"def",
"create_sas_locator",
"(",
"access_token",
",",
"asset_id",
",",
"accesspolicy_id",
")",
":",
"path",
"=",
"'/Locators'",
"endpoint",
"=",
"''",
".",
"join",
"(",
"[",
"ams_rest_endpoint",
",",
"path",
"]",
")",
"body",
"=",
"'{ \\\n\t\t\"AccessPolicyId\"... | Create Media Service SAS Locator.
Args:
access_token (str): A valid Azure authentication token.
asset_id (str): Media Service Asset ID.
accesspolicy_id (str): Media Service Access Policy ID.
Returns:
HTTP response. JSON body. | [
"Create",
"Media",
"Service",
"SAS",
"Locator",
"."
] | python | train |
saltstack/salt | salt/states/file.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/file.py#L8038-L8313 | def cached(name,
source_hash='',
source_hash_name=None,
skip_verify=False,
saltenv='base'):
'''
.. versionadded:: 2017.7.3
Ensures that a file is saved to the minion's cache. This state is primarily
invoked by other states to ensure that we do not re-download... | [
"def",
"cached",
"(",
"name",
",",
"source_hash",
"=",
"''",
",",
"source_hash_name",
"=",
"None",
",",
"skip_verify",
"=",
"False",
",",
"saltenv",
"=",
"'base'",
")",
":",
"ret",
"=",
"{",
"'changes'",
":",
"{",
"}",
",",
"'comment'",
":",
"''",
",... | .. versionadded:: 2017.7.3
Ensures that a file is saved to the minion's cache. This state is primarily
invoked by other states to ensure that we do not re-download a source file
if we do not need to.
name
The URL of the file to be cached. To cache a file from an environment
other than ... | [
"..",
"versionadded",
"::",
"2017",
".",
"7",
".",
"3"
] | python | train |
Legobot/Legobot | Legobot/Connectors/Discord.py | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Discord.py#L194-L219 | def _parse_metadata(self, message):
"""
Sets metadata in Legobot message
Args:
message (dict): Full message from Discord websocket connection"
Returns:
Legobot.Metadata
"""
metadata = Metadata(source=self.actor_urn).__dict__
if 'author' ... | [
"def",
"_parse_metadata",
"(",
"self",
",",
"message",
")",
":",
"metadata",
"=",
"Metadata",
"(",
"source",
"=",
"self",
".",
"actor_urn",
")",
".",
"__dict__",
"if",
"'author'",
"in",
"message",
"[",
"'d'",
"]",
":",
"metadata",
"[",
"'source_user'",
"... | Sets metadata in Legobot message
Args:
message (dict): Full message from Discord websocket connection"
Returns:
Legobot.Metadata | [
"Sets",
"metadata",
"in",
"Legobot",
"message"
] | python | train |
xtuml/pyxtuml | xtuml/persist.py | https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/persist.py#L211-L223 | def persist_unique_identifiers(metamodel, path, mode='w'):
'''
Persist all unique identifiers in a *metamodel* by serializing them and
saving to a *path* on disk.
'''
with open(path, mode) as f:
for metaclass in metamodel.metaclasses.values():
for index_name, attribute_names in m... | [
"def",
"persist_unique_identifiers",
"(",
"metamodel",
",",
"path",
",",
"mode",
"=",
"'w'",
")",
":",
"with",
"open",
"(",
"path",
",",
"mode",
")",
"as",
"f",
":",
"for",
"metaclass",
"in",
"metamodel",
".",
"metaclasses",
".",
"values",
"(",
")",
":... | Persist all unique identifiers in a *metamodel* by serializing them and
saving to a *path* on disk. | [
"Persist",
"all",
"unique",
"identifiers",
"in",
"a",
"*",
"metamodel",
"*",
"by",
"serializing",
"them",
"and",
"saving",
"to",
"a",
"*",
"path",
"*",
"on",
"disk",
"."
] | python | test |
log2timeline/plaso | docs/conf.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/docs/conf.py#L388-L407 | def find_and_replace(self, node):
"""Parses URIs containing .md and replaces them with their HTML page.
Args:
node(node): docutils node.
Returns:
node: docutils node.
"""
if isinstance(node, nodes.reference) and 'refuri' in node:
reference_uri = node['refuri']
if referenc... | [
"def",
"find_and_replace",
"(",
"self",
",",
"node",
")",
":",
"if",
"isinstance",
"(",
"node",
",",
"nodes",
".",
"reference",
")",
"and",
"'refuri'",
"in",
"node",
":",
"reference_uri",
"=",
"node",
"[",
"'refuri'",
"]",
"if",
"reference_uri",
".",
"en... | Parses URIs containing .md and replaces them with their HTML page.
Args:
node(node): docutils node.
Returns:
node: docutils node. | [
"Parses",
"URIs",
"containing",
".",
"md",
"and",
"replaces",
"them",
"with",
"their",
"HTML",
"page",
"."
] | python | train |
lesscpy/lesscpy | lesscpy/lessc/color.py | https://github.com/lesscpy/lesscpy/blob/51e392fb4a3cd4ccfb6175e0e42ce7d2f6b78126/lesscpy/lessc/color.py#L148-L163 | def hsl(self, *args):
""" Translate hsl(...) to color string
raises:
ValueError
returns:
str
"""
if len(args) == 4:
return self.hsla(*args)
elif len(args) == 3:
h, s, l = args
rgb = colorsys.hls_to_rgb(
... | [
"def",
"hsl",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"4",
":",
"return",
"self",
".",
"hsla",
"(",
"*",
"args",
")",
"elif",
"len",
"(",
"args",
")",
"==",
"3",
":",
"h",
",",
"s",
",",
"l",
"=",
"ar... | Translate hsl(...) to color string
raises:
ValueError
returns:
str | [
"Translate",
"hsl",
"(",
"...",
")",
"to",
"color",
"string",
"raises",
":",
"ValueError",
"returns",
":",
"str"
] | python | valid |
mitsei/dlkit | dlkit/handcar/repository/managers.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/handcar/repository/managers.py#L1441-L1464 | def get_composition_admin_session(self):
"""Gets a composition administration session for creating, updating
and deleting compositions.
return: (osid.repository.CompositionAdminSession) - a
CompositionAdminSession
raise: OperationFailed - unable to complete request
... | [
"def",
"get_composition_admin_session",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"supports_composition_admin",
"(",
")",
":",
"raise",
"Unimplemented",
"(",
")",
"try",
":",
"from",
".",
"import",
"sessions",
"except",
"ImportError",
":",
"raise",
"# O... | Gets a composition administration session for creating, updating
and deleting compositions.
return: (osid.repository.CompositionAdminSession) - a
CompositionAdminSession
raise: OperationFailed - unable to complete request
raise: Unimplemented - supports_composition_adm... | [
"Gets",
"a",
"composition",
"administration",
"session",
"for",
"creating",
"updating",
"and",
"deleting",
"compositions",
"."
] | python | train |
shexSpec/grammar | parsers/python/pyshexc/parser_impl/shex_shape_expression_parser.py | https://github.com/shexSpec/grammar/blob/4497cd1f73fa6703bca6e2cb53ba9c120f22e48c/parsers/python/pyshexc/parser_impl/shex_shape_expression_parser.py#L79-L88 | def visitInlineShapeAnd(self, ctx: ShExDocParser.InlineShapeAndContext):
""" inlineShapeAnd: inlineShapeNot (KW_AND inlineShapeNot)* """
if len(ctx.inlineShapeNot()) > 1:
self.expr = ShapeAnd(id=self.label, shapeExprs=[])
for sa in ctx.inlineShapeNot():
sep = Shex... | [
"def",
"visitInlineShapeAnd",
"(",
"self",
",",
"ctx",
":",
"ShExDocParser",
".",
"InlineShapeAndContext",
")",
":",
"if",
"len",
"(",
"ctx",
".",
"inlineShapeNot",
"(",
")",
")",
">",
"1",
":",
"self",
".",
"expr",
"=",
"ShapeAnd",
"(",
"id",
"=",
"se... | inlineShapeAnd: inlineShapeNot (KW_AND inlineShapeNot)* | [
"inlineShapeAnd",
":",
"inlineShapeNot",
"(",
"KW_AND",
"inlineShapeNot",
")",
"*"
] | python | train |
sernst/cauldron | cauldron/runner/__init__.py | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/runner/__init__.py#L82-L123 | def reload_libraries(library_directories: list = None):
"""
Reload the libraries stored in the project's local and shared library
directories
"""
directories = library_directories or []
project = cauldron.project.get_internal_project()
if project:
directories += project.library_direc... | [
"def",
"reload_libraries",
"(",
"library_directories",
":",
"list",
"=",
"None",
")",
":",
"directories",
"=",
"library_directories",
"or",
"[",
"]",
"project",
"=",
"cauldron",
".",
"project",
".",
"get_internal_project",
"(",
")",
"if",
"project",
":",
"dire... | Reload the libraries stored in the project's local and shared library
directories | [
"Reload",
"the",
"libraries",
"stored",
"in",
"the",
"project",
"s",
"local",
"and",
"shared",
"library",
"directories"
] | python | train |
sdispater/orator | orator/orm/mixins/soft_deletes.py | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/mixins/soft_deletes.py#L92-L106 | def only_trashed(cls):
"""
Get a new query builder that only includes soft deletes
:type cls: orator.orm.model.Model
:rtype: orator.orm.builder.Builder
"""
instance = cls()
column = instance.get_qualified_deleted_at_column()
return instance.new_query_w... | [
"def",
"only_trashed",
"(",
"cls",
")",
":",
"instance",
"=",
"cls",
"(",
")",
"column",
"=",
"instance",
".",
"get_qualified_deleted_at_column",
"(",
")",
"return",
"instance",
".",
"new_query_without_scope",
"(",
"SoftDeletingScope",
"(",
")",
")",
".",
"whe... | Get a new query builder that only includes soft deletes
:type cls: orator.orm.model.Model
:rtype: orator.orm.builder.Builder | [
"Get",
"a",
"new",
"query",
"builder",
"that",
"only",
"includes",
"soft",
"deletes"
] | python | train |
DarkEnergySurvey/ugali | ugali/scratch/simulation/simulate_population.py | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/scratch/simulation/simulate_population.py#L84-L99 | def meanFracdet(map_fracdet, lon_population, lat_population, radius_population):
"""
Compute the mean fracdet within circular aperture (radius specified in decimal degrees)
lon, lat, and radius are taken to be arrays of the same length
"""
nside_fracdet = healpy.npix2nside(len(map_fracdet))
map... | [
"def",
"meanFracdet",
"(",
"map_fracdet",
",",
"lon_population",
",",
"lat_population",
",",
"radius_population",
")",
":",
"nside_fracdet",
"=",
"healpy",
".",
"npix2nside",
"(",
"len",
"(",
"map_fracdet",
")",
")",
"map_fracdet_zero",
"=",
"np",
".",
"where",
... | Compute the mean fracdet within circular aperture (radius specified in decimal degrees)
lon, lat, and radius are taken to be arrays of the same length | [
"Compute",
"the",
"mean",
"fracdet",
"within",
"circular",
"aperture",
"(",
"radius",
"specified",
"in",
"decimal",
"degrees",
")"
] | python | train |
keenlabs/KeenClient-Python | keen/Padding.py | https://github.com/keenlabs/KeenClient-Python/blob/266387c3376d1e000d117e17c45045ae3439d43f/keen/Padding.py#L194-L205 | def removeSpacePadding(str, blocksize=AES_blocksize):
'Remove padding with spaces'
pad_len = 0
for char in str[::-1]: # str[::-1] reverses string
if char == ' ':
pad_len += 1
else:
break
str = str[:-pad_len]
return str | [
"def",
"removeSpacePadding",
"(",
"str",
",",
"blocksize",
"=",
"AES_blocksize",
")",
":",
"pad_len",
"=",
"0",
"for",
"char",
"in",
"str",
"[",
":",
":",
"-",
"1",
"]",
":",
"# str[::-1] reverses string",
"if",
"char",
"==",
"' '",
":",
"pad_len",
"+=",... | Remove padding with spaces | [
"Remove",
"padding",
"with",
"spaces"
] | python | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L15019-L15040 | def vrotv(v, axis, theta):
"""
Rotate a vector about a specified axis vector by a
specified angle and return the rotated vector.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vrotv_c.html
:param v: Vector to be rotated.
:type v: 3-Element Array of floats
:param axis: Axis of the... | [
"def",
"vrotv",
"(",
"v",
",",
"axis",
",",
"theta",
")",
":",
"v",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"v",
")",
"axis",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"axis",
")",
"theta",
"=",
"ctypes",
".",
"c_double",
"(",
"theta",
")",
"r"... | Rotate a vector about a specified axis vector by a
specified angle and return the rotated vector.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vrotv_c.html
:param v: Vector to be rotated.
:type v: 3-Element Array of floats
:param axis: Axis of the rotation.
:type axis: 3-Element A... | [
"Rotate",
"a",
"vector",
"about",
"a",
"specified",
"axis",
"vector",
"by",
"a",
"specified",
"angle",
"and",
"return",
"the",
"rotated",
"vector",
"."
] | python | train |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L1591-L1605 | def stage_tc_indicator_entity(self, indicator_data):
"""Convert JSON data to TCEntity.
Args:
indicator_data (str): [description]
Returns:
[type]: [description]
"""
path = '@.{value: summary, '
path += 'type: type, '
path += 'ownerName: ow... | [
"def",
"stage_tc_indicator_entity",
"(",
"self",
",",
"indicator_data",
")",
":",
"path",
"=",
"'@.{value: summary, '",
"path",
"+=",
"'type: type, '",
"path",
"+=",
"'ownerName: ownerName, '",
"path",
"+=",
"'confidence: confidence || `0`, '",
"path",
"+=",
"'rating: rat... | Convert JSON data to TCEntity.
Args:
indicator_data (str): [description]
Returns:
[type]: [description] | [
"Convert",
"JSON",
"data",
"to",
"TCEntity",
"."
] | python | train |
exosite-labs/pyonep | pyonep/portals/__init__.py | https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/__init__.py#L501-L504 | def get_user_permission_from_email(self, email):
""" Returns a user's permissions object when given the user email."""
_id = self.get_user_id_from_email(email)
return self.get_user_permission(_id) | [
"def",
"get_user_permission_from_email",
"(",
"self",
",",
"email",
")",
":",
"_id",
"=",
"self",
".",
"get_user_id_from_email",
"(",
"email",
")",
"return",
"self",
".",
"get_user_permission",
"(",
"_id",
")"
] | Returns a user's permissions object when given the user email. | [
"Returns",
"a",
"user",
"s",
"permissions",
"object",
"when",
"given",
"the",
"user",
"email",
"."
] | python | train |
hydraplatform/hydra-base | hydra_base/util/dataset_util.py | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/util/dataset_util.py#L214-L228 | def validate_ENUM(in_value, restriction):
"""
Test to ensure that the given value is contained in the provided list.
the value parameter must be either a single value or a 1-dimensional list.
All the values in this list must satisfy the ENUM
"""
value = _get_val(in_value)
if type... | [
"def",
"validate_ENUM",
"(",
"in_value",
",",
"restriction",
")",
":",
"value",
"=",
"_get_val",
"(",
"in_value",
")",
"if",
"type",
"(",
"value",
")",
"is",
"list",
":",
"for",
"subval",
"in",
"value",
":",
"if",
"type",
"(",
"subval",
")",
"is",
"t... | Test to ensure that the given value is contained in the provided list.
the value parameter must be either a single value or a 1-dimensional list.
All the values in this list must satisfy the ENUM | [
"Test",
"to",
"ensure",
"that",
"the",
"given",
"value",
"is",
"contained",
"in",
"the",
"provided",
"list",
".",
"the",
"value",
"parameter",
"must",
"be",
"either",
"a",
"single",
"value",
"or",
"a",
"1",
"-",
"dimensional",
"list",
".",
"All",
"the",
... | python | train |
mongodb/motor | motor/core.py | https://github.com/mongodb/motor/blob/6af22720723bde7c78eb8cb126962cfbfc034b2c/motor/core.py#L1161-L1170 | def close(self):
"""Explicitly kill this cursor on the server. Call like (in Tornado):
.. code-block:: python
yield cursor.close()
"""
if not self.closed:
self.closed = True
yield self._framework.yieldable(self._close()) | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"closed",
":",
"self",
".",
"closed",
"=",
"True",
"yield",
"self",
".",
"_framework",
".",
"yieldable",
"(",
"self",
".",
"_close",
"(",
")",
")"
] | Explicitly kill this cursor on the server. Call like (in Tornado):
.. code-block:: python
yield cursor.close() | [
"Explicitly",
"kill",
"this",
"cursor",
"on",
"the",
"server",
".",
"Call",
"like",
"(",
"in",
"Tornado",
")",
":"
] | python | train |
CalebBell/thermo | thermo/thermal_conductivity.py | https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/thermal_conductivity.py#L1244-L1272 | def load_all_methods(self):
r'''Method to initialize the object by precomputing any values which
may be used repeatedly and by retrieving mixture-specific variables.
All data are stored as attributes. This method also sets :obj:`Tmin`,
:obj:`Tmax`, and :obj:`all_methods` as a set of met... | [
"def",
"load_all_methods",
"(",
"self",
")",
":",
"methods",
"=",
"[",
"DIPPR_9H",
",",
"SIMPLE",
"]",
"if",
"len",
"(",
"self",
".",
"CASs",
")",
"==",
"2",
":",
"methods",
".",
"append",
"(",
"FILIPPOV",
")",
"if",
"'7732-18-5'",
"in",
"self",
".",... | r'''Method to initialize the object by precomputing any values which
may be used repeatedly and by retrieving mixture-specific variables.
All data are stored as attributes. This method also sets :obj:`Tmin`,
:obj:`Tmax`, and :obj:`all_methods` as a set of methods which should
work to c... | [
"r",
"Method",
"to",
"initialize",
"the",
"object",
"by",
"precomputing",
"any",
"values",
"which",
"may",
"be",
"used",
"repeatedly",
"and",
"by",
"retrieving",
"mixture",
"-",
"specific",
"variables",
".",
"All",
"data",
"are",
"stored",
"as",
"attributes",
... | python | valid |
shoebot/shoebot | lib/web/BeautifulSoup.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L711-L719 | def decompose(self):
"""Recursively destroys the contents of this tree."""
contents = [i for i in self.contents]
for i in contents:
if isinstance(i, Tag):
i.decompose()
else:
i.extract()
self.extract() | [
"def",
"decompose",
"(",
"self",
")",
":",
"contents",
"=",
"[",
"i",
"for",
"i",
"in",
"self",
".",
"contents",
"]",
"for",
"i",
"in",
"contents",
":",
"if",
"isinstance",
"(",
"i",
",",
"Tag",
")",
":",
"i",
".",
"decompose",
"(",
")",
"else",
... | Recursively destroys the contents of this tree. | [
"Recursively",
"destroys",
"the",
"contents",
"of",
"this",
"tree",
"."
] | python | valid |
tumblr/pytumblr | pytumblr/__init__.py | https://github.com/tumblr/pytumblr/blob/4a5cd7c4b8ae78d12811d9fd52620afa1692a415/pytumblr/__init__.py#L96-L111 | def tagged(self, tag, **kwargs):
"""
Gets a list of posts tagged with the given tag
:param tag: a string, the tag you want to look for
:param before: a unix timestamp, the timestamp you want to start at
to look at posts.
:param limit: the number of results... | [
"def",
"tagged",
"(",
"self",
",",
"tag",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"update",
"(",
"{",
"'tag'",
":",
"tag",
"}",
")",
"return",
"self",
".",
"send_api_request",
"(",
"\"get\"",
",",
"'/v2/tagged'",
",",
"kwargs",
",",
"[",
... | Gets a list of posts tagged with the given tag
:param tag: a string, the tag you want to look for
:param before: a unix timestamp, the timestamp you want to start at
to look at posts.
:param limit: the number of results you want
:param filter: the post format that... | [
"Gets",
"a",
"list",
"of",
"posts",
"tagged",
"with",
"the",
"given",
"tag"
] | python | train |
tanghaibao/goatools | goatools/godag_plot.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/godag_plot.py#L26-L37 | def plot_results(fout_png, goea_results, *args, **kws):
"""Given a list of GOEA results, plot result GOs up to top."""
if "{NS}" not in fout_png:
plt_goea_results(fout_png, goea_results, *args, **kws)
else:
# Plot separately by NS: BP, MF, CC
ns2goea_results = cx.defaultdict(list)
... | [
"def",
"plot_results",
"(",
"fout_png",
",",
"goea_results",
",",
"*",
"args",
",",
"*",
"*",
"kws",
")",
":",
"if",
"\"{NS}\"",
"not",
"in",
"fout_png",
":",
"plt_goea_results",
"(",
"fout_png",
",",
"goea_results",
",",
"*",
"args",
",",
"*",
"*",
"k... | Given a list of GOEA results, plot result GOs up to top. | [
"Given",
"a",
"list",
"of",
"GOEA",
"results",
"plot",
"result",
"GOs",
"up",
"to",
"top",
"."
] | python | train |
nathan-hoad/outbox | outbox.py | https://github.com/nathan-hoad/outbox/blob/afd28cd14023fdbcd40ad8925ea09c2a9b4d98cb/outbox.py#L219-L235 | def add_attachment(message, attachment, rfc2231=True):
'''Attach an attachment to a message as a side effect.
Arguments:
message: MIMEMultipart instance.
attachment: Attachment instance.
'''
data = attachment.read()
part = MIMEBase('application', 'octet-stream')
part.set_payloa... | [
"def",
"add_attachment",
"(",
"message",
",",
"attachment",
",",
"rfc2231",
"=",
"True",
")",
":",
"data",
"=",
"attachment",
".",
"read",
"(",
")",
"part",
"=",
"MIMEBase",
"(",
"'application'",
",",
"'octet-stream'",
")",
"part",
".",
"set_payload",
"(",... | Attach an attachment to a message as a side effect.
Arguments:
message: MIMEMultipart instance.
attachment: Attachment instance. | [
"Attach",
"an",
"attachment",
"to",
"a",
"message",
"as",
"a",
"side",
"effect",
"."
] | python | train |
trevisanj/a99 | a99/textinterface.py | https://github.com/trevisanj/a99/blob/193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539/a99/textinterface.py#L377-L395 | def markdown_table(data, headers):
"""
Creates MarkDown table. Returns list of strings
Arguments:
data -- [(cell00, cell01, ...), (cell10, cell11, ...), ...]
headers -- sequence of strings: (header0, header1, ...)
"""
maxx = [max([len(x) for x in column]) for column in zip(*da... | [
"def",
"markdown_table",
"(",
"data",
",",
"headers",
")",
":",
"maxx",
"=",
"[",
"max",
"(",
"[",
"len",
"(",
"x",
")",
"for",
"x",
"in",
"column",
"]",
")",
"for",
"column",
"in",
"zip",
"(",
"*",
"data",
")",
"]",
"maxx",
"=",
"[",
"max",
... | Creates MarkDown table. Returns list of strings
Arguments:
data -- [(cell00, cell01, ...), (cell10, cell11, ...), ...]
headers -- sequence of strings: (header0, header1, ...) | [
"Creates",
"MarkDown",
"table",
".",
"Returns",
"list",
"of",
"strings",
"Arguments",
":",
"data",
"--",
"[",
"(",
"cell00",
"cell01",
"...",
")",
"(",
"cell10",
"cell11",
"...",
")",
"...",
"]",
"headers",
"--",
"sequence",
"of",
"strings",
":",
"(",
... | python | train |
jenisys/parse_type | parse_type/cardinality.py | https://github.com/jenisys/parse_type/blob/7cad3a67a5ca725cb786da31f656fd473084289f/parse_type/cardinality.py#L67-L78 | def compute_group_count(self, pattern):
"""Compute the number of regexp match groups when the pattern is provided
to the :func:`Cardinality.make_pattern()` method.
:param pattern: Item regexp pattern (as string).
:return: Number of regexp match groups in the cardinality pattern.
... | [
"def",
"compute_group_count",
"(",
"self",
",",
"pattern",
")",
":",
"group_count",
"=",
"self",
".",
"group_count",
"pattern_repeated",
"=",
"1",
"if",
"self",
".",
"is_many",
"(",
")",
":",
"pattern_repeated",
"=",
"2",
"return",
"group_count",
"+",
"patte... | Compute the number of regexp match groups when the pattern is provided
to the :func:`Cardinality.make_pattern()` method.
:param pattern: Item regexp pattern (as string).
:return: Number of regexp match groups in the cardinality pattern. | [
"Compute",
"the",
"number",
"of",
"regexp",
"match",
"groups",
"when",
"the",
"pattern",
"is",
"provided",
"to",
"the",
":",
"func",
":",
"Cardinality",
".",
"make_pattern",
"()",
"method",
"."
] | python | train |
mitsei/dlkit | dlkit/handcar/learning/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/handcar/learning/sessions.py#L154-L172 | def get_objective(self, objective_id=None):
"""Gets the Objective specified by its Id.
In plenary mode, the exact Id is found or a NotFound results.
Otherwise, the returned Objective may have a different Id than
requested, such as the case where a duplicate Id was assigned to
an ... | [
"def",
"get_objective",
"(",
"self",
",",
"objective_id",
"=",
"None",
")",
":",
"if",
"objective_id",
"is",
"None",
":",
"raise",
"NullArgument",
"(",
")",
"url_path",
"=",
"construct_url",
"(",
"'objectives'",
",",
"obj_id",
"=",
"objective_id",
")",
"retu... | Gets the Objective specified by its Id.
In plenary mode, the exact Id is found or a NotFound results.
Otherwise, the returned Objective may have a different Id than
requested, such as the case where a duplicate Id was assigned to
an Objective and retained for compatibility.
arg: ... | [
"Gets",
"the",
"Objective",
"specified",
"by",
"its",
"Id",
".",
"In",
"plenary",
"mode",
"the",
"exact",
"Id",
"is",
"found",
"or",
"a",
"NotFound",
"results",
".",
"Otherwise",
"the",
"returned",
"Objective",
"may",
"have",
"a",
"different",
"Id",
"than"... | python | train |
gwastro/pycbc | pycbc/tmpltbank/coord_utils.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/tmpltbank/coord_utils.py#L26-L73 | def estimate_mass_range(numPoints, massRangeParams, metricParams, fUpper,\
covary=True):
"""
This function will generate a large set of points with random masses and
spins (using pycbc.tmpltbank.get_random_mass) and translate these points
into the xi_i coordinate system for the g... | [
"def",
"estimate_mass_range",
"(",
"numPoints",
",",
"massRangeParams",
",",
"metricParams",
",",
"fUpper",
",",
"covary",
"=",
"True",
")",
":",
"vals_set",
"=",
"get_random_mass",
"(",
"numPoints",
",",
"massRangeParams",
")",
"mass1",
"=",
"vals_set",
"[",
... | This function will generate a large set of points with random masses and
spins (using pycbc.tmpltbank.get_random_mass) and translate these points
into the xi_i coordinate system for the given upper frequency cutoff.
Parameters
----------
numPoints : int
Number of systems to simulate
mas... | [
"This",
"function",
"will",
"generate",
"a",
"large",
"set",
"of",
"points",
"with",
"random",
"masses",
"and",
"spins",
"(",
"using",
"pycbc",
".",
"tmpltbank",
".",
"get_random_mass",
")",
"and",
"translate",
"these",
"points",
"into",
"the",
"xi_i",
"coor... | python | train |
MLAB-project/pymlab | examples/I2CSPI_HBSTEP_CAMPAP.py | https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/examples/I2CSPI_HBSTEP_CAMPAP.py#L88-L98 | def Move(self, units):
' Move some distance units from current position '
steps = units * self.SPU # translate units to steps
if steps > 0: # look for direction
spi.SPI_write_byte(self.CS, 0x40 | (~self.Dir & 1))
else:
... | [
"def",
"Move",
"(",
"self",
",",
"units",
")",
":",
"steps",
"=",
"units",
"*",
"self",
".",
"SPU",
"# translate units to steps ",
"if",
"steps",
">",
"0",
":",
"# look for direction",
"spi",
".",
"SPI_write_byte",
"(",
"self",
".",
"CS",
",",
"0x40",
"|... | Move some distance units from current position | [
"Move",
"some",
"distance",
"units",
"from",
"current",
"position"
] | python | train |
pandas-dev/pandas | pandas/io/parsers.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/parsers.py#L3535-L3571 | def get_rows(self, infer_nrows, skiprows=None):
"""
Read rows from self.f, skipping as specified.
We distinguish buffer_rows (the first <= infer_nrows
lines) from the rows returned to detect_colspecs
because it's simpler to leave the other locations
with skiprows logic a... | [
"def",
"get_rows",
"(",
"self",
",",
"infer_nrows",
",",
"skiprows",
"=",
"None",
")",
":",
"if",
"skiprows",
"is",
"None",
":",
"skiprows",
"=",
"set",
"(",
")",
"buffer_rows",
"=",
"[",
"]",
"detect_rows",
"=",
"[",
"]",
"for",
"i",
",",
"row",
"... | Read rows from self.f, skipping as specified.
We distinguish buffer_rows (the first <= infer_nrows
lines) from the rows returned to detect_colspecs
because it's simpler to leave the other locations
with skiprows logic alone than to modify them to
deal with the fact we skipped so... | [
"Read",
"rows",
"from",
"self",
".",
"f",
"skipping",
"as",
"specified",
"."
] | python | train |
bluedynamics/cone.ugm | src/cone/ugm/browser/remote.py | https://github.com/bluedynamics/cone.ugm/blob/3c197075f3f6e94781289311c5637bb9c8e5597c/src/cone/ugm/browser/remote.py#L12-L124 | def remote_add_user(model, request):
"""Add user via remote service.
Returns a JSON response containing success state and a message indicating
what happened::
{
success: true, // respective false
message: 'message'
}
Expected request parameters:
id
New user id.
... | [
"def",
"remote_add_user",
"(",
"model",
",",
"request",
")",
":",
"params",
"=",
"request",
".",
"params",
"uid",
"=",
"params",
".",
"get",
"(",
"'id'",
")",
"if",
"not",
"uid",
":",
"return",
"{",
"'success'",
":",
"False",
",",
"'message'",
":",
"... | Add user via remote service.
Returns a JSON response containing success state and a message indicating
what happened::
{
success: true, // respective false
message: 'message'
}
Expected request parameters:
id
New user id.
password
User password to be set ... | [
"Add",
"user",
"via",
"remote",
"service",
"."
] | python | train |
annoviko/pyclustering | pyclustering/cluster/ga.py | https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/cluster/ga.py#L675-L706 | def _calc_fitness_function(centres, data, chromosomes):
"""!
@brief Calculate fitness function values for chromosomes.
@param[in] centres (list): Cluster centers.
@param[in] data (list): Input data that is used for clustering process.
@param[in] chromosomes (list): Chrom... | [
"def",
"_calc_fitness_function",
"(",
"centres",
",",
"data",
",",
"chromosomes",
")",
":",
"# Get count of chromosomes and clusters",
"count_chromosome",
"=",
"len",
"(",
"chromosomes",
")",
"# Initialize fitness function values",
"fitness_function",
"=",
"np",
".",
"zer... | !
@brief Calculate fitness function values for chromosomes.
@param[in] centres (list): Cluster centers.
@param[in] data (list): Input data that is used for clustering process.
@param[in] chromosomes (list): Chromosomes whose fitness function's values are calculated.
... | [
"!"
] | python | valid |
NatLibFi/Skosify | skosify/skosify.py | https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/skosify.py#L546-L569 | def setup_top_concepts(rdf, mark_top_concepts):
"""Determine the top concepts of each concept scheme and mark them using
hasTopConcept/topConceptOf."""
for cs in sorted(rdf.subjects(RDF.type, SKOS.ConceptScheme)):
for conc in sorted(rdf.subjects(SKOS.inScheme, cs)):
if (conc, RDF.type, ... | [
"def",
"setup_top_concepts",
"(",
"rdf",
",",
"mark_top_concepts",
")",
":",
"for",
"cs",
"in",
"sorted",
"(",
"rdf",
".",
"subjects",
"(",
"RDF",
".",
"type",
",",
"SKOS",
".",
"ConceptScheme",
")",
")",
":",
"for",
"conc",
"in",
"sorted",
"(",
"rdf",... | Determine the top concepts of each concept scheme and mark them using
hasTopConcept/topConceptOf. | [
"Determine",
"the",
"top",
"concepts",
"of",
"each",
"concept",
"scheme",
"and",
"mark",
"them",
"using",
"hasTopConcept",
"/",
"topConceptOf",
"."
] | python | train |
tchellomello/python-arlo | pyarlo/camera.py | https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/camera.py#L304-L317 | def motion_detection_sensitivity(self):
"""Sensitivity level of Camera motion detection."""
if not self.triggers:
return None
for trigger in self.triggers:
if trigger.get("type") != "pirMotionActive":
continue
sensitivity = trigger.get("sensi... | [
"def",
"motion_detection_sensitivity",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"triggers",
":",
"return",
"None",
"for",
"trigger",
"in",
"self",
".",
"triggers",
":",
"if",
"trigger",
".",
"get",
"(",
"\"type\"",
")",
"!=",
"\"pirMotionActive\"",
... | Sensitivity level of Camera motion detection. | [
"Sensitivity",
"level",
"of",
"Camera",
"motion",
"detection",
"."
] | python | train |
amzn/ion-python | amazon/ion/reader_text.py | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L474-L480 | def set_ion_type(self, ion_type):
"""Sets context to the given IonType."""
if ion_type is self.ion_type:
return self
self.ion_type = ion_type
self.line_comment = False
return self | [
"def",
"set_ion_type",
"(",
"self",
",",
"ion_type",
")",
":",
"if",
"ion_type",
"is",
"self",
".",
"ion_type",
":",
"return",
"self",
"self",
".",
"ion_type",
"=",
"ion_type",
"self",
".",
"line_comment",
"=",
"False",
"return",
"self"
] | Sets context to the given IonType. | [
"Sets",
"context",
"to",
"the",
"given",
"IonType",
"."
] | python | train |
Neurita/boyle | boyle/dicom/comparison.py | https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/dicom/comparison.py#L521-L540 | def merge_groups(self, indices):
"""Extend the lists within the DICOM groups dictionary.
The indices will indicate which list have to be extended by which
other list.
Parameters
----------
indices: list or tuple of 2 iterables of int, bot having the same len
... | [
"def",
"merge_groups",
"(",
"self",
",",
"indices",
")",
":",
"try",
":",
"merged",
"=",
"merge_dict_of_lists",
"(",
"self",
".",
"dicom_groups",
",",
"indices",
",",
"pop_later",
"=",
"True",
",",
"copy",
"=",
"True",
")",
"self",
".",
"dicom_groups",
"... | Extend the lists within the DICOM groups dictionary.
The indices will indicate which list have to be extended by which
other list.
Parameters
----------
indices: list or tuple of 2 iterables of int, bot having the same len
The indices of the lists that have to be me... | [
"Extend",
"the",
"lists",
"within",
"the",
"DICOM",
"groups",
"dictionary",
".",
"The",
"indices",
"will",
"indicate",
"which",
"list",
"have",
"to",
"be",
"extended",
"by",
"which",
"other",
"list",
"."
] | python | valid |
mlperf/training | image_classification/tensorflow/official/resnet/imagenet_main.py | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/resnet/imagenet_main.py#L242-L273 | def _get_block_sizes(resnet_size):
"""Retrieve the size of each block_layer in the ResNet model.
The number of block layers used for the Resnet model varies according
to the size of the model. This helper grabs the layer set we want, throwing
an error if a non-standard size has been selected.
Args:
resn... | [
"def",
"_get_block_sizes",
"(",
"resnet_size",
")",
":",
"choices",
"=",
"{",
"18",
":",
"[",
"2",
",",
"2",
",",
"2",
",",
"2",
"]",
",",
"34",
":",
"[",
"3",
",",
"4",
",",
"6",
",",
"3",
"]",
",",
"50",
":",
"[",
"3",
",",
"4",
",",
... | Retrieve the size of each block_layer in the ResNet model.
The number of block layers used for the Resnet model varies according
to the size of the model. This helper grabs the layer set we want, throwing
an error if a non-standard size has been selected.
Args:
resnet_size: The number of convolutional lay... | [
"Retrieve",
"the",
"size",
"of",
"each",
"block_layer",
"in",
"the",
"ResNet",
"model",
"."
] | python | train |
deepmind/pysc2 | pysc2/lib/stopwatch.py | https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/stopwatch.py#L254-L282 | def str(self, threshold=0.1):
"""Return a string representation of the timings."""
if not self._times:
return ""
total = sum(s.sum for k, s in six.iteritems(self._times) if "." not in k)
table = [["", "% total", "sum", "avg", "dev", "min", "max", "num"]]
for k, v in sorted(self._times.items())... | [
"def",
"str",
"(",
"self",
",",
"threshold",
"=",
"0.1",
")",
":",
"if",
"not",
"self",
".",
"_times",
":",
"return",
"\"\"",
"total",
"=",
"sum",
"(",
"s",
".",
"sum",
"for",
"k",
",",
"s",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"_ti... | Return a string representation of the timings. | [
"Return",
"a",
"string",
"representation",
"of",
"the",
"timings",
"."
] | python | train |
saltstack/salt | salt/utils/aggregation.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/aggregation.py#L151-L185 | def levelise(level):
'''
Describe which levels are allowed to do deep merging.
level can be:
True
all levels are True
False
all levels are False
an int
only the first levels are True, the others are False
a sequence
it describes which levels are True, it ... | [
"def",
"levelise",
"(",
"level",
")",
":",
"if",
"not",
"level",
":",
"# False, 0, [] ...",
"return",
"False",
",",
"False",
"if",
"level",
"is",
"True",
":",
"return",
"True",
",",
"True",
"if",
"isinstance",
"(",
"level",
",",
"int",
")",
":",
"retur... | Describe which levels are allowed to do deep merging.
level can be:
True
all levels are True
False
all levels are False
an int
only the first levels are True, the others are False
a sequence
it describes which levels are True, it can be:
* a list of bool... | [
"Describe",
"which",
"levels",
"are",
"allowed",
"to",
"do",
"deep",
"merging",
"."
] | python | train |
ming060/robotframework-uiautomatorlibrary | uiautomatorlibrary/Mobile.py | https://github.com/ming060/robotframework-uiautomatorlibrary/blob/b70202b6a8aa68b4efd9d029c2845407fb33451a/uiautomatorlibrary/Mobile.py#L296-L302 | def swipe_bottom(self, steps=10, *args, **selectors):
"""
Swipe the UI object with *selectors* from center to bottom
See `Swipe Left` for more details.
"""
self.device(**selectors).swipe.down(steps=steps) | [
"def",
"swipe_bottom",
"(",
"self",
",",
"steps",
"=",
"10",
",",
"*",
"args",
",",
"*",
"*",
"selectors",
")",
":",
"self",
".",
"device",
"(",
"*",
"*",
"selectors",
")",
".",
"swipe",
".",
"down",
"(",
"steps",
"=",
"steps",
")"
] | Swipe the UI object with *selectors* from center to bottom
See `Swipe Left` for more details. | [
"Swipe",
"the",
"UI",
"object",
"with",
"*",
"selectors",
"*",
"from",
"center",
"to",
"bottom"
] | python | train |
ask/carrot | carrot/backends/queue.py | https://github.com/ask/carrot/blob/5889a25cd2e274642071c9bba39772f4b3e3d9da/carrot/backends/queue.py#L74-L78 | def queue_purge(self, queue, **kwargs):
"""Discard all messages in the queue."""
qsize = mqueue.qsize()
mqueue.queue.clear()
return qsize | [
"def",
"queue_purge",
"(",
"self",
",",
"queue",
",",
"*",
"*",
"kwargs",
")",
":",
"qsize",
"=",
"mqueue",
".",
"qsize",
"(",
")",
"mqueue",
".",
"queue",
".",
"clear",
"(",
")",
"return",
"qsize"
] | Discard all messages in the queue. | [
"Discard",
"all",
"messages",
"in",
"the",
"queue",
"."
] | python | train |
uber/rides-python-sdk | uber_rides/client.py | https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/uber_rides/client.py#L211-L242 | def get_promotions(
self,
start_latitude,
start_longitude,
end_latitude,
end_longitude,
):
"""Get information about the promotions available to a user.
Parameters
start_latitude (float)
The latitude component of a start location.
... | [
"def",
"get_promotions",
"(",
"self",
",",
"start_latitude",
",",
"start_longitude",
",",
"end_latitude",
",",
"end_longitude",
",",
")",
":",
"args",
"=",
"OrderedDict",
"(",
"[",
"(",
"'start_latitude'",
",",
"start_latitude",
")",
",",
"(",
"'start_longitude'... | Get information about the promotions available to a user.
Parameters
start_latitude (float)
The latitude component of a start location.
start_longitude (float)
The longitude component of a start location.
end_latitude (float)
T... | [
"Get",
"information",
"about",
"the",
"promotions",
"available",
"to",
"a",
"user",
"."
] | python | train |
networks-lab/metaknowledge | metaknowledge/medline/tagProcessing/tagFunctions.py | https://github.com/networks-lab/metaknowledge/blob/8162bf95e66bb6f9916081338e6e2a6132faff75/metaknowledge/medline/tagProcessing/tagFunctions.py#L218-L225 | def AD(val):
"""Affiliation
Undoing what the parser does then splitting at the semicolons and dropping newlines extra fitlering is required beacuse some AD's end with a semicolon"""
retDict = {}
for v in val:
split = v.split(' : ')
retDict[split[0]] = [s for s in' : '.join(split[1:]).rep... | [
"def",
"AD",
"(",
"val",
")",
":",
"retDict",
"=",
"{",
"}",
"for",
"v",
"in",
"val",
":",
"split",
"=",
"v",
".",
"split",
"(",
"' : '",
")",
"retDict",
"[",
"split",
"[",
"0",
"]",
"]",
"=",
"[",
"s",
"for",
"s",
"in",
"' : '",
".",
"join... | Affiliation
Undoing what the parser does then splitting at the semicolons and dropping newlines extra fitlering is required beacuse some AD's end with a semicolon | [
"Affiliation",
"Undoing",
"what",
"the",
"parser",
"does",
"then",
"splitting",
"at",
"the",
"semicolons",
"and",
"dropping",
"newlines",
"extra",
"fitlering",
"is",
"required",
"beacuse",
"some",
"AD",
"s",
"end",
"with",
"a",
"semicolon"
] | python | train |
Trax-air/swagger-parser | swagger_parser/swagger_parser.py | https://github.com/Trax-air/swagger-parser/blob/d97f962a417e76320c59c33dcb223e4373e516d5/swagger_parser/swagger_parser.py#L535-L569 | def _validate_type(self, properties_spec, value):
"""Validate the given value with the given property spec.
Args:
properties_dict: specification of the property to check (From definition not route).
value: value to check.
Returns:
True if the value is valid ... | [
"def",
"_validate_type",
"(",
"self",
",",
"properties_spec",
",",
"value",
")",
":",
"if",
"'type'",
"not",
"in",
"properties_spec",
".",
"keys",
"(",
")",
":",
"# Validate sub definition",
"def_name",
"=",
"self",
".",
"get_definition_name_from_ref",
"(",
"pro... | Validate the given value with the given property spec.
Args:
properties_dict: specification of the property to check (From definition not route).
value: value to check.
Returns:
True if the value is valid for the given spec. | [
"Validate",
"the",
"given",
"value",
"with",
"the",
"given",
"property",
"spec",
"."
] | python | train |
cldf/pycldf | src/pycldf/__main__.py | https://github.com/cldf/pycldf/blob/636f1eb3ea769394e14ad9e42a83b6096efa9728/src/pycldf/__main__.py#L37-L47 | def validate(args):
"""
cldf validate <DATASET>
Validate a dataset against the CLDF specification, i.e. check
- whether required tables and columns are present
- whether values for required columns are present
- the referential integrity of the dataset
"""
ds = _get_dataset(args)
ds... | [
"def",
"validate",
"(",
"args",
")",
":",
"ds",
"=",
"_get_dataset",
"(",
"args",
")",
"ds",
".",
"validate",
"(",
"log",
"=",
"args",
".",
"log",
")"
] | cldf validate <DATASET>
Validate a dataset against the CLDF specification, i.e. check
- whether required tables and columns are present
- whether values for required columns are present
- the referential integrity of the dataset | [
"cldf",
"validate",
"<DATASET",
">"
] | python | valid |
pypa/pipenv | pipenv/vendor/urllib3/packages/backports/makefile.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/packages/backports/makefile.py#L14-L53 | def backport_makefile(self, mode="r", buffering=None, encoding=None,
errors=None, newline=None):
"""
Backport of ``socket.makefile`` from Python 3.5.
"""
if not set(mode) <= {"r", "w", "b"}:
raise ValueError(
"invalid mode %r (only r, w, b allowed)" % (mode,)
... | [
"def",
"backport_makefile",
"(",
"self",
",",
"mode",
"=",
"\"r\"",
",",
"buffering",
"=",
"None",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"None",
",",
"newline",
"=",
"None",
")",
":",
"if",
"not",
"set",
"(",
"mode",
")",
"<=",
"{",
"\"... | Backport of ``socket.makefile`` from Python 3.5. | [
"Backport",
"of",
"socket",
".",
"makefile",
"from",
"Python",
"3",
".",
"5",
"."
] | python | train |
abourget/gevent-socketio | socketio/virtsocket.py | https://github.com/abourget/gevent-socketio/blob/1cdb1594a315326987a17ce0924ea448a82fab01/socketio/virtsocket.py#L331-L334 | def send_packet(self, pkt):
"""Low-level interface to queue a packet on the wire (encoded as wire
protocol"""
self.put_client_msg(packet.encode(pkt, self.json_dumps)) | [
"def",
"send_packet",
"(",
"self",
",",
"pkt",
")",
":",
"self",
".",
"put_client_msg",
"(",
"packet",
".",
"encode",
"(",
"pkt",
",",
"self",
".",
"json_dumps",
")",
")"
] | Low-level interface to queue a packet on the wire (encoded as wire
protocol | [
"Low",
"-",
"level",
"interface",
"to",
"queue",
"a",
"packet",
"on",
"the",
"wire",
"(",
"encoded",
"as",
"wire",
"protocol"
] | python | valid |
RetailMeNotSandbox/acky | acky/ec2.py | https://github.com/RetailMeNotSandbox/acky/blob/fcd4d092c42892ede7c924cafc41e9cf4be3fb9f/acky/ec2.py#L260-L288 | def Launcher(self, config=None):
"""Provides a configurable launcher for EC2 instances."""
class _launcher(EC2ApiClient):
"""Configurable launcher for EC2 instances. Create the Launcher
(passing an optional dict of its attributes), set its attributes
(as described in ... | [
"def",
"Launcher",
"(",
"self",
",",
"config",
"=",
"None",
")",
":",
"class",
"_launcher",
"(",
"EC2ApiClient",
")",
":",
"\"\"\"Configurable launcher for EC2 instances. Create the Launcher\n (passing an optional dict of its attributes), set its attributes\n (a... | Provides a configurable launcher for EC2 instances. | [
"Provides",
"a",
"configurable",
"launcher",
"for",
"EC2",
"instances",
"."
] | python | train |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/validators.py | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/validators.py#L104-L108 | def validate_owner_repo_distro(ctx, param, value):
"""Ensure that owner/repo/distro/version is formatted correctly."""
# pylint: disable=unused-argument
form = "OWNER/REPO/DISTRO[/RELEASE]"
return validate_slashes(param, value, minimum=3, maximum=4, form=form) | [
"def",
"validate_owner_repo_distro",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"# pylint: disable=unused-argument",
"form",
"=",
"\"OWNER/REPO/DISTRO[/RELEASE]\"",
"return",
"validate_slashes",
"(",
"param",
",",
"value",
",",
"minimum",
"=",
"3",
",",
"maxi... | Ensure that owner/repo/distro/version is formatted correctly. | [
"Ensure",
"that",
"owner",
"/",
"repo",
"/",
"distro",
"/",
"version",
"is",
"formatted",
"correctly",
"."
] | python | train |
materialsproject/pymatgen | pymatgen/symmetry/groups.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/symmetry/groups.py#L66-L77 | def is_subgroup(self, supergroup):
"""
True if this group is a subgroup of the supplied group.
Args:
supergroup (SymmetryGroup): Supergroup to test.
Returns:
True if this group is a subgroup of the supplied group.
"""
warnings.warn("This is not f... | [
"def",
"is_subgroup",
"(",
"self",
",",
"supergroup",
")",
":",
"warnings",
".",
"warn",
"(",
"\"This is not fully functional. Only trivial subsets are tested right now. \"",
")",
"return",
"set",
"(",
"self",
".",
"symmetry_ops",
")",
".",
"issubset",
"(",
"supergrou... | True if this group is a subgroup of the supplied group.
Args:
supergroup (SymmetryGroup): Supergroup to test.
Returns:
True if this group is a subgroup of the supplied group. | [
"True",
"if",
"this",
"group",
"is",
"a",
"subgroup",
"of",
"the",
"supplied",
"group",
"."
] | python | train |
flo-compbio/genometools | genometools/expression/matrix.py | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/expression/matrix.py#L469-L493 | def write_tsv(self, file_path: str, encoding: str = 'UTF-8',
sep: str = '\t'):
"""Write expression matrix to a tab-delimited text file.
Parameters
----------
file_path: str
The path of the output file.
encoding: str, optional
The file en... | [
"def",
"write_tsv",
"(",
"self",
",",
"file_path",
":",
"str",
",",
"encoding",
":",
"str",
"=",
"'UTF-8'",
",",
"sep",
":",
"str",
"=",
"'\\t'",
")",
":",
"#if six.PY2:",
"# sep = sep.encode('UTF-8')",
"self",
".",
"to_csv",
"(",
"file_path",
",",
"sep... | Write expression matrix to a tab-delimited text file.
Parameters
----------
file_path: str
The path of the output file.
encoding: str, optional
The file encoding. ("UTF-8")
Returns
-------
None | [
"Write",
"expression",
"matrix",
"to",
"a",
"tab",
"-",
"delimited",
"text",
"file",
"."
] | python | train |
drbild/sslpsk | sslpsk/sslpsk.py | https://github.com/drbild/sslpsk/blob/583f7b1f775c33ddc1196a400188005c50cfeb0f/sslpsk/sslpsk.py#L38-L47 | def _python_psk_client_callback(ssl_id, hint):
"""Called by _sslpsk.c to return the (psk, identity) tuple for the socket with
the specified ssl socket.
"""
if ssl_id not in _callbacks:
return ("", "")
else:
res = _callbacks[ssl_id](hint)
return res if isinstance(res, tuple) ... | [
"def",
"_python_psk_client_callback",
"(",
"ssl_id",
",",
"hint",
")",
":",
"if",
"ssl_id",
"not",
"in",
"_callbacks",
":",
"return",
"(",
"\"\"",
",",
"\"\"",
")",
"else",
":",
"res",
"=",
"_callbacks",
"[",
"ssl_id",
"]",
"(",
"hint",
")",
"return",
... | Called by _sslpsk.c to return the (psk, identity) tuple for the socket with
the specified ssl socket. | [
"Called",
"by",
"_sslpsk",
".",
"c",
"to",
"return",
"the",
"(",
"psk",
"identity",
")",
"tuple",
"for",
"the",
"socket",
"with",
"the",
"specified",
"ssl",
"socket",
"."
] | python | train |
shexSpec/grammar | parsers/python/pyshexc/parser_impl/shex_shape_expression_parser.py | https://github.com/shexSpec/grammar/blob/4497cd1f73fa6703bca6e2cb53ba9c120f22e48c/parsers/python/pyshexc/parser_impl/shex_shape_expression_parser.py#L46-L55 | def visitShapeOr(self, ctx: ShExDocParser.ShapeOrContext):
""" shapeOr: shapeAnd (KW_OR shapeAnd)* """
if len(ctx.shapeAnd()) > 1:
self.expr = ShapeOr(id=self.label, shapeExprs=[])
for sa in ctx.shapeAnd():
sep = ShexShapeExpressionParser(self.context)
... | [
"def",
"visitShapeOr",
"(",
"self",
",",
"ctx",
":",
"ShExDocParser",
".",
"ShapeOrContext",
")",
":",
"if",
"len",
"(",
"ctx",
".",
"shapeAnd",
"(",
")",
")",
">",
"1",
":",
"self",
".",
"expr",
"=",
"ShapeOr",
"(",
"id",
"=",
"self",
".",
"label"... | shapeOr: shapeAnd (KW_OR shapeAnd)* | [
"shapeOr",
":",
"shapeAnd",
"(",
"KW_OR",
"shapeAnd",
")",
"*"
] | python | train |
spyder-ide/spyder | spyder/plugins/ipythonconsole/plugin.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/plugin.py#L191-L219 | def apply_plugin_settings(self, options):
"""Apply configuration file's plugin settings"""
font_n = 'plugin_font'
font_o = self.get_plugin_font()
help_n = 'connect_to_oi'
help_o = CONF.get('help', 'connect/ipython_console')
color_scheme_n = 'color_scheme_name'
... | [
"def",
"apply_plugin_settings",
"(",
"self",
",",
"options",
")",
":",
"font_n",
"=",
"'plugin_font'",
"font_o",
"=",
"self",
".",
"get_plugin_font",
"(",
")",
"help_n",
"=",
"'connect_to_oi'",
"help_o",
"=",
"CONF",
".",
"get",
"(",
"'help'",
",",
"'connect... | Apply configuration file's plugin settings | [
"Apply",
"configuration",
"file",
"s",
"plugin",
"settings"
] | python | train |
stianaske/pybotvac | pybotvac/account.py | https://github.com/stianaske/pybotvac/blob/e3f655e81070ff209aaa4efb7880016cf2599e6d/pybotvac/account.py#L151-L163 | def refresh_persistent_maps(self):
"""
Get information about persistent maps of the robots.
:return:
"""
for robot in self._robots:
resp2 = (requests.get(urljoin(
self.ENDPOINT,
'users/me/robots/{}/persistent_maps'.format(robot.serial)... | [
"def",
"refresh_persistent_maps",
"(",
"self",
")",
":",
"for",
"robot",
"in",
"self",
".",
"_robots",
":",
"resp2",
"=",
"(",
"requests",
".",
"get",
"(",
"urljoin",
"(",
"self",
".",
"ENDPOINT",
",",
"'users/me/robots/{}/persistent_maps'",
".",
"format",
"... | Get information about persistent maps of the robots.
:return: | [
"Get",
"information",
"about",
"persistent",
"maps",
"of",
"the",
"robots",
"."
] | python | valid |
poppy-project/pypot | pypot/dynamixel/io/io_320.py | https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/dynamixel/io/io_320.py#L32-L43 | def factory_reset(self, ids, except_ids=False, except_baudrate_and_ids=False):
""" Reset all motors on the bus to their factory default settings. """
mode = (0x02 if except_baudrate_and_ids else
0x01 if except_ids else 0xFF)
for id in ids:
try:
self.... | [
"def",
"factory_reset",
"(",
"self",
",",
"ids",
",",
"except_ids",
"=",
"False",
",",
"except_baudrate_and_ids",
"=",
"False",
")",
":",
"mode",
"=",
"(",
"0x02",
"if",
"except_baudrate_and_ids",
"else",
"0x01",
"if",
"except_ids",
"else",
"0xFF",
")",
"for... | Reset all motors on the bus to their factory default settings. | [
"Reset",
"all",
"motors",
"on",
"the",
"bus",
"to",
"their",
"factory",
"default",
"settings",
"."
] | python | train |
SeabornGames/RequestClient | example_bindings/user.py | https://github.com/SeabornGames/RequestClient/blob/21aeb951ddfdb6ee453ad0edc896ff224e06425d/example_bindings/user.py#L132-L142 | def post(self, user_ids=None, usernames=None, status=None):
"""
:param user_ids: list of int of the user_ids to return
:param usernames: list of str of the usernames to return
:param status: str of the status
:return: list of User
"""
return self.conn... | [
"def",
"post",
"(",
"self",
",",
"user_ids",
"=",
"None",
",",
"usernames",
"=",
"None",
",",
"status",
"=",
"None",
")",
":",
"return",
"self",
".",
"connection",
".",
"post",
"(",
"'user/array'",
",",
"data",
"=",
"dict",
"(",
"user_ids",
"=",
"use... | :param user_ids: list of int of the user_ids to return
:param usernames: list of str of the usernames to return
:param status: str of the status
:return: list of User | [
":",
"param",
"user_ids",
":",
"list",
"of",
"int",
"of",
"the",
"user_ids",
"to",
"return",
":",
"param",
"usernames",
":",
"list",
"of",
"str",
"of",
"the",
"usernames",
"to",
"return",
":",
"param",
"status",
":",
"str",
"of",
"the",
"status",
":",
... | python | train |
spyder-ide/spyder | spyder/plugins/editor/widgets/base.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/base.py#L520-L543 | def cursor_position_changed(self):
"""Brace matching"""
if self.bracepos is not None:
self.__highlight(self.bracepos, cancel=True)
self.bracepos = None
cursor = self.textCursor()
if cursor.position() == 0:
return
cursor.movePosition(QTe... | [
"def",
"cursor_position_changed",
"(",
"self",
")",
":",
"if",
"self",
".",
"bracepos",
"is",
"not",
"None",
":",
"self",
".",
"__highlight",
"(",
"self",
".",
"bracepos",
",",
"cancel",
"=",
"True",
")",
"self",
".",
"bracepos",
"=",
"None",
"cursor",
... | Brace matching | [
"Brace",
"matching"
] | python | train |
mozilla/mozilla-django-oidc | mozilla_django_oidc/contrib/drf.py | https://github.com/mozilla/mozilla-django-oidc/blob/e780130deacccbafc85a92f48d1407e042f5f955/mozilla_django_oidc/contrib/drf.py#L96-L120 | def get_access_token(self, request):
"""
Get the access token based on a request.
Returns None if no authentication details were provided. Raises
AuthenticationFailed if the token is incorrect.
"""
header = authentication.get_authorization_header(request)
if not ... | [
"def",
"get_access_token",
"(",
"self",
",",
"request",
")",
":",
"header",
"=",
"authentication",
".",
"get_authorization_header",
"(",
"request",
")",
"if",
"not",
"header",
":",
"return",
"None",
"header",
"=",
"header",
".",
"decode",
"(",
"authentication"... | Get the access token based on a request.
Returns None if no authentication details were provided. Raises
AuthenticationFailed if the token is incorrect. | [
"Get",
"the",
"access",
"token",
"based",
"on",
"a",
"request",
"."
] | python | train |
oscarlazoarjona/fast | build/lib/fast/rk4.py | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/rk4.py#L56-L411 | def write_rk4(path,name,laser,omega,gamma,r,Lij,states=None,verbose=1):
r"""
This function writes the Fortran code needed to calculate the time evolution of the density matrix elements
`\rho_{ij}` using the Runge-Kutta method of order 4.
INPUT:
- ``path`` - A string with the working directory where a... | [
"def",
"write_rk4",
"(",
"path",
",",
"name",
",",
"laser",
",",
"omega",
",",
"gamma",
",",
"r",
",",
"Lij",
",",
"states",
"=",
"None",
",",
"verbose",
"=",
"1",
")",
":",
"global",
"omega_rescaled",
"t0",
"=",
"time",
"(",
")",
"Ne",
"=",
"len... | r"""
This function writes the Fortran code needed to calculate the time evolution of the density matrix elements
`\rho_{ij}` using the Runge-Kutta method of order 4.
INPUT:
- ``path`` - A string with the working directory where all files will be stored. It must end with ``/``.
- ``name`` - A stri... | [
"r",
"This",
"function",
"writes",
"the",
"Fortran",
"code",
"needed",
"to",
"calculate",
"the",
"time",
"evolution",
"of",
"the",
"density",
"matrix",
"elements",
"\\",
"rho_",
"{",
"ij",
"}",
"using",
"the",
"Runge",
"-",
"Kutta",
"method",
"of",
"order"... | python | train |
pypyr/pypyr-cli | pypyr/moduleloader.py | https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/moduleloader.py#L15-L48 | def get_module(module_abs_import):
"""Use importlib to get the module dynamically.
Get instance of the module specified by the module_abs_import.
This means that module_abs_import must be resolvable from this package.
Args:
module_abs_import: string. Absolute name of module to import.
Rai... | [
"def",
"get_module",
"(",
"module_abs_import",
")",
":",
"logger",
".",
"debug",
"(",
"\"starting\"",
")",
"logger",
".",
"debug",
"(",
"f\"loading module {module_abs_import}\"",
")",
"try",
":",
"imported_module",
"=",
"importlib",
".",
"import_module",
"(",
"mod... | Use importlib to get the module dynamically.
Get instance of the module specified by the module_abs_import.
This means that module_abs_import must be resolvable from this package.
Args:
module_abs_import: string. Absolute name of module to import.
Raises:
PyModuleNotFoundError: if mod... | [
"Use",
"importlib",
"to",
"get",
"the",
"module",
"dynamically",
"."
] | python | train |
zyga/json-schema-validator | json_schema_validator/validator.py | https://github.com/zyga/json-schema-validator/blob/0504605da5c0a9a5b5b05c41b37661aec9652144/json_schema_validator/validator.py#L166-L169 | def _push_property_schema(self, prop):
"""Construct a sub-schema from a property of the current schema."""
schema = Schema(self._schema.properties[prop])
self._push_schema(schema, ".properties." + prop) | [
"def",
"_push_property_schema",
"(",
"self",
",",
"prop",
")",
":",
"schema",
"=",
"Schema",
"(",
"self",
".",
"_schema",
".",
"properties",
"[",
"prop",
"]",
")",
"self",
".",
"_push_schema",
"(",
"schema",
",",
"\".properties.\"",
"+",
"prop",
")"
] | Construct a sub-schema from a property of the current schema. | [
"Construct",
"a",
"sub",
"-",
"schema",
"from",
"a",
"property",
"of",
"the",
"current",
"schema",
"."
] | python | train |
Yubico/python-yubico | yubico/yubikey_neo_usb_hid.py | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_neo_usb_hid.py#L323-L329 | def to_frame(self, slot=SLOT.DEVICE_CONFIG):
"""
Return the current configuration as a YubiKeyFrame object.
"""
data = self.to_string()
payload = data.ljust(64, b'\0')
return yubikey_frame.YubiKeyFrame(command=slot, payload=payload) | [
"def",
"to_frame",
"(",
"self",
",",
"slot",
"=",
"SLOT",
".",
"DEVICE_CONFIG",
")",
":",
"data",
"=",
"self",
".",
"to_string",
"(",
")",
"payload",
"=",
"data",
".",
"ljust",
"(",
"64",
",",
"b'\\0'",
")",
"return",
"yubikey_frame",
".",
"YubiKeyFram... | Return the current configuration as a YubiKeyFrame object. | [
"Return",
"the",
"current",
"configuration",
"as",
"a",
"YubiKeyFrame",
"object",
"."
] | python | train |
tomplus/kubernetes_asyncio | kubernetes_asyncio/client/api/settings_v1alpha1_api.py | https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/api/settings_v1alpha1_api.py#L755-L779 | def patch_namespaced_pod_preset(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_pod_preset # noqa: E501
partially update the specified PodPreset # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please... | [
"def",
"patch_namespaced_pod_preset",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")"... | patch_namespaced_pod_preset # noqa: E501
partially update the specified PodPreset # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_pod_preset(name, namespace, body, ... | [
"patch_namespaced_pod_preset",
"#",
"noqa",
":",
"E501"
] | python | train |
evhub/coconut | coconut/compiler/header.py | https://github.com/evhub/coconut/blob/ff97177344e7604e89a0a98a977a87ed2a56fc6d/coconut/compiler/header.py#L103-L234 | def process_header_args(which, target, use_hash, no_tco, strict):
"""Create the dictionary passed to str.format in the header, target_startswith, and target_info."""
target_startswith = one_num_ver(target)
target_info = get_target_info(target)
try_backport_lru_cache = r'''try:
from backports.functo... | [
"def",
"process_header_args",
"(",
"which",
",",
"target",
",",
"use_hash",
",",
"no_tco",
",",
"strict",
")",
":",
"target_startswith",
"=",
"one_num_ver",
"(",
"target",
")",
"target_info",
"=",
"get_target_info",
"(",
"target",
")",
"try_backport_lru_cache",
... | Create the dictionary passed to str.format in the header, target_startswith, and target_info. | [
"Create",
"the",
"dictionary",
"passed",
"to",
"str",
".",
"format",
"in",
"the",
"header",
"target_startswith",
"and",
"target_info",
"."
] | python | train |
pycontribs/pyrax | pyrax/autoscale.py | https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/autoscale.py#L1041-L1053 | def update(self, scaling_group, name=None, cooldown=None, min_entities=None,
max_entities=None, metadata=None):
"""
Updates an existing ScalingGroup. One or more of the attributes can be
specified.
NOTE: if you specify metadata, it will *replace* any existing metadata.
... | [
"def",
"update",
"(",
"self",
",",
"scaling_group",
",",
"name",
"=",
"None",
",",
"cooldown",
"=",
"None",
",",
"min_entities",
"=",
"None",
",",
"max_entities",
"=",
"None",
",",
"metadata",
"=",
"None",
")",
":",
"return",
"self",
".",
"_manager",
"... | Updates an existing ScalingGroup. One or more of the attributes can be
specified.
NOTE: if you specify metadata, it will *replace* any existing metadata.
If you want to add to it, you either need to pass the complete dict of
metadata, or call the update_metadata() method. | [
"Updates",
"an",
"existing",
"ScalingGroup",
".",
"One",
"or",
"more",
"of",
"the",
"attributes",
"can",
"be",
"specified",
"."
] | python | train |
Infinidat/infi.clickhouse_orm | src/infi/clickhouse_orm/utils.py | https://github.com/Infinidat/infi.clickhouse_orm/blob/595f2023e334e3925a5c3fbfdd6083a5992a7169/src/infi/clickhouse_orm/utils.py#L50-L81 | def parse_array(array_string):
"""
Parse an array string as returned by clickhouse. For example:
"['hello', 'world']" ==> ["hello", "world"]
"[1,2,3]" ==> [1, 2, 3]
"""
# Sanity check
if len(array_string) < 2 or array_string[0] != '[' or array_string[-1] != ']':
ra... | [
"def",
"parse_array",
"(",
"array_string",
")",
":",
"# Sanity check",
"if",
"len",
"(",
"array_string",
")",
"<",
"2",
"or",
"array_string",
"[",
"0",
"]",
"!=",
"'['",
"or",
"array_string",
"[",
"-",
"1",
"]",
"!=",
"']'",
":",
"raise",
"ValueError",
... | Parse an array string as returned by clickhouse. For example:
"['hello', 'world']" ==> ["hello", "world"]
"[1,2,3]" ==> [1, 2, 3] | [
"Parse",
"an",
"array",
"string",
"as",
"returned",
"by",
"clickhouse",
".",
"For",
"example",
":",
"[",
"hello",
"world",
"]",
"==",
">",
"[",
"hello",
"world",
"]",
"[",
"1",
"2",
"3",
"]",
"==",
">",
"[",
"1",
"2",
"3",
"]"
] | python | train |
gwpy/gwpy | gwpy/io/nds2.py | https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/io/nds2.py#L524-L543 | def _strip_ctype(name, ctype, protocol=2):
"""Strip the ctype from a channel name for the given nds server version
This is needed because NDS1 servers store trend channels _including_
the suffix, but not raw channels, and NDS2 doesn't do this.
"""
# parse channel type from name (e.g. 'L1:GDS-CALIB_... | [
"def",
"_strip_ctype",
"(",
"name",
",",
"ctype",
",",
"protocol",
"=",
"2",
")",
":",
"# parse channel type from name (e.g. 'L1:GDS-CALIB_STRAIN,reduced')",
"try",
":",
"name",
",",
"ctypestr",
"=",
"name",
".",
"rsplit",
"(",
"','",
",",
"1",
")",
"except",
... | Strip the ctype from a channel name for the given nds server version
This is needed because NDS1 servers store trend channels _including_
the suffix, but not raw channels, and NDS2 doesn't do this. | [
"Strip",
"the",
"ctype",
"from",
"a",
"channel",
"name",
"for",
"the",
"given",
"nds",
"server",
"version"
] | python | train |
linnarsson-lab/loompy | loompy/loom_layer.py | https://github.com/linnarsson-lab/loompy/blob/62c8373a92b058753baa3a95331fb541f560f599/loompy/loom_layer.py#L146-L197 | def map(self, f_list: List[Callable[[np.ndarray], int]], axis: int = 0, chunksize: int = 1000, selection: np.ndarray = None) -> List[np.ndarray]:
"""
Apply a function along an axis without loading the entire dataset in memory.
Args:
f_list (list of func): Function(s) that takes a numpy ndarray as argument
... | [
"def",
"map",
"(",
"self",
",",
"f_list",
":",
"List",
"[",
"Callable",
"[",
"[",
"np",
".",
"ndarray",
"]",
",",
"int",
"]",
"]",
",",
"axis",
":",
"int",
"=",
"0",
",",
"chunksize",
":",
"int",
"=",
"1000",
",",
"selection",
":",
"np",
".",
... | Apply a function along an axis without loading the entire dataset in memory.
Args:
f_list (list of func): Function(s) that takes a numpy ndarray as argument
axis (int): Axis along which to apply the function (0 = rows, 1 = columns)
chunksize (int): Number of rows (columns) to load per chunk
selectio... | [
"Apply",
"a",
"function",
"along",
"an",
"axis",
"without",
"loading",
"the",
"entire",
"dataset",
"in",
"memory",
"."
] | python | train |
amperser/proselint | proselint/checks/redundancy/misc.py | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/checks/redundancy/misc.py#L126-L141 | def check_nordquist(text):
"""Suggest the preferred forms.
source: Richard Nordquist
source_url: http://grammar.about.com/bio/Richard-Nordquist-22176.htm
"""
err = "redundancy.nordquist"
msg = "Redundancy. Use '{}' instead of '{}'."
redundancies = [
["essential", ["abs... | [
"def",
"check_nordquist",
"(",
"text",
")",
":",
"err",
"=",
"\"redundancy.nordquist\"",
"msg",
"=",
"\"Redundancy. Use '{}' instead of '{}'.\"",
"redundancies",
"=",
"[",
"[",
"\"essential\"",
",",
"[",
"\"absolutely essential\"",
"]",
"]",
",",
"[",
"\"necessary\"",... | Suggest the preferred forms.
source: Richard Nordquist
source_url: http://grammar.about.com/bio/Richard-Nordquist-22176.htm | [
"Suggest",
"the",
"preferred",
"forms",
"."
] | python | train |
saltstack/salt | salt/modules/rh_service.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_service.py#L364-L382 | def available(name, limit=''):
'''
Return True if the named service is available. Use the ``limit`` param to
restrict results to services of that type.
CLI Examples:
.. code-block:: bash
salt '*' service.available sshd
salt '*' service.available sshd limit=upstart
salt '*... | [
"def",
"available",
"(",
"name",
",",
"limit",
"=",
"''",
")",
":",
"if",
"limit",
"==",
"'upstart'",
":",
"return",
"_service_is_upstart",
"(",
"name",
")",
"elif",
"limit",
"==",
"'sysvinit'",
":",
"return",
"_service_is_sysv",
"(",
"name",
")",
"else",
... | Return True if the named service is available. Use the ``limit`` param to
restrict results to services of that type.
CLI Examples:
.. code-block:: bash
salt '*' service.available sshd
salt '*' service.available sshd limit=upstart
salt '*' service.available sshd limit=sysvinit | [
"Return",
"True",
"if",
"the",
"named",
"service",
"is",
"available",
".",
"Use",
"the",
"limit",
"param",
"to",
"restrict",
"results",
"to",
"services",
"of",
"that",
"type",
"."
] | python | train |
laurencium/Causalinference | causalinference/core/summary.py | https://github.com/laurencium/Causalinference/blob/3b20ae0560c711628fba47975180c8484d8aa3e7/causalinference/core/summary.py#L40-L49 | def _summarize_pscore(self, pscore_c, pscore_t):
"""
Called by Strata class during initialization.
"""
self._dict['p_min'] = min(pscore_c.min(), pscore_t.min())
self._dict['p_max'] = max(pscore_c.max(), pscore_t.max())
self._dict['p_c_mean'] = pscore_c.mean()
self._dict['p_t_mean'] = pscore_t.mean() | [
"def",
"_summarize_pscore",
"(",
"self",
",",
"pscore_c",
",",
"pscore_t",
")",
":",
"self",
".",
"_dict",
"[",
"'p_min'",
"]",
"=",
"min",
"(",
"pscore_c",
".",
"min",
"(",
")",
",",
"pscore_t",
".",
"min",
"(",
")",
")",
"self",
".",
"_dict",
"["... | Called by Strata class during initialization. | [
"Called",
"by",
"Strata",
"class",
"during",
"initialization",
"."
] | python | train |
dmlc/gluon-nlp | src/gluonnlp/model/convolutional_encoder.py | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/convolutional_encoder.py#L135-L166 | def hybrid_forward(self, F, inputs, mask=None): # pylint: disable=arguments-differ
r"""
Forward computation for char_encoder
Parameters
----------
inputs: NDArray
The input tensor is of shape `(seq_len, batch_size, embedding_size)` TNC.
mask: NDArray
... | [
"def",
"hybrid_forward",
"(",
"self",
",",
"F",
",",
"inputs",
",",
"mask",
"=",
"None",
")",
":",
"# pylint: disable=arguments-differ",
"if",
"mask",
"is",
"not",
"None",
":",
"inputs",
"=",
"F",
".",
"broadcast_mul",
"(",
"inputs",
",",
"mask",
".",
"e... | r"""
Forward computation for char_encoder
Parameters
----------
inputs: NDArray
The input tensor is of shape `(seq_len, batch_size, embedding_size)` TNC.
mask: NDArray
The mask applied to the input of shape `(seq_len, batch_size)`, the mask will
... | [
"r",
"Forward",
"computation",
"for",
"char_encoder"
] | python | train |
ianmiell/shutit | shutit_class.py | https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L2657-L2664 | def get_shutit_pexpect_session_from_id(self, shutit_pexpect_id):
"""Get the pexpect session from the given identifier.
"""
shutit_global.shutit_global_object.yield_to_draw()
for key in self.shutit_pexpect_sessions:
if self.shutit_pexpect_sessions[key].pexpect_session_id == shutit_pexpect_id:
return self.... | [
"def",
"get_shutit_pexpect_session_from_id",
"(",
"self",
",",
"shutit_pexpect_id",
")",
":",
"shutit_global",
".",
"shutit_global_object",
".",
"yield_to_draw",
"(",
")",
"for",
"key",
"in",
"self",
".",
"shutit_pexpect_sessions",
":",
"if",
"self",
".",
"shutit_pe... | Get the pexpect session from the given identifier. | [
"Get",
"the",
"pexpect",
"session",
"from",
"the",
"given",
"identifier",
"."
] | python | train |
usc-isi-i2/etk | etk/extractors/spacy_rule_extractor.py | https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/extractors/spacy_rule_extractor.py#L346-L361 | def _full_shape_filter(t: List, shapes: List) -> bool:
"""
Shape filter
Args:
t: List, list of tokens
shapes: List
Returns: bool
"""
if shapes:
for a_token in t:
if a_token._.full_shape not in shapes:
... | [
"def",
"_full_shape_filter",
"(",
"t",
":",
"List",
",",
"shapes",
":",
"List",
")",
"->",
"bool",
":",
"if",
"shapes",
":",
"for",
"a_token",
"in",
"t",
":",
"if",
"a_token",
".",
"_",
".",
"full_shape",
"not",
"in",
"shapes",
":",
"return",
"False"... | Shape filter
Args:
t: List, list of tokens
shapes: List
Returns: bool | [
"Shape",
"filter",
"Args",
":",
"t",
":",
"List",
"list",
"of",
"tokens",
"shapes",
":",
"List"
] | python | train |
tcalmant/ipopo | pelix/rsa/providers/distribution/__init__.py | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/providers/distribution/__init__.py#L513-L529 | def _find_export(self, func):
# type: (Callable[[Tuple[Any, EndpointDescription]], bool]) -> Optional[Tuple[Any, EndpointDescription]]
"""
Look for an export using the given lookup method
The lookup method must accept a single parameter, which is a tuple
containing a service ins... | [
"def",
"_find_export",
"(",
"self",
",",
"func",
")",
":",
"# type: (Callable[[Tuple[Any, EndpointDescription]], bool]) -> Optional[Tuple[Any, EndpointDescription]]",
"with",
"self",
".",
"_exported_instances_lock",
":",
"for",
"val",
"in",
"self",
".",
"_exported_services",
... | Look for an export using the given lookup method
The lookup method must accept a single parameter, which is a tuple
containing a service instance and endpoint description.
:param func: A function to look for the excepted export
:return: The found tuple or None | [
"Look",
"for",
"an",
"export",
"using",
"the",
"given",
"lookup",
"method"
] | python | train |
jazzband/django-mongonaut | mongonaut/sites.py | https://github.com/jazzband/django-mongonaut/blob/5485b2e029dff8ae267a4cb39c92d0a72cb5b144/mongonaut/sites.py#L53-L55 | def has_delete_permission(self, request):
""" Can delete this object """
return request.user.is_authenticated and request.user.is_active and request.user.is_superuser | [
"def",
"has_delete_permission",
"(",
"self",
",",
"request",
")",
":",
"return",
"request",
".",
"user",
".",
"is_authenticated",
"and",
"request",
".",
"user",
".",
"is_active",
"and",
"request",
".",
"user",
".",
"is_superuser"
] | Can delete this object | [
"Can",
"delete",
"this",
"object"
] | python | valid |
pytroll/pyorbital | pyorbital/tlefile.py | https://github.com/pytroll/pyorbital/blob/647007934dc827a4c698629cf32a84a5167844b2/pyorbital/tlefile.py#L91-L97 | def read(platform, tle_file=None, line1=None, line2=None):
"""Read TLE for `platform` from `tle_file`
File is read from `line1` to `line2`, from the newest file provided in the
TLES pattern, or from internet if none is provided.
"""
return Tle(platform, tle_file=tle_file, line1=line1, line2=line2) | [
"def",
"read",
"(",
"platform",
",",
"tle_file",
"=",
"None",
",",
"line1",
"=",
"None",
",",
"line2",
"=",
"None",
")",
":",
"return",
"Tle",
"(",
"platform",
",",
"tle_file",
"=",
"tle_file",
",",
"line1",
"=",
"line1",
",",
"line2",
"=",
"line2",
... | Read TLE for `platform` from `tle_file`
File is read from `line1` to `line2`, from the newest file provided in the
TLES pattern, or from internet if none is provided. | [
"Read",
"TLE",
"for",
"platform",
"from",
"tle_file"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.