repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
gear11/pypelogs | pypein/flickr.py | https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/flickr.py#L149-L155 | def _load_rsp(rsp):
"""
Converts raw Flickr string response to Python dict
"""
first = rsp.find('(') + 1
last = rsp.rfind(')')
return json.loads(rsp[first:last]) | [
"def",
"_load_rsp",
"(",
"rsp",
")",
":",
"first",
"=",
"rsp",
".",
"find",
"(",
"'('",
")",
"+",
"1",
"last",
"=",
"rsp",
".",
"rfind",
"(",
"')'",
")",
"return",
"json",
".",
"loads",
"(",
"rsp",
"[",
"first",
":",
"last",
"]",
")"
] | Converts raw Flickr string response to Python dict | [
"Converts",
"raw",
"Flickr",
"string",
"response",
"to",
"Python",
"dict"
] | python | train | 29 |
mandiant/ioc_writer | ioc_writer/utils/xmlutils.py | https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/utils/xmlutils.py#L30-L57 | def read_xml(filename):
"""
Use et to read in a xml file, or string, into a Element object.
:param filename: File to parse.
:return: lxml._elementTree object or None
"""
parser = et.XMLParser(remove_blank_text=True)
isfile=False
try:
isfile = os.path.exists(filename)
except ... | [
"def",
"read_xml",
"(",
"filename",
")",
":",
"parser",
"=",
"et",
".",
"XMLParser",
"(",
"remove_blank_text",
"=",
"True",
")",
"isfile",
"=",
"False",
"try",
":",
"isfile",
"=",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
"except",
"Value... | Use et to read in a xml file, or string, into a Element object.
:param filename: File to parse.
:return: lxml._elementTree object or None | [
"Use",
"et",
"to",
"read",
"in",
"a",
"xml",
"file",
"or",
"string",
"into",
"a",
"Element",
"object",
"."
] | python | train | 28.535714 |
fastai/fastai | fastai/data_block.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/data_block.py#L71-L76 | def process(self, processor:PreProcessors=None):
"Apply `processor` or `self.processor` to `self`."
if processor is not None: self.processor = processor
self.processor = listify(self.processor)
for p in self.processor: p.process(self)
return self | [
"def",
"process",
"(",
"self",
",",
"processor",
":",
"PreProcessors",
"=",
"None",
")",
":",
"if",
"processor",
"is",
"not",
"None",
":",
"self",
".",
"processor",
"=",
"processor",
"self",
".",
"processor",
"=",
"listify",
"(",
"self",
".",
"processor"... | Apply `processor` or `self.processor` to `self`. | [
"Apply",
"processor",
"or",
"self",
".",
"processor",
"to",
"self",
"."
] | python | train | 46.833333 |
inasafe/inasafe | safe/gui/tools/wizard/step_kw30_field.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw30_field.py#L185-L197 | def selected_fields(self):
"""Obtain the fields selected by user.
:returns: Keyword of the selected field.
:rtype: list, str
"""
items = self.lstFields.selectedItems()
if items and self.mode == MULTI_MODE:
return [item.text() for item in items]
elif i... | [
"def",
"selected_fields",
"(",
"self",
")",
":",
"items",
"=",
"self",
".",
"lstFields",
".",
"selectedItems",
"(",
")",
"if",
"items",
"and",
"self",
".",
"mode",
"==",
"MULTI_MODE",
":",
"return",
"[",
"item",
".",
"text",
"(",
")",
"for",
"item",
... | Obtain the fields selected by user.
:returns: Keyword of the selected field.
:rtype: list, str | [
"Obtain",
"the",
"fields",
"selected",
"by",
"user",
"."
] | python | train | 31.769231 |
osrg/ryu | ryu/ofproto/ofproto_v1_5_parser.py | https://github.com/osrg/ryu/blob/6f906e72c92e10bd0264c9b91a2f7bb85b97780c/ryu/ofproto/ofproto_v1_5_parser.py#L937-L961 | def serialize(self, buf, offset):
"""
Outputs the expression of the wire protocol of the flow stats into
the buf.
Returns the output length.
"""
fields = [ofproto.oxs_from_user(k, uv) for (k, uv)
in self.fields]
hdr_pack_str = '!HH'
fiel... | [
"def",
"serialize",
"(",
"self",
",",
"buf",
",",
"offset",
")",
":",
"fields",
"=",
"[",
"ofproto",
".",
"oxs_from_user",
"(",
"k",
",",
"uv",
")",
"for",
"(",
"k",
",",
"uv",
")",
"in",
"self",
".",
"fields",
"]",
"hdr_pack_str",
"=",
"'!HH'",
... | Outputs the expression of the wire protocol of the flow stats into
the buf.
Returns the output length. | [
"Outputs",
"the",
"expression",
"of",
"the",
"wire",
"protocol",
"of",
"the",
"flow",
"stats",
"into",
"the",
"buf",
".",
"Returns",
"the",
"output",
"length",
"."
] | python | train | 33.64 |
littlemo/mohand | source/mohand/load_file.py | https://github.com/littlemo/mohand/blob/9bd4591e457d594f2ce3a0c089ef28d3b4e027e8/source/mohand/load_file.py#L99-L112 | def extract_commands(imported_vars):
"""
从传入的变量列表中提取命令( ``click.core.Command`` )对象
:param dict_items imported_vars: 字典的键值条目列表
:return: 判定为终端命令的对象字典
:rtype: dict(str, object)
"""
commands = dict()
for tup in imported_vars:
name, obj = tup
if is_command_object(obj):
... | [
"def",
"extract_commands",
"(",
"imported_vars",
")",
":",
"commands",
"=",
"dict",
"(",
")",
"for",
"tup",
"in",
"imported_vars",
":",
"name",
",",
"obj",
"=",
"tup",
"if",
"is_command_object",
"(",
"obj",
")",
":",
"commands",
".",
"setdefault",
"(",
"... | 从传入的变量列表中提取命令( ``click.core.Command`` )对象
:param dict_items imported_vars: 字典的键值条目列表
:return: 判定为终端命令的对象字典
:rtype: dict(str, object) | [
"从传入的变量列表中提取命令",
"(",
"click",
".",
"core",
".",
"Command",
")",
"对象"
] | python | test | 25.928571 |
lappis-unb/salic-ml | src/salicml/metrics/finance/common_items_ratio.py | https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/common_items_ratio.py#L83-L106 | def common_items_metrics(all_items, common_items):
"""
Calculates the percentage of common items for each project
in each segment and calculates the mean and std of this percentage
for each segment.
"""
segments = common_items.index.unique()
metrics = {}
for seg in segments:
seg_... | [
"def",
"common_items_metrics",
"(",
"all_items",
",",
"common_items",
")",
":",
"segments",
"=",
"common_items",
".",
"index",
".",
"unique",
"(",
")",
"metrics",
"=",
"{",
"}",
"for",
"seg",
"in",
"segments",
":",
"seg_common_items",
"=",
"segment_common_item... | Calculates the percentage of common items for each project
in each segment and calculates the mean and std of this percentage
for each segment. | [
"Calculates",
"the",
"percentage",
"of",
"common",
"items",
"for",
"each",
"project",
"in",
"each",
"segment",
"and",
"calculates",
"the",
"mean",
"and",
"std",
"of",
"this",
"percentage",
"for",
"each",
"segment",
"."
] | python | train | 32.083333 |
petl-developers/petl | petl/io/csv.py | https://github.com/petl-developers/petl/blob/1d33ca055f7e04e0d28a772041c9fd30c8d415d6/petl/io/csv.py#L65-L74 | def fromtsv(source=None, encoding=None, errors='strict', header=None,
**csvargs):
"""
Convenience function, as :func:`petl.io.csv.fromcsv` but with different
default dialect (tab delimited).
"""
csvargs.setdefault('dialect', 'excel-tab')
return fromcsv(source, encoding=encoding, e... | [
"def",
"fromtsv",
"(",
"source",
"=",
"None",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"'strict'",
",",
"header",
"=",
"None",
",",
"*",
"*",
"csvargs",
")",
":",
"csvargs",
".",
"setdefault",
"(",
"'dialect'",
",",
"'excel-tab'",
")",
"return... | Convenience function, as :func:`petl.io.csv.fromcsv` but with different
default dialect (tab delimited). | [
"Convenience",
"function",
"as",
":",
"func",
":",
"petl",
".",
"io",
".",
"csv",
".",
"fromcsv",
"but",
"with",
"different",
"default",
"dialect",
"(",
"tab",
"delimited",
")",
"."
] | python | train | 33.5 |
bihealth/vcfpy | vcfpy/header.py | https://github.com/bihealth/vcfpy/blob/99e2165df30f11e0c95f3170f31bc5191d9e9e15/vcfpy/header.py#L277-L295 | def _build_indices(self):
"""Build indices for the different field types"""
result = {key: OrderedDict() for key in LINES_WITH_ID}
for line in self.lines:
if line.key in LINES_WITH_ID:
result.setdefault(line.key, OrderedDict())
if line.mapping["ID"] in... | [
"def",
"_build_indices",
"(",
"self",
")",
":",
"result",
"=",
"{",
"key",
":",
"OrderedDict",
"(",
")",
"for",
"key",
"in",
"LINES_WITH_ID",
"}",
"for",
"line",
"in",
"self",
".",
"lines",
":",
"if",
"line",
".",
"key",
"in",
"LINES_WITH_ID",
":",
"... | Build indices for the different field types | [
"Build",
"indices",
"for",
"the",
"different",
"field",
"types"
] | python | train | 43.578947 |
openfisca/openfisca-core | openfisca_core/populations.py | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/populations.py#L401-L414 | def nb_persons(self, role = None):
"""
Returns the number of persons contained in the entity.
If ``role`` is provided, only the entity member with the given role are taken into account.
"""
if role:
if role.subroles:
role_condition = np.logica... | [
"def",
"nb_persons",
"(",
"self",
",",
"role",
"=",
"None",
")",
":",
"if",
"role",
":",
"if",
"role",
".",
"subroles",
":",
"role_condition",
"=",
"np",
".",
"logical_or",
".",
"reduce",
"(",
"[",
"self",
".",
"members_role",
"==",
"subrole",
"for",
... | Returns the number of persons contained in the entity.
If ``role`` is provided, only the entity member with the given role are taken into account. | [
"Returns",
"the",
"number",
"of",
"persons",
"contained",
"in",
"the",
"entity",
"."
] | python | train | 40.642857 |
icgood/pymap | pymap/selected.py | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/selected.py#L170-L188 | def get_all(self, seq_set: SequenceSet) \
-> Sequence[Tuple[int, CachedMessage]]:
"""Return the cached messages, and their sequence numbers, for the
given sequence set.
Args:
seq_set: The message sequence set.
"""
if seq_set.uid:
all_uids = s... | [
"def",
"get_all",
"(",
"self",
",",
"seq_set",
":",
"SequenceSet",
")",
"->",
"Sequence",
"[",
"Tuple",
"[",
"int",
",",
"CachedMessage",
"]",
"]",
":",
"if",
"seq_set",
".",
"uid",
":",
"all_uids",
"=",
"seq_set",
".",
"flatten",
"(",
"self",
".",
"... | Return the cached messages, and their sequence numbers, for the
given sequence set.
Args:
seq_set: The message sequence set. | [
"Return",
"the",
"cached",
"messages",
"and",
"their",
"sequence",
"numbers",
"for",
"the",
"given",
"sequence",
"set",
"."
] | python | train | 37 |
Divirad/PythonTranslate | pythontranslate/__init__.py | https://github.com/Divirad/PythonTranslate/blob/625e97563bb586692f4a128b284a2aa79f82c279/pythontranslate/__init__.py#L49-L70 | def detect_language(self, text: str, hint: str = None):
"""
Detects the language of a text
:param text:
Text to analyze
:param hint:
A list which are hints for the API
in which language the text is written in
example:
"de, ... | [
"def",
"detect_language",
"(",
"self",
",",
"text",
":",
"str",
",",
"hint",
":",
"str",
"=",
"None",
")",
":",
"encodedtext",
"=",
"urllib",
".",
"parse",
".",
"quote",
"(",
"text",
")",
"args",
"=",
"\"&text=\"",
"+",
"encodedtext",
"if",
"hint",
"... | Detects the language of a text
:param text:
Text to analyze
:param hint:
A list which are hints for the API
in which language the text is written in
example:
"de, en"
:return:
detected language code. example: "en" | [
"Detects",
"the",
"language",
"of",
"a",
"text",
":",
"param",
"text",
":",
"Text",
"to",
"analyze",
":",
"param",
"hint",
":",
"A",
"list",
"which",
"are",
"hints",
"for",
"the",
"API",
"in",
"which",
"language",
"the",
"text",
"is",
"written",
"in",
... | python | train | 29.727273 |
cloudendpoints/endpoints-python | endpoints/resource_container.py | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/resource_container.py#L103-L122 | def add_to_cache(cls, remote_info, container): # pylint: disable=g-bad-name
"""Adds a ResourceContainer to a cache tying it to a protorpc method.
Args:
remote_info: Instance of protorpc.remote._RemoteMethodInfo corresponding
to a method.
container: An instance of ResourceContainer.
... | [
"def",
"add_to_cache",
"(",
"cls",
",",
"remote_info",
",",
"container",
")",
":",
"# pylint: disable=g-bad-name",
"if",
"not",
"isinstance",
"(",
"container",
",",
"cls",
")",
":",
"raise",
"TypeError",
"(",
"'%r not an instance of %r, could not be added to cache.'",
... | Adds a ResourceContainer to a cache tying it to a protorpc method.
Args:
remote_info: Instance of protorpc.remote._RemoteMethodInfo corresponding
to a method.
container: An instance of ResourceContainer.
Raises:
TypeError: if the container is not an instance of cls.
KeyError:... | [
"Adds",
"a",
"ResourceContainer",
"to",
"a",
"cache",
"tying",
"it",
"to",
"a",
"protorpc",
"method",
"."
] | python | train | 44.15 |
cohorte/cohorte-herald | python/herald/transports/http/discovery_multicast.py | https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/herald/transports/http/discovery_multicast.py#L481-L497 | def __read(self):
"""
Reads packets from the socket
"""
# Set the socket as non-blocking
self._socket.setblocking(0)
while not self._stop_event.is_set():
# Watch for content
ready = select.select([self._socket], [], [], 1)
if ready[0]:... | [
"def",
"__read",
"(",
"self",
")",
":",
"# Set the socket as non-blocking",
"self",
".",
"_socket",
".",
"setblocking",
"(",
"0",
")",
"while",
"not",
"self",
".",
"_stop_event",
".",
"is_set",
"(",
")",
":",
"# Watch for content",
"ready",
"=",
"select",
".... | Reads packets from the socket | [
"Reads",
"packets",
"from",
"the",
"socket"
] | python | train | 34.941176 |
Kensuke-Mitsuzawa/JapaneseTokenizers | JapaneseTokenizer/mecab_wrapper/mecab_wrapper.py | https://github.com/Kensuke-Mitsuzawa/JapaneseTokenizers/blob/3bdfb6be73de0f78e5c08f3a51376ad3efa00b6c/JapaneseTokenizer/mecab_wrapper/mecab_wrapper.py#L92-L111 | def __check_mecab_dict_path(self):
"""check path to dict of Mecab in system environment
"""
mecab_dic_cmd = "echo `{} --dicdir`".format(os.path.join(self._path_mecab_config, 'mecab-config'))
try:
if six.PY2:
path_mecab_dict = subprocess.check_output( mecab_di... | [
"def",
"__check_mecab_dict_path",
"(",
"self",
")",
":",
"mecab_dic_cmd",
"=",
"\"echo `{} --dicdir`\"",
".",
"format",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_path_mecab_config",
",",
"'mecab-config'",
")",
")",
"try",
":",
"if",
"six",
"."... | check path to dict of Mecab in system environment | [
"check",
"path",
"to",
"dict",
"of",
"Mecab",
"in",
"system",
"environment"
] | python | train | 49.9 |
gtaylor/python-route53 | route53/transport.py | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/transport.py#L67-L88 | def get_request_headers(self):
"""
Determine the headers to send along with the request. These are
pretty much the same for every request, with Route53.
"""
date_header = time.asctime(time.gmtime())
# We sign the time string above with the user's AWS secret access key
... | [
"def",
"get_request_headers",
"(",
"self",
")",
":",
"date_header",
"=",
"time",
".",
"asctime",
"(",
"time",
".",
"gmtime",
"(",
")",
")",
"# We sign the time string above with the user's AWS secret access key",
"# in order to authenticate our request.",
"signing_key",
"="... | Determine the headers to send along with the request. These are
pretty much the same for every request, with Route53. | [
"Determine",
"the",
"headers",
"to",
"send",
"along",
"with",
"the",
"request",
".",
"These",
"are",
"pretty",
"much",
"the",
"same",
"for",
"every",
"request",
"with",
"Route53",
"."
] | python | test | 35.409091 |
rflamary/POT | ot/datasets.py | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/datasets.py#L46-L79 | def make_2D_samples_gauss(n, m, sigma, random_state=None):
"""return n samples drawn from 2D gaussian N(m,sigma)
Parameters
----------
n : int
number of samples to make
m : np.array (2,)
mean value of the gaussian distribution
sigma : np.array (2,2)
covariance matrix of... | [
"def",
"make_2D_samples_gauss",
"(",
"n",
",",
"m",
",",
"sigma",
",",
"random_state",
"=",
"None",
")",
":",
"generator",
"=",
"check_random_state",
"(",
"random_state",
")",
"if",
"np",
".",
"isscalar",
"(",
"sigma",
")",
":",
"sigma",
"=",
"np",
".",
... | return n samples drawn from 2D gaussian N(m,sigma)
Parameters
----------
n : int
number of samples to make
m : np.array (2,)
mean value of the gaussian distribution
sigma : np.array (2,2)
covariance matrix of the gaussian distribution
random_state : int, RandomState ins... | [
"return",
"n",
"samples",
"drawn",
"from",
"2D",
"gaussian",
"N",
"(",
"m",
"sigma",
")"
] | python | train | 30.852941 |
noxdafox/clipspy | clips/environment.py | https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/environment.py#L188-L202 | def define_function(self, function, name=None):
"""Define the Python function within the CLIPS environment.
If a name is given, it will be the function name within CLIPS.
Otherwise, the name of the Python function will be used.
The Python function will be accessible within CLIPS via it... | [
"def",
"define_function",
"(",
"self",
",",
"function",
",",
"name",
"=",
"None",
")",
":",
"name",
"=",
"name",
"if",
"name",
"is",
"not",
"None",
"else",
"function",
".",
"__name__",
"ENVIRONMENT_DATA",
"[",
"self",
".",
"_env",
"]",
".",
"user_functio... | Define the Python function within the CLIPS environment.
If a name is given, it will be the function name within CLIPS.
Otherwise, the name of the Python function will be used.
The Python function will be accessible within CLIPS via its name
as if it was defined via the `deffunction` c... | [
"Define",
"the",
"Python",
"function",
"within",
"the",
"CLIPS",
"environment",
"."
] | python | train | 37.666667 |
zhmcclient/python-zhmcclient | zhmcclient/_cpc.py | https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_cpc.py#L377-L412 | def maximum_active_partitions(self):
"""
Integer: The maximum number of active logical partitions or partitions
of this CPC.
The following table shows the maximum number of active logical
partitions or partitions by machine generations supported at the HMC
API:
... | [
"def",
"maximum_active_partitions",
"(",
"self",
")",
":",
"machine_type",
"=",
"self",
".",
"get_property",
"(",
"'machine-type'",
")",
"try",
":",
"max_parts",
"=",
"self",
".",
"_MAX_PARTITIONS_BY_MACHINE_TYPE",
"[",
"machine_type",
"]",
"except",
"KeyError",
"... | Integer: The maximum number of active logical partitions or partitions
of this CPC.
The following table shows the maximum number of active logical
partitions or partitions by machine generations supported at the HMC
API:
========================= ==================
Mac... | [
"Integer",
":",
"The",
"maximum",
"number",
"of",
"active",
"logical",
"partitions",
"or",
"partitions",
"of",
"this",
"CPC",
"."
] | python | train | 39.833333 |
project-ncl/pnc-cli | pnc_cli/tools/scm_utils.py | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/tools/scm_utils.py#L23-L47 | def get_scm_status(config, read_modules=False, repo_url=None, mvn_repo_local=None, additional_params=None):
"""
Gets the artifact status (MavenArtifact instance) from SCM defined by config. Only the top-level artifact is read by
default, although it can be requested to read the whole available module struct... | [
"def",
"get_scm_status",
"(",
"config",
",",
"read_modules",
"=",
"False",
",",
"repo_url",
"=",
"None",
",",
"mvn_repo_local",
"=",
"None",
",",
"additional_params",
"=",
"None",
")",
":",
"global",
"scm_status_cache",
"if",
"config",
".",
"artifact",
"in",
... | Gets the artifact status (MavenArtifact instance) from SCM defined by config. Only the top-level artifact is read by
default, although it can be requested to read the whole available module structure.
:param config: artifact config (ArtifactConfig instance)
:param read_modules: if True all modules are read... | [
"Gets",
"the",
"artifact",
"status",
"(",
"MavenArtifact",
"instance",
")",
"from",
"SCM",
"defined",
"by",
"config",
".",
"Only",
"the",
"top",
"-",
"level",
"artifact",
"is",
"read",
"by",
"default",
"although",
"it",
"can",
"be",
"requested",
"to",
"rea... | python | train | 54.76 |
lsst-sqre/ltd-conveyor | ltdconveyor/keeper/login.py | https://github.com/lsst-sqre/ltd-conveyor/blob/c492937c4c1e050ccc4a0b9dcc38f9980d57e305/ltdconveyor/keeper/login.py#L12-L39 | def get_keeper_token(host, username, password):
"""Get a temporary auth token from LTD Keeper.
Parameters
----------
host : `str`
Hostname of the LTD Keeper API (e.g., ``'https://keeper.lsst.codes'``).
username : `str`
Username.
password : `str`
Password.
Returns
... | [
"def",
"get_keeper_token",
"(",
"host",
",",
"username",
",",
"password",
")",
":",
"token_endpoint",
"=",
"urljoin",
"(",
"host",
",",
"'/token'",
")",
"r",
"=",
"requests",
".",
"get",
"(",
"token_endpoint",
",",
"auth",
"=",
"(",
"username",
",",
"pas... | Get a temporary auth token from LTD Keeper.
Parameters
----------
host : `str`
Hostname of the LTD Keeper API (e.g., ``'https://keeper.lsst.codes'``).
username : `str`
Username.
password : `str`
Password.
Returns
-------
token : `str`
LTD Keeper API toke... | [
"Get",
"a",
"temporary",
"auth",
"token",
"from",
"LTD",
"Keeper",
"."
] | python | test | 27.357143 |
cloud-custodian/cloud-custodian | c7n/log.py | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/log.py#L143-L148 | def format_message(self, msg):
"""format message."""
return {'timestamp': int(msg.created * 1000),
'message': self.format(msg),
'stream': self.log_stream or msg.name,
'group': self.log_group} | [
"def",
"format_message",
"(",
"self",
",",
"msg",
")",
":",
"return",
"{",
"'timestamp'",
":",
"int",
"(",
"msg",
".",
"created",
"*",
"1000",
")",
",",
"'message'",
":",
"self",
".",
"format",
"(",
"msg",
")",
",",
"'stream'",
":",
"self",
".",
"l... | format message. | [
"format",
"message",
"."
] | python | train | 41.666667 |
Unidata/MetPy | metpy/interpolate/grid.py | https://github.com/Unidata/MetPy/blob/16f68a94919b9a82dcf9cada2169cf039129e67b/metpy/interpolate/grid.py#L177-L179 | def natural_neighbor(xp, yp, variable, grid_x, grid_y):
"""Wrap natural_neighbor_to_grid for deprecated natural_neighbor function."""
return natural_neighbor_to_grid(xp, yp, variable, grid_x, grid_y) | [
"def",
"natural_neighbor",
"(",
"xp",
",",
"yp",
",",
"variable",
",",
"grid_x",
",",
"grid_y",
")",
":",
"return",
"natural_neighbor_to_grid",
"(",
"xp",
",",
"yp",
",",
"variable",
",",
"grid_x",
",",
"grid_y",
")"
] | Wrap natural_neighbor_to_grid for deprecated natural_neighbor function. | [
"Wrap",
"natural_neighbor_to_grid",
"for",
"deprecated",
"natural_neighbor",
"function",
"."
] | python | train | 68.333333 |
singularityhub/sregistry-cli | sregistry/utils/recipes.py | https://github.com/singularityhub/sregistry-cli/blob/abc96140a1d15b5e96d83432e1e0e1f4f8f36331/sregistry/utils/recipes.py#L104-L148 | def find_folder_recipes(base_folder,
pattern="Singularity",
manifest=None,
base=None):
'''find folder recipes will find recipes based on a particular pattern.
Parameters
==========
base_folder: the base folder to r... | [
"def",
"find_folder_recipes",
"(",
"base_folder",
",",
"pattern",
"=",
"\"Singularity\"",
",",
"manifest",
"=",
"None",
",",
"base",
"=",
"None",
")",
":",
"# The user is not appending to an existing manifest",
"if",
"manifest",
"is",
"None",
":",
"manifest",
"=",
... | find folder recipes will find recipes based on a particular pattern.
Parameters
==========
base_folder: the base folder to recursively walk
pattern: a default pattern to search for
manifest: an already started manifest
base: if defined, consider folders under this level... | [
"find",
"folder",
"recipes",
"will",
"find",
"recipes",
"based",
"on",
"a",
"particular",
"pattern",
".",
"Parameters",
"==========",
"base_folder",
":",
"the",
"base",
"folder",
"to",
"recursively",
"walk",
"pattern",
":",
"a",
"default",
"pattern",
"to",
"se... | python | test | 36.355556 |
saltstack/salt | salt/cloud/__init__.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L912-L926 | def provider_list(self, lookup='all'):
'''
Return a mapping of all image data for available providers
'''
data = {}
lookups = self.lookup_providers(lookup)
if not lookups:
return data
for alias, driver in lookups:
if alias not in data:
... | [
"def",
"provider_list",
"(",
"self",
",",
"lookup",
"=",
"'all'",
")",
":",
"data",
"=",
"{",
"}",
"lookups",
"=",
"self",
".",
"lookup_providers",
"(",
"lookup",
")",
"if",
"not",
"lookups",
":",
"return",
"data",
"for",
"alias",
",",
"driver",
"in",
... | Return a mapping of all image data for available providers | [
"Return",
"a",
"mapping",
"of",
"all",
"image",
"data",
"for",
"available",
"providers"
] | python | train | 29.2 |
GNS3/gns3-server | gns3server/controller/compute.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/compute.py#L640-L646 | def list_files(self, project):
"""
List files in the project on computes
"""
path = "/projects/{}/files".format(project.id)
res = yield from self.http_query("GET", path, timeout=120)
return res.json | [
"def",
"list_files",
"(",
"self",
",",
"project",
")",
":",
"path",
"=",
"\"/projects/{}/files\"",
".",
"format",
"(",
"project",
".",
"id",
")",
"res",
"=",
"yield",
"from",
"self",
".",
"http_query",
"(",
"\"GET\"",
",",
"path",
",",
"timeout",
"=",
... | List files in the project on computes | [
"List",
"files",
"in",
"the",
"project",
"on",
"computes"
] | python | train | 34.285714 |
wandb/client | wandb/vendor/prompt_toolkit/document.py | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/document.py#L986-L1001 | def insert_before(self, text):
"""
Create a new document, with this text inserted before the buffer.
It keeps selection ranges and cursor position in sync.
"""
selection_state = self.selection
if selection_state:
selection_state = SelectionState(
... | [
"def",
"insert_before",
"(",
"self",
",",
"text",
")",
":",
"selection_state",
"=",
"self",
".",
"selection",
"if",
"selection_state",
":",
"selection_state",
"=",
"SelectionState",
"(",
"original_cursor_position",
"=",
"selection_state",
".",
"original_cursor_positio... | Create a new document, with this text inserted before the buffer.
It keeps selection ranges and cursor position in sync. | [
"Create",
"a",
"new",
"document",
"with",
"this",
"text",
"inserted",
"before",
"the",
"buffer",
".",
"It",
"keeps",
"selection",
"ranges",
"and",
"cursor",
"position",
"in",
"sync",
"."
] | python | train | 37.75 |
wandb/client | wandb/vendor/prompt_toolkit/buffer.py | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/buffer.py#L592-L606 | def auto_up(self, count=1, go_to_start_of_line_if_history_changes=False):
"""
If we're not on the first line (of a multiline input) go a line up,
otherwise go back in history. (If nothing is selected.)
"""
if self.complete_state:
self.complete_previous(count=count)
... | [
"def",
"auto_up",
"(",
"self",
",",
"count",
"=",
"1",
",",
"go_to_start_of_line_if_history_changes",
"=",
"False",
")",
":",
"if",
"self",
".",
"complete_state",
":",
"self",
".",
"complete_previous",
"(",
"count",
"=",
"count",
")",
"elif",
"self",
".",
... | If we're not on the first line (of a multiline input) go a line up,
otherwise go back in history. (If nothing is selected.) | [
"If",
"we",
"re",
"not",
"on",
"the",
"first",
"line",
"(",
"of",
"a",
"multiline",
"input",
")",
"go",
"a",
"line",
"up",
"otherwise",
"go",
"back",
"in",
"history",
".",
"(",
"If",
"nothing",
"is",
"selected",
".",
")"
] | python | train | 44.2 |
tensorforce/tensorforce | tensorforce/execution/threaded_runner.py | https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/execution/threaded_runner.py#L88-L186 | def run(
self,
num_episodes=-1,
max_episode_timesteps=-1,
episode_finished=None,
summary_report=None,
summary_interval=0,
num_timesteps=None,
deterministic=False,
episodes=None,
max_timesteps=None,
testing=False,
sleep=None
... | [
"def",
"run",
"(",
"self",
",",
"num_episodes",
"=",
"-",
"1",
",",
"max_episode_timesteps",
"=",
"-",
"1",
",",
"episode_finished",
"=",
"None",
",",
"summary_report",
"=",
"None",
",",
"summary_interval",
"=",
"0",
",",
"num_timesteps",
"=",
"None",
",",... | Executes this runner by starting all Agents in parallel (each one in one thread).
Args:
episodes (int): Deprecated; see num_episodes.
max_timesteps (int): Deprecated; see max_episode_timesteps. | [
"Executes",
"this",
"runner",
"by",
"starting",
"all",
"Agents",
"in",
"parallel",
"(",
"each",
"one",
"in",
"one",
"thread",
")",
"."
] | python | valid | 42.959596 |
hardbyte/python-can | can/interfaces/systec/ucanbus.py | https://github.com/hardbyte/python-can/blob/cdc5254d96072df7739263623f3e920628a7d214/can/interfaces/systec/ucanbus.py#L206-L214 | def flush_tx_buffer(self):
"""
Flushes the transmit buffer.
:raises can.CanError:
If flushing of the transmit buffer failed.
"""
log.info('Flushing transmit buffer')
self._ucan.reset_can(self.channel, ResetFlags.RESET_ONLY_TX_BUFF) | [
"def",
"flush_tx_buffer",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"'Flushing transmit buffer'",
")",
"self",
".",
"_ucan",
".",
"reset_can",
"(",
"self",
".",
"channel",
",",
"ResetFlags",
".",
"RESET_ONLY_TX_BUFF",
")"
] | Flushes the transmit buffer.
:raises can.CanError:
If flushing of the transmit buffer failed. | [
"Flushes",
"the",
"transmit",
"buffer",
"."
] | python | train | 31.555556 |
Unity-Technologies/ml-agents | ml-agents-envs/mlagents/envs/brain.py | https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents-envs/mlagents/envs/brain.py#L85-L138 | def from_agent_proto(agent_info_list, brain_params):
"""
Converts list of agent infos to BrainInfo.
"""
vis_obs = []
for i in range(brain_params.number_visual_observations):
obs = [BrainInfo.process_pixels(x.visual_observations[i],
... | [
"def",
"from_agent_proto",
"(",
"agent_info_list",
",",
"brain_params",
")",
":",
"vis_obs",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"brain_params",
".",
"number_visual_observations",
")",
":",
"obs",
"=",
"[",
"BrainInfo",
".",
"process_pixels",
"(",
... | Converts list of agent infos to BrainInfo. | [
"Converts",
"list",
"of",
"agent",
"infos",
"to",
"BrainInfo",
"."
] | python | train | 51.703704 |
ioos/compliance-checker | compliance_checker/ioos.py | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/ioos.py#L311-L322 | def check_geophysical_vars_fill_value(self, ds):
'''
Check that geophysical variables contain fill values.
:param netCDF4.Dataset ds: An open netCDF dataset
'''
results = []
for geo_var in get_geophysical_variables(ds):
results.append(
self._h... | [
"def",
"check_geophysical_vars_fill_value",
"(",
"self",
",",
"ds",
")",
":",
"results",
"=",
"[",
"]",
"for",
"geo_var",
"in",
"get_geophysical_variables",
"(",
"ds",
")",
":",
"results",
".",
"append",
"(",
"self",
".",
"_has_var_attr",
"(",
"ds",
",",
"... | Check that geophysical variables contain fill values.
:param netCDF4.Dataset ds: An open netCDF dataset | [
"Check",
"that",
"geophysical",
"variables",
"contain",
"fill",
"values",
"."
] | python | train | 34.75 |
waleedka/hiddenlayer | hiddenlayer/canvas.py | https://github.com/waleedka/hiddenlayer/blob/294f8732b271cbdd6310c55bdf5ce855cbf61c75/hiddenlayer/canvas.py#L161-L169 | def draw_summary(self, history, title=""):
"""Inserts a text summary at the top that lists the number of steps and total
training time."""
# Generate summary string
time_str = str(history.get_total_time()).split(".")[0] # remove microseconds
summary = "Step: {} Time: {}".fo... | [
"def",
"draw_summary",
"(",
"self",
",",
"history",
",",
"title",
"=",
"\"\"",
")",
":",
"# Generate summary string",
"time_str",
"=",
"str",
"(",
"history",
".",
"get_total_time",
"(",
")",
")",
".",
"split",
"(",
"\".\"",
")",
"[",
"0",
"]",
"# remove ... | Inserts a text summary at the top that lists the number of steps and total
training time. | [
"Inserts",
"a",
"text",
"summary",
"at",
"the",
"top",
"that",
"lists",
"the",
"number",
"of",
"steps",
"and",
"total",
"training",
"time",
"."
] | python | train | 49.222222 |
andrea-cuttone/geoplotlib | geoplotlib/colors.py | https://github.com/andrea-cuttone/geoplotlib/blob/a1c355bccec91cabd157569fad6daf53cf7687a1/geoplotlib/colors.py#L92-L108 | def create_set_cmap(values, cmap_name, alpha=255):
"""
return a dict of colors corresponding to the unique values
:param values: values to be mapped
:param cmap_name: colormap name
:param alpha: color alpha
:return: dict of colors corresponding to the unique values
"""
unique_values... | [
"def",
"create_set_cmap",
"(",
"values",
",",
"cmap_name",
",",
"alpha",
"=",
"255",
")",
":",
"unique_values",
"=",
"list",
"(",
"set",
"(",
"values",
")",
")",
"shuffle",
"(",
"unique_values",
")",
"from",
"pylab",
"import",
"get_cmap",
"cmap",
"=",
"g... | return a dict of colors corresponding to the unique values
:param values: values to be mapped
:param cmap_name: colormap name
:param alpha: color alpha
:return: dict of colors corresponding to the unique values | [
"return",
"a",
"dict",
"of",
"colors",
"corresponding",
"to",
"the",
"unique",
"values",
":",
"param",
"values",
":",
"values",
"to",
"be",
"mapped",
":",
"param",
"cmap_name",
":",
"colormap",
"name",
":",
"param",
"alpha",
":",
"color",
"alpha",
":",
"... | python | train | 33.352941 |
ThreatConnect-Inc/tcex | tcex/tcex_bin.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin.py#L109-L118 | def handle_error(err, halt=True):
"""Print errors message and optionally exit.
Args:
err (str): The error message to print.
halt (bool, optional): Defaults to True. If True the script will exit.
"""
print('{}{}{}'.format(c.Style.BRIGHT, c.Fore.RED, err))
... | [
"def",
"handle_error",
"(",
"err",
",",
"halt",
"=",
"True",
")",
":",
"print",
"(",
"'{}{}{}'",
".",
"format",
"(",
"c",
".",
"Style",
".",
"BRIGHT",
",",
"c",
".",
"Fore",
".",
"RED",
",",
"err",
")",
")",
"if",
"halt",
":",
"sys",
".",
"exit... | Print errors message and optionally exit.
Args:
err (str): The error message to print.
halt (bool, optional): Defaults to True. If True the script will exit. | [
"Print",
"errors",
"message",
"and",
"optionally",
"exit",
"."
] | python | train | 34.3 |
saltstack/salt | salt/modules/timezone.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/timezone.py#L378-L488 | def get_hwclock():
'''
Get current hardware clock setting (UTC or localtime)
CLI Example:
.. code-block:: bash
salt '*' timezone.get_hwclock
'''
if salt.utils.path.which('timedatectl'):
ret = _timedatectl()
for line in (x.strip() for x in ret['stdout'].splitlines()):
... | [
"def",
"get_hwclock",
"(",
")",
":",
"if",
"salt",
".",
"utils",
".",
"path",
".",
"which",
"(",
"'timedatectl'",
")",
":",
"ret",
"=",
"_timedatectl",
"(",
")",
"for",
"line",
"in",
"(",
"x",
".",
"strip",
"(",
")",
"for",
"x",
"in",
"ret",
"[",... | Get current hardware clock setting (UTC or localtime)
CLI Example:
.. code-block:: bash
salt '*' timezone.get_hwclock | [
"Get",
"current",
"hardware",
"clock",
"setting",
"(",
"UTC",
"or",
"localtime",
")"
] | python | train | 40.288288 |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_fcoe_ext.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_fcoe_ext.py#L337-L351 | def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_rx_flogi(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcoe_get_interface = ET.Element("fcoe_get_interface")
config = fcoe_get_interface
output = ET.SubElement(fcoe_get_interface, "output")... | [
"def",
"fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_rx_flogi",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"fcoe_get_interface",
"=",
"ET",
".",
"Element",
"(",
"\"fcoe_get_interface\"",
")",
... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 52.133333 |
gc3-uzh-ch/elasticluster | elasticluster/providers/ec2_boto.py | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/providers/ec2_boto.py#L498-L510 | def _build_cached_instances(self):
"""
Build lookup table of VM instances known to the cloud provider.
The returned dictionary links VM id with the actual VM object.
"""
connection = self._connect()
reservations = connection.get_all_reservations()
cached_instance... | [
"def",
"_build_cached_instances",
"(",
"self",
")",
":",
"connection",
"=",
"self",
".",
"_connect",
"(",
")",
"reservations",
"=",
"connection",
".",
"get_all_reservations",
"(",
")",
"cached_instances",
"=",
"{",
"}",
"for",
"rs",
"in",
"reservations",
":",
... | Build lookup table of VM instances known to the cloud provider.
The returned dictionary links VM id with the actual VM object. | [
"Build",
"lookup",
"table",
"of",
"VM",
"instances",
"known",
"to",
"the",
"cloud",
"provider",
"."
] | python | train | 35.307692 |
Rikanishu/static-bundle | static_bundle/bundles.py | https://github.com/Rikanishu/static-bundle/blob/2f6458cb9d9d9049b4fd829f7d6951a45d547c68/static_bundle/bundles.py#L62-L69 | def add_file(self, *args):
"""
Add single file or list of files to bundle
:type: file_path: str|unicode
"""
for file_path in args:
self.files.append(FilePath(file_path, self)) | [
"def",
"add_file",
"(",
"self",
",",
"*",
"args",
")",
":",
"for",
"file_path",
"in",
"args",
":",
"self",
".",
"files",
".",
"append",
"(",
"FilePath",
"(",
"file_path",
",",
"self",
")",
")"
] | Add single file or list of files to bundle
:type: file_path: str|unicode | [
"Add",
"single",
"file",
"or",
"list",
"of",
"files",
"to",
"bundle"
] | python | valid | 27.625 |
UCL-INGI/INGInious | inginious/frontend/pages/register.py | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/register.py#L153-L177 | def reset_passwd(self, data):
""" Reset the user password """
error = False
msg = ""
# Check input format
if len(data["passwd"]) < 6:
error = True
msg = _("Password too short.")
elif data["passwd"] != data["passwd2"]:
error = True
... | [
"def",
"reset_passwd",
"(",
"self",
",",
"data",
")",
":",
"error",
"=",
"False",
"msg",
"=",
"\"\"",
"# Check input format",
"if",
"len",
"(",
"data",
"[",
"\"passwd\"",
"]",
")",
"<",
"6",
":",
"error",
"=",
"True",
"msg",
"=",
"_",
"(",
"\"Passwor... | Reset the user password | [
"Reset",
"the",
"user",
"password"
] | python | train | 38.36 |
dereneaton/ipyrad | ipyrad/assemble/cluster_within.py | https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/cluster_within.py#L622-L642 | def setup_dirs(data):
""" sets up directories for step3 data """
## make output folder for clusters
pdir = os.path.realpath(data.paramsdict["project_dir"])
data.dirs.clusts = os.path.join(pdir, "{}_clust_{}"\
.format(data.name, data.paramsdict["clust_threshold"]))
if not os.pa... | [
"def",
"setup_dirs",
"(",
"data",
")",
":",
"## make output folder for clusters",
"pdir",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"data",
".",
"paramsdict",
"[",
"\"project_dir\"",
"]",
")",
"data",
".",
"dirs",
".",
"clusts",
"=",
"os",
".",
"path",... | sets up directories for step3 data | [
"sets",
"up",
"directories",
"for",
"step3",
"data"
] | python | valid | 45.428571 |
shakefu/pyconfig | pyconfig/__init__.py | https://github.com/shakefu/pyconfig/blob/000cb127db51e03cb4070aae6943e956193cbad5/pyconfig/__init__.py#L195-L213 | def get(self, name, default, allow_default=True):
""" Return a setting value.
:param str name: Setting key name.
:param default: Default value of setting if it's not explicitly
set.
:param bool allow_default: If true, use the parameter default as
... | [
"def",
"get",
"(",
"self",
",",
"name",
",",
"default",
",",
"allow_default",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"settings",
".",
"get",
"(",
"'pyconfig.case_sensitive'",
",",
"False",
")",
":",
"name",
"=",
"name",
".",
"lower",
"(",
"... | Return a setting value.
:param str name: Setting key name.
:param default: Default value of setting if it's not explicitly
set.
:param bool allow_default: If true, use the parameter default as
default if the key is not set, els... | [
"Return",
"a",
"setting",
"value",
"."
] | python | valid | 45.736842 |
tinybike/weightedstats | weightedstats/__init__.py | https://github.com/tinybike/weightedstats/blob/0e2638099dba7f288a1553a83e957a95522229da/weightedstats/__init__.py#L69-L87 | def weighted_median(data, weights=None):
"""Calculate the weighted median of a list."""
if weights is None:
return median(data)
midpoint = 0.5 * sum(weights)
if any([j > midpoint for j in weights]):
return data[weights.index(max(weights))]
if any([j > 0 for j in weights]):
so... | [
"def",
"weighted_median",
"(",
"data",
",",
"weights",
"=",
"None",
")",
":",
"if",
"weights",
"is",
"None",
":",
"return",
"median",
"(",
"data",
")",
"midpoint",
"=",
"0.5",
"*",
"sum",
"(",
"weights",
")",
"if",
"any",
"(",
"[",
"j",
">",
"midpo... | Calculate the weighted median of a list. | [
"Calculate",
"the",
"weighted",
"median",
"of",
"a",
"list",
"."
] | python | train | 47.105263 |
colab/colab-superarchives-plugin | src/colab_superarchives/management/commands/import_emails.py | https://github.com/colab/colab-superarchives-plugin/blob/fe588a1d4fac874ccad2063ee19a857028a22721/src/colab_superarchives/management/commands/import_emails.py#L239-L263 | def import_emails(self, archives_path, all, exclude_lists=None):
"""Get emails from the filesystem from the `archives_path`
and store them into the database. If `all` is set to True all
the filesystem storage will be imported otherwise the
importation will resume from the last message pr... | [
"def",
"import_emails",
"(",
"self",
",",
"archives_path",
",",
"all",
",",
"exclude_lists",
"=",
"None",
")",
":",
"count",
"=",
"0",
"email_generator",
"=",
"self",
".",
"get_emails",
"(",
"archives_path",
",",
"all",
",",
"exclude_lists",
")",
"for",
"m... | Get emails from the filesystem from the `archives_path`
and store them into the database. If `all` is set to True all
the filesystem storage will be imported otherwise the
importation will resume from the last message previously
imported. The lists set in `exclude_lists` won't be importe... | [
"Get",
"emails",
"from",
"the",
"filesystem",
"from",
"the",
"archives_path",
"and",
"store",
"them",
"into",
"the",
"database",
".",
"If",
"all",
"is",
"set",
"to",
"True",
"all",
"the",
"filesystem",
"storage",
"will",
"be",
"imported",
"otherwise",
"the",... | python | train | 38.08 |
gitpython-developers/GitPython | git/objects/commit.py | https://github.com/gitpython-developers/GitPython/blob/1f66e25c25cde2423917ee18c4704fff83b837d1/git/objects/commit.py#L251-L279 | def _iter_from_process_or_stream(cls, repo, proc_or_stream):
"""Parse out commit information into a list of Commit objects
We expect one-line per commit, and parse the actual commit information directly
from our lighting fast object database
:param proc: git-rev-list process instance - ... | [
"def",
"_iter_from_process_or_stream",
"(",
"cls",
",",
"repo",
",",
"proc_or_stream",
")",
":",
"stream",
"=",
"proc_or_stream",
"if",
"not",
"hasattr",
"(",
"stream",
",",
"'readline'",
")",
":",
"stream",
"=",
"proc_or_stream",
".",
"stdout",
"readline",
"=... | Parse out commit information into a list of Commit objects
We expect one-line per commit, and parse the actual commit information directly
from our lighting fast object database
:param proc: git-rev-list process instance - one sha per line
:return: iterator returning Commit objects | [
"Parse",
"out",
"commit",
"information",
"into",
"a",
"list",
"of",
"Commit",
"objects",
"We",
"expect",
"one",
"-",
"line",
"per",
"commit",
"and",
"parse",
"the",
"actual",
"commit",
"information",
"directly",
"from",
"our",
"lighting",
"fast",
"object",
"... | python | train | 43.068966 |
F5Networks/f5-common-python | f5/bigip/resource.py | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/resource.py#L519-L594 | def _update(self, **kwargs):
"""wrapped with update, override that in a subclass to customize"""
requests_params, update_uri, session, read_only = \
self._prepare_put_or_patch(kwargs)
read_only_mutations = []
for attr in read_only:
if attr in kwargs:
... | [
"def",
"_update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"requests_params",
",",
"update_uri",
",",
"session",
",",
"read_only",
"=",
"self",
".",
"_prepare_put_or_patch",
"(",
"kwargs",
")",
"read_only_mutations",
"=",
"[",
"]",
"for",
"attr",
"i... | wrapped with update, override that in a subclass to customize | [
"wrapped",
"with",
"update",
"override",
"that",
"in",
"a",
"subclass",
"to",
"customize"
] | python | train | 40.776316 |
census-instrumentation/opencensus-python | opencensus/metrics/export/gauge.py | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/metrics/export/gauge.py#L336-L355 | def get_or_create_time_series(self, label_values):
"""Get a mutable measurement for the given set of label values.
:type label_values: list(:class:`LabelValue`)
:param label_values: The measurement's label values.
:rtype: :class:`GaugePointLong`, :class:`GaugePointDouble`
:... | [
"def",
"get_or_create_time_series",
"(",
"self",
",",
"label_values",
")",
":",
"if",
"label_values",
"is",
"None",
":",
"raise",
"ValueError",
"if",
"any",
"(",
"lv",
"is",
"None",
"for",
"lv",
"in",
"label_values",
")",
":",
"raise",
"ValueError",
"if",
... | Get a mutable measurement for the given set of label values.
:type label_values: list(:class:`LabelValue`)
:param label_values: The measurement's label values.
:rtype: :class:`GaugePointLong`, :class:`GaugePointDouble`
:class:`opencensus.metrics.export.cumulative.CumulativePointLon... | [
"Get",
"a",
"mutable",
"measurement",
"for",
"the",
"given",
"set",
"of",
"label",
"values",
"."
] | python | train | 42.75 |
cloud-custodian/cloud-custodian | c7n/resources/appelb.py | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/resources/appelb.py#L81-L88 | def get_resources(self, ids, cache=True):
"""Support server side filtering on arns or names
"""
if ids[0].startswith('arn:'):
params = {'LoadBalancerArns': ids}
else:
params = {'Names': ids}
return self.query.filter(self.manager, **params) | [
"def",
"get_resources",
"(",
"self",
",",
"ids",
",",
"cache",
"=",
"True",
")",
":",
"if",
"ids",
"[",
"0",
"]",
".",
"startswith",
"(",
"'arn:'",
")",
":",
"params",
"=",
"{",
"'LoadBalancerArns'",
":",
"ids",
"}",
"else",
":",
"params",
"=",
"{"... | Support server side filtering on arns or names | [
"Support",
"server",
"side",
"filtering",
"on",
"arns",
"or",
"names"
] | python | train | 37 |
blag/django-secure-mail | secure_mail/utils.py | https://github.com/blag/django-secure-mail/blob/52987b6ce829e6de2dc8ab38ed3190bc2752b341/secure_mail/utils.py#L25-L31 | def addresses_for_key(gpg, key):
"""
Takes a key and extracts the email addresses for it.
"""
return [address.split("<")[-1].strip(">")
for address in gpg.list_keys().key_map[key['fingerprint']]["uids"]
if address] | [
"def",
"addresses_for_key",
"(",
"gpg",
",",
"key",
")",
":",
"return",
"[",
"address",
".",
"split",
"(",
"\"<\"",
")",
"[",
"-",
"1",
"]",
".",
"strip",
"(",
"\">\"",
")",
"for",
"address",
"in",
"gpg",
".",
"list_keys",
"(",
")",
".",
"key_map",... | Takes a key and extracts the email addresses for it. | [
"Takes",
"a",
"key",
"and",
"extracts",
"the",
"email",
"addresses",
"for",
"it",
"."
] | python | train | 36.285714 |
cloudendpoints/endpoints-python | endpoints/api_config.py | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L2181-L2224 | def get_descriptor_defaults(self, api_info, hostname=None):
"""Gets a default configuration for a service.
Args:
api_info: _ApiInfo object for this service.
hostname: string, Hostname of the API, to override the value set on the
current service. Defaults to None.
Returns:
A dicti... | [
"def",
"get_descriptor_defaults",
"(",
"self",
",",
"api_info",
",",
"hostname",
"=",
"None",
")",
":",
"hostname",
"=",
"(",
"hostname",
"or",
"endpoints_util",
".",
"get_app_hostname",
"(",
")",
"or",
"api_info",
".",
"hostname",
")",
"protocol",
"=",
"'ht... | Gets a default configuration for a service.
Args:
api_info: _ApiInfo object for this service.
hostname: string, Hostname of the API, to override the value set on the
current service. Defaults to None.
Returns:
A dictionary with the default configuration. | [
"Gets",
"a",
"default",
"configuration",
"for",
"a",
"service",
"."
] | python | train | 37.5 |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers2.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers2.py#L304-L383 | def convert_convolution(builder, layer, input_names, output_names, keras_layer):
"""
Convert convolution layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
_check... | [
"def",
"convert_convolution",
"(",
"builder",
",",
"layer",
",",
"input_names",
",",
"output_names",
",",
"keras_layer",
")",
":",
"_check_data_format",
"(",
"keras_layer",
")",
"# Get input and output names",
"input_name",
",",
"output_name",
"=",
"(",
"input_names",... | Convert convolution layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object. | [
"Convert",
"convolution",
"layer",
"from",
"keras",
"to",
"coreml",
"."
] | python | train | 32.6375 |
Parsely/schemato | schemato/validator.py | https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/validator.py#L174-L189 | def _superclasses_for_subject(self, graph, typeof):
"""helper, returns a list of all superclasses of a given class"""
# TODO - this might be replacing a fairly simple graph API query where
# it doesn't need to
classes = []
superclass = typeof
while True:
found... | [
"def",
"_superclasses_for_subject",
"(",
"self",
",",
"graph",
",",
"typeof",
")",
":",
"# TODO - this might be replacing a fairly simple graph API query where",
"# it doesn't need to",
"classes",
"=",
"[",
"]",
"superclass",
"=",
"typeof",
"while",
"True",
":",
"found",
... | helper, returns a list of all superclasses of a given class | [
"helper",
"returns",
"a",
"list",
"of",
"all",
"superclasses",
"of",
"a",
"given",
"class"
] | python | train | 38.625 |
xflows/rdm | rdm/db/converters.py | https://github.com/xflows/rdm/blob/d984e2a0297e5fa8d799953bbd0dba79b05d403d/rdm/db/converters.py#L157-L166 | def all_examples(self, pred_name=None):
'''
Emits all examples in prolog form for RSD.
:param pred_name: override for the emitted predicate name
'''
target = self.db.target_table
pred_name = pred_name if pred_name else target
examples = self.db.rows(target, [... | [
"def",
"all_examples",
"(",
"self",
",",
"pred_name",
"=",
"None",
")",
":",
"target",
"=",
"self",
".",
"db",
".",
"target_table",
"pred_name",
"=",
"pred_name",
"if",
"pred_name",
"else",
"target",
"examples",
"=",
"self",
".",
"db",
".",
"rows",
"(",
... | Emits all examples in prolog form for RSD.
:param pred_name: override for the emitted predicate name | [
"Emits",
"all",
"examples",
"in",
"prolog",
"form",
"for",
"RSD",
"."
] | python | train | 46.5 |
asphalt-framework/asphalt-templating | asphalt/templating/api.py | https://github.com/asphalt-framework/asphalt-templating/blob/e5f836290820aa295b048b17b96d3896d5f1eeac/asphalt/templating/api.py#L53-L65 | def render(self, template: str, **vars) -> str:
"""
Render the named template.
The current context will be available to the template as the ``ctx`` variable.
:param template: name of the template file
:param vars: extra template variables
:return: the rendered results
... | [
"def",
"render",
"(",
"self",
",",
"template",
":",
"str",
",",
"*",
"*",
"vars",
")",
"->",
"str",
":",
"vars",
".",
"setdefault",
"(",
"'ctx'",
",",
"self",
".",
"_ctx",
")",
"return",
"self",
".",
"_renderer",
".",
"render",
"(",
"template",
","... | Render the named template.
The current context will be available to the template as the ``ctx`` variable.
:param template: name of the template file
:param vars: extra template variables
:return: the rendered results | [
"Render",
"the",
"named",
"template",
"."
] | python | train | 32 |
iotile/coretools | iotilecore/iotile/core/utilities/intelhex/__init__.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/__init__.py#L1100-L1124 | def diff_dumps(ih1, ih2, tofile=None, name1="a", name2="b", n_context=3):
"""Diff 2 IntelHex objects and produce unified diff output for their
hex dumps.
@param ih1 first IntelHex object to compare
@param ih2 second IntelHex object to compare
@param tofile file-like object to writ... | [
"def",
"diff_dumps",
"(",
"ih1",
",",
"ih2",
",",
"tofile",
"=",
"None",
",",
"name1",
"=",
"\"a\"",
",",
"name2",
"=",
"\"b\"",
",",
"n_context",
"=",
"3",
")",
":",
"def",
"prepare_lines",
"(",
"ih",
")",
":",
"sio",
"=",
"StringIO",
"(",
")",
... | Diff 2 IntelHex objects and produce unified diff output for their
hex dumps.
@param ih1 first IntelHex object to compare
@param ih2 second IntelHex object to compare
@param tofile file-like object to write output
@param name1 name of the first hex file to show in the diff hea... | [
"Diff",
"2",
"IntelHex",
"objects",
"and",
"produce",
"unified",
"diff",
"output",
"for",
"their",
"hex",
"dumps",
"."
] | python | train | 39.08 |
tensorpack/tensorpack | tensorpack/callbacks/param.py | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/param.py#L68-L76 | def setup_graph(self):
""" Will setup the assign operator for that variable. """
all_vars = tfv1.global_variables() + tfv1.local_variables()
for v in all_vars:
if v.name == self.var_name:
self.var = v
break
else:
raise ValueError("{... | [
"def",
"setup_graph",
"(",
"self",
")",
":",
"all_vars",
"=",
"tfv1",
".",
"global_variables",
"(",
")",
"+",
"tfv1",
".",
"local_variables",
"(",
")",
"for",
"v",
"in",
"all_vars",
":",
"if",
"v",
".",
"name",
"==",
"self",
".",
"var_name",
":",
"se... | Will setup the assign operator for that variable. | [
"Will",
"setup",
"the",
"assign",
"operator",
"for",
"that",
"variable",
"."
] | python | train | 41 |
soasme/dogeon | dson/__init__.py | https://github.com/soasme/dogeon/blob/496b9a5b099946d14434ed0cd7a94a270f607207/dson/__init__.py#L125-L193 | def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, indent=None, separators=None,
encoding='utf-8', default=None, sort_keys=False, **kw):
"""Serialize ``obj`` as a DSON formatted stream to ``fp`` (a
``.write()``-supporting file-like object).
I... | [
"def",
"dump",
"(",
"obj",
",",
"fp",
",",
"skipkeys",
"=",
"False",
",",
"ensure_ascii",
"=",
"True",
",",
"check_circular",
"=",
"True",
",",
"allow_nan",
"=",
"True",
",",
"cls",
"=",
"None",
",",
"indent",
"=",
"None",
",",
"separators",
"=",
"No... | Serialize ``obj`` as a DSON formatted stream to ``fp`` (a
``.write()``-supporting file-like object).
If ``skipkeys`` is true then ``dict`` keys that are not basic types
(``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
will be skipped instead of raising a ``TypeError``.
If `... | [
"Serialize",
"obj",
"as",
"a",
"DSON",
"formatted",
"stream",
"to",
"fp",
"(",
"a",
".",
"write",
"()",
"-",
"supporting",
"file",
"-",
"like",
"object",
")",
"."
] | python | train | 50.028986 |
liampauling/betfair | betfairlightweight/endpoints/scores.py | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/endpoints/scores.py#L52-L66 | def list_scores(self, update_keys, session=None, lightweight=None):
"""
Returns a list of current scores for the given events.
:param list update_keys: The filter to select desired markets. All markets that match
the criteria in the filter are selected e.g. [{'eventId': '28205674', 'las... | [
"def",
"list_scores",
"(",
"self",
",",
"update_keys",
",",
"session",
"=",
"None",
",",
"lightweight",
"=",
"None",
")",
":",
"params",
"=",
"clean_locals",
"(",
"locals",
"(",
")",
")",
"method",
"=",
"'%s%s'",
"%",
"(",
"self",
".",
"URI",
",",
"'... | Returns a list of current scores for the given events.
:param list update_keys: The filter to select desired markets. All markets that match
the criteria in the filter are selected e.g. [{'eventId': '28205674', 'lastUpdateSequenceProcessed': 2}]
:param requests.session session: Requests session... | [
"Returns",
"a",
"list",
"of",
"current",
"scores",
"for",
"the",
"given",
"events",
"."
] | python | train | 52 |
PyCQA/pylint | pylint/checkers/base.py | https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L1153-L1211 | def visit_lambda(self, node):
"""check whether or not the lambda is suspicious
"""
# if the body of the lambda is a call expression with the same
# argument list as the lambda itself, then the lambda is
# possibly unnecessary and at least suspicious.
if node.args.defaults... | [
"def",
"visit_lambda",
"(",
"self",
",",
"node",
")",
":",
"# if the body of the lambda is a call expression with the same",
"# argument list as the lambda itself, then the lambda is",
"# possibly unnecessary and at least suspicious.",
"if",
"node",
".",
"args",
".",
"defaults",
":... | check whether or not the lambda is suspicious | [
"check",
"whether",
"or",
"not",
"the",
"lambda",
"is",
"suspicious"
] | python | test | 42.372881 |
lawsie/guizero | guizero/ButtonGroup.py | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/ButtonGroup.py#L262-L276 | def remove(self, option):
"""
Removes the first `option` from the ButtonGroup.
Returns `True` if an item was removed.
:param string option:
The value of the option to remove from the ButtonGroup.
"""
for existing_option in self._options:
if exist... | [
"def",
"remove",
"(",
"self",
",",
"option",
")",
":",
"for",
"existing_option",
"in",
"self",
".",
"_options",
":",
"if",
"existing_option",
"[",
"1",
"]",
"==",
"option",
":",
"self",
".",
"_options",
".",
"remove",
"(",
"existing_option",
")",
"self",... | Removes the first `option` from the ButtonGroup.
Returns `True` if an item was removed.
:param string option:
The value of the option to remove from the ButtonGroup. | [
"Removes",
"the",
"first",
"option",
"from",
"the",
"ButtonGroup",
"."
] | python | train | 31.533333 |
latchset/custodia | docs/source/examples/cfgparser.py | https://github.com/latchset/custodia/blob/5ad4cd7a2f40babc6b8b5d16215b7e27ca993b6d/docs/source/examples/cfgparser.py#L109-L117 | def getsecret(self, section, option, **kwargs):
"""Get a secret from Custodia
"""
# keyword-only arguments, vars and fallback are directly passed through
raw = kwargs.get('raw', False)
value = self.get(section, option, **kwargs)
if raw:
return value
re... | [
"def",
"getsecret",
"(",
"self",
",",
"section",
",",
"option",
",",
"*",
"*",
"kwargs",
")",
":",
"# keyword-only arguments, vars and fallback are directly passed through",
"raw",
"=",
"kwargs",
".",
"get",
"(",
"'raw'",
",",
"False",
")",
"value",
"=",
"self",... | Get a secret from Custodia | [
"Get",
"a",
"secret",
"from",
"Custodia"
] | python | train | 39.444444 |
ceph/ceph-deploy | ceph_deploy/conf/ceph.py | https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/conf/ceph.py#L34-L46 | def safe_get(self, section, key):
"""
Attempt to get a configuration value from a certain section
in a ``cfg`` object but returning None if not found. Avoids the need
to be doing try/except {ConfigParser Exceptions} every time.
"""
try:
#Use full parent functi... | [
"def",
"safe_get",
"(",
"self",
",",
"section",
",",
"key",
")",
":",
"try",
":",
"#Use full parent function so we can replace it in the class",
"# if desired",
"return",
"configparser",
".",
"RawConfigParser",
".",
"get",
"(",
"self",
",",
"section",
",",
"key",
... | Attempt to get a configuration value from a certain section
in a ``cfg`` object but returning None if not found. Avoids the need
to be doing try/except {ConfigParser Exceptions} every time. | [
"Attempt",
"to",
"get",
"a",
"configuration",
"value",
"from",
"a",
"certain",
"section",
"in",
"a",
"cfg",
"object",
"but",
"returning",
"None",
"if",
"not",
"found",
".",
"Avoids",
"the",
"need",
"to",
"be",
"doing",
"try",
"/",
"except",
"{",
"ConfigP... | python | train | 42.692308 |
nickjj/ansigenome | ansigenome/utils.py | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/utils.py#L390-L407 | def create_meta_main(create_path, config, role, categories):
"""
Create a meta template.
"""
meta_file = c.DEFAULT_META_FILE.replace(
"%author_name", config["author_name"])
meta_file = meta_file.replace(
"%author_company", config["author_company"])
meta_file = meta_file.replace("... | [
"def",
"create_meta_main",
"(",
"create_path",
",",
"config",
",",
"role",
",",
"categories",
")",
":",
"meta_file",
"=",
"c",
".",
"DEFAULT_META_FILE",
".",
"replace",
"(",
"\"%author_name\"",
",",
"config",
"[",
"\"author_name\"",
"]",
")",
"meta_file",
"=",... | Create a meta template. | [
"Create",
"a",
"meta",
"template",
"."
] | python | train | 34.222222 |
mcash/merchant-api-python-sdk | mcash/mapi_client/pusherconnector.py | https://github.com/mcash/merchant-api-python-sdk/blob/ebe8734126790354b71077aca519ff263235944e/mcash/mapi_client/pusherconnector.py#L33-L39 | def _pusher_connect_handler(self, data):
"""Event handler for the connection_established event. Binds the
shortlink_scanned event
"""
self.channel = self.pusher.subscribe(self.pos_callback_chan)
for listener in self.pusher_connected_listeners:
listener(data) | [
"def",
"_pusher_connect_handler",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"channel",
"=",
"self",
".",
"pusher",
".",
"subscribe",
"(",
"self",
".",
"pos_callback_chan",
")",
"for",
"listener",
"in",
"self",
".",
"pusher_connected_listeners",
":",
"... | Event handler for the connection_established event. Binds the
shortlink_scanned event | [
"Event",
"handler",
"for",
"the",
"connection_established",
"event",
".",
"Binds",
"the",
"shortlink_scanned",
"event"
] | python | train | 43.428571 |
abe-winter/pg13-py | pg13/sqparse2.py | https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/sqparse2.py#L137-L141 | def t_NAME(self,t):
'[A-Za-z]\w*|\"char\"'
# warning: this allows stuff like SeLeCt with mixed case. who cares.
t.type = KEYWORDS[t.value.lower()] if t.value.lower() in KEYWORDS else 'BOOL' if t.value.lower() in ('is','not') else 'NAME'
return t | [
"def",
"t_NAME",
"(",
"self",
",",
"t",
")",
":",
"# warning: this allows stuff like SeLeCt with mixed case. who cares.",
"t",
".",
"type",
"=",
"KEYWORDS",
"[",
"t",
".",
"value",
".",
"lower",
"(",
")",
"]",
"if",
"t",
".",
"value",
".",
"lower",
"(",
")... | [A-Za-z]\w*|\"char\" | [
"[",
"A",
"-",
"Za",
"-",
"z",
"]",
"\\",
"w",
"*",
"|",
"\\",
"char",
"\\"
] | python | train | 51.4 |
esheldon/fitsio | fitsio/hdu/table.py | https://github.com/esheldon/fitsio/blob/a6f07919f457a282fe240adad9d2c30906b71a15/fitsio/hdu/table.py#L128-L240 | def write(self, data, **keys):
"""
Write data into this HDU
parameters
----------
data: ndarray or list of ndarray
A numerical python array. Should be an ordinary array for image
HDUs, should have fields for tables. To write an ordinary array to
... | [
"def",
"write",
"(",
"self",
",",
"data",
",",
"*",
"*",
"keys",
")",
":",
"slow",
"=",
"keys",
".",
"get",
"(",
"'slow'",
",",
"False",
")",
"isrec",
"=",
"False",
"if",
"isinstance",
"(",
"data",
",",
"(",
"list",
",",
"dict",
")",
")",
":",
... | Write data into this HDU
parameters
----------
data: ndarray or list of ndarray
A numerical python array. Should be an ordinary array for image
HDUs, should have fields for tables. To write an ordinary array to
a column in a table HDU, use write_column. If... | [
"Write",
"data",
"into",
"this",
"HDU"
] | python | train | 39.345133 |
Metatab/metapack | metapack/cli/wp.py | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/cli/wp.py#L143-L263 | def publish_wp(site_name, output_file, resources, args):
"""Publish a notebook to a wordpress post, using Gutenberg blocks.
Here is what the metadata looks like, in a section of the notebook tagged 'frontmatter'
show_input: hide
github: https://github.com/sandiegodata/notebooks/blob/master/tutorial/A... | [
"def",
"publish_wp",
"(",
"site_name",
",",
"output_file",
",",
"resources",
",",
"args",
")",
":",
"from",
"wordpress_xmlrpc",
"import",
"Client",
",",
"WordPressPost",
"from",
"wordpress_xmlrpc",
".",
"methods",
".",
"media",
"import",
"UploadFile",
",",
"GetM... | Publish a notebook to a wordpress post, using Gutenberg blocks.
Here is what the metadata looks like, in a section of the notebook tagged 'frontmatter'
show_input: hide
github: https://github.com/sandiegodata/notebooks/blob/master/tutorial/American%20Community%20Survey.ipynb
identifier: 5c987397-a954-... | [
"Publish",
"a",
"notebook",
"to",
"a",
"wordpress",
"post",
"using",
"Gutenberg",
"blocks",
"."
] | python | train | 30.512397 |
pyca/pynacl | src/nacl/hash.py | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/hash.py#L86-L118 | def blake2b(data, digest_size=BLAKE2B_BYTES, key=b'',
salt=b'', person=b'',
encoder=nacl.encoding.HexEncoder):
"""
Hashes ``data`` with blake2b.
:param data: the digest input byte sequence
:type data: bytes
:param digest_size: the requested digest size; must be at most
... | [
"def",
"blake2b",
"(",
"data",
",",
"digest_size",
"=",
"BLAKE2B_BYTES",
",",
"key",
"=",
"b''",
",",
"salt",
"=",
"b''",
",",
"person",
"=",
"b''",
",",
"encoder",
"=",
"nacl",
".",
"encoding",
".",
"HexEncoder",
")",
":",
"digest",
"=",
"_b2b_hash",
... | Hashes ``data`` with blake2b.
:param data: the digest input byte sequence
:type data: bytes
:param digest_size: the requested digest size; must be at most
:const:`BLAKE2B_BYTES_MAX`;
the default digest size is
:const:`BLAKE2B_BYTES`
... | [
"Hashes",
"data",
"with",
"blake2b",
"."
] | python | train | 38.666667 |
mlperf/training | data_generation/fractal_graph_expansions/util.py | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/data_generation/fractal_graph_expansions/util.py#L34-L38 | def load_df_from_file(file_path, sep=",", header=0):
"""Wrapper around pandas' read_csv."""
with tf.gfile.Open(file_path) as infile:
df = pd.read_csv(infile, sep=sep, header=header)
return df | [
"def",
"load_df_from_file",
"(",
"file_path",
",",
"sep",
"=",
"\",\"",
",",
"header",
"=",
"0",
")",
":",
"with",
"tf",
".",
"gfile",
".",
"Open",
"(",
"file_path",
")",
"as",
"infile",
":",
"df",
"=",
"pd",
".",
"read_csv",
"(",
"infile",
",",
"s... | Wrapper around pandas' read_csv. | [
"Wrapper",
"around",
"pandas",
"read_csv",
"."
] | python | train | 39.4 |
SBRG/ssbio | ssbio/core/protein.py | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/core/protein.py#L503-L571 | def set_representative_sequence(self, force_rerun=False):
"""Automatically consolidate loaded sequences (manual, UniProt, or KEGG) and set a single representative
sequence.
Manually set representative sequences override all existing mappings. UniProt mappings override KEGG mappings
exce... | [
"def",
"set_representative_sequence",
"(",
"self",
",",
"force_rerun",
"=",
"False",
")",
":",
"if",
"len",
"(",
"self",
".",
"sequences",
")",
"==",
"0",
":",
"log",
".",
"error",
"(",
"'{}: no sequences mapped'",
".",
"format",
"(",
"self",
".",
"id",
... | Automatically consolidate loaded sequences (manual, UniProt, or KEGG) and set a single representative
sequence.
Manually set representative sequences override all existing mappings. UniProt mappings override KEGG mappings
except when KEGG mappings have PDBs associated with them and UniProt does... | [
"Automatically",
"consolidate",
"loaded",
"sequences",
"(",
"manual",
"UniProt",
"or",
"KEGG",
")",
"and",
"set",
"a",
"single",
"representative",
"sequence",
"."
] | python | train | 51.101449 |
yt-project/unyt | unyt/array.py | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L2041-L2059 | def udot(op1, op2):
"""Matrix or vector dot product that preserves units
This is a wrapper around np.dot that preserves units.
Examples
--------
>>> from unyt import km, s
>>> a = np.eye(2)*km
>>> b = (np.ones((2, 2)) * 2)*s
>>> print(udot(a, b))
[[2. 2.]
[2. 2.]] km*s
"""... | [
"def",
"udot",
"(",
"op1",
",",
"op2",
")",
":",
"dot",
"=",
"np",
".",
"dot",
"(",
"op1",
".",
"d",
",",
"op2",
".",
"d",
")",
"units",
"=",
"op1",
".",
"units",
"*",
"op2",
".",
"units",
"if",
"dot",
".",
"shape",
"==",
"(",
")",
":",
"... | Matrix or vector dot product that preserves units
This is a wrapper around np.dot that preserves units.
Examples
--------
>>> from unyt import km, s
>>> a = np.eye(2)*km
>>> b = (np.ones((2, 2)) * 2)*s
>>> print(udot(a, b))
[[2. 2.]
[2. 2.]] km*s | [
"Matrix",
"or",
"vector",
"dot",
"product",
"that",
"preserves",
"units"
] | python | train | 24.526316 |
mgraffg/EvoDAG | EvoDAG/population.py | https://github.com/mgraffg/EvoDAG/blob/e11fa1fd1ca9e69cca92696c86661a3dc7b3a1d5/EvoDAG/population.py#L402-L419 | def replace(self, v):
"""Replace an individual selected by negative tournament selection with
individual v"""
if self.popsize < self._popsize:
return self.add(v)
k = self.tournament(negative=True)
self.clean(self.population[k])
self.population[k] = v
v... | [
"def",
"replace",
"(",
"self",
",",
"v",
")",
":",
"if",
"self",
".",
"popsize",
"<",
"self",
".",
"_popsize",
":",
"return",
"self",
".",
"add",
"(",
"v",
")",
"k",
"=",
"self",
".",
"tournament",
"(",
"negative",
"=",
"True",
")",
"self",
".",
... | Replace an individual selected by negative tournament selection with
individual v | [
"Replace",
"an",
"individual",
"selected",
"by",
"negative",
"tournament",
"selection",
"with",
"individual",
"v"
] | python | train | 34.722222 |
jwkvam/bowtie | bowtie/_magic.py | https://github.com/jwkvam/bowtie/blob/c494850671ac805bf186fbf2bdb07d2a34ae876d/bowtie/_magic.py#L27-L47 | def get_notebook_name() -> str:
"""Return the full path of the jupyter notebook.
References
----------
https://github.com/jupyter/notebook/issues/1000#issuecomment-359875246
"""
kernel_id = re.search( # type: ignore
'kernel-(.*).json',
ipykernel.connect.get_connection_file()
... | [
"def",
"get_notebook_name",
"(",
")",
"->",
"str",
":",
"kernel_id",
"=",
"re",
".",
"search",
"(",
"# type: ignore",
"'kernel-(.*).json'",
",",
"ipykernel",
".",
"connect",
".",
"get_connection_file",
"(",
")",
")",
".",
"group",
"(",
"1",
")",
"servers",
... | Return the full path of the jupyter notebook.
References
----------
https://github.com/jupyter/notebook/issues/1000#issuecomment-359875246 | [
"Return",
"the",
"full",
"path",
"of",
"the",
"jupyter",
"notebook",
"."
] | python | train | 38.047619 |
Toilal/rebulk | rebulk/rebulk.py | https://github.com/Toilal/rebulk/blob/7511a4671f2fd9493e3df1e5177b7656789069e8/rebulk/rebulk.py#L146-L156 | def string(self, *pattern, **kwargs):
"""
Add string pattern
:param pattern:
:type pattern:
:return: self
:rtype: Rebulk
"""
self.pattern(self.build_string(*pattern, **kwargs))
return self | [
"def",
"string",
"(",
"self",
",",
"*",
"pattern",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"pattern",
"(",
"self",
".",
"build_string",
"(",
"*",
"pattern",
",",
"*",
"*",
"kwargs",
")",
")",
"return",
"self"
] | Add string pattern
:param pattern:
:type pattern:
:return: self
:rtype: Rebulk | [
"Add",
"string",
"pattern"
] | python | train | 22.818182 |
PyMLGame/pymlgame | pymlgame/surface.py | https://github.com/PyMLGame/pymlgame/blob/450fe77d35f9a26c107586d6954f69c3895bf504/pymlgame/surface.py#L34-L44 | def draw_dot(self, pos, color):
"""
Draw one single dot with the given color on the screen.
:param pos: Position of the dot
:param color: COlor for the dot
:type pos: tuple
:type color: tuple
"""
if 0 <= pos[0] < self.width and 0 <= pos[1] < self.height:
... | [
"def",
"draw_dot",
"(",
"self",
",",
"pos",
",",
"color",
")",
":",
"if",
"0",
"<=",
"pos",
"[",
"0",
"]",
"<",
"self",
".",
"width",
"and",
"0",
"<=",
"pos",
"[",
"1",
"]",
"<",
"self",
".",
"height",
":",
"self",
".",
"matrix",
"[",
"pos",
... | Draw one single dot with the given color on the screen.
:param pos: Position of the dot
:param color: COlor for the dot
:type pos: tuple
:type color: tuple | [
"Draw",
"one",
"single",
"dot",
"with",
"the",
"given",
"color",
"on",
"the",
"screen",
"."
] | python | train | 32.454545 |
CenturyLinkCloud/clc-python-sdk | src/clc/APIv2/account.py | https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/account.py#L94-L104 | def PrimaryDatacenter(self):
"""Returns the primary datacenter object associated with the account.
>>> clc.v2.Account(alias='BTDI').PrimaryDatacenter()
<clc.APIv2.datacenter.Datacenter instance at 0x10a45ce18>
>>> print _
WA1
"""
return(clc.v2.Datacenter(alias=... | [
"def",
"PrimaryDatacenter",
"(",
"self",
")",
":",
"return",
"(",
"clc",
".",
"v2",
".",
"Datacenter",
"(",
"alias",
"=",
"self",
".",
"alias",
",",
"location",
"=",
"self",
".",
"data",
"[",
"'primaryDataCenter'",
"]",
",",
"session",
"=",
"self",
"."... | Returns the primary datacenter object associated with the account.
>>> clc.v2.Account(alias='BTDI').PrimaryDatacenter()
<clc.APIv2.datacenter.Datacenter instance at 0x10a45ce18>
>>> print _
WA1 | [
"Returns",
"the",
"primary",
"datacenter",
"object",
"associated",
"with",
"the",
"account",
"."
] | python | train | 34.909091 |
Cito/DBUtils | DBUtils/SteadyPg.py | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyPg.py#L230-L242 | def begin(self, sql=None):
"""Begin a transaction."""
self._transaction = True
try:
begin = self._con.begin
except AttributeError:
return self._con.query(sql or 'begin')
else:
# use existing method if available
if sql:
... | [
"def",
"begin",
"(",
"self",
",",
"sql",
"=",
"None",
")",
":",
"self",
".",
"_transaction",
"=",
"True",
"try",
":",
"begin",
"=",
"self",
".",
"_con",
".",
"begin",
"except",
"AttributeError",
":",
"return",
"self",
".",
"_con",
".",
"query",
"(",
... | Begin a transaction. | [
"Begin",
"a",
"transaction",
"."
] | python | train | 29.307692 |
manns/pyspread | pyspread/src/gui/_widgets.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/gui/_widgets.py#L637-L641 | def OnMeasureItem(self, item):
"""Returns the height of the items in the popup"""
item_name = self.GetItems()[item]
return icons[item_name].GetHeight() | [
"def",
"OnMeasureItem",
"(",
"self",
",",
"item",
")",
":",
"item_name",
"=",
"self",
".",
"GetItems",
"(",
")",
"[",
"item",
"]",
"return",
"icons",
"[",
"item_name",
"]",
".",
"GetHeight",
"(",
")"
] | Returns the height of the items in the popup | [
"Returns",
"the",
"height",
"of",
"the",
"items",
"in",
"the",
"popup"
] | python | train | 34.4 |
lightning-viz/lightning-python | lightning/types/base.py | https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/types/base.py#L80-L106 | def _clean_data(cls, *args, **kwargs):
"""
Convert raw data into a dictionary with plot-type specific methods.
The result of the cleaning operation should be a dictionary.
If the dictionary contains a 'data' field it will be passed directly
(ensuring appropriate formatting). Oth... | [
"def",
"_clean_data",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"datadict",
"=",
"cls",
".",
"clean",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"'data'",
"in",
"datadict",
":",
"data",
"=",
"datadict",
"[",
"'da... | Convert raw data into a dictionary with plot-type specific methods.
The result of the cleaning operation should be a dictionary.
If the dictionary contains a 'data' field it will be passed directly
(ensuring appropriate formatting). Otherwise, it should be a
dictionary of data-type spec... | [
"Convert",
"raw",
"data",
"into",
"a",
"dictionary",
"with",
"plot",
"-",
"type",
"specific",
"methods",
"."
] | python | train | 36.37037 |
apache/spark | python/pyspark/ml/clustering.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/ml/clustering.py#L522-L531 | def summary(self):
"""
Gets summary (e.g. cluster assignments, cluster sizes) of the model trained on the
training set. An exception is thrown if no summary exists.
"""
if self.hasSummary:
return BisectingKMeansSummary(super(BisectingKMeansModel, self).summary)
... | [
"def",
"summary",
"(",
"self",
")",
":",
"if",
"self",
".",
"hasSummary",
":",
"return",
"BisectingKMeansSummary",
"(",
"super",
"(",
"BisectingKMeansModel",
",",
"self",
")",
".",
"summary",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"No training summa... | Gets summary (e.g. cluster assignments, cluster sizes) of the model trained on the
training set. An exception is thrown if no summary exists. | [
"Gets",
"summary",
"(",
"e",
".",
"g",
".",
"cluster",
"assignments",
"cluster",
"sizes",
")",
"of",
"the",
"model",
"trained",
"on",
"the",
"training",
"set",
".",
"An",
"exception",
"is",
"thrown",
"if",
"no",
"summary",
"exists",
"."
] | python | train | 45.1 |
nerdvegas/rez | src/rez/vendor/version/version.py | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L1033-L1040 | def iter_intersecting(self, iterable, key=None, descending=False):
"""Like `iter_intersect_test`, but returns intersections only.
Returns:
An iterator that returns items from `iterable` that intersect.
"""
return _ContainsVersionIterator(self, iterable, key, descending,
... | [
"def",
"iter_intersecting",
"(",
"self",
",",
"iterable",
",",
"key",
"=",
"None",
",",
"descending",
"=",
"False",
")",
":",
"return",
"_ContainsVersionIterator",
"(",
"self",
",",
"iterable",
",",
"key",
",",
"descending",
",",
"mode",
"=",
"_ContainsVersi... | Like `iter_intersect_test`, but returns intersections only.
Returns:
An iterator that returns items from `iterable` that intersect. | [
"Like",
"iter_intersect_test",
"but",
"returns",
"intersections",
"only",
"."
] | python | train | 46.125 |
aliyun/aliyun-odps-python-sdk | odps/df/expr/window.py | https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/df/expr/window.py#L515-L524 | def cume_dist(expr, sort=None, ascending=True):
"""
Calculate cumulative ratio of a sequence expression.
:param expr: expression for calculation
:param sort: name of the sort column
:param ascending: whether to sort in ascending order
:return: calculated column
"""
return _rank_op(expr,... | [
"def",
"cume_dist",
"(",
"expr",
",",
"sort",
"=",
"None",
",",
"ascending",
"=",
"True",
")",
":",
"return",
"_rank_op",
"(",
"expr",
",",
"CumeDist",
",",
"types",
".",
"float64",
",",
"sort",
"=",
"sort",
",",
"ascending",
"=",
"ascending",
")"
] | Calculate cumulative ratio of a sequence expression.
:param expr: expression for calculation
:param sort: name of the sort column
:param ascending: whether to sort in ascending order
:return: calculated column | [
"Calculate",
"cumulative",
"ratio",
"of",
"a",
"sequence",
"expression",
"."
] | python | train | 36.8 |
mikedh/trimesh | trimesh/ray/ray_util.py | https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/ray/ray_util.py#L9-L132 | def contains_points(intersector,
points,
check_direction=None):
"""
Check if a mesh contains a set of points, using ray tests.
If the point is on the surface of the mesh, behavior is
undefined.
Parameters
---------
mesh: Trimesh object
points: (n... | [
"def",
"contains_points",
"(",
"intersector",
",",
"points",
",",
"check_direction",
"=",
"None",
")",
":",
"# convert points to float and make sure they are 3D",
"points",
"=",
"np",
".",
"asanyarray",
"(",
"points",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
... | Check if a mesh contains a set of points, using ray tests.
If the point is on the surface of the mesh, behavior is
undefined.
Parameters
---------
mesh: Trimesh object
points: (n,3) points in space
Returns
---------
contains : (n) bool
Whether point is inside mes... | [
"Check",
"if",
"a",
"mesh",
"contains",
"a",
"set",
"of",
"points",
"using",
"ray",
"tests",
"."
] | python | train | 35.104839 |
pandas-dev/pandas | pandas/core/ops.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/ops.py#L1962-L2039 | def _bool_method_SERIES(cls, op, special):
"""
Wrapper function for Series arithmetic operations, to avoid
code duplication.
"""
op_name = _get_op_name(op, special)
def na_op(x, y):
try:
result = op(x, y)
except TypeError:
assert not isinstance(y, (list, ... | [
"def",
"_bool_method_SERIES",
"(",
"cls",
",",
"op",
",",
"special",
")",
":",
"op_name",
"=",
"_get_op_name",
"(",
"op",
",",
"special",
")",
"def",
"na_op",
"(",
"x",
",",
"y",
")",
":",
"try",
":",
"result",
"=",
"op",
"(",
"x",
",",
"y",
")",... | Wrapper function for Series arithmetic operations, to avoid
code duplication. | [
"Wrapper",
"function",
"for",
"Series",
"arithmetic",
"operations",
"to",
"avoid",
"code",
"duplication",
"."
] | python | train | 39.25641 |
openeemeter/eemeter | eemeter/caltrack/usage_per_day.py | https://github.com/openeemeter/eemeter/blob/e03b1cc5f4906e8f4f7fd16183bc037107d1dfa0/eemeter/caltrack/usage_per_day.py#L876-L922 | def get_parameter_p_value_too_high_warning(
model_type, model_params, parameter, p_value, maximum_p_value
):
""" Return an empty list or a single warning wrapped in a list indicating
whether model parameter p-value is too high.
Parameters
----------
model_type : :any:`str`
Model type (e... | [
"def",
"get_parameter_p_value_too_high_warning",
"(",
"model_type",
",",
"model_params",
",",
"parameter",
",",
"p_value",
",",
"maximum_p_value",
")",
":",
"warnings",
"=",
"[",
"]",
"if",
"p_value",
">",
"maximum_p_value",
":",
"data",
"=",
"{",
"\"{}_p_value\""... | Return an empty list or a single warning wrapped in a list indicating
whether model parameter p-value is too high.
Parameters
----------
model_type : :any:`str`
Model type (e.g., ``'cdd_hdd'``).
model_params : :any:`dict`
Parameters as stored in :any:`eemeter.CalTRACKUsagePerDayCand... | [
"Return",
"an",
"empty",
"list",
"or",
"a",
"single",
"warning",
"wrapped",
"in",
"a",
"list",
"indicating",
"whether",
"model",
"parameter",
"p",
"-",
"value",
"is",
"too",
"high",
"."
] | python | train | 34.234043 |
MultipedRobotics/pyxl320 | bin/servo_ping.py | https://github.com/MultipedRobotics/pyxl320/blob/1a56540e208b028ee47d5fa0a7c7babcee0d9214/bin/servo_ping.py#L45-L87 | def sweep(port, rate, ID, retry=3):
"""
Sends a ping packet to ID's from 0 to maximum and prints out any returned
messages.
Actually send a broadcast and will retry (resend) the ping 3 times ...
"""
if port == 'dummy':
s = ServoSerial(port, rate, fake=True)
else:
s = ServoSerial(port, rate)
if ID < 0:
I... | [
"def",
"sweep",
"(",
"port",
",",
"rate",
",",
"ID",
",",
"retry",
"=",
"3",
")",
":",
"if",
"port",
"==",
"'dummy'",
":",
"s",
"=",
"ServoSerial",
"(",
"port",
",",
"rate",
",",
"fake",
"=",
"True",
")",
"else",
":",
"s",
"=",
"ServoSerial",
"... | Sends a ping packet to ID's from 0 to maximum and prints out any returned
messages.
Actually send a broadcast and will retry (resend) the ping 3 times ... | [
"Sends",
"a",
"ping",
"packet",
"to",
"ID",
"s",
"from",
"0",
"to",
"maximum",
"and",
"prints",
"out",
"any",
"returned",
"messages",
"."
] | python | train | 19.860465 |
truemped/tornadotools | tornadotools/caching.py | https://github.com/truemped/tornadotools/blob/d22632b83810afc353fa886fbc9e265bee78653f/tornadotools/caching.py#L75-L87 | def cache_key(*args, **kwargs):
"""
Base method for computing the cache key with respect to the given
arguments.
"""
key = ""
for arg in args:
if callable(arg):
key += ":%s" % repr(arg)
else:
key += ":%s" % str(arg)
return key | [
"def",
"cache_key",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"key",
"=",
"\"\"",
"for",
"arg",
"in",
"args",
":",
"if",
"callable",
"(",
"arg",
")",
":",
"key",
"+=",
"\":%s\"",
"%",
"repr",
"(",
"arg",
")",
"else",
":",
"key",
"+="... | Base method for computing the cache key with respect to the given
arguments. | [
"Base",
"method",
"for",
"computing",
"the",
"cache",
"key",
"with",
"respect",
"to",
"the",
"given",
"arguments",
"."
] | python | train | 21.769231 |
elemoine/papyrus | papyrus/xsd.py | https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/xsd.py#L73-L144 | def add_column_xsd(self, tb, column, attrs):
""" Add the XSD for a column to tb (a TreeBuilder) """
if column.nullable:
attrs['minOccurs'] = str(0)
attrs['nillable'] = 'true'
for cls, xsd_type in six.iteritems(self.SIMPLE_XSD_TYPES):
if isinstance(column.type,... | [
"def",
"add_column_xsd",
"(",
"self",
",",
"tb",
",",
"column",
",",
"attrs",
")",
":",
"if",
"column",
".",
"nullable",
":",
"attrs",
"[",
"'minOccurs'",
"]",
"=",
"str",
"(",
"0",
")",
"attrs",
"[",
"'nillable'",
"]",
"=",
"'true'",
"for",
"cls",
... | Add the XSD for a column to tb (a TreeBuilder) | [
"Add",
"the",
"XSD",
"for",
"a",
"column",
"to",
"tb",
"(",
"a",
"TreeBuilder",
")"
] | python | train | 50.611111 |
fjwCode/cerium | cerium/androiddriver.py | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L372-L379 | def view_package_path(self, package: str) -> _PATH:
'''Print the path to the APK of the given.'''
if package not in self.view_packgets_list():
raise NoSuchPackageException(
f'There is no such package {package!r}.')
output, _ = self._execute(
'-s', self.dev... | [
"def",
"view_package_path",
"(",
"self",
",",
"package",
":",
"str",
")",
"->",
"_PATH",
":",
"if",
"package",
"not",
"in",
"self",
".",
"view_packgets_list",
"(",
")",
":",
"raise",
"NoSuchPackageException",
"(",
"f'There is no such package {package!r}.'",
")",
... | Print the path to the APK of the given. | [
"Print",
"the",
"path",
"to",
"the",
"APK",
"of",
"the",
"given",
"."
] | python | train | 47.5 |
intel-analytics/BigDL | pyspark/bigdl/transform/vision/image.py | https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/transform/vision/image.py#L36-L41 | def transform(self, image_feature, bigdl_type="float"):
"""
transform ImageFeature
"""
callBigDlFunc(bigdl_type, "transformImageFeature", self.value, image_feature)
return image_feature | [
"def",
"transform",
"(",
"self",
",",
"image_feature",
",",
"bigdl_type",
"=",
"\"float\"",
")",
":",
"callBigDlFunc",
"(",
"bigdl_type",
",",
"\"transformImageFeature\"",
",",
"self",
".",
"value",
",",
"image_feature",
")",
"return",
"image_feature"
] | transform ImageFeature | [
"transform",
"ImageFeature"
] | python | test | 36.666667 |
tanghaibao/jcvi | jcvi/projects/misc.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/misc.py#L152-L211 | def birch(args):
"""
%prog birch seqids layout
Plot birch macro-synteny, with an embedded phylogenetic tree to the right.
"""
p = OptionParser(birch.__doc__)
opts, args, iopts = p.set_image_options(args, figsize="8x6")
if len(args) != 2:
sys.exit(not p.print_help())
seqids, la... | [
"def",
"birch",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"birch",
".",
"__doc__",
")",
"opts",
",",
"args",
",",
"iopts",
"=",
"p",
".",
"set_image_options",
"(",
"args",
",",
"figsize",
"=",
"\"8x6\"",
")",
"if",
"len",
"(",
"args",
"... | %prog birch seqids layout
Plot birch macro-synteny, with an embedded phylogenetic tree to the right. | [
"%prog",
"birch",
"seqids",
"layout"
] | python | train | 37 |
TUNE-Archive/freight_forwarder | freight_forwarder/container/host_config.py | https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/container/host_config.py#L418-L434 | def port_bindings(self, value):
"""
{
u'8080/tcp': [
{
u'host_port': u'8080',
u'host_ip': u''
}
]
}
"""
if isinstance(value, (list, dict)):
... | [
"def",
"port_bindings",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"dict",
")",
")",
":",
"self",
".",
"_port_bindings",
"=",
"self",
".",
"_convert_port_bindings",
"(",
"value",
")",
"elif",
"value",
... | {
u'8080/tcp': [
{
u'host_port': u'8080',
u'host_ip': u''
}
]
} | [
"{",
"u",
"8080",
"/",
"tcp",
":",
"[",
"{",
"u",
"host_port",
":",
"u",
"8080",
"u",
"host_ip",
":",
"u",
"}",
"]",
"}"
] | python | train | 32.764706 |
gitpython-developers/GitPython | git/remote.py | https://github.com/gitpython-developers/GitPython/blob/1f66e25c25cde2423917ee18c4704fff83b837d1/git/remote.py#L619-L626 | def remove(cls, repo, name):
"""Remove the remote with the given name
:return: the passed remote name to remove
"""
repo.git.remote("rm", name)
if isinstance(name, cls):
name._clear_cache()
return name | [
"def",
"remove",
"(",
"cls",
",",
"repo",
",",
"name",
")",
":",
"repo",
".",
"git",
".",
"remote",
"(",
"\"rm\"",
",",
"name",
")",
"if",
"isinstance",
"(",
"name",
",",
"cls",
")",
":",
"name",
".",
"_clear_cache",
"(",
")",
"return",
"name"
] | Remove the remote with the given name
:return: the passed remote name to remove | [
"Remove",
"the",
"remote",
"with",
"the",
"given",
"name",
":",
"return",
":",
"the",
"passed",
"remote",
"name",
"to",
"remove"
] | python | train | 31.75 |
minhhoit/yacms | yacms/core/templatetags/yacms_tags.py | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/templatetags/yacms_tags.py#L466-L474 | def richtext_filters(content):
"""
Takes a value edited via the WYSIWYG editor, and passes it through
each of the functions specified by the RICHTEXT_FILTERS setting.
"""
for filter_name in settings.RICHTEXT_FILTERS:
filter_func = import_dotted_path(filter_name)
content = filter_func... | [
"def",
"richtext_filters",
"(",
"content",
")",
":",
"for",
"filter_name",
"in",
"settings",
".",
"RICHTEXT_FILTERS",
":",
"filter_func",
"=",
"import_dotted_path",
"(",
"filter_name",
")",
"content",
"=",
"filter_func",
"(",
"content",
")",
"return",
"content"
] | Takes a value edited via the WYSIWYG editor, and passes it through
each of the functions specified by the RICHTEXT_FILTERS setting. | [
"Takes",
"a",
"value",
"edited",
"via",
"the",
"WYSIWYG",
"editor",
"and",
"passes",
"it",
"through",
"each",
"of",
"the",
"functions",
"specified",
"by",
"the",
"RICHTEXT_FILTERS",
"setting",
"."
] | python | train | 37.777778 |
alex-kostirin/pyatomac | atomac/ldtpd/combo_box.py | https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/combo_box.py#L241-L258 | def hidelist(self, window_name, object_name):
"""
Hide combo box list / menu
@param window_name: Window name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to type in, either full na... | [
"def",
"hidelist",
"(",
"self",
",",
"window_name",
",",
"object_name",
")",
":",
"object_handle",
"=",
"self",
".",
"_get_object_handle",
"(",
"window_name",
",",
"object_name",
")",
"object_handle",
".",
"activate",
"(",
")",
"object_handle",
".",
"sendKey",
... | Hide combo box list / menu
@param window_name: Window name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type... | [
"Hide",
"combo",
"box",
"list",
"/",
"menu",
"@param",
"window_name",
":",
"Window",
"name",
"to",
"type",
"in",
"either",
"full",
"name",
"LDTP",
"s",
"name",
"convention",
"or",
"a",
"Unix",
"glob",
".",
"@type",
"window_name",
":",
"string",
"@param",
... | python | valid | 35.444444 |
pikepdf/pikepdf | src/pikepdf/models/metadata.py | https://github.com/pikepdf/pikepdf/blob/07154f4dec007e2e9c0c6a8c07b964fd06bc5f77/src/pikepdf/models/metadata.py#L96-L124 | def encode_pdf_date(d: datetime) -> str:
"""Encode Python datetime object as PDF date string
From Adobe pdfmark manual:
(D:YYYYMMDDHHmmSSOHH'mm')
D: is an optional prefix. YYYY is the year. All fields after the year are
optional. MM is the month (01-12), DD is the day (01-31), HH is the
hour (0... | [
"def",
"encode_pdf_date",
"(",
"d",
":",
"datetime",
")",
"->",
"str",
":",
"# The formatting of %Y is not consistent as described in",
"# https://bugs.python.org/issue13305 and underspecification in libc.",
"# So explicitly format the year with leading zeros",
"s",
"=",
"\"{:04d}\"",
... | Encode Python datetime object as PDF date string
From Adobe pdfmark manual:
(D:YYYYMMDDHHmmSSOHH'mm')
D: is an optional prefix. YYYY is the year. All fields after the year are
optional. MM is the month (01-12), DD is the day (01-31), HH is the
hour (00-23), mm are the minutes (00-59), and SS are th... | [
"Encode",
"Python",
"datetime",
"object",
"as",
"PDF",
"date",
"string"
] | python | train | 46.37931 |
SheffieldML/GPy | GPy/util/warping_functions.py | https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/util/warping_functions.py#L108-L128 | def fgrad_y(self, y, return_precalc=False):
"""
gradient of f w.r.t to y ([N x 1])
:returns: Nx1 vector of derivatives, unless return_precalc is true,
then it also returns the precomputed stuff
"""
d = self.d
mpsi = self.psi
# vectorized version
... | [
"def",
"fgrad_y",
"(",
"self",
",",
"y",
",",
"return_precalc",
"=",
"False",
")",
":",
"d",
"=",
"self",
".",
"d",
"mpsi",
"=",
"self",
".",
"psi",
"# vectorized version",
"S",
"=",
"(",
"mpsi",
"[",
":",
",",
"1",
"]",
"*",
"(",
"y",
"[",
":"... | gradient of f w.r.t to y ([N x 1])
:returns: Nx1 vector of derivatives, unless return_precalc is true,
then it also returns the precomputed stuff | [
"gradient",
"of",
"f",
"w",
".",
"r",
".",
"t",
"to",
"y",
"(",
"[",
"N",
"x",
"1",
"]",
")"
] | python | train | 26.857143 |
ibis-project/ibis | ibis/expr/rules.py | https://github.com/ibis-project/ibis/blob/1e39a5fd9ef088b45c155e8a5f541767ee8ef2e7/ibis/expr/rules.py#L170-L178 | def instance_of(klass, arg):
"""Require that a value has a particular Python type."""
if not isinstance(arg, klass):
raise com.IbisTypeError(
'Given argument with type {} is not an instance of {}'.format(
type(arg), klass
)
)
return arg | [
"def",
"instance_of",
"(",
"klass",
",",
"arg",
")",
":",
"if",
"not",
"isinstance",
"(",
"arg",
",",
"klass",
")",
":",
"raise",
"com",
".",
"IbisTypeError",
"(",
"'Given argument with type {} is not an instance of {}'",
".",
"format",
"(",
"type",
"(",
"arg"... | Require that a value has a particular Python type. | [
"Require",
"that",
"a",
"value",
"has",
"a",
"particular",
"Python",
"type",
"."
] | python | train | 32.888889 |
spyder-ide/spyder | spyder/plugins/editor/widgets/editor.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/editor.py#L1191-L1201 | def get_tab_tip(self, filename, is_modified=None, is_readonly=None):
"""Return tab menu title"""
text = u"%s — %s"
text = self.__modified_readonly_title(text,
is_modified, is_readonly)
if self.tempfile_path is not None\
and f... | [
"def",
"get_tab_tip",
"(",
"self",
",",
"filename",
",",
"is_modified",
"=",
"None",
",",
"is_readonly",
"=",
"None",
")",
":",
"text",
"=",
"u\"%s — %s\"\r",
"text",
"=",
"self",
".",
"__modified_readonly_title",
"(",
"text",
",",
"is_modified",
",",
"is_re... | Return tab menu title | [
"Return",
"tab",
"menu",
"title"
] | python | train | 53.363636 |
luckydonald/pytgbot | pytgbot/api_types/receivable/updates.py | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/updates.py#L1295-L1311 | def from_array(array):
"""
Deserialize a new ResponseParameters from a given dictionary.
:return: new ResponseParameters instance.
:rtype: ResponseParameters
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, d... | [
"def",
"from_array",
"(",
"array",
")",
":",
"if",
"array",
"is",
"None",
"or",
"not",
"array",
":",
"return",
"None",
"# end if",
"assert_type_or_raise",
"(",
"array",
",",
"dict",
",",
"parameter_name",
"=",
"\"array\"",
")",
"data",
"=",
"{",
"}",
"da... | Deserialize a new ResponseParameters from a given dictionary.
:return: new ResponseParameters instance.
:rtype: ResponseParameters | [
"Deserialize",
"a",
"new",
"ResponseParameters",
"from",
"a",
"given",
"dictionary",
"."
] | python | train | 39 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.