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 |
|---|---|---|---|---|---|---|---|---|---|
pedrotgn/pyactor | pyactor/thread/future.py | https://github.com/pedrotgn/pyactor/blob/24d98d134dd4228f2ba38e83611e9c3f50ec2fd4/pyactor/thread/future.py#L60-L88 | def add_callback(self, method):
"""
Attaches a mehtod that will be called when the future finishes.
:param method: A callable from an actor that will be called
when the future completes. The only argument for that
method must be the future itself from wich you can get th... | [
"def",
"add_callback",
"(",
"self",
",",
"method",
")",
":",
"from_actor",
"=",
"get_current",
"(",
")",
"if",
"from_actor",
"is",
"not",
"None",
":",
"callback",
"=",
"(",
"method",
",",
"from_actor",
".",
"channel",
",",
"from_actor",
".",
"url",
")",
... | Attaches a mehtod that will be called when the future finishes.
:param method: A callable from an actor that will be called
when the future completes. The only argument for that
method must be the future itself from wich you can get the
result though `future.:meth:`result()`... | [
"Attaches",
"a",
"mehtod",
"that",
"will",
"be",
"called",
"when",
"the",
"future",
"finishes",
"."
] | python | train | 44.793103 |
tensorflow/tensor2tensor | tensor2tensor/utils/data_reader.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/data_reader.py#L269-L278 | def _file_num_records_cached(filename):
"""Return the number of TFRecords in a file."""
# Cache the result, as this is expensive to compute
if filename in _file_num_records_cache:
return _file_num_records_cache[filename]
ret = 0
for _ in tf.python_io.tf_record_iterator(filename):
ret += 1
_file_num_... | [
"def",
"_file_num_records_cached",
"(",
"filename",
")",
":",
"# Cache the result, as this is expensive to compute",
"if",
"filename",
"in",
"_file_num_records_cache",
":",
"return",
"_file_num_records_cache",
"[",
"filename",
"]",
"ret",
"=",
"0",
"for",
"_",
"in",
"tf... | Return the number of TFRecords in a file. | [
"Return",
"the",
"number",
"of",
"TFRecords",
"in",
"a",
"file",
"."
] | python | train | 35.3 |
ktbyers/netmiko | netmiko/_textfsm/_clitable.py | https://github.com/ktbyers/netmiko/blob/54e6116c0b4664de2123081937e0a9a27bdfdfea/netmiko/_textfsm/_clitable.py#L301-L306 | def _PreParse(self, key, value):
"""Executed against each field of each row read from index table."""
if key == "Command":
return re.sub(r"(\[\[.+?\]\])", self._Completion, value)
else:
return value | [
"def",
"_PreParse",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"key",
"==",
"\"Command\"",
":",
"return",
"re",
".",
"sub",
"(",
"r\"(\\[\\[.+?\\]\\])\"",
",",
"self",
".",
"_Completion",
",",
"value",
")",
"else",
":",
"return",
"value"
] | Executed against each field of each row read from index table. | [
"Executed",
"against",
"each",
"field",
"of",
"each",
"row",
"read",
"from",
"index",
"table",
"."
] | python | train | 40.166667 |
noahbenson/neuropythy | neuropythy/util/core.py | https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/util/core.py#L774-L782 | def power(a,b):
'''
power(a,b) is equivalent to a**b except that, like the neuropythy.util.times function, it
threads over the earliest dimension possible rather than the latest, as numpy's power function
and ** syntax do. The power() function also works with sparse arrays; though it must reify
... | [
"def",
"power",
"(",
"a",
",",
"b",
")",
":",
"(",
"a",
",",
"b",
")",
"=",
"unbroadcast",
"(",
"a",
",",
"b",
")",
"return",
"cpower",
"(",
"a",
",",
"b",
")"
] | power(a,b) is equivalent to a**b except that, like the neuropythy.util.times function, it
threads over the earliest dimension possible rather than the latest, as numpy's power function
and ** syntax do. The power() function also works with sparse arrays; though it must reify
them during the process. | [
"power",
"(",
"a",
"b",
")",
"is",
"equivalent",
"to",
"a",
"**",
"b",
"except",
"that",
"like",
"the",
"neuropythy",
".",
"util",
".",
"times",
"function",
"it",
"threads",
"over",
"the",
"earliest",
"dimension",
"possible",
"rather",
"than",
"the",
"la... | python | train | 44.222222 |
globocom/GloboNetworkAPI-client-python | networkapiclient/ApiEquipment.py | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/ApiEquipment.py#L99-L108 | def create(self, equipments):
"""
Method to create equipments
:param equipments: List containing equipments desired to be created on database
:return: None
"""
data = {'equipments': equipments}
return super(ApiEquipment, self).post('api/v3/equipment/', data) | [
"def",
"create",
"(",
"self",
",",
"equipments",
")",
":",
"data",
"=",
"{",
"'equipments'",
":",
"equipments",
"}",
"return",
"super",
"(",
"ApiEquipment",
",",
"self",
")",
".",
"post",
"(",
"'api/v3/equipment/'",
",",
"data",
")"
] | Method to create equipments
:param equipments: List containing equipments desired to be created on database
:return: None | [
"Method",
"to",
"create",
"equipments"
] | python | train | 30.7 |
aws/sagemaker-python-sdk | src/sagemaker/session.py | https://github.com/aws/sagemaker-python-sdk/blob/a9e724c7d3f5572b68c3903548c792a59d99799a/src/sagemaker/session.py#L497-L541 | def transform(self, job_name, model_name, strategy, max_concurrent_transforms, max_payload, env,
input_config, output_config, resource_config, tags):
"""Create an Amazon SageMaker transform job.
Args:
job_name (str): Name of the transform job being created.
mod... | [
"def",
"transform",
"(",
"self",
",",
"job_name",
",",
"model_name",
",",
"strategy",
",",
"max_concurrent_transforms",
",",
"max_payload",
",",
"env",
",",
"input_config",
",",
"output_config",
",",
"resource_config",
",",
"tags",
")",
":",
"transform_request",
... | Create an Amazon SageMaker transform job.
Args:
job_name (str): Name of the transform job being created.
model_name (str): Name of the SageMaker model being used for the transform job.
strategy (str): The strategy used to decide how to batch records in a single request.
... | [
"Create",
"an",
"Amazon",
"SageMaker",
"transform",
"job",
"."
] | python | train | 51.844444 |
deschler/django-modeltranslation | modeltranslation/manager.py | https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/manager.py#L500-L510 | def get_queryset(self):
"""
This method is repeated because some managers that don't use super() or alter queryset class
may return queryset that is not subclass of MultilingualQuerySet.
"""
qs = super(MultilingualManager, self).get_queryset()
if isinstance(qs, Multilingu... | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"qs",
"=",
"super",
"(",
"MultilingualManager",
",",
"self",
")",
".",
"get_queryset",
"(",
")",
"if",
"isinstance",
"(",
"qs",
",",
"MultilingualQuerySet",
")",
":",
"# Is already patched by MultilingualQuerysetManage... | This method is repeated because some managers that don't use super() or alter queryset class
may return queryset that is not subclass of MultilingualQuerySet. | [
"This",
"method",
"is",
"repeated",
"because",
"some",
"managers",
"that",
"don",
"t",
"use",
"super",
"()",
"or",
"alter",
"queryset",
"class",
"may",
"return",
"queryset",
"that",
"is",
"not",
"subclass",
"of",
"MultilingualQuerySet",
"."
] | python | train | 49.454545 |
benhoff/microphone | examples/record_audio.py | https://github.com/benhoff/microphone/blob/a89e339a9a4a17d19fd1a8cb99efee3402b65673/examples/record_audio.py#L15-L27 | def _create_file():
"""
Returns a file handle which is used to record audio
"""
f = wave.open('audio.wav', mode='wb')
f.setnchannels(2)
p = pyaudio.PyAudio()
f.setsampwidth(p.get_sample_size(pyaudio.paInt16))
f.setframerate(p.get_default_input_device_info()['defaultSampleRate'])
try:... | [
"def",
"_create_file",
"(",
")",
":",
"f",
"=",
"wave",
".",
"open",
"(",
"'audio.wav'",
",",
"mode",
"=",
"'wb'",
")",
"f",
".",
"setnchannels",
"(",
"2",
")",
"p",
"=",
"pyaudio",
".",
"PyAudio",
"(",
")",
"f",
".",
"setsampwidth",
"(",
"p",
".... | Returns a file handle which is used to record audio | [
"Returns",
"a",
"file",
"handle",
"which",
"is",
"used",
"to",
"record",
"audio"
] | python | test | 27.307692 |
mohamedattahri/PyXMLi | pyxmli/__init__.py | https://github.com/mohamedattahri/PyXMLi/blob/a81a245be822d62f1a20c734ca14b42c786ae81e/pyxmli/__init__.py#L734-L741 | def compute_payments(self, precision=None):
'''
Returns the total amount of payments made to this invoice.
@param precision:int Number of decimal places
@return: Decimal
'''
return quantize(sum([payment.amount for payment in self.__payments]),
prec... | [
"def",
"compute_payments",
"(",
"self",
",",
"precision",
"=",
"None",
")",
":",
"return",
"quantize",
"(",
"sum",
"(",
"[",
"payment",
".",
"amount",
"for",
"payment",
"in",
"self",
".",
"__payments",
"]",
")",
",",
"precision",
")"
] | Returns the total amount of payments made to this invoice.
@param precision:int Number of decimal places
@return: Decimal | [
"Returns",
"the",
"total",
"amount",
"of",
"payments",
"made",
"to",
"this",
"invoice",
"."
] | python | train | 39.875 |
kristianfoerster/melodist | melodist/data_io.py | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/data_io.py#L236-L320 | def write_smet(filename, data, metadata, nodata_value=-999, mode='h', check_nan=True):
"""writes smet files
Parameters
----
filename : filename/loction of output
data : data to write as pandas df
metadata: header to write input as dict
nodata_value: Nodata Value to write/use
... | [
"def",
"write_smet",
"(",
"filename",
",",
"data",
",",
"metadata",
",",
"nodata_value",
"=",
"-",
"999",
",",
"mode",
"=",
"'h'",
",",
"check_nan",
"=",
"True",
")",
":",
"# dictionary",
"# based on smet spec V.1.1 and selfdefined",
"# daily data",
"dict_d",
"=... | writes smet files
Parameters
----
filename : filename/loction of output
data : data to write as pandas df
metadata: header to write input as dict
nodata_value: Nodata Value to write/use
mode: defines if to write daily ("d") or continuos data (default 'h')
check_nan... | [
"writes",
"smet",
"files"
] | python | train | 28.352941 |
jbarlow83/OCRmyPDF | src/ocrmypdf/leptonica.py | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/leptonica.py#L402-L412 | def remove_colormap(self, removal_type):
"""Remove a palette (colormap); if no colormap, returns a copy of this
image
removal_type - any of lept.REMOVE_CMAP_*
"""
with _LeptonicaErrorTrap():
return Pix(
lept.pixRemoveColormapGeneral(self._cdata, ... | [
"def",
"remove_colormap",
"(",
"self",
",",
"removal_type",
")",
":",
"with",
"_LeptonicaErrorTrap",
"(",
")",
":",
"return",
"Pix",
"(",
"lept",
".",
"pixRemoveColormapGeneral",
"(",
"self",
".",
"_cdata",
",",
"removal_type",
",",
"lept",
".",
"L_COPY",
")... | Remove a palette (colormap); if no colormap, returns a copy of this
image
removal_type - any of lept.REMOVE_CMAP_* | [
"Remove",
"a",
"palette",
"(",
"colormap",
")",
";",
"if",
"no",
"colormap",
"returns",
"a",
"copy",
"of",
"this",
"image"
] | python | train | 31.818182 |
mitsei/dlkit | dlkit/aws_adapter/repository/aws_utils.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/aws_adapter/repository/aws_utils.py#L12-L31 | def get_aws_s3_handle(config_map):
"""Convenience function for getting AWS S3 objects
Added by cjshaw@mit.edu, Jan 9, 2015
Added to aws_adapter build by birdland@mit.edu, Jan 25, 2015, and
added support for Configuration
May 25, 2017: Switch to boto3
"""
url = 'https://' + config_map['s3_b... | [
"def",
"get_aws_s3_handle",
"(",
"config_map",
")",
":",
"url",
"=",
"'https://'",
"+",
"config_map",
"[",
"'s3_bucket'",
"]",
"+",
"'.s3.amazonaws.com'",
"if",
"not",
"AWS_CLIENT",
".",
"is_aws_s3_client_set",
"(",
")",
":",
"client",
"=",
"boto3",
".",
"clie... | Convenience function for getting AWS S3 objects
Added by cjshaw@mit.edu, Jan 9, 2015
Added to aws_adapter build by birdland@mit.edu, Jan 25, 2015, and
added support for Configuration
May 25, 2017: Switch to boto3 | [
"Convenience",
"function",
"for",
"getting",
"AWS",
"S3",
"objects"
] | python | train | 33.4 |
sdispater/orator | orator/query/processors/postgres_processor.py | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/query/processors/postgres_processor.py#L7-L36 | def process_insert_get_id(self, query, sql, values, sequence=None):
"""
Process an "insert get ID" query.
:param query: A QueryBuilder instance
:type query: QueryBuilder
:param sql: The sql query to execute
:type sql: str
:param values: The value bindings
... | [
"def",
"process_insert_get_id",
"(",
"self",
",",
"query",
",",
"sql",
",",
"values",
",",
"sequence",
"=",
"None",
")",
":",
"result",
"=",
"query",
".",
"get_connection",
"(",
")",
".",
"select_from_write_connection",
"(",
"sql",
",",
"values",
")",
"id"... | Process an "insert get ID" query.
:param query: A QueryBuilder instance
:type query: QueryBuilder
:param sql: The sql query to execute
:type sql: str
:param values: The value bindings
:type values: list
:param sequence: The ids sequence
:type sequence:... | [
"Process",
"an",
"insert",
"get",
"ID",
"query",
"."
] | python | train | 23.133333 |
Shoobx/xmldiff | xmldiff/_diff_match_patch_py3.py | https://github.com/Shoobx/xmldiff/blob/ec7835bce9ba69ff4ce03ab6c11397183b6f8411/xmldiff/_diff_match_patch_py3.py#L1059-L1078 | def diff_prettyHtml(self, diffs):
"""Convert a diff array into a pretty HTML report.
Args:
diffs: Array of diff tuples.
Returns:
HTML representation.
"""
html = []
for (op, data) in diffs:
text = (data.replace("&", "&").replace("<", "<")
.replace(">", ... | [
"def",
"diff_prettyHtml",
"(",
"self",
",",
"diffs",
")",
":",
"html",
"=",
"[",
"]",
"for",
"(",
"op",
",",
"data",
")",
"in",
"diffs",
":",
"text",
"=",
"(",
"data",
".",
"replace",
"(",
"\"&\"",
",",
"\"&\"",
")",
".",
"replace",
"(",
"\"<... | Convert a diff array into a pretty HTML report.
Args:
diffs: Array of diff tuples.
Returns:
HTML representation. | [
"Convert",
"a",
"diff",
"array",
"into",
"a",
"pretty",
"HTML",
"report",
"."
] | python | train | 32.9 |
arthurk/django-disqus | disqus/templatetags/disqus_tags.py | https://github.com/arthurk/django-disqus/blob/0db52c240906c6663189c0a7aca9979a0db004d1/disqus/templatetags/disqus_tags.py#L45-L62 | def get_config(context):
"""
Return the formatted javascript for any disqus config variables.
"""
conf_vars = ['disqus_developer',
'disqus_identifier',
'disqus_url',
'disqus_title',
'disqus_category_id'
]
js = '\t... | [
"def",
"get_config",
"(",
"context",
")",
":",
"conf_vars",
"=",
"[",
"'disqus_developer'",
",",
"'disqus_identifier'",
",",
"'disqus_url'",
",",
"'disqus_title'",
",",
"'disqus_category_id'",
"]",
"js",
"=",
"'\\tvar {} = \"{}\";'",
"output",
"=",
"[",
"js",
".",... | Return the formatted javascript for any disqus config variables. | [
"Return",
"the",
"formatted",
"javascript",
"for",
"any",
"disqus",
"config",
"variables",
"."
] | python | train | 25.111111 |
bskinn/opan | opan/utils/symm.py | https://github.com/bskinn/opan/blob/0b1b21662df6abc971407a9386db21a8796fbfe5/opan/utils/symm.py#L91-L118 | def point_rotate(pt, ax, theta):
""" Rotate a 3-D point around a 3-D axis through the origin.
Handedness is a counter-clockwise rotation when viewing the rotation
axis as pointing at the observer. Thus, in a right-handed x-y-z frame,
a 90deg rotation of (1,0,0) around the z-axis (0,0,1) yields a point... | [
"def",
"point_rotate",
"(",
"pt",
",",
"ax",
",",
"theta",
")",
":",
"# Imports",
"import",
"numpy",
"as",
"np",
"# Ensure pt is reducible to 3-D vector.",
"pt",
"=",
"make_nd_vec",
"(",
"pt",
",",
"nd",
"=",
"3",
",",
"t",
"=",
"np",
".",
"float64",
","... | Rotate a 3-D point around a 3-D axis through the origin.
Handedness is a counter-clockwise rotation when viewing the rotation
axis as pointing at the observer. Thus, in a right-handed x-y-z frame,
a 90deg rotation of (1,0,0) around the z-axis (0,0,1) yields a point at
(0,1,0).
.. todo:: Complete ... | [
"Rotate",
"a",
"3",
"-",
"D",
"point",
"around",
"a",
"3",
"-",
"D",
"axis",
"through",
"the",
"origin",
"."
] | python | train | 28.75 |
fredrike/pypoint | pypoint/__init__.py | https://github.com/fredrike/pypoint/blob/b5c9a701d2b7e24d796aa7f8c410360b61d8ec8a/pypoint/__init__.py#L106-L109 | def _request_devices(self, url, _type):
"""Request list of devices."""
res = self._request(url)
return res.get(_type) if res else {} | [
"def",
"_request_devices",
"(",
"self",
",",
"url",
",",
"_type",
")",
":",
"res",
"=",
"self",
".",
"_request",
"(",
"url",
")",
"return",
"res",
".",
"get",
"(",
"_type",
")",
"if",
"res",
"else",
"{",
"}"
] | Request list of devices. | [
"Request",
"list",
"of",
"devices",
"."
] | python | train | 38.25 |
materialsproject/pymatgen | pymatgen/io/abinit/flows.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/flows.py#L2039-L2060 | def set_spectator_mode(self, mode=True):
"""
When the flow is in spectator_mode, we have to disable signals, pickle dump and possible callbacks
A spectator can still operate on the flow but the new status of the flow won't be saved in
the pickle file. Usually the flow is in spectator mod... | [
"def",
"set_spectator_mode",
"(",
"self",
",",
"mode",
"=",
"True",
")",
":",
"# Set the flags of all the nodes in the flow.",
"mode",
"=",
"bool",
"(",
"mode",
")",
"self",
".",
"in_spectator_mode",
"=",
"mode",
"for",
"node",
"in",
"self",
".",
"iflat_nodes",
... | When the flow is in spectator_mode, we have to disable signals, pickle dump and possible callbacks
A spectator can still operate on the flow but the new status of the flow won't be saved in
the pickle file. Usually the flow is in spectator mode when we are already running it via
the scheduler or... | [
"When",
"the",
"flow",
"is",
"in",
"spectator_mode",
"we",
"have",
"to",
"disable",
"signals",
"pickle",
"dump",
"and",
"possible",
"callbacks",
"A",
"spectator",
"can",
"still",
"operate",
"on",
"the",
"flow",
"but",
"the",
"new",
"status",
"of",
"the",
"... | python | train | 51.636364 |
eventbrite/rebar | src/rebar/group.py | https://github.com/eventbrite/rebar/blob/32f8914a2c5529519009d21c85f0d47cc6601901/src/rebar/group.py#L208-L232 | def save(self):
"""Save the changes to the instance and any related objects."""
# first call save with commit=False for all Forms
for form in self._forms:
if isinstance(form, BaseForm):
form.save(commit=False)
# call save on the instance
self.instanc... | [
"def",
"save",
"(",
"self",
")",
":",
"# first call save with commit=False for all Forms",
"for",
"form",
"in",
"self",
".",
"_forms",
":",
"if",
"isinstance",
"(",
"form",
",",
"BaseForm",
")",
":",
"form",
".",
"save",
"(",
"commit",
"=",
"False",
")",
"... | Save the changes to the instance and any related objects. | [
"Save",
"the",
"changes",
"to",
"the",
"instance",
"and",
"any",
"related",
"objects",
"."
] | python | train | 32.24 |
astrocatalogs/astrocats | astrocats/catalog/spectrum.py | https://github.com/astrocatalogs/astrocats/blob/11abc3131c6366ecd23964369e55ff264add7805/astrocats/catalog/spectrum.py#L160-L168 | def sort_func(self, key):
"""Logic for sorting keys in a `Spectrum` relative to one another."""
if key == self._KEYS.TIME:
return 'aaa'
if key == self._KEYS.DATA:
return 'zzy'
if key == self._KEYS.SOURCE:
return 'zzz'
return key | [
"def",
"sort_func",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"==",
"self",
".",
"_KEYS",
".",
"TIME",
":",
"return",
"'aaa'",
"if",
"key",
"==",
"self",
".",
"_KEYS",
".",
"DATA",
":",
"return",
"'zzy'",
"if",
"key",
"==",
"self",
".",
"_K... | Logic for sorting keys in a `Spectrum` relative to one another. | [
"Logic",
"for",
"sorting",
"keys",
"in",
"a",
"Spectrum",
"relative",
"to",
"one",
"another",
"."
] | python | train | 32.888889 |
pandas-dev/pandas | pandas/core/ops.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/ops.py#L1123-L1155 | def mask_cmp_op(x, y, op, allowed_types):
"""
Apply the function `op` to only non-null points in x and y.
Parameters
----------
x : array-like
y : array-like
op : binary operation
allowed_types : class or tuple of classes
Returns
-------
result : ndarray[bool]
"""
#... | [
"def",
"mask_cmp_op",
"(",
"x",
",",
"y",
",",
"op",
",",
"allowed_types",
")",
":",
"# TODO: Can we make the allowed_types arg unnecessary?",
"xrav",
"=",
"x",
".",
"ravel",
"(",
")",
"result",
"=",
"np",
".",
"empty",
"(",
"x",
".",
"size",
",",
"dtype",... | Apply the function `op` to only non-null points in x and y.
Parameters
----------
x : array-like
y : array-like
op : binary operation
allowed_types : class or tuple of classes
Returns
-------
result : ndarray[bool] | [
"Apply",
"the",
"function",
"op",
"to",
"only",
"non",
"-",
"null",
"points",
"in",
"x",
"and",
"y",
"."
] | python | train | 27.333333 |
inasafe/inasafe | safe/report/expressions/map_report.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/map_report.py#L563-L575 | def north_arrow_path(feature, parent):
"""Retrieve the full path of default north arrow logo."""
_ = feature, parent # NOQA
north_arrow_file = setting(inasafe_north_arrow_path['setting_key'])
if os.path.exists(north_arrow_file):
return north_arrow_file
else:
LOGGER.info(
... | [
"def",
"north_arrow_path",
"(",
"feature",
",",
"parent",
")",
":",
"_",
"=",
"feature",
",",
"parent",
"# NOQA",
"north_arrow_file",
"=",
"setting",
"(",
"inasafe_north_arrow_path",
"[",
"'setting_key'",
"]",
")",
"if",
"os",
".",
"path",
".",
"exists",
"("... | Retrieve the full path of default north arrow logo. | [
"Retrieve",
"the",
"full",
"path",
"of",
"default",
"north",
"arrow",
"logo",
"."
] | python | train | 41.153846 |
pandas-dev/pandas | pandas/core/frame.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/frame.py#L3189-L3324 | def select_dtypes(self, include=None, exclude=None):
"""
Return a subset of the DataFrame's columns based on the column dtypes.
Parameters
----------
include, exclude : scalar or list-like
A selection of dtypes or strings to be included/excluded. At least
... | [
"def",
"select_dtypes",
"(",
"self",
",",
"include",
"=",
"None",
",",
"exclude",
"=",
"None",
")",
":",
"def",
"_get_info_slice",
"(",
"obj",
",",
"indexer",
")",
":",
"\"\"\"Slice the info axis of `obj` with `indexer`.\"\"\"",
"if",
"not",
"hasattr",
"(",
"obj... | Return a subset of the DataFrame's columns based on the column dtypes.
Parameters
----------
include, exclude : scalar or list-like
A selection of dtypes or strings to be included/excluded. At least
one of these parameters must be supplied.
Returns
-----... | [
"Return",
"a",
"subset",
"of",
"the",
"DataFrame",
"s",
"columns",
"based",
"on",
"the",
"column",
"dtypes",
"."
] | python | train | 36.632353 |
russ-/pychallonge | challonge/api.py | https://github.com/russ-/pychallonge/blob/bc202d7140cb08d11d345564f721c2f57129b84f/challonge/api.py#L83-L108 | def _parse(root):
"""Recursively convert an Element into python data types"""
if root.tag == "nil-classes":
return []
elif root.get("type") == "array":
return [_parse(child) for child in root]
d = {}
for child in root:
type = child.get("type") or "string"
if child.g... | [
"def",
"_parse",
"(",
"root",
")",
":",
"if",
"root",
".",
"tag",
"==",
"\"nil-classes\"",
":",
"return",
"[",
"]",
"elif",
"root",
".",
"get",
"(",
"\"type\"",
")",
"==",
"\"array\"",
":",
"return",
"[",
"_parse",
"(",
"child",
")",
"for",
"child",
... | Recursively convert an Element into python data types | [
"Recursively",
"convert",
"an",
"Element",
"into",
"python",
"data",
"types"
] | python | train | 28.846154 |
bertrandvidal/parse_this | parse_this/__init__.py | https://github.com/bertrandvidal/parse_this/blob/aa2e3737f19642300ef1ca65cae21c90049718a2/parse_this/__init__.py#L189-L225 | def _get_parser_call_method(self, parser_to_method):
"""Return the parser special method 'call' that handles sub-command
calling.
Args:
parser_to_method: mapping of the parser registered name
to the method it is linked to
"""
def inner_call(args=None,... | [
"def",
"_get_parser_call_method",
"(",
"self",
",",
"parser_to_method",
")",
":",
"def",
"inner_call",
"(",
"args",
"=",
"None",
",",
"instance",
"=",
"None",
")",
":",
"\"\"\"Allows to call the method invoked from the command line or\n provided argument.\n\n ... | Return the parser special method 'call' that handles sub-command
calling.
Args:
parser_to_method: mapping of the parser registered name
to the method it is linked to | [
"Return",
"the",
"parser",
"special",
"method",
"call",
"that",
"handles",
"sub",
"-",
"command",
"calling",
"."
] | python | train | 52.027027 |
williballenthin/python-evtx | scripts/evtx_record_structure.py | https://github.com/williballenthin/python-evtx/blob/4e9e29544adde64c79ff9b743269ecb18c677eb4/scripts/evtx_record_structure.py#L11-L80 | def describe_root(record, root, indent=0, suppress_values=False):
"""
Args:
record (Evtx.Record):
indent (int):
"""
def format_node(n, extra=None, indent=0):
"""
Depends on closure over `record` and `suppress_values`.
Args:
n (Evtx.Nodes.BXmlNode):
... | [
"def",
"describe_root",
"(",
"record",
",",
"root",
",",
"indent",
"=",
"0",
",",
"suppress_values",
"=",
"False",
")",
":",
"def",
"format_node",
"(",
"n",
",",
"extra",
"=",
"None",
",",
"indent",
"=",
"0",
")",
":",
"\"\"\"\n Depends on closure o... | Args:
record (Evtx.Record):
indent (int): | [
"Args",
":",
"record",
"(",
"Evtx",
".",
"Record",
")",
":",
"indent",
"(",
"int",
")",
":"
] | python | train | 30.842857 |
agoragames/leaderboard-python | leaderboard/leaderboard.py | https://github.com/agoragames/leaderboard-python/blob/ec309859b197a751ac0322374b36d134d8c5522f/leaderboard/leaderboard.py#L355-L365 | def remove_member_from(self, leaderboard_name, member):
'''
Remove the optional member data for a given member in the named leaderboard.
@param leaderboard_name [String] Name of the leaderboard.
@param member [String] Member name.
'''
pipeline = self.redis_connection.pip... | [
"def",
"remove_member_from",
"(",
"self",
",",
"leaderboard_name",
",",
"member",
")",
":",
"pipeline",
"=",
"self",
".",
"redis_connection",
".",
"pipeline",
"(",
")",
"pipeline",
".",
"zrem",
"(",
"leaderboard_name",
",",
"member",
")",
"pipeline",
".",
"h... | Remove the optional member data for a given member in the named leaderboard.
@param leaderboard_name [String] Name of the leaderboard.
@param member [String] Member name. | [
"Remove",
"the",
"optional",
"member",
"data",
"for",
"a",
"given",
"member",
"in",
"the",
"named",
"leaderboard",
"."
] | python | train | 42.090909 |
NarrativeScience/lsi | src/lsi/utils/hosts.py | https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/utils/hosts.py#L462-L472 | def get_region():
"""Use the environment to get the current region"""
global _REGION
if _REGION is None:
region_name = os.getenv("AWS_DEFAULT_REGION") or "us-east-1"
region_dict = {r.name: r for r in boto.regioninfo.get_regions("ec2")}
if region_name not in region_dict:
r... | [
"def",
"get_region",
"(",
")",
":",
"global",
"_REGION",
"if",
"_REGION",
"is",
"None",
":",
"region_name",
"=",
"os",
".",
"getenv",
"(",
"\"AWS_DEFAULT_REGION\"",
")",
"or",
"\"us-east-1\"",
"region_dict",
"=",
"{",
"r",
".",
"name",
":",
"r",
"for",
"... | Use the environment to get the current region | [
"Use",
"the",
"environment",
"to",
"get",
"the",
"current",
"region"
] | python | test | 46.545455 |
475Cumulus/TBone | tbone/resources/resources.py | https://github.com/475Cumulus/TBone/blob/5a6672d8bbac449a0ab9e99560609f671fe84d4d/tbone/resources/resources.py#L406-L413 | def parse(self, method, endpoint, body):
''' calls parse on list or detail '''
if isinstance(body, dict): # request body was already parsed
return body
if endpoint == 'list':
return self.parse_list(body)
return self.parse_detail(body) | [
"def",
"parse",
"(",
"self",
",",
"method",
",",
"endpoint",
",",
"body",
")",
":",
"if",
"isinstance",
"(",
"body",
",",
"dict",
")",
":",
"# request body was already parsed",
"return",
"body",
"if",
"endpoint",
"==",
"'list'",
":",
"return",
"self",
".",... | calls parse on list or detail | [
"calls",
"parse",
"on",
"list",
"or",
"detail"
] | python | train | 35.625 |
singularitti/text-stream | text_stream/__init__.py | https://github.com/singularitti/text-stream/blob/4df53b98e9f61d983dbd46edd96db93122577eb5/text_stream/__init__.py#L75-L83 | def infile_path(self) -> Optional[PurePath]:
"""
Read-only property.
:return: A ``pathlib.PurePath`` object or ``None``.
"""
if not self.__infile_path:
return Path(self.__infile_path).expanduser()
return None | [
"def",
"infile_path",
"(",
"self",
")",
"->",
"Optional",
"[",
"PurePath",
"]",
":",
"if",
"not",
"self",
".",
"__infile_path",
":",
"return",
"Path",
"(",
"self",
".",
"__infile_path",
")",
".",
"expanduser",
"(",
")",
"return",
"None"
] | Read-only property.
:return: A ``pathlib.PurePath`` object or ``None``. | [
"Read",
"-",
"only",
"property",
"."
] | python | train | 29 |
CyberReboot/vent | vent/menus/del_instances.py | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/menus/del_instances.py#L20-L24 | def when_value_edited(self, *args, **kargs):
""" Overrided to prevent user from selecting too many instances """
if len(self.value) > self.instance_num:
self.value.pop(-2)
self.display() | [
"def",
"when_value_edited",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kargs",
")",
":",
"if",
"len",
"(",
"self",
".",
"value",
")",
">",
"self",
".",
"instance_num",
":",
"self",
".",
"value",
".",
"pop",
"(",
"-",
"2",
")",
"self",
".",
... | Overrided to prevent user from selecting too many instances | [
"Overrided",
"to",
"prevent",
"user",
"from",
"selecting",
"too",
"many",
"instances"
] | python | train | 44.4 |
selectel/pyte | pyte/screens.py | https://github.com/selectel/pyte/blob/8adad489f86da1788a7995720c344a2fa44f244e/pyte/screens.py#L582-L589 | def linefeed(self):
"""Perform an index and, if :data:`~pyte.modes.LNM` is set, a
carriage return.
"""
self.index()
if mo.LNM in self.mode:
self.carriage_return() | [
"def",
"linefeed",
"(",
"self",
")",
":",
"self",
".",
"index",
"(",
")",
"if",
"mo",
".",
"LNM",
"in",
"self",
".",
"mode",
":",
"self",
".",
"carriage_return",
"(",
")"
] | Perform an index and, if :data:`~pyte.modes.LNM` is set, a
carriage return. | [
"Perform",
"an",
"index",
"and",
"if",
":",
"data",
":",
"~pyte",
".",
"modes",
".",
"LNM",
"is",
"set",
"a",
"carriage",
"return",
"."
] | python | train | 26 |
juga0/dhcpcanon | dhcpcanon/dhcpcapfsm.py | https://github.com/juga0/dhcpcanon/blob/9f51a29e57fe93dc93fb22bb0ed12fcfe9557e59/dhcpcanon/dhcpcapfsm.py#L590-L596 | def receive_nak_requesting(self, pkt):
"""Receive NAK in REQUESTING state."""
logger.debug("C3.1. Received NAK?, in REQUESTING state.")
if self.process_received_nak(pkt):
logger.debug("C3.1: T. Received NAK, in REQUESTING state, "
"raise INIT.")
r... | [
"def",
"receive_nak_requesting",
"(",
"self",
",",
"pkt",
")",
":",
"logger",
".",
"debug",
"(",
"\"C3.1. Received NAK?, in REQUESTING state.\"",
")",
"if",
"self",
".",
"process_received_nak",
"(",
"pkt",
")",
":",
"logger",
".",
"debug",
"(",
"\"C3.1: T. Receive... | Receive NAK in REQUESTING state. | [
"Receive",
"NAK",
"in",
"REQUESTING",
"state",
"."
] | python | test | 47.142857 |
saltstack/salt | salt/runners/cache.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/cache.py#L218-L236 | def clear_all(tgt=None, tgt_type='glob'):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Clear the cached pillar, grains, and mine data of the targeted minions
CLI Example:
.. code-block:: bash... | [
"def",
"clear_all",
"(",
"tgt",
"=",
"None",
",",
"tgt_type",
"=",
"'glob'",
")",
":",
"return",
"_clear_cache",
"(",
"tgt",
",",
"tgt_type",
",",
"clear_pillar_flag",
"=",
"True",
",",
"clear_grains_flag",
"=",
"True",
",",
"clear_mine_flag",
"=",
"True",
... | .. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Clear the cached pillar, grains, and mine data of the targeted minions
CLI Example:
.. code-block:: bash
salt-run cache.clear_all | [
"..",
"versionchanged",
"::",
"2017",
".",
"7",
".",
"0",
"The",
"expr_form",
"argument",
"has",
"been",
"renamed",
"to",
"tgt_type",
"earlier",
"releases",
"must",
"use",
"expr_form",
"."
] | python | train | 28.894737 |
gboeing/osmnx | osmnx/save_load.py | https://github.com/gboeing/osmnx/blob/be59fd313bcb68af8fc79242c56194f1247e26e2/osmnx/save_load.py#L309-L393 | def load_graphml(filename, folder=None, node_type=int):
"""
Load a GraphML file from disk and convert the node/edge attributes to
correct data types.
Parameters
----------
filename : string
the name of the graphml file (including file extension)
folder : string
the folder co... | [
"def",
"load_graphml",
"(",
"filename",
",",
"folder",
"=",
"None",
",",
"node_type",
"=",
"int",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"# read the graph from disk",
"if",
"folder",
"is",
"None",
":",
"folder",
"=",
"settings",
".",
... | Load a GraphML file from disk and convert the node/edge attributes to
correct data types.
Parameters
----------
filename : string
the name of the graphml file (including file extension)
folder : string
the folder containing the file, if None, use default data folder
node_type : ... | [
"Load",
"a",
"GraphML",
"file",
"from",
"disk",
"and",
"convert",
"the",
"node",
"/",
"edge",
"attributes",
"to",
"correct",
"data",
"types",
"."
] | python | train | 42.847059 |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/dataframeeditor.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/dataframeeditor.py#L1146-L1157 | def _resizeColumnToContents(self, header, data, col, limit_ms):
"""Resize a column by its contents."""
hdr_width = self._sizeHintForColumn(header, col, limit_ms)
data_width = self._sizeHintForColumn(data, col, limit_ms)
if data_width > hdr_width:
width = min(self.max_wid... | [
"def",
"_resizeColumnToContents",
"(",
"self",
",",
"header",
",",
"data",
",",
"col",
",",
"limit_ms",
")",
":",
"hdr_width",
"=",
"self",
".",
"_sizeHintForColumn",
"(",
"header",
",",
"col",
",",
"limit_ms",
")",
"data_width",
"=",
"self",
".",
"_sizeHi... | Resize a column by its contents. | [
"Resize",
"a",
"column",
"by",
"its",
"contents",
"."
] | python | train | 51 |
haizi-zh/scrapy-qiniu | scrapy_qiniu/impl.py | https://github.com/haizi-zh/scrapy-qiniu/blob/9a3dddacd2e665cb3c86308772040946c3b82415/scrapy_qiniu/impl.py#L168-L172 | def file_path(self, request, response=None, info=None):
"""
抓取到的资源存放到七牛的时候, 应该采用什么样的key? 返回的path是一个JSON字符串, 其中有bucket和key的信息
"""
return json.dumps(self._extract_key_info(request)) | [
"def",
"file_path",
"(",
"self",
",",
"request",
",",
"response",
"=",
"None",
",",
"info",
"=",
"None",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"self",
".",
"_extract_key_info",
"(",
"request",
")",
")"
] | 抓取到的资源存放到七牛的时候, 应该采用什么样的key? 返回的path是一个JSON字符串, 其中有bucket和key的信息 | [
"抓取到的资源存放到七牛的时候",
"应该采用什么样的key?",
"返回的path是一个JSON字符串",
"其中有bucket和key的信息"
] | python | train | 41.4 |
RedHatInsights/insights-core | insights/core/dr.py | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/dr.py#L647-L653 | def invoke(self, results):
"""
Handles invocation of the component. The default implementation invokes
it with positional arguments based on order of dependency declaration.
"""
args = [results.get(d) for d in self.deps]
return self.component(*args) | [
"def",
"invoke",
"(",
"self",
",",
"results",
")",
":",
"args",
"=",
"[",
"results",
".",
"get",
"(",
"d",
")",
"for",
"d",
"in",
"self",
".",
"deps",
"]",
"return",
"self",
".",
"component",
"(",
"*",
"args",
")"
] | Handles invocation of the component. The default implementation invokes
it with positional arguments based on order of dependency declaration. | [
"Handles",
"invocation",
"of",
"the",
"component",
".",
"The",
"default",
"implementation",
"invokes",
"it",
"with",
"positional",
"arguments",
"based",
"on",
"order",
"of",
"dependency",
"declaration",
"."
] | python | train | 41.571429 |
phareous/insteonlocal | insteonlocal/Hub.py | https://github.com/phareous/insteonlocal/blob/a4544a17d143fb285852cb873e862c270d55dd00/insteonlocal/Hub.py#L289-L298 | def get_device_model(self, cat, sub_cat, key=''):
"""Return the model name given cat/subcat or product key"""
if cat + ':' + sub_cat in self.device_models:
return self.device_models[cat + ':' + sub_cat]
else:
for i_key, i_val in self.device_models.items():
... | [
"def",
"get_device_model",
"(",
"self",
",",
"cat",
",",
"sub_cat",
",",
"key",
"=",
"''",
")",
":",
"if",
"cat",
"+",
"':'",
"+",
"sub_cat",
"in",
"self",
".",
"device_models",
":",
"return",
"self",
".",
"device_models",
"[",
"cat",
"+",
"':'",
"+"... | Return the model name given cat/subcat or product key | [
"Return",
"the",
"model",
"name",
"given",
"cat",
"/",
"subcat",
"or",
"product",
"key"
] | python | train | 43.6 |
gwastro/pycbc | pycbc/io/record.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/io/record.py#L1798-L1801 | def chi_eff(self):
"""Returns the effective spin."""
return conversions.chi_eff(self.mass1, self.mass2, self.spin1z,
self.spin2z) | [
"def",
"chi_eff",
"(",
"self",
")",
":",
"return",
"conversions",
".",
"chi_eff",
"(",
"self",
".",
"mass1",
",",
"self",
".",
"mass2",
",",
"self",
".",
"spin1z",
",",
"self",
".",
"spin2z",
")"
] | Returns the effective spin. | [
"Returns",
"the",
"effective",
"spin",
"."
] | python | train | 44.25 |
coopernurse/barrister | barrister/runtime.py | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L825-L841 | def get(self, name):
"""
Returns the struct, enum, or interface with the given name, or raises RpcException if
no elements match that name.
:Parameters:
name
Name of struct/enum/interface to return
"""
if self.structs.has_key(name):
retu... | [
"def",
"get",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"structs",
".",
"has_key",
"(",
"name",
")",
":",
"return",
"self",
".",
"structs",
"[",
"name",
"]",
"elif",
"self",
".",
"enums",
".",
"has_key",
"(",
"name",
")",
":",
"retur... | Returns the struct, enum, or interface with the given name, or raises RpcException if
no elements match that name.
:Parameters:
name
Name of struct/enum/interface to return | [
"Returns",
"the",
"struct",
"enum",
"or",
"interface",
"with",
"the",
"given",
"name",
"or",
"raises",
"RpcException",
"if",
"no",
"elements",
"match",
"that",
"name",
"."
] | python | train | 34.176471 |
google/transitfeed | transitfeed/shape.py | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/shape.py#L54-L96 | def AddShapePointObjectUnsorted(self, shapepoint, problems):
"""Insert a point into a correct position by sequence. """
if (len(self.sequence) == 0 or
shapepoint.shape_pt_sequence >= self.sequence[-1]):
index = len(self.sequence)
elif shapepoint.shape_pt_sequence <= self.sequence[0]:
ind... | [
"def",
"AddShapePointObjectUnsorted",
"(",
"self",
",",
"shapepoint",
",",
"problems",
")",
":",
"if",
"(",
"len",
"(",
"self",
".",
"sequence",
")",
"==",
"0",
"or",
"shapepoint",
".",
"shape_pt_sequence",
">=",
"self",
".",
"sequence",
"[",
"-",
"1",
"... | Insert a point into a correct position by sequence. | [
"Insert",
"a",
"point",
"into",
"a",
"correct",
"position",
"by",
"sequence",
"."
] | python | train | 52.209302 |
saltstack/salt | salt/modules/redismod.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L300-L311 | def hgetall(key, host=None, port=None, db=None, password=None):
'''
Get all fields and values from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hgetall foo_hash
'''
server = _connect(host, port, db, password)
return server.hgetall(key) | [
"def",
"hgetall",
"(",
"key",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"db",
",",
"password",
")",
"return",
"ser... | Get all fields and values from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hgetall foo_hash | [
"Get",
"all",
"fields",
"and",
"values",
"from",
"a",
"redis",
"hash",
"returns",
"dict"
] | python | train | 24.5 |
dpkp/kafka-python | kafka/conn.py | https://github.com/dpkp/kafka-python/blob/f6a8a38937688ea2cc5dc13d3d1039493be5c9b5/kafka/conn.py#L743-L757 | def connection_delay(self):
"""
Return the number of milliseconds to wait, based on the connection
state, before attempting to send data. When disconnected, this respects
the reconnect backoff time. When connecting, returns 0 to allow
non-blocking connect to finish. When connecte... | [
"def",
"connection_delay",
"(",
"self",
")",
":",
"time_waited",
"=",
"time",
".",
"time",
"(",
")",
"-",
"(",
"self",
".",
"last_attempt",
"or",
"0",
")",
"if",
"self",
".",
"state",
"is",
"ConnectionStates",
".",
"DISCONNECTED",
":",
"return",
"max",
... | Return the number of milliseconds to wait, based on the connection
state, before attempting to send data. When disconnected, this respects
the reconnect backoff time. When connecting, returns 0 to allow
non-blocking connect to finish. When connected, returns a very large
number to handle... | [
"Return",
"the",
"number",
"of",
"milliseconds",
"to",
"wait",
"based",
"on",
"the",
"connection",
"state",
"before",
"attempting",
"to",
"send",
"data",
".",
"When",
"disconnected",
"this",
"respects",
"the",
"reconnect",
"backoff",
"time",
".",
"When",
"conn... | python | train | 45.333333 |
OpenGov/og-python-utils | ogutils/collections/transformations.py | https://github.com/OpenGov/og-python-utils/blob/00f44927383dd1bd6348f47302c4453d56963479/ogutils/collections/transformations.py#L41-L57 | def merge_dicts(*dicts, **copy_check):
'''
Combines dictionaries into a single dictionary. If the 'copy' keyword is passed
then the first dictionary is copied before update.
merge_dicts({'a': 1, 'c': 1}, {'a': 2, 'b': 1})
# => {'a': 2, 'b': 1, 'c': 1}
'''
merged = {}
if not dic... | [
"def",
"merge_dicts",
"(",
"*",
"dicts",
",",
"*",
"*",
"copy_check",
")",
":",
"merged",
"=",
"{",
"}",
"if",
"not",
"dicts",
":",
"return",
"merged",
"for",
"index",
",",
"merge_dict",
"in",
"enumerate",
"(",
"dicts",
")",
":",
"if",
"index",
"==",... | Combines dictionaries into a single dictionary. If the 'copy' keyword is passed
then the first dictionary is copied before update.
merge_dicts({'a': 1, 'c': 1}, {'a': 2, 'b': 1})
# => {'a': 2, 'b': 1, 'c': 1} | [
"Combines",
"dictionaries",
"into",
"a",
"single",
"dictionary",
".",
"If",
"the",
"copy",
"keyword",
"is",
"passed",
"then",
"the",
"first",
"dictionary",
"is",
"copied",
"before",
"update",
".",
"merge_dicts",
"(",
"{",
"a",
":",
"1",
"c",
":",
"1",
"}... | python | train | 31.705882 |
photo/openphoto-python | trovebox/objects/photo.py | https://github.com/photo/openphoto-python/blob/209a1da27c8d8c88dbcf4ea6c6f57031ea1bc44b/trovebox/objects/photo.py#L32-L39 | def replace(self, photo_file, **kwds):
"""
Endpoint: /photo/<id>/replace.json
Uploads the specified photo file to replace this photo.
"""
result = self._client.photo.replace(self, photo_file, **kwds)
self._replace_fields(result.get_fields()) | [
"def",
"replace",
"(",
"self",
",",
"photo_file",
",",
"*",
"*",
"kwds",
")",
":",
"result",
"=",
"self",
".",
"_client",
".",
"photo",
".",
"replace",
"(",
"self",
",",
"photo_file",
",",
"*",
"*",
"kwds",
")",
"self",
".",
"_replace_fields",
"(",
... | Endpoint: /photo/<id>/replace.json
Uploads the specified photo file to replace this photo. | [
"Endpoint",
":",
"/",
"photo",
"/",
"<id",
">",
"/",
"replace",
".",
"json"
] | python | train | 35.375 |
saltstack/salt | salt/pillar/vmware_pillar.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/vmware_pillar.py#L473-L492 | def _recurse_config_to_dict(t_data):
'''
helper function to recurse through a vim object and attempt to return all child objects
'''
if not isinstance(t_data, type(None)):
if isinstance(t_data, list):
t_list = []
for i in t_data:
t_list.append(_recurse_con... | [
"def",
"_recurse_config_to_dict",
"(",
"t_data",
")",
":",
"if",
"not",
"isinstance",
"(",
"t_data",
",",
"type",
"(",
"None",
")",
")",
":",
"if",
"isinstance",
"(",
"t_data",
",",
"list",
")",
":",
"t_list",
"=",
"[",
"]",
"for",
"i",
"in",
"t_data... | helper function to recurse through a vim object and attempt to return all child objects | [
"helper",
"function",
"to",
"recurse",
"through",
"a",
"vim",
"object",
"and",
"attempt",
"to",
"return",
"all",
"child",
"objects"
] | python | train | 35.8 |
openid/JWTConnect-Python-CryptoJWT | src/cryptojwt/key_jar.py | https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/key_jar.py#L232-L242 | def get_signing_key(self, key_type="", owner="", kid=None, **kwargs):
"""
Shortcut to use for signing keys only.
:param key_type: Type of key (rsa, ec, oct, ..)
:param owner: Who is the owner of the keys, "" == me (default)
:param kid: A Key Identifier
:param kwargs: Ext... | [
"def",
"get_signing_key",
"(",
"self",
",",
"key_type",
"=",
"\"\"",
",",
"owner",
"=",
"\"\"",
",",
"kid",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"get",
"(",
"\"sig\"",
",",
"key_type",
",",
"owner",
",",
"kid",
","... | Shortcut to use for signing keys only.
:param key_type: Type of key (rsa, ec, oct, ..)
:param owner: Who is the owner of the keys, "" == me (default)
:param kid: A Key Identifier
:param kwargs: Extra key word arguments
:return: A possibly empty list of keys | [
"Shortcut",
"to",
"use",
"for",
"signing",
"keys",
"only",
"."
] | python | train | 41.181818 |
clalancette/pycdlib | pycdlib/pycdlib.py | https://github.com/clalancette/pycdlib/blob/1e7b77a809e905d67dc71e12d70e850be26b6233/pycdlib/pycdlib.py#L2686-L2709 | def _outfp_write_with_check(self, outfp, data, enable_overwrite_check=True):
# type: (BinaryIO, bytes, bool) -> None
'''
Internal method to write data out to the output file descriptor,
ensuring that it doesn't go beyond the bounds of the ISO.
Parameters:
outfp - The fi... | [
"def",
"_outfp_write_with_check",
"(",
"self",
",",
"outfp",
",",
"data",
",",
"enable_overwrite_check",
"=",
"True",
")",
":",
"# type: (BinaryIO, bytes, bool) -> None",
"start",
"=",
"outfp",
".",
"tell",
"(",
")",
"outfp",
".",
"write",
"(",
"data",
")",
"i... | Internal method to write data out to the output file descriptor,
ensuring that it doesn't go beyond the bounds of the ISO.
Parameters:
outfp - The file object to write to.
data - The actual data to write.
enable_overwrite_check - Whether to do overwrite checking if it is enab... | [
"Internal",
"method",
"to",
"write",
"data",
"out",
"to",
"the",
"output",
"file",
"descriptor",
"ensuring",
"that",
"it",
"doesn",
"t",
"go",
"beyond",
"the",
"bounds",
"of",
"the",
"ISO",
"."
] | python | train | 51.375 |
tensorpack/tensorpack | tensorpack/tfutils/summary.py | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/summary.py#L140-L158 | def add_activation_summary(x, types=None, name=None, collections=None):
"""
Call :func:`add_tensor_summary` under a reused 'activation-summary' name scope.
This function is a no-op if not calling from main training tower.
Args:
x (tf.Tensor): the tensor to summary.
types (list[str]): su... | [
"def",
"add_activation_summary",
"(",
"x",
",",
"types",
"=",
"None",
",",
"name",
"=",
"None",
",",
"collections",
"=",
"None",
")",
":",
"ndim",
"=",
"x",
".",
"get_shape",
"(",
")",
".",
"ndims",
"if",
"ndim",
"<",
"2",
":",
"logger",
".",
"warn... | Call :func:`add_tensor_summary` under a reused 'activation-summary' name scope.
This function is a no-op if not calling from main training tower.
Args:
x (tf.Tensor): the tensor to summary.
types (list[str]): summary types, defaults to ``['sparsity', 'rms', 'histogram']``.
name (str): i... | [
"Call",
":",
"func",
":",
"add_tensor_summary",
"under",
"a",
"reused",
"activation",
"-",
"summary",
"name",
"scope",
".",
"This",
"function",
"is",
"a",
"no",
"-",
"op",
"if",
"not",
"calling",
"from",
"main",
"training",
"tower",
"."
] | python | train | 42.842105 |
olgabot/prettyplotlib | prettyplotlib/__init__.py | https://github.com/olgabot/prettyplotlib/blob/aa964ff777e60d26f078d8ace386936bf41cbd15/prettyplotlib/__init__.py#L30-L40 | def switch_axis_limits(ax, which_axis):
'''
Switch the axis limits of either x or y. Or both!
'''
for a in which_axis:
assert a in ('x', 'y')
ax_limits = ax.axis()
if a == 'x':
ax.set_xlim(ax_limits[1], ax_limits[0])
else:
ax.set_ylim(ax_limits[3],... | [
"def",
"switch_axis_limits",
"(",
"ax",
",",
"which_axis",
")",
":",
"for",
"a",
"in",
"which_axis",
":",
"assert",
"a",
"in",
"(",
"'x'",
",",
"'y'",
")",
"ax_limits",
"=",
"ax",
".",
"axis",
"(",
")",
"if",
"a",
"==",
"'x'",
":",
"ax",
".",
"se... | Switch the axis limits of either x or y. Or both! | [
"Switch",
"the",
"axis",
"limits",
"of",
"either",
"x",
"or",
"y",
".",
"Or",
"both!"
] | python | train | 29.454545 |
awkman/pywifi | pywifi/_wifiutil_win.py | https://github.com/awkman/pywifi/blob/719baf73d8d32c623dbaf5e9de5d973face152a4/pywifi/_wifiutil_win.py#L460-L469 | def remove_all_network_profiles(self, obj):
"""Remove all the AP profiles."""
profile_name_list = self.network_profile_name_list(obj)
for profile_name in profile_name_list:
self._logger.debug("delete profile: %s", profile_name)
str_buf = create_unicode_buffer(profile_na... | [
"def",
"remove_all_network_profiles",
"(",
"self",
",",
"obj",
")",
":",
"profile_name_list",
"=",
"self",
".",
"network_profile_name_list",
"(",
"obj",
")",
"for",
"profile_name",
"in",
"profile_name_list",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"del... | Remove all the AP profiles. | [
"Remove",
"all",
"the",
"AP",
"profiles",
"."
] | python | train | 45 |
StackSentinel/stacksentinel-python | StackSentinel/__init__.py | https://github.com/StackSentinel/stacksentinel-python/blob/253664ac5ccaeb312f4288580e10061dac65403c/StackSentinel/__init__.py#L113-L190 | def handle_exception(self, exc_info=None, state=None, tags=None, return_feedback_urls=False,
dry_run=False):
"""
Call this method from within a try/except clause to generate a call to Stack Sentinel.
:param exc_info: Return value of sys.exc_info(). If you pass None, han... | [
"def",
"handle_exception",
"(",
"self",
",",
"exc_info",
"=",
"None",
",",
"state",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"return_feedback_urls",
"=",
"False",
",",
"dry_run",
"=",
"False",
")",
":",
"if",
"not",
"exc_info",
":",
"exc_info",
"=",
... | Call this method from within a try/except clause to generate a call to Stack Sentinel.
:param exc_info: Return value of sys.exc_info(). If you pass None, handle_exception will call sys.exc_info() itself
:param state: Dictionary of state information associated with the error. This could be form data, co... | [
"Call",
"this",
"method",
"from",
"within",
"a",
"try",
"/",
"except",
"clause",
"to",
"generate",
"a",
"call",
"to",
"Stack",
"Sentinel",
"."
] | python | test | 38.333333 |
alvinwan/TexSoup | TexSoup/reader.py | https://github.com/alvinwan/TexSoup/blob/63323ed71510fd2351102b8c36660a3b7703cead/TexSoup/reader.py#L169-L184 | def tokenize_math(text):
r"""Prevents math from being tokenized.
:param Buffer text: iterator over line, with current position
>>> b = Buffer(r'$\min_x$ \command')
>>> tokenize_math(b)
'$'
>>> b = Buffer(r'$$\min_x$$ \command')
>>> tokenize_math(b)
'$$'
"""
if text.startswith('... | [
"def",
"tokenize_math",
"(",
"text",
")",
":",
"if",
"text",
".",
"startswith",
"(",
"'$'",
")",
"and",
"(",
"text",
".",
"position",
"==",
"0",
"or",
"text",
".",
"peek",
"(",
"-",
"1",
")",
"!=",
"'\\\\'",
"or",
"text",
".",
"endswith",
"(",
"r... | r"""Prevents math from being tokenized.
:param Buffer text: iterator over line, with current position
>>> b = Buffer(r'$\min_x$ \command')
>>> tokenize_math(b)
'$'
>>> b = Buffer(r'$$\min_x$$ \command')
>>> tokenize_math(b)
'$$' | [
"r",
"Prevents",
"math",
"from",
"being",
"tokenized",
"."
] | python | train | 32.75 |
pandeylab/pythomics | pythomics/proteomics/parsers.py | https://github.com/pandeylab/pythomics/blob/ab0a5651a2e02a25def4d277b35fa09d1631bfcb/pythomics/proteomics/parsers.py#L1635-L1664 | def parseFullScan(self, i, modifications=False):
"""
parses scan info for giving a Spectrum Obj for plotting. takes significantly longer since it has to unzip/parse xml
"""
scanObj = PeptideObject()
peptide = str(i[1])
pid=i[2]
scanObj.acc = self.protein_map.get(i... | [
"def",
"parseFullScan",
"(",
"self",
",",
"i",
",",
"modifications",
"=",
"False",
")",
":",
"scanObj",
"=",
"PeptideObject",
"(",
")",
"peptide",
"=",
"str",
"(",
"i",
"[",
"1",
"]",
")",
"pid",
"=",
"i",
"[",
"2",
"]",
"scanObj",
".",
"acc",
"=... | parses scan info for giving a Spectrum Obj for plotting. takes significantly longer since it has to unzip/parse xml | [
"parses",
"scan",
"info",
"for",
"giving",
"a",
"Spectrum",
"Obj",
"for",
"plotting",
".",
"takes",
"significantly",
"longer",
"since",
"it",
"has",
"to",
"unzip",
"/",
"parse",
"xml"
] | python | train | 51.3 |
orb-framework/orb | orb/core/column_types/dtime.py | https://github.com/orb-framework/orb/blob/575be2689cb269e65a0a2678232ff940acc19e5a/orb/core/column_types/dtime.py#L507-L523 | def valueFromString(self, value, context=None):
"""
Converts the inputted string text to a value that matches the type from
this column type.
:param value | <str>
"""
if value in ('today', 'now'):
return datetime.date.utcnow()
try:
r... | [
"def",
"valueFromString",
"(",
"self",
",",
"value",
",",
"context",
"=",
"None",
")",
":",
"if",
"value",
"in",
"(",
"'today'",
",",
"'now'",
")",
":",
"return",
"datetime",
".",
"date",
".",
"utcnow",
"(",
")",
"try",
":",
"return",
"datetime",
"."... | Converts the inputted string text to a value that matches the type from
this column type.
:param value | <str> | [
"Converts",
"the",
"inputted",
"string",
"text",
"to",
"a",
"value",
"that",
"matches",
"the",
"type",
"from",
"this",
"column",
"type",
"."
] | python | train | 31.411765 |
timothycrosley/blox | blox/base.py | https://github.com/timothycrosley/blox/blob/dc410783d2a2ecad918d1e19c6ee000d20e42d35/blox/base.py#L450-L470 | def output(self, to=None, formatted=False, indent=0, indentation=' ', *args, **kwargs):
'''Outputs to a stream (like a file or request)'''
if formatted:
to.write(self.start_tag)
to.write('\n')
if not self.tag_self_closes:
for blok in self.blox:
... | [
"def",
"output",
"(",
"self",
",",
"to",
"=",
"None",
",",
"formatted",
"=",
"False",
",",
"indent",
"=",
"0",
",",
"indentation",
"=",
"' '",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"formatted",
":",
"to",
".",
"write",
"(",
... | Outputs to a stream (like a file or request) | [
"Outputs",
"to",
"a",
"stream",
"(",
"like",
"a",
"file",
"or",
"request",
")"
] | python | valid | 41.190476 |
rackerlabs/rackspace-python-neutronclient | neutronclient/v2_0/client.py | https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/v2_0/client.py#L1002-L1005 | def update_listener(self, lbaas_listener, body=None):
"""Updates a lbaas_listener."""
return self.put(self.lbaas_listener_path % (lbaas_listener),
body=body) | [
"def",
"update_listener",
"(",
"self",
",",
"lbaas_listener",
",",
"body",
"=",
"None",
")",
":",
"return",
"self",
".",
"put",
"(",
"self",
".",
"lbaas_listener_path",
"%",
"(",
"lbaas_listener",
")",
",",
"body",
"=",
"body",
")"
] | Updates a lbaas_listener. | [
"Updates",
"a",
"lbaas_listener",
"."
] | python | train | 48.5 |
mapbox/mapbox-sdk-py | mapbox/services/directions.py | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/directions.py#L143-L249 | def directions(self, features, profile='mapbox/driving',
alternatives=None, geometries=None, overview=None, steps=None,
continue_straight=None, waypoint_snapping=None, annotations=None,
language=None, **kwargs):
"""Request directions for waypoints encoded... | [
"def",
"directions",
"(",
"self",
",",
"features",
",",
"profile",
"=",
"'mapbox/driving'",
",",
"alternatives",
"=",
"None",
",",
"geometries",
"=",
"None",
",",
"overview",
"=",
"None",
",",
"steps",
"=",
"None",
",",
"continue_straight",
"=",
"None",
",... | Request directions for waypoints encoded as GeoJSON features.
Parameters
----------
features : iterable
An collection of GeoJSON features
profile : str
Name of a Mapbox profile such as 'mapbox.driving'
alternatives : bool
Whether to try to ret... | [
"Request",
"directions",
"for",
"waypoints",
"encoded",
"as",
"GeoJSON",
"features",
"."
] | python | train | 41.53271 |
DinoTools/python-overpy | overpy/__init__.py | https://github.com/DinoTools/python-overpy/blob/db8f80eeb1b4d1405816bd62c16ddb3364e0c46d/overpy/__init__.py#L966-L1005 | def from_json(cls, data, result=None):
"""
Create new Way element from JSON data
:param data: Element data from JSON
:type data: Dict
:param result: The result this element belongs to
:type result: overpy.Result
:return: New instance of Way
:rtype: overpy... | [
"def",
"from_json",
"(",
"cls",
",",
"data",
",",
"result",
"=",
"None",
")",
":",
"if",
"data",
".",
"get",
"(",
"\"type\"",
")",
"!=",
"cls",
".",
"_type_value",
":",
"raise",
"exception",
".",
"ElementDataWrongType",
"(",
"type_expected",
"=",
"cls",
... | Create new Way element from JSON data
:param data: Element data from JSON
:type data: Dict
:param result: The result this element belongs to
:type result: overpy.Result
:return: New instance of Way
:rtype: overpy.Way
:raises overpy.exception.ElementDataWrongType:... | [
"Create",
"new",
"Way",
"element",
"from",
"JSON",
"data"
] | python | train | 30.85 |
watson-developer-cloud/python-sdk | ibm_watson/personality_insights_v3.py | https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/personality_insights_v3.py#L454-L479 | def _from_dict(cls, _dict):
"""Initialize a ConsumptionPreferencesCategory object from a json dictionary."""
args = {}
if 'consumption_preference_category_id' in _dict:
args['consumption_preference_category_id'] = _dict.get(
'consumption_preference_category_id')
... | [
"def",
"_from_dict",
"(",
"cls",
",",
"_dict",
")",
":",
"args",
"=",
"{",
"}",
"if",
"'consumption_preference_category_id'",
"in",
"_dict",
":",
"args",
"[",
"'consumption_preference_category_id'",
"]",
"=",
"_dict",
".",
"get",
"(",
"'consumption_preference_cate... | Initialize a ConsumptionPreferencesCategory object from a json dictionary. | [
"Initialize",
"a",
"ConsumptionPreferencesCategory",
"object",
"from",
"a",
"json",
"dictionary",
"."
] | python | train | 43.307692 |
robertchase/ergaleia | ergaleia/load_from_path.py | https://github.com/robertchase/ergaleia/blob/df8e9a4b18c563022a503faa27e822c9a5755490/ergaleia/load_from_path.py#L9-L36 | def load_from_path(path, filetype=None, has_filetype=True):
""" load file content from a file specified as dot-separated
The file is located according to logic in normalize_path,
and the contents are returned. (See Note 1)
Parameters: (see normalize_path)
path - dot-sep... | [
"def",
"load_from_path",
"(",
"path",
",",
"filetype",
"=",
"None",
",",
"has_filetype",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"path",
",",
"str",
")",
":",
"try",
":",
"return",
"path",
".",
"read",
"(",
")",
"except",
"AttributeError... | load file content from a file specified as dot-separated
The file is located according to logic in normalize_path,
and the contents are returned. (See Note 1)
Parameters: (see normalize_path)
path - dot-separated path
filetype - optional filetype
... | [
"load",
"file",
"content",
"from",
"a",
"file",
"specified",
"as",
"dot",
"-",
"separated"
] | python | train | 41.071429 |
edeposit/marcxml_parser | src/marcxml_parser/query.py | https://github.com/edeposit/marcxml_parser/blob/6d1c77c61fc2827b71f1b3d5aa3332d7f5807820/src/marcxml_parser/query.py#L466-L479 | def get_ISSNs(self):
"""
Get list of VALID ISSNs (``022a``).
Returns:
list: List with *valid* ISSN strings.
"""
invalid_issns = set(self.get_invalid_ISSNs())
return [
self._clean_isbn(issn)
for issn in self["022a"]
if self... | [
"def",
"get_ISSNs",
"(",
"self",
")",
":",
"invalid_issns",
"=",
"set",
"(",
"self",
".",
"get_invalid_ISSNs",
"(",
")",
")",
"return",
"[",
"self",
".",
"_clean_isbn",
"(",
"issn",
")",
"for",
"issn",
"in",
"self",
"[",
"\"022a\"",
"]",
"if",
"self",
... | Get list of VALID ISSNs (``022a``).
Returns:
list: List with *valid* ISSN strings. | [
"Get",
"list",
"of",
"VALID",
"ISSNs",
"(",
"022a",
")",
"."
] | python | valid | 25.428571 |
StackStorm/pybind | pybind/nos/v6_0_2f/interface/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v6_0_2f/interface/__init__.py#L437-L461 | def _set_fcoe(self, v, load=False):
"""
Setter method for fcoe, mapped from YANG variable /interface/fcoe (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_fcoe is considered as a private
method. Backends looking to populate this variable should
do so via ca... | [
"def",
"_set_fcoe",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",
... | Setter method for fcoe, mapped from YANG variable /interface/fcoe (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_fcoe is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_fcoe() directly.
YANG De... | [
"Setter",
"method",
"for",
"fcoe",
"mapped",
"from",
"YANG",
"variable",
"/",
"interface",
"/",
"fcoe",
"(",
"list",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in",
"the",
"source",
"YANG",
"file",
"the... | python | train | 138.96 |
Microsoft/azure-devops-python-api | azure-devops/azure/devops/v5_0/build/build_client.py | https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_0/build/build_client.py#L1021-L1042 | def get_build_logs_zip(self, project, build_id, **kwargs):
"""GetBuildLogsZip.
Gets the logs for a build.
:param str project: Project ID or project name
:param int build_id: The ID of the build.
:rtype: object
"""
route_values = {}
if project is not None:
... | [
"def",
"get_build_logs_zip",
"(",
"self",
",",
"project",
",",
"build_id",
",",
"*",
"*",
"kwargs",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"project",
"is",
"not",
"None",
":",
"route_values",
"[",
"'project'",
"]",
"=",
"self",
".",
"_serialize",... | GetBuildLogsZip.
Gets the logs for a build.
:param str project: Project ID or project name
:param int build_id: The ID of the build.
:rtype: object | [
"GetBuildLogsZip",
".",
"Gets",
"the",
"logs",
"for",
"a",
"build",
".",
":",
"param",
"str",
"project",
":",
"Project",
"ID",
"or",
"project",
"name",
":",
"param",
"int",
"build_id",
":",
"The",
"ID",
"of",
"the",
"build",
".",
":",
"rtype",
":",
"... | python | train | 45.136364 |
tumblr/pytumblr | pytumblr/__init__.py | https://github.com/tumblr/pytumblr/blob/4a5cd7c4b8ae78d12811d9fd52620afa1692a415/pytumblr/__init__.py#L42-L51 | def avatar(self, blogname, size=64):
"""
Retrieves the url of the blog's avatar
:param blogname: a string, the blog you want the avatar for
:returns: A dict created from the JSON response
"""
url = "/v2/blog/{}/avatar/{}".format(blogname, size)
return self.send_... | [
"def",
"avatar",
"(",
"self",
",",
"blogname",
",",
"size",
"=",
"64",
")",
":",
"url",
"=",
"\"/v2/blog/{}/avatar/{}\"",
".",
"format",
"(",
"blogname",
",",
"size",
")",
"return",
"self",
".",
"send_api_request",
"(",
"\"get\"",
",",
"url",
")"
] | Retrieves the url of the blog's avatar
:param blogname: a string, the blog you want the avatar for
:returns: A dict created from the JSON response | [
"Retrieves",
"the",
"url",
"of",
"the",
"blog",
"s",
"avatar"
] | python | train | 33.4 |
CamDavidsonPilon/lifetimes | lifetimes/plotting.py | https://github.com/CamDavidsonPilon/lifetimes/blob/f926308bc03c17c1d12fead729de43885cf13321/lifetimes/plotting.py#L77-L133 | def plot_calibration_purchases_vs_holdout_purchases(
model, calibration_holdout_matrix, kind="frequency_cal", n=7, **kwargs
):
"""
Plot calibration purchases vs holdout.
This currently relies too much on the lifetimes.util calibration_and_holdout_data function.
Parameters
----------
model:... | [
"def",
"plot_calibration_purchases_vs_holdout_purchases",
"(",
"model",
",",
"calibration_holdout_matrix",
",",
"kind",
"=",
"\"frequency_cal\"",
",",
"n",
"=",
"7",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"matplotlib",
"import",
"pyplot",
"as",
"plt",
"x_label... | Plot calibration purchases vs holdout.
This currently relies too much on the lifetimes.util calibration_and_holdout_data function.
Parameters
----------
model: lifetimes model
A fitted lifetimes model.
calibration_holdout_matrix: pandas DataFrame
DataFrame from calibration_and_hold... | [
"Plot",
"calibration",
"purchases",
"vs",
"holdout",
"."
] | python | train | 37.438596 |
hydraplatform/hydra-base | hydra_base/db/model.py | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/db/model.py#L80-L89 | def _is_admin(user_id):
"""
Is the specified user an admin
"""
user = get_session().query(User).filter(User.id==user_id).one()
if user.is_admin():
return True
else:
return False | [
"def",
"_is_admin",
"(",
"user_id",
")",
":",
"user",
"=",
"get_session",
"(",
")",
".",
"query",
"(",
"User",
")",
".",
"filter",
"(",
"User",
".",
"id",
"==",
"user_id",
")",
".",
"one",
"(",
")",
"if",
"user",
".",
"is_admin",
"(",
")",
":",
... | Is the specified user an admin | [
"Is",
"the",
"specified",
"user",
"an",
"admin"
] | python | train | 21.3 |
google/python-gflags | gflags/flagvalues.py | https://github.com/google/python-gflags/blob/4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6/gflags/flagvalues.py#L1178-L1194 | def FlagsIntoString(self):
"""Returns a string with the flags assignments from this FlagValues object.
This function ignores flags whose value is None. Each flag
assignment is separated by a newline.
NOTE: MUST mirror the behavior of the C++ CommandlineFlagsIntoString
from http://code.google.com/... | [
"def",
"FlagsIntoString",
"(",
"self",
")",
":",
"s",
"=",
"''",
"for",
"flag",
"in",
"self",
".",
"FlagDict",
"(",
")",
".",
"values",
"(",
")",
":",
"if",
"flag",
".",
"value",
"is",
"not",
"None",
":",
"s",
"+=",
"flag",
".",
"serialize",
"(",... | Returns a string with the flags assignments from this FlagValues object.
This function ignores flags whose value is None. Each flag
assignment is separated by a newline.
NOTE: MUST mirror the behavior of the C++ CommandlineFlagsIntoString
from http://code.google.com/p/google-gflags
Returns:
... | [
"Returns",
"a",
"string",
"with",
"the",
"flags",
"assignments",
"from",
"this",
"FlagValues",
"object",
"."
] | python | train | 32.117647 |
475Cumulus/TBone | tbone/resources/resources.py | https://github.com/475Cumulus/TBone/blob/5a6672d8bbac449a0ab9e99560609f671fe84d4d/tbone/resources/resources.py#L311-L352 | async def dispatch(self, *args, **kwargs):
'''
This method handles the actual request to the resource.
It performs all the neccesary checks and then executes the relevant member method which is mapped to the method name.
Handles authentication and de-serialization before calling the requ... | [
"async",
"def",
"dispatch",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"method",
"=",
"self",
".",
"request_method",
"(",
")",
"# get the db object associated with the app and assign to resource",
"if",
"hasattr",
"(",
"self",
".",
"reques... | This method handles the actual request to the resource.
It performs all the neccesary checks and then executes the relevant member method which is mapped to the method name.
Handles authentication and de-serialization before calling the required method.
Handles the serialization of the response | [
"This",
"method",
"handles",
"the",
"actual",
"request",
"to",
"the",
"resource",
".",
"It",
"performs",
"all",
"the",
"neccesary",
"checks",
"and",
"then",
"executes",
"the",
"relevant",
"member",
"method",
"which",
"is",
"mapped",
"to",
"the",
"method",
"n... | python | train | 44.285714 |
joyent/python-manta | manta/cmdln.py | https://github.com/joyent/python-manta/blob/f68ef142bdbac058c981e3b28e18d77612f5b7c6/manta/cmdln.py#L1613-L1631 | def _get_trailing_whitespace(marker, s):
"""Return the whitespace content trailing the given 'marker' in string 's',
up to and including a newline.
"""
suffix = ''
start = s.index(marker) + len(marker)
i = start
while i < len(s):
if s[i] in ' \t':
suffix += s[i]
e... | [
"def",
"_get_trailing_whitespace",
"(",
"marker",
",",
"s",
")",
":",
"suffix",
"=",
"''",
"start",
"=",
"s",
".",
"index",
"(",
"marker",
")",
"+",
"len",
"(",
"marker",
")",
"i",
"=",
"start",
"while",
"i",
"<",
"len",
"(",
"s",
")",
":",
"if",... | Return the whitespace content trailing the given 'marker' in string 's',
up to and including a newline. | [
"Return",
"the",
"whitespace",
"content",
"trailing",
"the",
"given",
"marker",
"in",
"string",
"s",
"up",
"to",
"and",
"including",
"a",
"newline",
"."
] | python | train | 28.157895 |
jrigden/pyPodcastParser | pyPodcastParser/Item.py | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Item.py#L190-L200 | def set_itunes_element(self):
"""Set each of the itunes elements."""
self.set_itunes_author_name()
self.set_itunes_block()
self.set_itunes_closed_captioned()
self.set_itunes_duration()
self.set_itunes_explicit()
self.set_itune_image()
self.set_itunes_order... | [
"def",
"set_itunes_element",
"(",
"self",
")",
":",
"self",
".",
"set_itunes_author_name",
"(",
")",
"self",
".",
"set_itunes_block",
"(",
")",
"self",
".",
"set_itunes_closed_captioned",
"(",
")",
"self",
".",
"set_itunes_duration",
"(",
")",
"self",
".",
"se... | Set each of the itunes elements. | [
"Set",
"each",
"of",
"the",
"itunes",
"elements",
"."
] | python | train | 34.636364 |
zetaops/zengine | zengine/views/task_manager_actions.py | https://github.com/zetaops/zengine/blob/b5bc32d3b37bca799f8985be916f04528ac79e4a/zengine/views/task_manager_actions.py#L117-L133 | def select_postponed_date(self):
"""
The time intervals at which the workflow is to be extended are determined.
.. code-block:: python
# request:
{
'task_inv_key': string,
}
"""
_form = forms.Jso... | [
"def",
"select_postponed_date",
"(",
"self",
")",
":",
"_form",
"=",
"forms",
".",
"JsonForm",
"(",
"title",
"=",
"\"Postponed Workflow\"",
")",
"_form",
".",
"start_date",
"=",
"fields",
".",
"DateTime",
"(",
"\"Start Date\"",
")",
"_form",
".",
"finish_date"... | The time intervals at which the workflow is to be extended are determined.
.. code-block:: python
# request:
{
'task_inv_key': string,
} | [
"The",
"time",
"intervals",
"at",
"which",
"the",
"workflow",
"is",
"to",
"be",
"extended",
"are",
"determined",
".",
"..",
"code",
"-",
"block",
"::",
"python"
] | python | train | 31.294118 |
twisted/axiom | axiom/item.py | https://github.com/twisted/axiom/blob/7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68/axiom/item.py#L213-L270 | def powerUp(self, powerup, interface=None, priority=0):
"""
Installs a powerup (e.g. plugin) on an item or store.
Powerups will be returned in an iterator when queried for using the
'powerupsFor' method. Normally they will be returned in order of
installation [this may change i... | [
"def",
"powerUp",
"(",
"self",
",",
"powerup",
",",
"interface",
"=",
"None",
",",
"priority",
"=",
"0",
")",
":",
"if",
"interface",
"is",
"None",
":",
"for",
"iface",
",",
"priority",
"in",
"powerup",
".",
"_getPowerupInterfaces",
"(",
")",
":",
"sel... | Installs a powerup (e.g. plugin) on an item or store.
Powerups will be returned in an iterator when queried for using the
'powerupsFor' method. Normally they will be returned in order of
installation [this may change in future versions, so please don't
depend on it]. Higher priorities... | [
"Installs",
"a",
"powerup",
"(",
"e",
".",
"g",
".",
"plugin",
")",
"on",
"an",
"item",
"or",
"store",
"."
] | python | train | 47.775862 |
European-XFEL/karabo-bridge-py | karabo_bridge/simulation.py | https://github.com/European-XFEL/karabo-bridge-py/blob/ca20d72b8beb0039649d10cb01d027db42efd91c/karabo_bridge/simulation.py#L262-L328 | def start_gen(port, ser='msgpack', version='2.2', detector='AGIPD',
raw=False, nsources=1, datagen='random', *,
debug=True):
""""Karabo bridge server simulation.
Simulate a Karabo Bridge server and send random data from a detector,
either AGIPD or LPD.
Parameters
------... | [
"def",
"start_gen",
"(",
"port",
",",
"ser",
"=",
"'msgpack'",
",",
"version",
"=",
"'2.2'",
",",
"detector",
"=",
"'AGIPD'",
",",
"raw",
"=",
"False",
",",
"nsources",
"=",
"1",
",",
"datagen",
"=",
"'random'",
",",
"*",
",",
"debug",
"=",
"True",
... | Karabo bridge server simulation.
Simulate a Karabo Bridge server and send random data from a detector,
either AGIPD or LPD.
Parameters
----------
port: str
The port to on which the server is bound.
ser: str, optional
The serialization algorithm, default is msgpack.
version:... | [
"Karabo",
"bridge",
"server",
"simulation",
"."
] | python | train | 35.014925 |
apache/incubator-mxnet | python/mxnet/kvstore.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/kvstore.py#L513-L523 | def rank(self):
""" Returns the rank of this worker node.
Returns
-------
rank : int
The rank of this node, which is in range [0, num_workers())
"""
rank = ctypes.c_int()
check_call(_LIB.MXKVStoreGetRank(self.handle, ctypes.byref(rank)))
retur... | [
"def",
"rank",
"(",
"self",
")",
":",
"rank",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"check_call",
"(",
"_LIB",
".",
"MXKVStoreGetRank",
"(",
"self",
".",
"handle",
",",
"ctypes",
".",
"byref",
"(",
"rank",
")",
")",
")",
"return",
"rank",
".",
"va... | Returns the rank of this worker node.
Returns
-------
rank : int
The rank of this node, which is in range [0, num_workers()) | [
"Returns",
"the",
"rank",
"of",
"this",
"worker",
"node",
"."
] | python | train | 29.272727 |
saltstack/salt | salt/state.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L217-L232 | def state_args(id_, state, high):
'''
Return a set of the arguments passed to the named state
'''
args = set()
if id_ not in high:
return args
if state not in high[id_]:
return args
for item in high[id_][state]:
if not isinstance(item, dict):
continue
... | [
"def",
"state_args",
"(",
"id_",
",",
"state",
",",
"high",
")",
":",
"args",
"=",
"set",
"(",
")",
"if",
"id_",
"not",
"in",
"high",
":",
"return",
"args",
"if",
"state",
"not",
"in",
"high",
"[",
"id_",
"]",
":",
"return",
"args",
"for",
"item"... | Return a set of the arguments passed to the named state | [
"Return",
"a",
"set",
"of",
"the",
"arguments",
"passed",
"to",
"the",
"named",
"state"
] | python | train | 24.9375 |
brocade/pynos | pynos/versions/base/yang/ietf_netconf.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/base/yang/ietf_netconf.py#L82-L95 | def edit_config_input_target_config_target_candidate_candidate(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
edit_config = ET.Element("edit_config")
config = edit_config
input = ET.SubElement(edit_config, "input")
target = ET.SubElement... | [
"def",
"edit_config_input_target_config_target_candidate_candidate",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"edit_config",
"=",
"ET",
".",
"Element",
"(",
"\"edit_config\"",
")",
"config",
"="... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 42.714286 |
nion-software/nionswift-instrumentation-kit | nionswift_plugin/nion_instrumentation_ui/VideoControlPanel.py | https://github.com/nion-software/nionswift-instrumentation-kit/blob/b20c4fff17e840e8cb3d544705faf5bd05f1cbf7/nionswift_plugin/nion_instrumentation_ui/VideoControlPanel.py#L121-L130 | def initialize_state(self):
""" Call this to initialize the state of the UI after everything has been connected. """
if self.__hardware_source:
self.__data_item_states_changed_event_listener = self.__hardware_source.data_item_states_changed_event.listen(self.__data_item_states_changed)
... | [
"def",
"initialize_state",
"(",
"self",
")",
":",
"if",
"self",
".",
"__hardware_source",
":",
"self",
".",
"__data_item_states_changed_event_listener",
"=",
"self",
".",
"__hardware_source",
".",
"data_item_states_changed_event",
".",
"listen",
"(",
"self",
".",
"_... | Call this to initialize the state of the UI after everything has been connected. | [
"Call",
"this",
"to",
"initialize",
"the",
"state",
"of",
"the",
"UI",
"after",
"everything",
"has",
"been",
"connected",
"."
] | python | train | 69.4 |
mrcagney/gtfstk | gtfstk/helpers.py | https://github.com/mrcagney/gtfstk/blob/c91494e6fefc02523889655a0dc92d1c0eee8d03/gtfstk/helpers.py#L87-L114 | def weekday_to_str(
weekday: Union[int, str], *, inverse: bool = False
) -> Union[int, str]:
"""
Given a weekday number (integer in the range 0, 1, ..., 6),
return its corresponding weekday name as a lowercase string.
Here 0 -> 'monday', 1 -> 'tuesday', and so on.
If ``inverse``, then perform th... | [
"def",
"weekday_to_str",
"(",
"weekday",
":",
"Union",
"[",
"int",
",",
"str",
"]",
",",
"*",
",",
"inverse",
":",
"bool",
"=",
"False",
")",
"->",
"Union",
"[",
"int",
",",
"str",
"]",
":",
"s",
"=",
"[",
"\"monday\"",
",",
"\"tuesday\"",
",",
"... | Given a weekday number (integer in the range 0, 1, ..., 6),
return its corresponding weekday name as a lowercase string.
Here 0 -> 'monday', 1 -> 'tuesday', and so on.
If ``inverse``, then perform the inverse operation. | [
"Given",
"a",
"weekday",
"number",
"(",
"integer",
"in",
"the",
"range",
"0",
"1",
"...",
"6",
")",
"return",
"its",
"corresponding",
"weekday",
"name",
"as",
"a",
"lowercase",
"string",
".",
"Here",
"0",
"-",
">",
"monday",
"1",
"-",
">",
"tuesday",
... | python | train | 23.678571 |
mwhooker/jsonselect | jsonselect/jsonselect.py | https://github.com/mwhooker/jsonselect/blob/c64aa9ea930de0344797ff87b04c753c8fc096a6/jsonselect/jsonselect.py#L172-L223 | def selector_production(self, tokens):
"""Production for a full selector."""
validators = []
# the following productions should return predicate functions.
if self.peek(tokens, 'type'):
type_ = self.match(tokens, 'type')
validators.append(self.type_production(ty... | [
"def",
"selector_production",
"(",
"self",
",",
"tokens",
")",
":",
"validators",
"=",
"[",
"]",
"# the following productions should return predicate functions.",
"if",
"self",
".",
"peek",
"(",
"tokens",
",",
"'type'",
")",
":",
"type_",
"=",
"self",
".",
"matc... | Production for a full selector. | [
"Production",
"for",
"a",
"full",
"selector",
"."
] | python | test | 37.942308 |
pypa/setuptools | setuptools/command/egg_info.py | https://github.com/pypa/setuptools/blob/83c667e0b2a98193851c07115d1af65011ed0fb6/setuptools/command/egg_info.py#L598-L608 | def write_file(filename, contents):
"""Create a file with the specified name and write 'contents' (a
sequence of strings without line terminators) to it.
"""
contents = "\n".join(contents)
# assuming the contents has been vetted for utf-8 encoding
contents = contents.encode("utf-8")
with o... | [
"def",
"write_file",
"(",
"filename",
",",
"contents",
")",
":",
"contents",
"=",
"\"\\n\"",
".",
"join",
"(",
"contents",
")",
"# assuming the contents has been vetted for utf-8 encoding",
"contents",
"=",
"contents",
".",
"encode",
"(",
"\"utf-8\"",
")",
"with",
... | Create a file with the specified name and write 'contents' (a
sequence of strings without line terminators) to it. | [
"Create",
"a",
"file",
"with",
"the",
"specified",
"name",
"and",
"write",
"contents",
"(",
"a",
"sequence",
"of",
"strings",
"without",
"line",
"terminators",
")",
"to",
"it",
"."
] | python | train | 36.181818 |
gem/oq-engine | openquake/hazardlib/geo/surface/base.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/base.py#L268-L280 | def get_top_edge_depth(self):
"""
Return minimum depth of surface's top edge.
:returns:
Float value, the vertical distance between the earth surface
and the shallowest point in surface's top edge in km.
"""
top_edge = self.mesh[0:1]
if top_edge.de... | [
"def",
"get_top_edge_depth",
"(",
"self",
")",
":",
"top_edge",
"=",
"self",
".",
"mesh",
"[",
"0",
":",
"1",
"]",
"if",
"top_edge",
".",
"depths",
"is",
"None",
":",
"return",
"0",
"else",
":",
"return",
"numpy",
".",
"min",
"(",
"top_edge",
".",
... | Return minimum depth of surface's top edge.
:returns:
Float value, the vertical distance between the earth surface
and the shallowest point in surface's top edge in km. | [
"Return",
"minimum",
"depth",
"of",
"surface",
"s",
"top",
"edge",
"."
] | python | train | 30.923077 |
rigetti/pyquil | pyquil/quil.py | https://github.com/rigetti/pyquil/blob/ec98e453084b0037d69d8c3245f6822a5422593d/pyquil/quil.py#L318-L345 | def measure_all(self, *qubit_reg_pairs):
"""
Measures many qubits into their specified classical bits, in the order
they were entered. If no qubit/register pairs are provided, measure all qubits present in
the program into classical addresses of the same index.
:param Tuple qubi... | [
"def",
"measure_all",
"(",
"self",
",",
"*",
"qubit_reg_pairs",
")",
":",
"if",
"qubit_reg_pairs",
"==",
"(",
")",
":",
"qubit_inds",
"=",
"self",
".",
"get_qubits",
"(",
"indices",
"=",
"True",
")",
"if",
"len",
"(",
"qubit_inds",
")",
"==",
"0",
":",... | Measures many qubits into their specified classical bits, in the order
they were entered. If no qubit/register pairs are provided, measure all qubits present in
the program into classical addresses of the same index.
:param Tuple qubit_reg_pairs: Tuples of qubit indices paired with classical bi... | [
"Measures",
"many",
"qubits",
"into",
"their",
"specified",
"classical",
"bits",
"in",
"the",
"order",
"they",
"were",
"entered",
".",
"If",
"no",
"qubit",
"/",
"register",
"pairs",
"are",
"provided",
"measure",
"all",
"qubits",
"present",
"in",
"the",
"prog... | python | train | 37.857143 |
pgjones/quart | quart/app.py | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L354-L373 | async def update_template_context(self, context: dict) -> None:
"""Update the provided template context.
This adds additional context from the various template context
processors.
Arguments:
context: The context to update (mutate).
"""
processors = self.temp... | [
"async",
"def",
"update_template_context",
"(",
"self",
",",
"context",
":",
"dict",
")",
"->",
"None",
":",
"processors",
"=",
"self",
".",
"template_context_processors",
"[",
"None",
"]",
"if",
"has_request_context",
"(",
")",
":",
"blueprint",
"=",
"_reques... | Update the provided template context.
This adds additional context from the various template context
processors.
Arguments:
context: The context to update (mutate). | [
"Update",
"the",
"provided",
"template",
"context",
"."
] | python | train | 42.95 |
LCAV/pylocus | pylocus/opt_space.py | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/opt_space.py#L242-L257 | def getoptT(X, W, Y, Z, S, M_E, E, m0, rho):
''' Perform line search
'''
iter_max = 20
norm2WZ = np.linalg.norm(W, ord='fro')**2 + np.linalg.norm(Z, ord='fro')**2
f = np.zeros(iter_max + 1)
f[0] = F_t(X, Y, S, M_E, E, m0, rho)
t = -1e-1
for i in range(iter_max):
f[i + ... | [
"def",
"getoptT",
"(",
"X",
",",
"W",
",",
"Y",
",",
"Z",
",",
"S",
",",
"M_E",
",",
"E",
",",
"m0",
",",
"rho",
")",
":",
"iter_max",
"=",
"20",
"norm2WZ",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"W",
",",
"ord",
"=",
"'fro'",
")",
"... | Perform line search | [
"Perform",
"line",
"search"
] | python | train | 28.6875 |
tanghaibao/jcvi | jcvi/variation/str.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/variation/str.py#L1102-L1133 | def liftover(args):
"""
%prog liftover lobstr_v3.0.2_hg38_ref.bed hg38.upper.fa
LiftOver CODIS/Y-STR markers.
"""
p = OptionParser(liftover.__doc__)
p.add_option("--checkvalid", default=False, action="store_true",
help="Check minscore, period and length")
opts, args = p.pars... | [
"def",
"liftover",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"liftover",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--checkvalid\"",
",",
"default",
"=",
"False",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Check minsco... | %prog liftover lobstr_v3.0.2_hg38_ref.bed hg38.upper.fa
LiftOver CODIS/Y-STR markers. | [
"%prog",
"liftover",
"lobstr_v3",
".",
"0",
".",
"2_hg38_ref",
".",
"bed",
"hg38",
".",
"upper",
".",
"fa"
] | python | train | 29.21875 |
DerMitch/fritzbox-smarthome | fritzhome/__main__.py | https://github.com/DerMitch/fritzbox-smarthome/blob/84cbd7c1b33e6256add041b0395ff5fccc01f103/fritzhome/__main__.py#L40-L62 | def actors(context):
"""Display a list of actors"""
fritz = context.obj
fritz.login()
for actor in fritz.get_actors():
click.echo("{} ({} {}; AIN {} )".format(
actor.name,
actor.manufacturer,
actor.productname,
actor.actor_id,
))
i... | [
"def",
"actors",
"(",
"context",
")",
":",
"fritz",
"=",
"context",
".",
"obj",
"fritz",
".",
"login",
"(",
")",
"for",
"actor",
"in",
"fritz",
".",
"get_actors",
"(",
")",
":",
"click",
".",
"echo",
"(",
"\"{} ({} {}; AIN {} )\"",
".",
"format",
"(",
... | Display a list of actors | [
"Display",
"a",
"list",
"of",
"actors"
] | python | train | 30.217391 |
insomnia-lab/libreant | archivant/archivant.py | https://github.com/insomnia-lab/libreant/blob/55d529435baf4c05a86b8341899e9f5e14e50245/archivant/archivant.py#L241-L292 | def insert_volume(self, metadata, attachments=[]):
'''Insert a new volume
Returns the ID of the added volume
`metadata` must be a dict containg metadata of the volume::
{
"_language" : "it", # language of the metadata
"key1" : "value1", # attribute
... | [
"def",
"insert_volume",
"(",
"self",
",",
"metadata",
",",
"attachments",
"=",
"[",
"]",
")",
":",
"log",
".",
"debug",
"(",
"\"adding new volume:\\n\\tdata: {}\\n\\tfiles: {}\"",
".",
"format",
"(",
"metadata",
",",
"attachments",
")",
")",
"requiredFields",
"=... | Insert a new volume
Returns the ID of the added volume
`metadata` must be a dict containg metadata of the volume::
{
"_language" : "it", # language of the metadata
"key1" : "value1", # attribute
"key2" : "value2",
...
... | [
"Insert",
"a",
"new",
"volume"
] | python | train | 35.576923 |
coin-or/GiMPy | src/gimpy/tree.py | https://github.com/coin-or/GiMPy/blob/51853122a50eb6019d06bbdedbfc396a833b5a22/src/gimpy/tree.py#L228-L245 | def add_left_child(self, n, parent, **attrs):
'''
API: add_left_child(self, n, parent, **attrs)
Description:
Adds left child n to node parent.
Pre:
Left child of parent should not exist.
Input:
n: Node name.
parent: Parent node name... | [
"def",
"add_left_child",
"(",
"self",
",",
"n",
",",
"parent",
",",
"*",
"*",
"attrs",
")",
":",
"if",
"self",
".",
"get_left_child",
"(",
"parent",
")",
"is",
"not",
"None",
":",
"msg",
"=",
"\"Right child already exists for node \"",
"+",
"str",
"(",
"... | API: add_left_child(self, n, parent, **attrs)
Description:
Adds left child n to node parent.
Pre:
Left child of parent should not exist.
Input:
n: Node name.
parent: Parent node name.
attrs: Attributes of node n. | [
"API",
":",
"add_left_child",
"(",
"self",
"n",
"parent",
"**",
"attrs",
")",
"Description",
":",
"Adds",
"left",
"child",
"n",
"to",
"node",
"parent",
".",
"Pre",
":",
"Left",
"child",
"of",
"parent",
"should",
"not",
"exist",
".",
"Input",
":",
"n",
... | python | train | 35.388889 |
guaix-ucm/numina | numina/modeling/sumofgauss.py | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/modeling/sumofgauss.py#L14-L56 | def sum_of_gaussian_factory(N):
"""Return a model of the sum of N Gaussians and a constant background."""
name = "SumNGauss%d" % N
attr = {}
# parameters
for i in range(N):
key = "amplitude_%d" % i
attr[key] = Parameter(key)
key = "center_%d" % i
attr[key] = Paramet... | [
"def",
"sum_of_gaussian_factory",
"(",
"N",
")",
":",
"name",
"=",
"\"SumNGauss%d\"",
"%",
"N",
"attr",
"=",
"{",
"}",
"# parameters",
"for",
"i",
"in",
"range",
"(",
"N",
")",
":",
"key",
"=",
"\"amplitude_%d\"",
"%",
"i",
"attr",
"[",
"key",
"]",
"... | Return a model of the sum of N Gaussians and a constant background. | [
"Return",
"a",
"model",
"of",
"the",
"sum",
"of",
"N",
"Gaussians",
"and",
"a",
"constant",
"background",
"."
] | python | train | 31.116279 |
saltstack/salt | salt/states/sysctl.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/sysctl.py#L33-L131 | def present(name, value, config=None):
'''
Ensure that the named sysctl value is set in memory and persisted to the
named configuration file. The default sysctl configuration file is
/etc/sysctl.conf
name
The name of the sysctl value to edit
value
The sysctl value to apply
... | [
"def",
"present",
"(",
"name",
",",
"value",
",",
"config",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'changes'",
":",
"{",
"}",
",",
"'comment'",
":",
"''",
"}",
"if",
"config",
"is",
"Non... | Ensure that the named sysctl value is set in memory and persisted to the
named configuration file. The default sysctl configuration file is
/etc/sysctl.conf
name
The name of the sysctl value to edit
value
The sysctl value to apply
config
The location of the sysctl configur... | [
"Ensure",
"that",
"the",
"named",
"sysctl",
"value",
"is",
"set",
"in",
"memory",
"and",
"persisted",
"to",
"the",
"named",
"configuration",
"file",
".",
"The",
"default",
"sysctl",
"configuration",
"file",
"is",
"/",
"etc",
"/",
"sysctl",
".",
"conf"
] | python | train | 35.767677 |
brmscheiner/ideogram | ideogram/writer.py | https://github.com/brmscheiner/ideogram/blob/422bf566c51fd56f7bbb6e75b16d18d52b4c7568/ideogram/writer.py#L179-L196 | def tagAttributes_while(fdef_master_list,root):
'''Tag each node under root with the appropriate depth. '''
depth = 0
current = root
untagged_nodes = [root]
while untagged_nodes:
current = untagged_nodes.pop()
for x in fdef_master_list:
if jsName(x.path,x.name) == current... | [
"def",
"tagAttributes_while",
"(",
"fdef_master_list",
",",
"root",
")",
":",
"depth",
"=",
"0",
"current",
"=",
"root",
"untagged_nodes",
"=",
"[",
"root",
"]",
"while",
"untagged_nodes",
":",
"current",
"=",
"untagged_nodes",
".",
"pop",
"(",
")",
"for",
... | Tag each node under root with the appropriate depth. | [
"Tag",
"each",
"node",
"under",
"root",
"with",
"the",
"appropriate",
"depth",
"."
] | python | train | 34.055556 |
javipalanca/spade | spade/behaviour.py | https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/behaviour.py#L133-L144 | def kill(self, exit_code: Any = None):
"""
Stops the behaviour
Args:
exit_code (object, optional): the exit code of the behaviour (Default value = None)
"""
self._force_kill.set()
if exit_code is not None:
self._exit_code = exit_code
logger... | [
"def",
"kill",
"(",
"self",
",",
"exit_code",
":",
"Any",
"=",
"None",
")",
":",
"self",
".",
"_force_kill",
".",
"set",
"(",
")",
"if",
"exit_code",
"is",
"not",
"None",
":",
"self",
".",
"_exit_code",
"=",
"exit_code",
"logger",
".",
"info",
"(",
... | Stops the behaviour
Args:
exit_code (object, optional): the exit code of the behaviour (Default value = None) | [
"Stops",
"the",
"behaviour"
] | python | train | 31.833333 |
weld-project/weld | python/numpy/weldnumpy/weldnumpy.py | https://github.com/weld-project/weld/blob/8ddd6db6b28878bef0892da44b1d2002b564389c/python/numpy/weldnumpy/weldnumpy.py#L44-L53 | def get_supported_binary_ops():
'''
Returns a dictionary of the Weld supported binary ops, with values being their Weld symbol.
'''
binary_ops = {}
binary_ops[np.add.__name__] = '+'
binary_ops[np.subtract.__name__] = '-'
binary_ops[np.multiply.__name__] = '*'
binary_ops[np.divide.__name_... | [
"def",
"get_supported_binary_ops",
"(",
")",
":",
"binary_ops",
"=",
"{",
"}",
"binary_ops",
"[",
"np",
".",
"add",
".",
"__name__",
"]",
"=",
"'+'",
"binary_ops",
"[",
"np",
".",
"subtract",
".",
"__name__",
"]",
"=",
"'-'",
"binary_ops",
"[",
"np",
"... | Returns a dictionary of the Weld supported binary ops, with values being their Weld symbol. | [
"Returns",
"a",
"dictionary",
"of",
"the",
"Weld",
"supported",
"binary",
"ops",
"with",
"values",
"being",
"their",
"Weld",
"symbol",
"."
] | python | train | 34.1 |
observermedia/django-wordpress-rest | wordpress/loading.py | https://github.com/observermedia/django-wordpress-rest/blob/f0d96891d8ac5a69c8ba90e044876e756fad1bfe/wordpress/loading.py#L677-L690 | def process_post_categories(self, bulk_mode, api_post, post_categories):
"""
Create or update Categories related to a post.
:param bulk_mode: If True, minimize db operations by bulk creating post objects
:param api_post: the API data for the post
:param post_categories: a mappin... | [
"def",
"process_post_categories",
"(",
"self",
",",
"bulk_mode",
",",
"api_post",
",",
"post_categories",
")",
":",
"post_categories",
"[",
"api_post",
"[",
"\"ID\"",
"]",
"]",
"=",
"[",
"]",
"for",
"api_category",
"in",
"six",
".",
"itervalues",
"(",
"api_p... | Create or update Categories related to a post.
:param bulk_mode: If True, minimize db operations by bulk creating post objects
:param api_post: the API data for the post
:param post_categories: a mapping of Categories keyed by post ID
:return: None | [
"Create",
"or",
"update",
"Categories",
"related",
"to",
"a",
"post",
"."
] | python | train | 46.5 |
loli/medpy | medpy/features/intensity.py | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/features/intensity.py#L705-L724 | def _extract_centerdistance(image, mask = slice(None), voxelspacing = None):
"""
Internal, single-image version of `centerdistance`.
"""
image = numpy.array(image, copy=False)
if None == voxelspacing:
voxelspacing = [1.] * image.ndim
# get image center and an array holding ... | [
"def",
"_extract_centerdistance",
"(",
"image",
",",
"mask",
"=",
"slice",
"(",
"None",
")",
",",
"voxelspacing",
"=",
"None",
")",
":",
"image",
"=",
"numpy",
".",
"array",
"(",
"image",
",",
"copy",
"=",
"False",
")",
"if",
"None",
"==",
"voxelspacin... | Internal, single-image version of `centerdistance`. | [
"Internal",
"single",
"-",
"image",
"version",
"of",
"centerdistance",
"."
] | python | train | 38 |
tensorpack/tensorpack | tensorpack/tfutils/summary.py | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/summary.py#L41-L53 | def create_scalar_summary(name, v):
"""
Args:
name (str):
v (float): scalar value
Returns:
tf.Summary: a tf.Summary object with name and simple scalar value v.
"""
assert isinstance(name, six.string_types), type(name)
v = float(v)
s = tf.Summary()
s.value.add(tag=... | [
"def",
"create_scalar_summary",
"(",
"name",
",",
"v",
")",
":",
"assert",
"isinstance",
"(",
"name",
",",
"six",
".",
"string_types",
")",
",",
"type",
"(",
"name",
")",
"v",
"=",
"float",
"(",
"v",
")",
"s",
"=",
"tf",
".",
"Summary",
"(",
")",
... | Args:
name (str):
v (float): scalar value
Returns:
tf.Summary: a tf.Summary object with name and simple scalar value v. | [
"Args",
":",
"name",
"(",
"str",
")",
":",
"v",
"(",
"float",
")",
":",
"scalar",
"value",
"Returns",
":",
"tf",
".",
"Summary",
":",
"a",
"tf",
".",
"Summary",
"object",
"with",
"name",
"and",
"simple",
"scalar",
"value",
"v",
"."
] | python | train | 26.307692 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L4450-L4541 | def geotiff_tags(self):
"""Return consolidated metadata from GeoTIFF tags as dict."""
if not self.is_geotiff:
return None
tags = self.tags
gkd = tags['GeoKeyDirectoryTag'].value
if gkd[0] != 1:
log.warning('GeoTIFF tags: invalid GeoKeyDirectoryTag')
... | [
"def",
"geotiff_tags",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_geotiff",
":",
"return",
"None",
"tags",
"=",
"self",
".",
"tags",
"gkd",
"=",
"tags",
"[",
"'GeoKeyDirectoryTag'",
"]",
".",
"value",
"if",
"gkd",
"[",
"0",
"]",
"!=",
"1",
... | Return consolidated metadata from GeoTIFF tags as dict. | [
"Return",
"consolidated",
"metadata",
"from",
"GeoTIFF",
"tags",
"as",
"dict",
"."
] | python | train | 39.728261 |
quantmind/pulsar | pulsar/apps/wsgi/middleware.py | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/middleware.py#L61-L71 | def clean_path_middleware(environ, start_response=None):
'''Clean url from double slashes and redirect if needed.'''
path = environ['PATH_INFO']
if path and '//' in path:
url = re.sub("/+", '/', path)
if not url.startswith('/'):
url = '/%s' % url
qs = environ['QUERY_STRIN... | [
"def",
"clean_path_middleware",
"(",
"environ",
",",
"start_response",
"=",
"None",
")",
":",
"path",
"=",
"environ",
"[",
"'PATH_INFO'",
"]",
"if",
"path",
"and",
"'//'",
"in",
"path",
":",
"url",
"=",
"re",
".",
"sub",
"(",
"\"/+\"",
",",
"'/'",
",",... | Clean url from double slashes and redirect if needed. | [
"Clean",
"url",
"from",
"double",
"slashes",
"and",
"redirect",
"if",
"needed",
"."
] | python | train | 36.181818 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.