repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
kyegupov/py-unrar2 | UnRAR2/windows.py | https://github.com/kyegupov/py-unrar2/blob/186a4c1feb9ef3d96a2331f8fb3ebf88036e15e5/UnRAR2/windows.py#L150-L162 | def DosDateTimeToTimeTuple(dosDateTime):
"""Convert an MS-DOS format date time to a Python time tuple.
"""
dos_date = dosDateTime >> 16
dos_time = dosDateTime & 0xffff
day = dos_date & 0x1f
month = (dos_date >> 5) & 0xf
year = 1980 + (dos_date >> 9)
second = 2 * (dos_time & 0x1f)
min... | [
"def",
"DosDateTimeToTimeTuple",
"(",
"dosDateTime",
")",
":",
"dos_date",
"=",
"dosDateTime",
">>",
"16",
"dos_time",
"=",
"dosDateTime",
"&",
"0xffff",
"day",
"=",
"dos_date",
"&",
"0x1f",
"month",
"=",
"(",
"dos_date",
">>",
"5",
")",
"&",
"0xf",
"year"... | Convert an MS-DOS format date time to a Python time tuple. | [
"Convert",
"an",
"MS",
"-",
"DOS",
"format",
"date",
"time",
"to",
"a",
"Python",
"time",
"tuple",
"."
] | python | train |
quizl/quizler | quizler/models.py | https://github.com/quizl/quizler/blob/44b3fd91f7074e7013ffde8147455f45ebdccc46/quizler/models.py#L13-L27 | def from_dict(raw_data):
"""Create Image from raw dictionary data."""
url = None
width = None
height = None
try:
url = raw_data['url']
width = raw_data['width']
height = raw_data['height']
except KeyError:
raise ValueError('... | [
"def",
"from_dict",
"(",
"raw_data",
")",
":",
"url",
"=",
"None",
"width",
"=",
"None",
"height",
"=",
"None",
"try",
":",
"url",
"=",
"raw_data",
"[",
"'url'",
"]",
"width",
"=",
"raw_data",
"[",
"'width'",
"]",
"height",
"=",
"raw_data",
"[",
"'he... | Create Image from raw dictionary data. | [
"Create",
"Image",
"from",
"raw",
"dictionary",
"data",
"."
] | python | train |
xflr6/concepts | concepts/definitions.py | https://github.com/xflr6/concepts/blob/2801b27b05fa02cccee7d549451810ffcbf5c942/concepts/definitions.py#L350-L354 | def add_object(self, obj, properties=()):
"""Add an object to the definition and add ``properties`` as related."""
self._objects.add(obj)
self._properties |= properties
self._pairs.update((obj, p) for p in properties) | [
"def",
"add_object",
"(",
"self",
",",
"obj",
",",
"properties",
"=",
"(",
")",
")",
":",
"self",
".",
"_objects",
".",
"add",
"(",
"obj",
")",
"self",
".",
"_properties",
"|=",
"properties",
"self",
".",
"_pairs",
".",
"update",
"(",
"(",
"obj",
"... | Add an object to the definition and add ``properties`` as related. | [
"Add",
"an",
"object",
"to",
"the",
"definition",
"and",
"add",
"properties",
"as",
"related",
"."
] | python | train |
moonso/vcftoolbox | vcftoolbox/parse_variant.py | https://github.com/moonso/vcftoolbox/blob/438fb1d85a83812c389774b94802eb5921c89e3a/vcftoolbox/parse_variant.py#L113-L135 | def get_snpeff_info(snpeff_string, snpeff_header):
"""Make the vep annotations into a dictionaries
A snpeff dictionary will have the snpeff column names as keys and
the vep annotations as values.
The dictionaries are stored in a list.
One dictionary for each transcript.
... | [
"def",
"get_snpeff_info",
"(",
"snpeff_string",
",",
"snpeff_header",
")",
":",
"snpeff_annotations",
"=",
"[",
"dict",
"(",
"zip",
"(",
"snpeff_header",
",",
"snpeff_annotation",
".",
"split",
"(",
"'|'",
")",
")",
")",
"for",
"snpeff_annotation",
"in",
"snpe... | Make the vep annotations into a dictionaries
A snpeff dictionary will have the snpeff column names as keys and
the vep annotations as values.
The dictionaries are stored in a list.
One dictionary for each transcript.
Args:
snpeff_string (string): A string with... | [
"Make",
"the",
"vep",
"annotations",
"into",
"a",
"dictionaries",
"A",
"snpeff",
"dictionary",
"will",
"have",
"the",
"snpeff",
"column",
"names",
"as",
"keys",
"and",
"the",
"vep",
"annotations",
"as",
"values",
".",
"The",
"dictionaries",
"are",
"stored",
... | python | train |
scanny/python-pptx | pptx/action.py | https://github.com/scanny/python-pptx/blob/d6ab8234f8b03953d2f831ff9394b1852db34130/pptx/action.py#L242-L253 | def _remove_hlink(self):
"""
Remove the a:hlinkClick or a:hlinkHover element, including dropping
any relationship it might have.
"""
hlink = self._hlink
if hlink is None:
return
rId = hlink.rId
if rId:
self.part.drop_rel(rId)
... | [
"def",
"_remove_hlink",
"(",
"self",
")",
":",
"hlink",
"=",
"self",
".",
"_hlink",
"if",
"hlink",
"is",
"None",
":",
"return",
"rId",
"=",
"hlink",
".",
"rId",
"if",
"rId",
":",
"self",
".",
"part",
".",
"drop_rel",
"(",
"rId",
")",
"self",
".",
... | Remove the a:hlinkClick or a:hlinkHover element, including dropping
any relationship it might have. | [
"Remove",
"the",
"a",
":",
"hlinkClick",
"or",
"a",
":",
"hlinkHover",
"element",
"including",
"dropping",
"any",
"relationship",
"it",
"might",
"have",
"."
] | python | train |
CZ-NIC/yangson | yangson/instance.py | https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/instance.py#L634-L640 | def update(self, value: Union[RawValue, Value],
raw: bool = False) -> "ArrayEntry":
"""Update the receiver's value.
This method overrides the superclass method.
"""
return super().update(self._cook_value(value, raw), False) | [
"def",
"update",
"(",
"self",
",",
"value",
":",
"Union",
"[",
"RawValue",
",",
"Value",
"]",
",",
"raw",
":",
"bool",
"=",
"False",
")",
"->",
"\"ArrayEntry\"",
":",
"return",
"super",
"(",
")",
".",
"update",
"(",
"self",
".",
"_cook_value",
"(",
... | Update the receiver's value.
This method overrides the superclass method. | [
"Update",
"the",
"receiver",
"s",
"value",
"."
] | python | train |
ff0000/scarlet | scarlet/cms/item.py | https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cms/item.py#L684-L725 | def post(self, request, *args, **kwargs):
"""
Method for handling POST requests.
Expects the 'vid' of the version to act on
to be passed as in the POST variable 'version'.
If a POST variable 'revert' is present this will
call the revert method and then return a 'render
... | [
"def",
"post",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"versions",
"=",
"self",
".",
"_get_versions",
"(",
")",
"url",
"=",
"self",
".",
"get_done_url",
"(",
")",
"msg",
"=",
"None",
"try",
":",
"vid",
"=... | Method for handling POST requests.
Expects the 'vid' of the version to act on
to be passed as in the POST variable 'version'.
If a POST variable 'revert' is present this will
call the revert method and then return a 'render
redirect' to the result of the `get_done_url` method.
... | [
"Method",
"for",
"handling",
"POST",
"requests",
".",
"Expects",
"the",
"vid",
"of",
"the",
"version",
"to",
"act",
"on",
"to",
"be",
"passed",
"as",
"in",
"the",
"POST",
"variable",
"version",
"."
] | python | train |
BlackEarth/bxml | bxml/xml.py | https://github.com/BlackEarth/bxml/blob/8fbea5dad7fadc7b854ddbeff6ecfb55aaceeb77/bxml/xml.py#L850-L890 | def fragment_nesting(cls, elem1, tag2, namespaces=None):
"""for elem1 containing elements with tag2,
fragment elem1 into elems that are adjacent to and nested within tag2"""
elems2 = elem1.xpath("child::%s" % tag2, namespaces=namespaces)
while len(elems2) > 0:
elem2 = e... | [
"def",
"fragment_nesting",
"(",
"cls",
",",
"elem1",
",",
"tag2",
",",
"namespaces",
"=",
"None",
")",
":",
"elems2",
"=",
"elem1",
".",
"xpath",
"(",
"\"child::%s\"",
"%",
"tag2",
",",
"namespaces",
"=",
"namespaces",
")",
"while",
"len",
"(",
"elems2",... | for elem1 containing elements with tag2,
fragment elem1 into elems that are adjacent to and nested within tag2 | [
"for",
"elem1",
"containing",
"elements",
"with",
"tag2",
"fragment",
"elem1",
"into",
"elems",
"that",
"are",
"adjacent",
"to",
"and",
"nested",
"within",
"tag2"
] | python | train |
saltstack/salt | salt/modules/virt.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L380-L413 | def _get_nics(dom):
'''
Get domain network interfaces from a libvirt domain object.
'''
nics = {}
doc = ElementTree.fromstring(dom.XMLDesc(0))
for iface_node in doc.findall('devices/interface'):
nic = {}
nic['type'] = iface_node.get('type')
for v_node in iface_node:
... | [
"def",
"_get_nics",
"(",
"dom",
")",
":",
"nics",
"=",
"{",
"}",
"doc",
"=",
"ElementTree",
".",
"fromstring",
"(",
"dom",
".",
"XMLDesc",
"(",
"0",
")",
")",
"for",
"iface_node",
"in",
"doc",
".",
"findall",
"(",
"'devices/interface'",
")",
":",
"ni... | Get domain network interfaces from a libvirt domain object. | [
"Get",
"domain",
"network",
"interfaces",
"from",
"a",
"libvirt",
"domain",
"object",
"."
] | python | train |
saltstack/salt | salt/modules/capirca_acl.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/capirca_acl.py#L473-L511 | def _get_term_object(filter_name,
term_name,
pillar_key='acl',
pillarenv=None,
saltenv=None,
merge_pillar=True,
**term_fields):
'''
Return an instance of the ``_Term`` class given the te... | [
"def",
"_get_term_object",
"(",
"filter_name",
",",
"term_name",
",",
"pillar_key",
"=",
"'acl'",
",",
"pillarenv",
"=",
"None",
",",
"saltenv",
"=",
"None",
",",
"merge_pillar",
"=",
"True",
",",
"*",
"*",
"term_fields",
")",
":",
"log",
".",
"debug",
"... | Return an instance of the ``_Term`` class given the term options. | [
"Return",
"an",
"instance",
"of",
"the",
"_Term",
"class",
"given",
"the",
"term",
"options",
"."
] | python | train |
fastai/fastai | fastai/metrics.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/metrics.py#L46-L54 | def dice(input:Tensor, targs:Tensor, iou:bool=False)->Rank0Tensor:
"Dice coefficient metric for binary target. If iou=True, returns iou metric, classic for segmentation problems."
n = targs.shape[0]
input = input.argmax(dim=1).view(n,-1)
targs = targs.view(n,-1)
intersect = (input * targs).sum().flo... | [
"def",
"dice",
"(",
"input",
":",
"Tensor",
",",
"targs",
":",
"Tensor",
",",
"iou",
":",
"bool",
"=",
"False",
")",
"->",
"Rank0Tensor",
":",
"n",
"=",
"targs",
".",
"shape",
"[",
"0",
"]",
"input",
"=",
"input",
".",
"argmax",
"(",
"dim",
"=",
... | Dice coefficient metric for binary target. If iou=True, returns iou metric, classic for segmentation problems. | [
"Dice",
"coefficient",
"metric",
"for",
"binary",
"target",
".",
"If",
"iou",
"=",
"True",
"returns",
"iou",
"metric",
"classic",
"for",
"segmentation",
"problems",
"."
] | python | train |
Azure/azure-kusto-python | azure-kusto-data/azure/kusto/data/request.py | https://github.com/Azure/azure-kusto-python/blob/92466a2ae175d6353d1dee3496a02517b2a71a86/azure-kusto-data/azure/kusto/data/request.py#L328-L338 | def execute(self, database, query, properties=None):
"""Executes a query or management command.
:param str database: Database against query will be executed.
:param str query: Query to be executed.
:param azure.kusto.data.request.ClientRequestProperties properties: Optional additiona... | [
"def",
"execute",
"(",
"self",
",",
"database",
",",
"query",
",",
"properties",
"=",
"None",
")",
":",
"if",
"query",
".",
"startswith",
"(",
"\".\"",
")",
":",
"return",
"self",
".",
"execute_mgmt",
"(",
"database",
",",
"query",
",",
"properties",
"... | Executes a query or management command.
:param str database: Database against query will be executed.
:param str query: Query to be executed.
:param azure.kusto.data.request.ClientRequestProperties properties: Optional additional properties.
:return: Kusto response data set.
... | [
"Executes",
"a",
"query",
"or",
"management",
"command",
".",
":",
"param",
"str",
"database",
":",
"Database",
"against",
"query",
"will",
"be",
"executed",
".",
":",
"param",
"str",
"query",
":",
"Query",
"to",
"be",
"executed",
".",
":",
"param",
"azu... | python | train |
spacetelescope/synphot_refactor | synphot/spectrum.py | https://github.com/spacetelescope/synphot_refactor/blob/9c064f3cff0c41dd8acadc0f67c6350931275b9f/synphot/spectrum.py#L523-L549 | def barlam(self, wavelengths=None):
"""Calculate :ref:`mean log wavelength <synphot-formula-barlam>`.
Parameters
----------
wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None`
Wavelength values for sampling.
If not a Quantity, assumed to be in... | [
"def",
"barlam",
"(",
"self",
",",
"wavelengths",
"=",
"None",
")",
":",
"x",
"=",
"self",
".",
"_validate_wavelengths",
"(",
"wavelengths",
")",
".",
"value",
"y",
"=",
"self",
"(",
"x",
")",
".",
"value",
"num",
"=",
"np",
".",
"trapz",
"(",
"y",... | Calculate :ref:`mean log wavelength <synphot-formula-barlam>`.
Parameters
----------
wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None`
Wavelength values for sampling.
If not a Quantity, assumed to be in Angstrom.
If `None`, `waveset` is ... | [
"Calculate",
":",
"ref",
":",
"mean",
"log",
"wavelength",
"<synphot",
"-",
"formula",
"-",
"barlam",
">",
"."
] | python | train |
Cologler/fsoopify-python | fsoopify/nodes.py | https://github.com/Cologler/fsoopify-python/blob/83d45f16ae9abdea4fcc829373c32df501487dda/fsoopify/nodes.py#L317-L321 | def get_dirinfo(self, name: str):
'''
get a `DirectoryInfo` for a directory (without create actual directory).
'''
return DirectoryInfo(os.path.join(self._path, name)) | [
"def",
"get_dirinfo",
"(",
"self",
",",
"name",
":",
"str",
")",
":",
"return",
"DirectoryInfo",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_path",
",",
"name",
")",
")"
] | get a `DirectoryInfo` for a directory (without create actual directory). | [
"get",
"a",
"DirectoryInfo",
"for",
"a",
"directory",
"(",
"without",
"create",
"actual",
"directory",
")",
"."
] | python | train |
flaviogrossi/sockjs-cyclone | sockjs/cyclone/session.py | https://github.com/flaviogrossi/sockjs-cyclone/blob/d3ca053ec1aa1e85f652347bff562c2319be37a2/sockjs/cyclone/session.py#L310-L318 | def verify_state(self):
""" Verify if session was not yet opened. If it is, open it and call
connections C{connectionMade} """
# If we're in CONNECTING state - send 'o' message to the client
if self.state == SESSION_STATE.CONNECTING:
self.handler.send_pack(proto.CONNECT)
... | [
"def",
"verify_state",
"(",
"self",
")",
":",
"# If we're in CONNECTING state - send 'o' message to the client",
"if",
"self",
".",
"state",
"==",
"SESSION_STATE",
".",
"CONNECTING",
":",
"self",
".",
"handler",
".",
"send_pack",
"(",
"proto",
".",
"CONNECT",
")",
... | Verify if session was not yet opened. If it is, open it and call
connections C{connectionMade} | [
"Verify",
"if",
"session",
"was",
"not",
"yet",
"opened",
".",
"If",
"it",
"is",
"open",
"it",
"and",
"call",
"connections",
"C",
"{",
"connectionMade",
"}"
] | python | train |
gwastro/pycbc | pycbc/workflow/datafind.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/datafind.py#L665-L733 | def convert_cachelist_to_filelist(datafindcache_list):
"""
Take as input a list of glue.lal.Cache objects and return a pycbc FileList
containing all frames within those caches.
Parameters
-----------
datafindcache_list : list of glue.lal.Cache objects
The list of cache files to convert.... | [
"def",
"convert_cachelist_to_filelist",
"(",
"datafindcache_list",
")",
":",
"prev_file",
"=",
"None",
"prev_name",
"=",
"None",
"this_name",
"=",
"None",
"datafind_filelist",
"=",
"FileList",
"(",
"[",
"]",
")",
"for",
"cache",
"in",
"datafindcache_list",
":",
... | Take as input a list of glue.lal.Cache objects and return a pycbc FileList
containing all frames within those caches.
Parameters
-----------
datafindcache_list : list of glue.lal.Cache objects
The list of cache files to convert.
Returns
--------
datafind_filelist : FileList of fram... | [
"Take",
"as",
"input",
"a",
"list",
"of",
"glue",
".",
"lal",
".",
"Cache",
"objects",
"and",
"return",
"a",
"pycbc",
"FileList",
"containing",
"all",
"frames",
"within",
"those",
"caches",
"."
] | python | train |
Netflix-Skunkworks/historical | historical/security_group/collector.py | https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/security_group/collector.py#L135-L170 | def capture_update_records(records):
"""Writes all updated configuration info to DynamoDB"""
for rec in records:
data = cloudwatch.get_historical_base_info(rec)
group = describe_group(rec, cloudwatch.get_region(rec))
if len(group) > 1:
raise Exception(f'[X] Multiple groups f... | [
"def",
"capture_update_records",
"(",
"records",
")",
":",
"for",
"rec",
"in",
"records",
":",
"data",
"=",
"cloudwatch",
".",
"get_historical_base_info",
"(",
"rec",
")",
"group",
"=",
"describe_group",
"(",
"rec",
",",
"cloudwatch",
".",
"get_region",
"(",
... | Writes all updated configuration info to DynamoDB | [
"Writes",
"all",
"updated",
"configuration",
"info",
"to",
"DynamoDB"
] | python | train |
lrq3000/pyFileFixity | pyFileFixity/lib/profilers/visual/pympler/classtracker.py | https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/profilers/visual/pympler/classtracker.py#L232-L236 | def label(self):
"""Return timestamped label for this snapshot, or a raw timestamp."""
if not self.desc:
return "%.3fs" % self.timestamp
return "%s (%.3fs)" % (self.desc, self.timestamp) | [
"def",
"label",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"desc",
":",
"return",
"\"%.3fs\"",
"%",
"self",
".",
"timestamp",
"return",
"\"%s (%.3fs)\"",
"%",
"(",
"self",
".",
"desc",
",",
"self",
".",
"timestamp",
")"
] | Return timestamped label for this snapshot, or a raw timestamp. | [
"Return",
"timestamped",
"label",
"for",
"this",
"snapshot",
"or",
"a",
"raw",
"timestamp",
"."
] | python | train |
lk-geimfari/mimesis | mimesis/providers/code.py | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/code.py#L71-L86 | def ean(self, fmt: Optional[EANFormat] = None) -> str:
"""Generate EAN.
To change EAN format, pass parameter ``fmt`` with needed value of
the enum object :class:`~mimesis.enums.EANFormat`.
:param fmt: Format of EAN.
:return: EAN.
:raises NonEnumerableError: if fmt is no... | [
"def",
"ean",
"(",
"self",
",",
"fmt",
":",
"Optional",
"[",
"EANFormat",
"]",
"=",
"None",
")",
"->",
"str",
":",
"key",
"=",
"self",
".",
"_validate_enum",
"(",
"item",
"=",
"fmt",
",",
"enum",
"=",
"EANFormat",
",",
")",
"mask",
"=",
"EAN_MASKS"... | Generate EAN.
To change EAN format, pass parameter ``fmt`` with needed value of
the enum object :class:`~mimesis.enums.EANFormat`.
:param fmt: Format of EAN.
:return: EAN.
:raises NonEnumerableError: if fmt is not enum EANFormat. | [
"Generate",
"EAN",
"."
] | python | train |
reingart/gui2py | gui/component.py | https://github.com/reingart/gui2py/blob/aca0a05f6fcde55c94ad7cc058671a06608b01a4/gui/component.py#L1022-L1043 | def __tile_background(self, dc):
"make several copies of the background bitmap"
sz = self.wx_obj.GetClientSize()
bmp = self._bitmap.get_bits()
w = bmp.GetWidth()
h = bmp.GetHeight()
if isinstance(self, wx.ScrolledWindow):
# adjust for scrolled positio... | [
"def",
"__tile_background",
"(",
"self",
",",
"dc",
")",
":",
"sz",
"=",
"self",
".",
"wx_obj",
".",
"GetClientSize",
"(",
")",
"bmp",
"=",
"self",
".",
"_bitmap",
".",
"get_bits",
"(",
")",
"w",
"=",
"bmp",
".",
"GetWidth",
"(",
")",
"h",
"=",
"... | make several copies of the background bitmap | [
"make",
"several",
"copies",
"of",
"the",
"background",
"bitmap"
] | python | test |
juju/charm-helpers | charmhelpers/contrib/openstack/amulet/utils.py | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L660-L672 | def authenticate_swift_user(self, keystone, user, password, tenant):
"""Authenticates a regular user with swift api."""
self.log.debug('Authenticating swift user ({})...'.format(user))
ep = keystone.service_catalog.url_for(service_type='identity',
in... | [
"def",
"authenticate_swift_user",
"(",
"self",
",",
"keystone",
",",
"user",
",",
"password",
",",
"tenant",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Authenticating swift user ({})...'",
".",
"format",
"(",
"user",
")",
")",
"ep",
"=",
"keystone",
... | Authenticates a regular user with swift api. | [
"Authenticates",
"a",
"regular",
"user",
"with",
"swift",
"api",
"."
] | python | train |
rosenbrockc/fortpy | fortpy/interop/ftypes.py | https://github.com/rosenbrockc/fortpy/blob/1ed0757c52d549e41d9d44bdea68cb89529293a5/fortpy/interop/ftypes.py#L575-L600 | def _py_clean(parameter, tab):
"""Returns the code line to clean the output value of the specified parameter.
"""
if "out" in parameter.direction:
if parameter.D > 0:
if ":" in parameter.dimension and ("allocatable" in parameter.modifiers or
... | [
"def",
"_py_clean",
"(",
"parameter",
",",
"tab",
")",
":",
"if",
"\"out\"",
"in",
"parameter",
".",
"direction",
":",
"if",
"parameter",
".",
"D",
">",
"0",
":",
"if",
"\":\"",
"in",
"parameter",
".",
"dimension",
"and",
"(",
"\"allocatable\"",
"in",
... | Returns the code line to clean the output value of the specified parameter. | [
"Returns",
"the",
"code",
"line",
"to",
"clean",
"the",
"output",
"value",
"of",
"the",
"specified",
"parameter",
"."
] | python | train |
jf-parent/brome | brome/runner/ec2_instance.py | https://github.com/jf-parent/brome/blob/784f45d96b83b703dd2181cb59ca8ea777c2510e/brome/runner/ec2_instance.py#L306-L318 | def tear_down(self):
"""Tear down the instance
"""
import boto.ec2
if not self.browser_config.get('terminate'):
self.warning_log("Skipping terminate")
return
self.info_log("Tearing down...")
ec2 = boto.ec2.connect_to_region(self.browser_config.g... | [
"def",
"tear_down",
"(",
"self",
")",
":",
"import",
"boto",
".",
"ec2",
"if",
"not",
"self",
".",
"browser_config",
".",
"get",
"(",
"'terminate'",
")",
":",
"self",
".",
"warning_log",
"(",
"\"Skipping terminate\"",
")",
"return",
"self",
".",
"info_log"... | Tear down the instance | [
"Tear",
"down",
"the",
"instance"
] | python | train |
hobson/pug-dj | pug/dj/db.py | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L1343-L1370 | def django_object_from_row(row, model, field_names=None, ignore_fields=('id', 'pk'), ignore_related=True, strip=True, ignore_errors=True, verbosity=0):
"""Construct Django model instance from values provided in a python dict or Mapping
Args:
row (list or dict): Data (values of any type) to be assigned to... | [
"def",
"django_object_from_row",
"(",
"row",
",",
"model",
",",
"field_names",
"=",
"None",
",",
"ignore_fields",
"=",
"(",
"'id'",
",",
"'pk'",
")",
",",
"ignore_related",
"=",
"True",
",",
"strip",
"=",
"True",
",",
"ignore_errors",
"=",
"True",
",",
"... | Construct Django model instance from values provided in a python dict or Mapping
Args:
row (list or dict): Data (values of any type) to be assigned to fields in the Django object.
If `row` is a list, then the column names (header row) can be provided in `field_names`.
If `row` is a list and n... | [
"Construct",
"Django",
"model",
"instance",
"from",
"values",
"provided",
"in",
"a",
"python",
"dict",
"or",
"Mapping"
] | python | train |
hbldh/pyefd | pyefd.py | https://github.com/hbldh/pyefd/blob/5c4e880fd6e70e8077fc8c0be4eec9df5b9ee596/pyefd.py#L116-L136 | def calculate_dc_coefficients(contour):
"""Calculate the :math:`A_0` and :math:`C_0` coefficients of the elliptic Fourier series.
:param numpy.ndarray contour: A contour array of size ``[M x 2]``.
:return: The :math:`A_0` and :math:`C_0` coefficients.
:rtype: tuple
"""
dxy = np.diff(contour, a... | [
"def",
"calculate_dc_coefficients",
"(",
"contour",
")",
":",
"dxy",
"=",
"np",
".",
"diff",
"(",
"contour",
",",
"axis",
"=",
"0",
")",
"dt",
"=",
"np",
".",
"sqrt",
"(",
"(",
"dxy",
"**",
"2",
")",
".",
"sum",
"(",
"axis",
"=",
"1",
")",
")",... | Calculate the :math:`A_0` and :math:`C_0` coefficients of the elliptic Fourier series.
:param numpy.ndarray contour: A contour array of size ``[M x 2]``.
:return: The :math:`A_0` and :math:`C_0` coefficients.
:rtype: tuple | [
"Calculate",
"the",
":",
"math",
":",
"A_0",
"and",
":",
"math",
":",
"C_0",
"coefficients",
"of",
"the",
"elliptic",
"Fourier",
"series",
"."
] | python | train |
borntyping/python-colorlog | colorlog/logging.py | https://github.com/borntyping/python-colorlog/blob/d2be1e0e9bff0ceb288c6a6381a6d12cf550e1e7/colorlog/logging.py#L13-L24 | def basicConfig(**kwargs):
"""Call ``logging.basicConfig`` and override the formatter it creates."""
logging.basicConfig(**kwargs)
logging._acquireLock()
try:
stream = logging.root.handlers[0]
stream.setFormatter(
ColoredFormatter(
fmt=kwargs.get('format', BAS... | [
"def",
"basicConfig",
"(",
"*",
"*",
"kwargs",
")",
":",
"logging",
".",
"basicConfig",
"(",
"*",
"*",
"kwargs",
")",
"logging",
".",
"_acquireLock",
"(",
")",
"try",
":",
"stream",
"=",
"logging",
".",
"root",
".",
"handlers",
"[",
"0",
"]",
"stream... | Call ``logging.basicConfig`` and override the formatter it creates. | [
"Call",
"logging",
".",
"basicConfig",
"and",
"override",
"the",
"formatter",
"it",
"creates",
"."
] | python | train |
20tab/twentytab-tree | tree/views.py | https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/views.py#L26-L32 | def view_500(request, url=None):
"""
it returns a 500 http response
"""
res = render_to_response("500.html", context_instance=RequestContext(request))
res.status_code = 500
return res | [
"def",
"view_500",
"(",
"request",
",",
"url",
"=",
"None",
")",
":",
"res",
"=",
"render_to_response",
"(",
"\"500.html\"",
",",
"context_instance",
"=",
"RequestContext",
"(",
"request",
")",
")",
"res",
".",
"status_code",
"=",
"500",
"return",
"res"
] | it returns a 500 http response | [
"it",
"returns",
"a",
"500",
"http",
"response"
] | python | train |
squaresLab/BugZoo | bugzoo/core/fileline.py | https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/core/fileline.py#L160-L169 | def intersection(self, other: 'FileLineSet') -> 'FileLineSet':
"""
Returns a set of file lines that contains the intersection of the lines
within this set and a given set.
"""
assert isinstance(other, FileLineSet)
set_self = set(self)
set_other = set(other)
... | [
"def",
"intersection",
"(",
"self",
",",
"other",
":",
"'FileLineSet'",
")",
"->",
"'FileLineSet'",
":",
"assert",
"isinstance",
"(",
"other",
",",
"FileLineSet",
")",
"set_self",
"=",
"set",
"(",
"self",
")",
"set_other",
"=",
"set",
"(",
"other",
")",
... | Returns a set of file lines that contains the intersection of the lines
within this set and a given set. | [
"Returns",
"a",
"set",
"of",
"file",
"lines",
"that",
"contains",
"the",
"intersection",
"of",
"the",
"lines",
"within",
"this",
"set",
"and",
"a",
"given",
"set",
"."
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/utils/decoding.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/decoding.py#L843-L876 | def _get_sorted_inputs(filename, delimiter="\n"):
"""Returning inputs sorted according to decreasing length.
This causes inputs of similar lengths to be processed in the same batch,
facilitating early stopping for short sequences.
Longer sequences are sorted first so that if you're going to get OOMs,
you'll... | [
"def",
"_get_sorted_inputs",
"(",
"filename",
",",
"delimiter",
"=",
"\"\\n\"",
")",
":",
"tf",
".",
"logging",
".",
"info",
"(",
"\"Getting sorted inputs\"",
")",
"with",
"tf",
".",
"gfile",
".",
"Open",
"(",
"filename",
")",
"as",
"f",
":",
"text",
"="... | Returning inputs sorted according to decreasing length.
This causes inputs of similar lengths to be processed in the same batch,
facilitating early stopping for short sequences.
Longer sequences are sorted first so that if you're going to get OOMs,
you'll see it in the first batch.
Args:
filename: path... | [
"Returning",
"inputs",
"sorted",
"according",
"to",
"decreasing",
"length",
"."
] | python | train |
materialsproject/pymatgen-db | matgendb/creator.py | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/creator.py#L299-L395 | def post_process(self, dir_name, d):
"""
Simple post-processing for various files other than the vasprun.xml.
Called by generate_task_doc. Modify this if your runs have other
kinds of processing requirements.
Args:
dir_name:
The dir_name.
... | [
"def",
"post_process",
"(",
"self",
",",
"dir_name",
",",
"d",
")",
":",
"logger",
".",
"info",
"(",
"\"Post-processing dir:{}\"",
".",
"format",
"(",
"dir_name",
")",
")",
"fullpath",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"dir_name",
")",
"# VASP... | Simple post-processing for various files other than the vasprun.xml.
Called by generate_task_doc. Modify this if your runs have other
kinds of processing requirements.
Args:
dir_name:
The dir_name.
d:
Current doc generated. | [
"Simple",
"post",
"-",
"processing",
"for",
"various",
"files",
"other",
"than",
"the",
"vasprun",
".",
"xml",
".",
"Called",
"by",
"generate_task_doc",
".",
"Modify",
"this",
"if",
"your",
"runs",
"have",
"other",
"kinds",
"of",
"processing",
"requirements",
... | python | train |
log2timeline/plaso | plaso/analysis/manager.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/analysis/manager.py#L48-L71 | def GetAllPluginInformation(cls, show_all=True):
"""Retrieves a list of the registered analysis plugins.
Args:
show_all (Optional[bool]): True if all analysis plugin names should
be listed.
Returns:
list[tuple[str, str, str]]: the name, docstring and type string of each
ana... | [
"def",
"GetAllPluginInformation",
"(",
"cls",
",",
"show_all",
"=",
"True",
")",
":",
"results",
"=",
"[",
"]",
"for",
"plugin_class",
"in",
"iter",
"(",
"cls",
".",
"_plugin_classes",
".",
"values",
"(",
")",
")",
":",
"plugin_object",
"=",
"plugin_class"... | Retrieves a list of the registered analysis plugins.
Args:
show_all (Optional[bool]): True if all analysis plugin names should
be listed.
Returns:
list[tuple[str, str, str]]: the name, docstring and type string of each
analysis plugin in alphabetical order. | [
"Retrieves",
"a",
"list",
"of",
"the",
"registered",
"analysis",
"plugins",
"."
] | python | train |
ktbyers/netmiko | netmiko/vyos/vyos_ssh.py | https://github.com/ktbyers/netmiko/blob/54e6116c0b4664de2123081937e0a9a27bdfdfea/netmiko/vyos/vyos_ssh.py#L56-L88 | def commit(self, comment="", delay_factor=0.1):
"""
Commit the candidate configuration.
Commit the entered configuration. Raise an error and return the failure
if the commit fails.
default:
command_string = commit
comment:
command_string = commit c... | [
"def",
"commit",
"(",
"self",
",",
"comment",
"=",
"\"\"",
",",
"delay_factor",
"=",
"0.1",
")",
":",
"delay_factor",
"=",
"self",
".",
"select_delay_factor",
"(",
"delay_factor",
")",
"error_marker",
"=",
"[",
"\"Failed to generate committed config\"",
",",
"\"... | Commit the candidate configuration.
Commit the entered configuration. Raise an error and return the failure
if the commit fails.
default:
command_string = commit
comment:
command_string = commit comment <comment> | [
"Commit",
"the",
"candidate",
"configuration",
"."
] | python | train |
intel-analytics/BigDL | pyspark/bigdl/nn/layer.py | https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/nn/layer.py#L426-L438 | def predict_distributed(self, data_rdd, batch_size = -1):
"""
Model inference base on the given data.
You need to invoke collect() to trigger those action \
as the returning result is an RDD.
:param data_rdd: the data to be predict.
:param batch_size: total batch size of... | [
"def",
"predict_distributed",
"(",
"self",
",",
"data_rdd",
",",
"batch_size",
"=",
"-",
"1",
")",
":",
"result",
"=",
"callBigDlFunc",
"(",
"self",
".",
"bigdl_type",
",",
"\"modelPredictRDD\"",
",",
"self",
".",
"value",
",",
"data_rdd",
",",
"batch_size",... | Model inference base on the given data.
You need to invoke collect() to trigger those action \
as the returning result is an RDD.
:param data_rdd: the data to be predict.
:param batch_size: total batch size of prediction.
:return: An RDD represent the predict result. | [
"Model",
"inference",
"base",
"on",
"the",
"given",
"data",
".",
"You",
"need",
"to",
"invoke",
"collect",
"()",
"to",
"trigger",
"those",
"action",
"\\",
"as",
"the",
"returning",
"result",
"is",
"an",
"RDD",
"."
] | python | test |
limix/numpy-sugar | numpy_sugar/linalg/diag.py | https://github.com/limix/numpy-sugar/blob/4bdfa26913135c76ef3cd542a332f4e5861e948b/numpy_sugar/linalg/diag.py#L5-L26 | def trace2(A, B):
r"""Trace of :math:`\mathrm A \mathrm B^\intercal`.
Args:
A (array_like): Left-hand side.
B (array_like): Right-hand side.
Returns:
float: Trace of :math:`\mathrm A \mathrm B^\intercal`.
"""
A = asarray(A, float)
B = asarray(B, float)
layout_error... | [
"def",
"trace2",
"(",
"A",
",",
"B",
")",
":",
"A",
"=",
"asarray",
"(",
"A",
",",
"float",
")",
"B",
"=",
"asarray",
"(",
"B",
",",
"float",
")",
"layout_error",
"=",
"\"Wrong matrix layout.\"",
"if",
"not",
"(",
"len",
"(",
"A",
".",
"shape",
"... | r"""Trace of :math:`\mathrm A \mathrm B^\intercal`.
Args:
A (array_like): Left-hand side.
B (array_like): Right-hand side.
Returns:
float: Trace of :math:`\mathrm A \mathrm B^\intercal`. | [
"r",
"Trace",
"of",
":",
"math",
":",
"\\",
"mathrm",
"A",
"\\",
"mathrm",
"B^",
"\\",
"intercal",
"."
] | python | train |
Alignak-monitoring/alignak | alignak/misc/serialization.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/misc/serialization.py#L31-L78 | def serialize(obj, no_dump=False):
"""
Serialize an object.
Returns a dict containing an `_error` property if a MemoryError happens during the
object serialization. See #369.
:param obj: the object to serialize
:type obj: alignak.objects.item.Item | dict | list | str
:param no_dump: if Tru... | [
"def",
"serialize",
"(",
"obj",
",",
"no_dump",
"=",
"False",
")",
":",
"# print(\"Serialize (%s): %s\" % (no_dump, obj))",
"if",
"hasattr",
"(",
"obj",
",",
"\"serialize\"",
")",
"and",
"isinstance",
"(",
"obj",
".",
"serialize",
",",
"collections",
".",
"Calla... | Serialize an object.
Returns a dict containing an `_error` property if a MemoryError happens during the
object serialization. See #369.
:param obj: the object to serialize
:type obj: alignak.objects.item.Item | dict | list | str
:param no_dump: if True return dict, otherwise return a json
:typ... | [
"Serialize",
"an",
"object",
"."
] | python | train |
yakupadakli/python-unsplash | unsplash/auth.py | https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/auth.py#L83-L88 | def refresh_token(self):
"""
Refreshing the current expired access token
"""
self.token = self.oauth.refresh_token(self.access_token_url, refresh_token=self.get_refresh_token())
self.access_token = self.token.get("access_token") | [
"def",
"refresh_token",
"(",
"self",
")",
":",
"self",
".",
"token",
"=",
"self",
".",
"oauth",
".",
"refresh_token",
"(",
"self",
".",
"access_token_url",
",",
"refresh_token",
"=",
"self",
".",
"get_refresh_token",
"(",
")",
")",
"self",
".",
"access_tok... | Refreshing the current expired access token | [
"Refreshing",
"the",
"current",
"expired",
"access",
"token"
] | python | train |
HazyResearch/fonduer | src/fonduer/utils/data_model_utils/utils.py | https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/utils/data_model_utils/utils.py#L9-L18 | def _to_span(x, idx=0):
"""Convert a Candidate, Mention, or Span to a span."""
if isinstance(x, Candidate):
return x[idx].context
elif isinstance(x, Mention):
return x.context
elif isinstance(x, TemporarySpanMention):
return x
else:
raise ValueError(f"{type(x)} is an ... | [
"def",
"_to_span",
"(",
"x",
",",
"idx",
"=",
"0",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"Candidate",
")",
":",
"return",
"x",
"[",
"idx",
"]",
".",
"context",
"elif",
"isinstance",
"(",
"x",
",",
"Mention",
")",
":",
"return",
"x",
".",
... | Convert a Candidate, Mention, or Span to a span. | [
"Convert",
"a",
"Candidate",
"Mention",
"or",
"Span",
"to",
"a",
"span",
"."
] | python | train |
ramses-tech/nefertari | nefertari/view.py | https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/view.py#L160-L167 | def set_override_rendered(self):
""" Set self.request.override_renderer if needed. """
if '' in self.request.accept:
self.request.override_renderer = self._default_renderer
elif 'application/json' in self.request.accept:
self.request.override_renderer = 'nefertari_json'
... | [
"def",
"set_override_rendered",
"(",
"self",
")",
":",
"if",
"''",
"in",
"self",
".",
"request",
".",
"accept",
":",
"self",
".",
"request",
".",
"override_renderer",
"=",
"self",
".",
"_default_renderer",
"elif",
"'application/json'",
"in",
"self",
".",
"re... | Set self.request.override_renderer if needed. | [
"Set",
"self",
".",
"request",
".",
"override_renderer",
"if",
"needed",
"."
] | python | train |
MrYsLab/pymata-aio | examples/sparkfun_redbot/sparkfun_experiments/library/redbot.py | https://github.com/MrYsLab/pymata-aio/blob/015081a4628b9d47dfe3f8d6c698ff903f107810/examples/sparkfun_redbot/sparkfun_experiments/library/redbot.py#L116-L124 | def right_motor(self, speed, durationS=-1.0):
"""Basically the same as drive(), but omitting the left motor."""
if speed > 0:
self.right_fwd(min(abs(speed), 255))
else:
self.right_rev(min(abs(speed), 255))
if durationS > 0:
self.board.sleep(durationS)
... | [
"def",
"right_motor",
"(",
"self",
",",
"speed",
",",
"durationS",
"=",
"-",
"1.0",
")",
":",
"if",
"speed",
">",
"0",
":",
"self",
".",
"right_fwd",
"(",
"min",
"(",
"abs",
"(",
"speed",
")",
",",
"255",
")",
")",
"else",
":",
"self",
".",
"ri... | Basically the same as drive(), but omitting the left motor. | [
"Basically",
"the",
"same",
"as",
"drive",
"()",
"but",
"omitting",
"the",
"left",
"motor",
"."
] | python | train |
PythonCharmers/python-future | src/future/backports/email/_header_value_parser.py | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/_header_value_parser.py#L2568-L2588 | def get_extended_attribute(value):
""" [CFWS] 1*extended_attrtext [CFWS]
This is like the non-extended version except we allow % characters, so that
we can pick up an encoded value as a single string.
"""
# XXX: should we have an ExtendedAttribute TokenList?
attribute = Attribute()
if valu... | [
"def",
"get_extended_attribute",
"(",
"value",
")",
":",
"# XXX: should we have an ExtendedAttribute TokenList?",
"attribute",
"=",
"Attribute",
"(",
")",
"if",
"value",
"and",
"value",
"[",
"0",
"]",
"in",
"CFWS_LEADER",
":",
"token",
",",
"value",
"=",
"get_cfws... | [CFWS] 1*extended_attrtext [CFWS]
This is like the non-extended version except we allow % characters, so that
we can pick up an encoded value as a single string. | [
"[",
"CFWS",
"]",
"1",
"*",
"extended_attrtext",
"[",
"CFWS",
"]"
] | python | train |
SuLab/WikidataIntegrator | wikidataintegrator/wdi_core.py | https://github.com/SuLab/WikidataIntegrator/blob/8ceb2ed1c08fec070ec9edfcf7db7b8691481b62/wikidataintegrator/wdi_core.py#L282-L305 | def parse_wd_json(self, wd_json):
"""
Parses a WD entity json and generates the datatype objects, sets self.wd_json_representation
:param wd_json: the json of a WD entity
:type wd_json: A Python Json representation of a WD item
:return: returns the json representation containing ... | [
"def",
"parse_wd_json",
"(",
"self",
",",
"wd_json",
")",
":",
"wd_data",
"=",
"{",
"x",
":",
"wd_json",
"[",
"x",
"]",
"for",
"x",
"in",
"(",
"'labels'",
",",
"'descriptions'",
",",
"'claims'",
",",
"'aliases'",
")",
"if",
"x",
"in",
"wd_json",
"}",... | Parses a WD entity json and generates the datatype objects, sets self.wd_json_representation
:param wd_json: the json of a WD entity
:type wd_json: A Python Json representation of a WD item
:return: returns the json representation containing 'labels', 'descriptions', 'claims', 'aliases', 'siteli... | [
"Parses",
"a",
"WD",
"entity",
"json",
"and",
"generates",
"the",
"datatype",
"objects",
"sets",
"self",
".",
"wd_json_representation",
":",
"param",
"wd_json",
":",
"the",
"json",
"of",
"a",
"WD",
"entity",
":",
"type",
"wd_json",
":",
"A",
"Python",
"Jso... | python | train |
sarenji/pyrc | pyrc/bots.py | https://github.com/sarenji/pyrc/blob/5e8377ddcda6e0ef4ba7d66cf400e243b1fb8f68/pyrc/bots.py#L173-L179 | def _connect(self):
"Connects a socket to the server using options defined in `config`."
self.socket = socket.socket()
self.socket.connect((self.config['host'], self.config['port']))
self.cmd("NICK %s" % self.config['nick'])
self.cmd("USER %s %s bla :%s" %
(self.c... | [
"def",
"_connect",
"(",
"self",
")",
":",
"self",
".",
"socket",
"=",
"socket",
".",
"socket",
"(",
")",
"self",
".",
"socket",
".",
"connect",
"(",
"(",
"self",
".",
"config",
"[",
"'host'",
"]",
",",
"self",
".",
"config",
"[",
"'port'",
"]",
"... | Connects a socket to the server using options defined in `config`. | [
"Connects",
"a",
"socket",
"to",
"the",
"server",
"using",
"options",
"defined",
"in",
"config",
"."
] | python | train |
KnowledgeLinks/rdfframework | rdfframework/datatypes/namespaces.py | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/datatypes/namespaces.py#L503-L518 | def load(self, filepath, file_encoding=None):
""" Reads the the beginning of a turtle file and sets the prefix's used
in that file and sets the prefix attribute
Args:
filepath: the path to the turtle file
file_encoding: specify a specific encoding if necessary
""... | [
"def",
"load",
"(",
"self",
",",
"filepath",
",",
"file_encoding",
"=",
"None",
")",
":",
"with",
"open",
"(",
"filepath",
",",
"encoding",
"=",
"file_encoding",
")",
"as",
"inf",
":",
"for",
"line",
"in",
"inf",
":",
"current_line",
"=",
"str",
"(",
... | Reads the the beginning of a turtle file and sets the prefix's used
in that file and sets the prefix attribute
Args:
filepath: the path to the turtle file
file_encoding: specify a specific encoding if necessary | [
"Reads",
"the",
"the",
"beginning",
"of",
"a",
"turtle",
"file",
"and",
"sets",
"the",
"prefix",
"s",
"used",
"in",
"that",
"file",
"and",
"sets",
"the",
"prefix",
"attribute"
] | python | train |
douban/brownant | brownant/app.py | https://github.com/douban/brownant/blob/3c7e6d30f67b8f0f8ca1f823ea3daed74e8725cd/brownant/app.py#L83-L104 | def dispatch_url(self, url_string):
"""Dispatch the URL string to the target endpoint function.
:param url_string: the origin URL string.
:returns: the return value of calling dispatched function.
"""
url, url_adapter, query_args = self.parse_url(url_string)
try:
... | [
"def",
"dispatch_url",
"(",
"self",
",",
"url_string",
")",
":",
"url",
",",
"url_adapter",
",",
"query_args",
"=",
"self",
".",
"parse_url",
"(",
"url_string",
")",
"try",
":",
"endpoint",
",",
"kwargs",
"=",
"url_adapter",
".",
"match",
"(",
")",
"exce... | Dispatch the URL string to the target endpoint function.
:param url_string: the origin URL string.
:returns: the return value of calling dispatched function. | [
"Dispatch",
"the",
"URL",
"string",
"to",
"the",
"target",
"endpoint",
"function",
"."
] | python | train |
ransford/sllurp | sllurp/llrp.py | https://github.com/ransford/sllurp/blob/d744b7e17d7ba64a24d9a31bde6cba65d91ad9b1/sllurp/llrp.py#L1103-L1124 | def stopPolitely(self, disconnect=False):
"""Delete all active ROSpecs. Return a Deferred that will be called
when the DELETE_ROSPEC_RESPONSE comes back."""
logger.info('stopping politely')
if disconnect:
logger.info('will disconnect when stopped')
self.discon... | [
"def",
"stopPolitely",
"(",
"self",
",",
"disconnect",
"=",
"False",
")",
":",
"logger",
".",
"info",
"(",
"'stopping politely'",
")",
"if",
"disconnect",
":",
"logger",
".",
"info",
"(",
"'will disconnect when stopped'",
")",
"self",
".",
"disconnecting",
"="... | Delete all active ROSpecs. Return a Deferred that will be called
when the DELETE_ROSPEC_RESPONSE comes back. | [
"Delete",
"all",
"active",
"ROSpecs",
".",
"Return",
"a",
"Deferred",
"that",
"will",
"be",
"called",
"when",
"the",
"DELETE_ROSPEC_RESPONSE",
"comes",
"back",
"."
] | python | train |
globality-corp/microcosm-postgres | microcosm_postgres/store.py | https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/store.py#L99-L109 | def retrieve(self, identifier, *criterion):
"""
Retrieve a model by primary key and zero or more other criteria.
:raises `NotFound` if there is no existing model
"""
return self._retrieve(
self.model_class.id == identifier,
*criterion
) | [
"def",
"retrieve",
"(",
"self",
",",
"identifier",
",",
"*",
"criterion",
")",
":",
"return",
"self",
".",
"_retrieve",
"(",
"self",
".",
"model_class",
".",
"id",
"==",
"identifier",
",",
"*",
"criterion",
")"
] | Retrieve a model by primary key and zero or more other criteria.
:raises `NotFound` if there is no existing model | [
"Retrieve",
"a",
"model",
"by",
"primary",
"key",
"and",
"zero",
"or",
"more",
"other",
"criteria",
"."
] | python | train |
Miserlou/Zappa | zappa/cli.py | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L1102-L1139 | def undeploy(self, no_confirm=False, remove_logs=False):
"""
Tear down an existing deployment.
"""
if not no_confirm: # pragma: no cover
confirm = input("Are you sure you want to undeploy? [y/n] ")
if confirm != 'y':
return
if self.use_al... | [
"def",
"undeploy",
"(",
"self",
",",
"no_confirm",
"=",
"False",
",",
"remove_logs",
"=",
"False",
")",
":",
"if",
"not",
"no_confirm",
":",
"# pragma: no cover",
"confirm",
"=",
"input",
"(",
"\"Are you sure you want to undeploy? [y/n] \"",
")",
"if",
"confirm",
... | Tear down an existing deployment. | [
"Tear",
"down",
"an",
"existing",
"deployment",
"."
] | python | train |
dailymuse/oz | oz/sqlalchemy/middleware.py | https://github.com/dailymuse/oz/blob/4329f6a207dc9d2a8fbeb4d16d415dbe4570b5bd/oz/sqlalchemy/middleware.py#L32-L53 | def _sqlalchemy_on_finish(self):
"""
Closes the sqlalchemy transaction. Rolls back if an error occurred.
"""
if hasattr(self, "_db_conns"):
try:
if self.get_status() >= 200 and self.get_status() <= 399:
for db_conn in self._db_conns.values... | [
"def",
"_sqlalchemy_on_finish",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"_db_conns\"",
")",
":",
"try",
":",
"if",
"self",
".",
"get_status",
"(",
")",
">=",
"200",
"and",
"self",
".",
"get_status",
"(",
")",
"<=",
"399",
":",
"fo... | Closes the sqlalchemy transaction. Rolls back if an error occurred. | [
"Closes",
"the",
"sqlalchemy",
"transaction",
".",
"Rolls",
"back",
"if",
"an",
"error",
"occurred",
"."
] | python | train |
genialis/resolwe | resolwe/flow/models/data.py | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/data.py#L236-L271 | def save_storage(self, instance, schema):
"""Save basic:json values to a Storage collection."""
for field_schema, fields in iterate_fields(instance, schema):
name = field_schema['name']
value = fields[name]
if field_schema.get('type', '').startswith('basic:json:'):
... | [
"def",
"save_storage",
"(",
"self",
",",
"instance",
",",
"schema",
")",
":",
"for",
"field_schema",
",",
"fields",
"in",
"iterate_fields",
"(",
"instance",
",",
"schema",
")",
":",
"name",
"=",
"field_schema",
"[",
"'name'",
"]",
"value",
"=",
"fields",
... | Save basic:json values to a Storage collection. | [
"Save",
"basic",
":",
"json",
"values",
"to",
"a",
"Storage",
"collection",
"."
] | python | train |
NoneGG/aredis | aredis/pubsub.py | https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/pubsub.py#L206-L209 | async def listen(self):
"Listen for messages on channels this client has been subscribed to"
if self.subscribed:
return self.handle_message(await self.parse_response(block=True)) | [
"async",
"def",
"listen",
"(",
"self",
")",
":",
"if",
"self",
".",
"subscribed",
":",
"return",
"self",
".",
"handle_message",
"(",
"await",
"self",
".",
"parse_response",
"(",
"block",
"=",
"True",
")",
")"
] | Listen for messages on channels this client has been subscribed to | [
"Listen",
"for",
"messages",
"on",
"channels",
"this",
"client",
"has",
"been",
"subscribed",
"to"
] | python | train |
pybel/pybel | src/pybel/struct/graph.py | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/graph.py#L705-L707 | def edge_to_bel(u: BaseEntity, v: BaseEntity, edge_data: EdgeData, sep: Optional[str] = None) -> str:
"""Serialize a pair of nodes and related edge data as a BEL relation."""
return edge_to_bel(u, v, data=edge_data, sep=sep) | [
"def",
"edge_to_bel",
"(",
"u",
":",
"BaseEntity",
",",
"v",
":",
"BaseEntity",
",",
"edge_data",
":",
"EdgeData",
",",
"sep",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"str",
":",
"return",
"edge_to_bel",
"(",
"u",
",",
"v",
",",
"... | Serialize a pair of nodes and related edge data as a BEL relation. | [
"Serialize",
"a",
"pair",
"of",
"nodes",
"and",
"related",
"edge",
"data",
"as",
"a",
"BEL",
"relation",
"."
] | python | train |
gccxml/pygccxml | pygccxml/declarations/type_traits_classes.py | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits_classes.py#L261-L270 | def has_public_constructor(class_):
"""if class has any public constructor, this function will return list of
them, otherwise None"""
class_ = class_traits.get_declaration(class_)
decls = class_.constructors(
lambda c: not is_copy_constructor(c) and c.access_type == 'public',
recursive=F... | [
"def",
"has_public_constructor",
"(",
"class_",
")",
":",
"class_",
"=",
"class_traits",
".",
"get_declaration",
"(",
"class_",
")",
"decls",
"=",
"class_",
".",
"constructors",
"(",
"lambda",
"c",
":",
"not",
"is_copy_constructor",
"(",
"c",
")",
"and",
"c"... | if class has any public constructor, this function will return list of
them, otherwise None | [
"if",
"class",
"has",
"any",
"public",
"constructor",
"this",
"function",
"will",
"return",
"list",
"of",
"them",
"otherwise",
"None"
] | python | train |
kstaniek/condoor | condoor/chain.py | https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/chain.py#L149-L155 | def tail_disconnect(self, index):
"""Mark all devices disconnected except target in the chain."""
try:
for device in self.devices[index + 1:]:
device.connected = False
except IndexError:
pass | [
"def",
"tail_disconnect",
"(",
"self",
",",
"index",
")",
":",
"try",
":",
"for",
"device",
"in",
"self",
".",
"devices",
"[",
"index",
"+",
"1",
":",
"]",
":",
"device",
".",
"connected",
"=",
"False",
"except",
"IndexError",
":",
"pass"
] | Mark all devices disconnected except target in the chain. | [
"Mark",
"all",
"devices",
"disconnected",
"except",
"target",
"in",
"the",
"chain",
"."
] | python | train |
rsmuc/health_monitoring_plugins | health_monitoring_plugins/check_snmp_eaton_ups/check_snmp_eaton_ups.py | https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/check_snmp_eaton_ups/check_snmp_eaton_ups.py#L78-L90 | def check_ups_input_frequency(the_session, the_helper, the_snmp_value):
"""
OID .1.3.6.1.2.1.33.1.3.3.1.2.1
MIB excerpt
The present input frequency.
"""
a_frequency = calc_frequency_from_snmpvalue(the_snmp_value)
the_helper.add_metric(
label=the_helper.options.type,
value=a_f... | [
"def",
"check_ups_input_frequency",
"(",
"the_session",
",",
"the_helper",
",",
"the_snmp_value",
")",
":",
"a_frequency",
"=",
"calc_frequency_from_snmpvalue",
"(",
"the_snmp_value",
")",
"the_helper",
".",
"add_metric",
"(",
"label",
"=",
"the_helper",
".",
"options... | OID .1.3.6.1.2.1.33.1.3.3.1.2.1
MIB excerpt
The present input frequency. | [
"OID",
".",
"1",
".",
"3",
".",
"6",
".",
"1",
".",
"2",
".",
"1",
".",
"33",
".",
"1",
".",
"3",
".",
"3",
".",
"1",
".",
"2",
".",
"1",
"MIB",
"excerpt",
"The",
"present",
"input",
"frequency",
"."
] | python | train |
nickmckay/LiPD-utilities | Python/lipd/misc.py | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/misc.py#L724-L741 | def rm_keys_from_dict(d, keys):
"""
Given a dictionary and a key list, remove any data in the dictionary with the given keys.
:param dict d: Metadata
:param list keys: Keys to be removed
:return dict d: Metadata
"""
# Loop for each key given
for key in keys:
# Is the key in the ... | [
"def",
"rm_keys_from_dict",
"(",
"d",
",",
"keys",
")",
":",
"# Loop for each key given",
"for",
"key",
"in",
"keys",
":",
"# Is the key in the dictionary?",
"if",
"key",
"in",
"d",
":",
"try",
":",
"d",
".",
"pop",
"(",
"key",
",",
"None",
")",
"except",
... | Given a dictionary and a key list, remove any data in the dictionary with the given keys.
:param dict d: Metadata
:param list keys: Keys to be removed
:return dict d: Metadata | [
"Given",
"a",
"dictionary",
"and",
"a",
"key",
"list",
"remove",
"any",
"data",
"in",
"the",
"dictionary",
"with",
"the",
"given",
"keys",
"."
] | python | train |
git-afsantos/bonsai | bonsai/model.py | https://github.com/git-afsantos/bonsai/blob/aa5af3f535b3b506bfc95c107c501fc9c4bcd072/bonsai/model.py#L1356-L1362 | def _add_default_branch(self, body):
"""Add a default body for this conditional (the `else` branch)."""
assert isinstance(body, CodeStatement)
if isinstance(body, CodeBlock):
self.else_body = body
else:
self.else_body._add(body) | [
"def",
"_add_default_branch",
"(",
"self",
",",
"body",
")",
":",
"assert",
"isinstance",
"(",
"body",
",",
"CodeStatement",
")",
"if",
"isinstance",
"(",
"body",
",",
"CodeBlock",
")",
":",
"self",
".",
"else_body",
"=",
"body",
"else",
":",
"self",
"."... | Add a default body for this conditional (the `else` branch). | [
"Add",
"a",
"default",
"body",
"for",
"this",
"conditional",
"(",
"the",
"else",
"branch",
")",
"."
] | python | train |
apache/spark | python/pyspark/ml/regression.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/ml/regression.py#L1679-L1690 | def summary(self):
"""
Gets summary (e.g. residuals, deviance, pValues) of model on
training set. An exception is thrown if
`trainingSummary is None`.
"""
if self.hasSummary:
return GeneralizedLinearRegressionTrainingSummary(
super(GeneralizedL... | [
"def",
"summary",
"(",
"self",
")",
":",
"if",
"self",
".",
"hasSummary",
":",
"return",
"GeneralizedLinearRegressionTrainingSummary",
"(",
"super",
"(",
"GeneralizedLinearRegressionModel",
",",
"self",
")",
".",
"summary",
")",
"else",
":",
"raise",
"RuntimeError... | Gets summary (e.g. residuals, deviance, pValues) of model on
training set. An exception is thrown if
`trainingSummary is None`. | [
"Gets",
"summary",
"(",
"e",
".",
"g",
".",
"residuals",
"deviance",
"pValues",
")",
"of",
"model",
"on",
"training",
"set",
".",
"An",
"exception",
"is",
"thrown",
"if",
"trainingSummary",
"is",
"None",
"."
] | python | train |
joestump/python-oauth2 | oauth2/__init__.py | https://github.com/joestump/python-oauth2/blob/b94f69b1ad195513547924e380d9265133e995fa/oauth2/__init__.py#L714-L720 | def verify_request(self, request, consumer, token):
"""Verifies an api call and checks all the parameters."""
self._check_version(request)
self._check_signature(request, consumer, token)
parameters = request.get_nonoauth_parameters()
return parameters | [
"def",
"verify_request",
"(",
"self",
",",
"request",
",",
"consumer",
",",
"token",
")",
":",
"self",
".",
"_check_version",
"(",
"request",
")",
"self",
".",
"_check_signature",
"(",
"request",
",",
"consumer",
",",
"token",
")",
"parameters",
"=",
"requ... | Verifies an api call and checks all the parameters. | [
"Verifies",
"an",
"api",
"call",
"and",
"checks",
"all",
"the",
"parameters",
"."
] | python | train |
Esri/ArcREST | src/arcrest/security/security.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/security/security.py#L148-L173 | def _initURL(self,
org_url,
referer_url):
""" sets proper URLs for AGOL """
if org_url is not None and org_url != '':
if not org_url.startswith('http://') and not org_url.startswith('https://'):
org_url = 'https://' + org_url
se... | [
"def",
"_initURL",
"(",
"self",
",",
"org_url",
",",
"referer_url",
")",
":",
"if",
"org_url",
"is",
"not",
"None",
"and",
"org_url",
"!=",
"''",
":",
"if",
"not",
"org_url",
".",
"startswith",
"(",
"'http://'",
")",
"and",
"not",
"org_url",
".",
"star... | sets proper URLs for AGOL | [
"sets",
"proper",
"URLs",
"for",
"AGOL"
] | python | train |
artefactual-labs/mets-reader-writer | metsrw/fsentry.py | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/fsentry.py#L419-L433 | def is_empty_dir(self):
"""Returns ``True`` if this fs item is a directory with no children or
a directory with only other empty directories as children.
"""
if self.mets_div_type == "Directory":
children = self._children
if children:
if all(child.... | [
"def",
"is_empty_dir",
"(",
"self",
")",
":",
"if",
"self",
".",
"mets_div_type",
"==",
"\"Directory\"",
":",
"children",
"=",
"self",
".",
"_children",
"if",
"children",
":",
"if",
"all",
"(",
"child",
".",
"is_empty_dir",
"for",
"child",
"in",
"children"... | Returns ``True`` if this fs item is a directory with no children or
a directory with only other empty directories as children. | [
"Returns",
"True",
"if",
"this",
"fs",
"item",
"is",
"a",
"directory",
"with",
"no",
"children",
"or",
"a",
"directory",
"with",
"only",
"other",
"empty",
"directories",
"as",
"children",
"."
] | python | train |
doconix/django-mako-plus | django_mako_plus/apps.py | https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/apps.py#L88-L94 | def is_registered_app(self, app):
'''Returns true if the given app/app name is registered with DMP'''
if app is None:
return False
if isinstance(app, AppConfig):
app = app.name
return app in self.registered_apps | [
"def",
"is_registered_app",
"(",
"self",
",",
"app",
")",
":",
"if",
"app",
"is",
"None",
":",
"return",
"False",
"if",
"isinstance",
"(",
"app",
",",
"AppConfig",
")",
":",
"app",
"=",
"app",
".",
"name",
"return",
"app",
"in",
"self",
".",
"registe... | Returns true if the given app/app name is registered with DMP | [
"Returns",
"true",
"if",
"the",
"given",
"app",
"/",
"app",
"name",
"is",
"registered",
"with",
"DMP"
] | python | train |
petebachant/PXL | pxl/timeseries.py | https://github.com/petebachant/PXL/blob/d7d06cb74422e1ac0154741351fbecea080cfcc0/pxl/timeseries.py#L23-L55 | def psd(t, data, window=None, n_band_average=1):
"""Compute one-sided power spectral density, subtracting mean automatically.
Parameters
----------
t : Time array
data : Time series data
window : {None, "Hanning"}
n_band_average : Number of samples over which to band average
... | [
"def",
"psd",
"(",
"t",
",",
"data",
",",
"window",
"=",
"None",
",",
"n_band_average",
"=",
"1",
")",
":",
"dt",
"=",
"t",
"[",
"1",
"]",
"-",
"t",
"[",
"0",
"]",
"N",
"=",
"len",
"(",
"data",
")",
"data",
"=",
"data",
"-",
"np",
".",
"m... | Compute one-sided power spectral density, subtracting mean automatically.
Parameters
----------
t : Time array
data : Time series data
window : {None, "Hanning"}
n_band_average : Number of samples over which to band average
Returns
-------
f : Frequency array
psd : ... | [
"Compute",
"one",
"-",
"sided",
"power",
"spectral",
"density",
"subtracting",
"mean",
"automatically",
".",
"Parameters",
"----------",
"t",
":",
"Time",
"array",
"data",
":",
"Time",
"series",
"data",
"window",
":",
"{",
"None",
"Hanning",
"}",
"n_band_avera... | python | train |
senaite/senaite.core | bika/lims/content/analysisrequest.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/content/analysisrequest.py#L1619-L1643 | def getBillableItems(self):
"""Returns the items to be billed
"""
# Assigned profiles
profiles = self.getProfiles()
# Billable profiles which have a fixed price set
billable_profiles = filter(
lambda pr: pr.getUseAnalysisProfilePrice(), profiles)
# All... | [
"def",
"getBillableItems",
"(",
"self",
")",
":",
"# Assigned profiles",
"profiles",
"=",
"self",
".",
"getProfiles",
"(",
")",
"# Billable profiles which have a fixed price set",
"billable_profiles",
"=",
"filter",
"(",
"lambda",
"pr",
":",
"pr",
".",
"getUseAnalysis... | Returns the items to be billed | [
"Returns",
"the",
"items",
"to",
"be",
"billed"
] | python | train |
imjoey/pyhaproxy | pyhaproxy/parse.py | https://github.com/imjoey/pyhaproxy/blob/4f0904acfc6bdb29ba6104ce2f6724c0330441d3/pyhaproxy/parse.py#L170-L206 | def build_frontend(self, frontend_node):
"""parse `frontend` sections, and return a config.Frontend
Args:
frontend_node (TreeNode): Description
Raises:
Exception: Description
Returns:
config.Frontend: an object
"""
proxy_name = front... | [
"def",
"build_frontend",
"(",
"self",
",",
"frontend_node",
")",
":",
"proxy_name",
"=",
"frontend_node",
".",
"frontend_header",
".",
"proxy_name",
".",
"text",
"service_address_node",
"=",
"frontend_node",
".",
"frontend_header",
".",
"service_address",
"# parse the... | parse `frontend` sections, and return a config.Frontend
Args:
frontend_node (TreeNode): Description
Raises:
Exception: Description
Returns:
config.Frontend: an object | [
"parse",
"frontend",
"sections",
"and",
"return",
"a",
"config",
".",
"Frontend"
] | python | train |
pypa/pipenv | pipenv/patched/notpip/_internal/pep425tags.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/pep425tags.py#L64-L75 | def get_impl_version_info():
# type: () -> Tuple[int, ...]
"""Return sys.version_info-like tuple for use in decrementing the minor
version."""
if get_abbr_impl() == 'pp':
# as per https://github.com/pypa/pip/issues/2882
# attrs exist only on pypy
return (sys.version_info[0],
... | [
"def",
"get_impl_version_info",
"(",
")",
":",
"# type: () -> Tuple[int, ...]",
"if",
"get_abbr_impl",
"(",
")",
"==",
"'pp'",
":",
"# as per https://github.com/pypa/pip/issues/2882",
"# attrs exist only on pypy",
"return",
"(",
"sys",
".",
"version_info",
"[",
"0",
"]",
... | Return sys.version_info-like tuple for use in decrementing the minor
version. | [
"Return",
"sys",
".",
"version_info",
"-",
"like",
"tuple",
"for",
"use",
"in",
"decrementing",
"the",
"minor",
"version",
"."
] | python | train |
sernst/cauldron | docker-builder.py | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/docker-builder.py#L19-L32 | def update_base_image(path: str):
"""Pulls the latest version of the base image"""
with open(path, 'r') as file_handle:
contents = file_handle.read()
regex = re.compile('from\s+(?P<source>[^\s]+)', re.IGNORECASE)
matches = regex.findall(contents)
if not matches:
return None
ma... | [
"def",
"update_base_image",
"(",
"path",
":",
"str",
")",
":",
"with",
"open",
"(",
"path",
",",
"'r'",
")",
"as",
"file_handle",
":",
"contents",
"=",
"file_handle",
".",
"read",
"(",
")",
"regex",
"=",
"re",
".",
"compile",
"(",
"'from\\s+(?P<source>[^... | Pulls the latest version of the base image | [
"Pulls",
"the",
"latest",
"version",
"of",
"the",
"base",
"image"
] | python | train |
titusjan/argos | argos/repo/filesytemrtis.py | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/filesytemrtis.py#L85-L110 | def detectRtiFromFileName(fileName):
""" Determines the type of RepoTreeItem to use given a file name.
Uses a DirectoryRti for directories and an UnknownFileRti if the file
extension doesn't match one of the registered RTI extensions.
Returns (cls, regItem) tuple. Both the cls ond the regIt... | [
"def",
"detectRtiFromFileName",
"(",
"fileName",
")",
":",
"_",
",",
"extension",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"fileName",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"fileName",
")",
":",
"rtiRegItem",
"=",
"None",
"cls",
"=",
... | Determines the type of RepoTreeItem to use given a file name.
Uses a DirectoryRti for directories and an UnknownFileRti if the file
extension doesn't match one of the registered RTI extensions.
Returns (cls, regItem) tuple. Both the cls ond the regItem can be None.
If the file is a dire... | [
"Determines",
"the",
"type",
"of",
"RepoTreeItem",
"to",
"use",
"given",
"a",
"file",
"name",
".",
"Uses",
"a",
"DirectoryRti",
"for",
"directories",
"and",
"an",
"UnknownFileRti",
"if",
"the",
"file",
"extension",
"doesn",
"t",
"match",
"one",
"of",
"the",
... | python | train |
Erotemic/utool | utool/util_list.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L2983-L3005 | def make_index_lookup(list_, dict_factory=dict):
r"""
Args:
list_ (list): assumed to have unique items
Returns:
dict: mapping from item to index
CommandLine:
python -m utool.util_list --exec-make_index_lookup
Example:
>>> # ENABLE_DOCTEST
>>> from utool.uti... | [
"def",
"make_index_lookup",
"(",
"list_",
",",
"dict_factory",
"=",
"dict",
")",
":",
"return",
"dict_factory",
"(",
"zip",
"(",
"list_",
",",
"range",
"(",
"len",
"(",
"list_",
")",
")",
")",
")"
] | r"""
Args:
list_ (list): assumed to have unique items
Returns:
dict: mapping from item to index
CommandLine:
python -m utool.util_list --exec-make_index_lookup
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool as u... | [
"r",
"Args",
":",
"list_",
"(",
"list",
")",
":",
"assumed",
"to",
"have",
"unique",
"items"
] | python | train |
pycontribs/pyrax | pyrax/autoscale.py | https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/autoscale.py#L179-L183 | def delete_policy(self, policy):
"""
Deletes the specified policy from this scaling group.
"""
return self.manager.delete_policy(scaling_group=self, policy=policy) | [
"def",
"delete_policy",
"(",
"self",
",",
"policy",
")",
":",
"return",
"self",
".",
"manager",
".",
"delete_policy",
"(",
"scaling_group",
"=",
"self",
",",
"policy",
"=",
"policy",
")"
] | Deletes the specified policy from this scaling group. | [
"Deletes",
"the",
"specified",
"policy",
"from",
"this",
"scaling",
"group",
"."
] | python | train |
AlexMathew/scrapple | scrapple/utils/dynamicdispatch.py | https://github.com/AlexMathew/scrapple/blob/eeb604601b155d6cc7e035855ff4d3f48f8bed74/scrapple/utils/dynamicdispatch.py#L8-L23 | def get_command_class(command):
"""
Called from runCLI() to select the command class for the selected command.
:param command: The command to be implemented
:return: The command class corresponding to the selected command
"""
from scrapple.commands import genconfig, generate, run, web
comma... | [
"def",
"get_command_class",
"(",
"command",
")",
":",
"from",
"scrapple",
".",
"commands",
"import",
"genconfig",
",",
"generate",
",",
"run",
",",
"web",
"commandMapping",
"=",
"{",
"'genconfig'",
":",
"genconfig",
",",
"'generate'",
":",
"generate",
",",
"... | Called from runCLI() to select the command class for the selected command.
:param command: The command to be implemented
:return: The command class corresponding to the selected command | [
"Called",
"from",
"runCLI",
"()",
"to",
"select",
"the",
"command",
"class",
"for",
"the",
"selected",
"command",
"."
] | python | train |
ebu/PlugIt | plugit_proxy/views.py | https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L143-L176 | def gen403(request, baseURI, reason, project=None):
"""Return a 403 error"""
orgas = None
public_ask = False
if not settings.PIAPI_STANDALONE:
from organizations.models import Organization
if project and project.plugItLimitOrgaJoinable:
orgas = project.plugItOrgaJoinable.or... | [
"def",
"gen403",
"(",
"request",
",",
"baseURI",
",",
"reason",
",",
"project",
"=",
"None",
")",
":",
"orgas",
"=",
"None",
"public_ask",
"=",
"False",
"if",
"not",
"settings",
".",
"PIAPI_STANDALONE",
":",
"from",
"organizations",
".",
"models",
"import"... | Return a 403 error | [
"Return",
"a",
"403",
"error"
] | python | train |
onelogin/python-saml | src/onelogin/saml2/logout_request.py | https://github.com/onelogin/python-saml/blob/9fe7a72da5b4caa1529c1640b52d2649447ce49b/src/onelogin/saml2/logout_request.py#L261-L280 | def get_issuer(request):
"""
Gets the Issuer of the Logout Request Message
:param request: Logout Request Message
:type request: string|DOMDocument
:return: The Issuer
:rtype: string
"""
if isinstance(request, etree._Element):
elem = request
... | [
"def",
"get_issuer",
"(",
"request",
")",
":",
"if",
"isinstance",
"(",
"request",
",",
"etree",
".",
"_Element",
")",
":",
"elem",
"=",
"request",
"else",
":",
"if",
"isinstance",
"(",
"request",
",",
"Document",
")",
":",
"request",
"=",
"request",
"... | Gets the Issuer of the Logout Request Message
:param request: Logout Request Message
:type request: string|DOMDocument
:return: The Issuer
:rtype: string | [
"Gets",
"the",
"Issuer",
"of",
"the",
"Logout",
"Request",
"Message",
":",
"param",
"request",
":",
"Logout",
"Request",
"Message",
":",
"type",
"request",
":",
"string|DOMDocument",
":",
"return",
":",
"The",
"Issuer",
":",
"rtype",
":",
"string"
] | python | train |
biosignalsnotebooks/biosignalsnotebooks | biosignalsnotebooks/build/lib/biosignalsnotebooks/__notebook_support__.py | https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/__notebook_support__.py#L1023-L1135 | def plot_before_after_filter(signal, sr, band_begin, band_end, order=1, x_lim=[], y_lim=[],
orientation="hor", show_plot=False, file_name=None):
"""
-----
Brief
-----
The use of the current function is very useful for comparing two power spectrum's (before and
after ... | [
"def",
"plot_before_after_filter",
"(",
"signal",
",",
"sr",
",",
"band_begin",
",",
"band_end",
",",
"order",
"=",
"1",
",",
"x_lim",
"=",
"[",
"]",
",",
"y_lim",
"=",
"[",
"]",
",",
"orientation",
"=",
"\"hor\"",
",",
"show_plot",
"=",
"False",
",",
... | -----
Brief
-----
The use of the current function is very useful for comparing two power spectrum's (before and
after filtering the signal).
This function invokes "plot_informational_band" in order to get the power spectrum before
applying the signal to the lowpass filter.
-----------
D... | [
"-----",
"Brief",
"-----",
"The",
"use",
"of",
"the",
"current",
"function",
"is",
"very",
"useful",
"for",
"comparing",
"two",
"power",
"spectrum",
"s",
"(",
"before",
"and",
"after",
"filtering",
"the",
"signal",
")",
".",
"This",
"function",
"invokes",
... | python | train |
log2timeline/plaso | plaso/storage/sqlite/sqlite_file.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/storage/sqlite/sqlite_file.py#L887-L918 | def GetSessions(self):
"""Retrieves the sessions.
Yields:
Session: session attribute container.
Raises:
IOError: if there is a mismatch in session identifiers between the
session start and completion attribute containers.
OSError: if there is a mismatch in session identifiers b... | [
"def",
"GetSessions",
"(",
"self",
")",
":",
"session_start_generator",
"=",
"self",
".",
"_GetAttributeContainers",
"(",
"self",
".",
"_CONTAINER_TYPE_SESSION_START",
")",
"session_completion_generator",
"=",
"self",
".",
"_GetAttributeContainers",
"(",
"self",
".",
... | Retrieves the sessions.
Yields:
Session: session attribute container.
Raises:
IOError: if there is a mismatch in session identifiers between the
session start and completion attribute containers.
OSError: if there is a mismatch in session identifiers between the
session s... | [
"Retrieves",
"the",
"sessions",
"."
] | python | train |
blockstack/blockstack-core | blockstack/lib/client.py | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/client.py#L2705-L2832 | def get_blockstack_transactions_at(block_id, proxy=None, hostport=None):
"""
Get the *prior* states of the blockstack records that were
affected at the given block height.
Return the list of name records at the given height on success.
Return {'error': ...} on error.
"""
assert proxy or host... | [
"def",
"get_blockstack_transactions_at",
"(",
"block_id",
",",
"proxy",
"=",
"None",
",",
"hostport",
"=",
"None",
")",
":",
"assert",
"proxy",
"or",
"hostport",
",",
"'Need proxy or hostport'",
"if",
"proxy",
"is",
"None",
":",
"proxy",
"=",
"connect_hostport",... | Get the *prior* states of the blockstack records that were
affected at the given block height.
Return the list of name records at the given height on success.
Return {'error': ...} on error. | [
"Get",
"the",
"*",
"prior",
"*",
"states",
"of",
"the",
"blockstack",
"records",
"that",
"were",
"affected",
"at",
"the",
"given",
"block",
"height",
".",
"Return",
"the",
"list",
"of",
"name",
"records",
"at",
"the",
"given",
"height",
"on",
"success",
... | python | train |
Clinical-Genomics/housekeeper | housekeeper/store/api.py | https://github.com/Clinical-Genomics/housekeeper/blob/a7d10d327dc9f06274bdef5504ed1b9413f2c8c1/housekeeper/store/api.py#L32-L38 | def version(self, bundle: str, date: dt.datetime) -> models.Version:
"""Fetch a version from the store."""
return (self.Version.query
.join(models.Version.bundle)
.filter(models.Bundle.name == bundle,
models.Vers... | [
"def",
"version",
"(",
"self",
",",
"bundle",
":",
"str",
",",
"date",
":",
"dt",
".",
"datetime",
")",
"->",
"models",
".",
"Version",
":",
"return",
"(",
"self",
".",
"Version",
".",
"query",
".",
"join",
"(",
"models",
".",
"Version",
".",
"bund... | Fetch a version from the store. | [
"Fetch",
"a",
"version",
"from",
"the",
"store",
"."
] | python | train |
scopus-api/scopus | scopus/deprecated_/scopus_author.py | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/deprecated_/scopus_author.py#L157-L174 | def publication_history(self):
"""List of tuples of authored publications in the form
(title, abbreviation, type, issn), where issn is only given
for journals. abbreviation and issn may be None.
"""
pub_hist = self.xml.findall('author-profile/journal-history/')
hist = []... | [
"def",
"publication_history",
"(",
"self",
")",
":",
"pub_hist",
"=",
"self",
".",
"xml",
".",
"findall",
"(",
"'author-profile/journal-history/'",
")",
"hist",
"=",
"[",
"]",
"for",
"pub",
"in",
"pub_hist",
":",
"try",
":",
"issn",
"=",
"pub",
".",
"fin... | List of tuples of authored publications in the form
(title, abbreviation, type, issn), where issn is only given
for journals. abbreviation and issn may be None. | [
"List",
"of",
"tuples",
"of",
"authored",
"publications",
"in",
"the",
"form",
"(",
"title",
"abbreviation",
"type",
"issn",
")",
"where",
"issn",
"is",
"only",
"given",
"for",
"journals",
".",
"abbreviation",
"and",
"issn",
"may",
"be",
"None",
"."
] | python | train |
halcy/Mastodon.py | mastodon/Mastodon.py | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1917-L1925 | def account_pin(self, id):
"""
Pin / endorse a user.
Returns a `relationship dict`_ containing the updated relationship to the user.
"""
id = self.__unpack_id(id)
url = '/api/v1/accounts/{0}/pin'.format(str(id))
return self.__api_request('POST', url) | [
"def",
"account_pin",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/accounts/{0}/pin'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'POST... | Pin / endorse a user.
Returns a `relationship dict`_ containing the updated relationship to the user. | [
"Pin",
"/",
"endorse",
"a",
"user",
".",
"Returns",
"a",
"relationship",
"dict",
"_",
"containing",
"the",
"updated",
"relationship",
"to",
"the",
"user",
"."
] | python | train |
svenevs/exhale | exhale/graph.py | https://github.com/svenevs/exhale/blob/fe7644829057af622e467bb529db6c03a830da99/exhale/graph.py#L2084-L2122 | def generateAPIRootHeader(self):
'''
This method creates the root library api file that will include all of the
different hierarchy views and full api listing. If ``self.root_directory`` is
not a current directory, it is created first. Afterward, the root API file is
created an... | [
"def",
"generateAPIRootHeader",
"(",
"self",
")",
":",
"try",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"self",
".",
"root_directory",
")",
":",
"os",
".",
"mkdir",
"(",
"self",
".",
"root_directory",
")",
"except",
":",
"utils",
".",
"... | This method creates the root library api file that will include all of the
different hierarchy views and full api listing. If ``self.root_directory`` is
not a current directory, it is created first. Afterward, the root API file is
created and its title is written, as well as the value of
... | [
"This",
"method",
"creates",
"the",
"root",
"library",
"api",
"file",
"that",
"will",
"include",
"all",
"of",
"the",
"different",
"hierarchy",
"views",
"and",
"full",
"api",
"listing",
".",
"If",
"self",
".",
"root_directory",
"is",
"not",
"a",
"current",
... | python | train |
apache/incubator-heron | third_party/python/cpplint/cpplint.py | https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L4998-L5056 | def CheckGlobalStatic(filename, clean_lines, linenum, error):
"""Check for unsafe global or static objects.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors ... | [
"def",
"CheckGlobalStatic",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"# Match two lines at a time to support multiline declarations",
"if",
"linenum",
"+",
"1",
"<",
... | Check for unsafe global or static objects.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | [
"Check",
"for",
"unsafe",
"global",
"or",
"static",
"objects",
"."
] | python | valid |
frasertweedale/ledgertools | ltlib/readers/CSV.py | https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/readers/CSV.py#L92-L101 | def next(self):
"""Return the next transaction object.
StopIteration will be propagated from self.csvreader.next()
"""
try:
return self.dict_to_xn(self.csvreader.next())
except MetadataException:
# row was metadata; proceed to next row
return ... | [
"def",
"next",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"dict_to_xn",
"(",
"self",
".",
"csvreader",
".",
"next",
"(",
")",
")",
"except",
"MetadataException",
":",
"# row was metadata; proceed to next row",
"return",
"next",
"(",
"self",
")... | Return the next transaction object.
StopIteration will be propagated from self.csvreader.next() | [
"Return",
"the",
"next",
"transaction",
"object",
"."
] | python | train |
mdiener/grace | grace/py27/pyjsdoc.py | https://github.com/mdiener/grace/blob/2dab13a2cf636da5da989904c5885166fc94d36d/grace/py27/pyjsdoc.py#L1395-L1416 | def topological_sort(dependencies, start_nodes):
"""
Perform a topological sort on the dependency graph `dependencies`, starting
from list `start_nodes`.
"""
retval = []
def edges(node): return dependencies[node][1]
def in_degree(node): return dependencies[node][0]
def remove_incoming(no... | [
"def",
"topological_sort",
"(",
"dependencies",
",",
"start_nodes",
")",
":",
"retval",
"=",
"[",
"]",
"def",
"edges",
"(",
"node",
")",
":",
"return",
"dependencies",
"[",
"node",
"]",
"[",
"1",
"]",
"def",
"in_degree",
"(",
"node",
")",
":",
"return"... | Perform a topological sort on the dependency graph `dependencies`, starting
from list `start_nodes`. | [
"Perform",
"a",
"topological",
"sort",
"on",
"the",
"dependency",
"graph",
"dependencies",
"starting",
"from",
"list",
"start_nodes",
"."
] | python | train |
obulpathi/cdn-fastly-python | fastly/__init__.py | https://github.com/obulpathi/cdn-fastly-python/blob/db2564b047e8af4bce72c3b88d6c27d3d0291425/fastly/__init__.py#L900-L903 | def get_generated_vcl_html(self, service_id, version_number):
"""Display the content of generated VCL with HTML syntax highlighting."""
content = self._fetch("/service/%s/version/%d/generated_vcl/content" % (service_id, version_number))
return content.get("content", None) | [
"def",
"get_generated_vcl_html",
"(",
"self",
",",
"service_id",
",",
"version_number",
")",
":",
"content",
"=",
"self",
".",
"_fetch",
"(",
"\"/service/%s/version/%d/generated_vcl/content\"",
"%",
"(",
"service_id",
",",
"version_number",
")",
")",
"return",
"cont... | Display the content of generated VCL with HTML syntax highlighting. | [
"Display",
"the",
"content",
"of",
"generated",
"VCL",
"with",
"HTML",
"syntax",
"highlighting",
"."
] | python | train |
pytroll/posttroll | posttroll/ns.py | https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/ns.py#L59-L73 | def get_pub_addresses(names=None, timeout=10, nameserver="localhost"):
"""Get the address of the publisher for a given list of publisher *names*
from the nameserver on *nameserver* (localhost by default).
"""
addrs = []
if names is None:
names = ["", ]
for name in names:
then = d... | [
"def",
"get_pub_addresses",
"(",
"names",
"=",
"None",
",",
"timeout",
"=",
"10",
",",
"nameserver",
"=",
"\"localhost\"",
")",
":",
"addrs",
"=",
"[",
"]",
"if",
"names",
"is",
"None",
":",
"names",
"=",
"[",
"\"\"",
",",
"]",
"for",
"name",
"in",
... | Get the address of the publisher for a given list of publisher *names*
from the nameserver on *nameserver* (localhost by default). | [
"Get",
"the",
"address",
"of",
"the",
"publisher",
"for",
"a",
"given",
"list",
"of",
"publisher",
"*",
"names",
"*",
"from",
"the",
"nameserver",
"on",
"*",
"nameserver",
"*",
"(",
"localhost",
"by",
"default",
")",
"."
] | python | train |
eyurtsev/FlowCytometryTools | FlowCytometryTools/core/graph.py | https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/FlowCytometryTools/core/graph.py#L636-L686 | def _plot_table(matrix, text_format='{:.2f}', cmap=None, **kwargs):
"""
Plot a numpy matrix as a table. Uses the current axis bounding box to decide on limits.
text_format specifies the formatting to apply to the values.
Parameters
----------
matrix : ndarray
text_format : str
Ind... | [
"def",
"_plot_table",
"(",
"matrix",
",",
"text_format",
"=",
"'{:.2f}'",
",",
"cmap",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"shape",
"=",
"matrix",
".",
"shape",
"xtick_pos",
"=",
"numpy",
".",
"arange",
"(",
"shape",
"[",
"1",
"]",
")",
... | Plot a numpy matrix as a table. Uses the current axis bounding box to decide on limits.
text_format specifies the formatting to apply to the values.
Parameters
----------
matrix : ndarray
text_format : str
Indicates how to format the the values
text_format = {:.2} -> keeps all dig... | [
"Plot",
"a",
"numpy",
"matrix",
"as",
"a",
"table",
".",
"Uses",
"the",
"current",
"axis",
"bounding",
"box",
"to",
"decide",
"on",
"limits",
".",
"text_format",
"specifies",
"the",
"formatting",
"to",
"apply",
"to",
"the",
"values",
"."
] | python | train |
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 |
qiniu/python-sdk | qiniu/services/compute/app.py | https://github.com/qiniu/python-sdk/blob/a69fbef4e3e6ea1ebe09f4610a5b18bb2c17de59/qiniu/services/compute/app.py#L148-L164 | def get_region_products(self, region):
"""获得指定区域的产品信息
Args:
- region: 区域,如:"nq"
Returns:
返回该区域的产品信息,若失败则返回None
"""
regions, retInfo = self.list_regions()
if regions is None:
return None
for r in regions:
if r.get... | [
"def",
"get_region_products",
"(",
"self",
",",
"region",
")",
":",
"regions",
",",
"retInfo",
"=",
"self",
".",
"list_regions",
"(",
")",
"if",
"regions",
"is",
"None",
":",
"return",
"None",
"for",
"r",
"in",
"regions",
":",
"if",
"r",
".",
"get",
... | 获得指定区域的产品信息
Args:
- region: 区域,如:"nq"
Returns:
返回该区域的产品信息,若失败则返回None | [
"获得指定区域的产品信息"
] | python | train |
HazyResearch/fonduer | src/fonduer/utils/data_model_utils/structural.py | https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/utils/data_model_utils/structural.py#L108-L123 | def get_ancestor_class_names(mention):
"""Return the HTML classes of the Mention's ancestors.
If a candidate is passed in, only the ancestors of its first Mention are
returned.
:param mention: The Mention to evaluate
:rtype: list of strings
"""
span = _to_span(mention)
class_names = []... | [
"def",
"get_ancestor_class_names",
"(",
"mention",
")",
":",
"span",
"=",
"_to_span",
"(",
"mention",
")",
"class_names",
"=",
"[",
"]",
"i",
"=",
"_get_node",
"(",
"span",
".",
"sentence",
")",
"while",
"i",
"is",
"not",
"None",
":",
"class_names",
".",... | Return the HTML classes of the Mention's ancestors.
If a candidate is passed in, only the ancestors of its first Mention are
returned.
:param mention: The Mention to evaluate
:rtype: list of strings | [
"Return",
"the",
"HTML",
"classes",
"of",
"the",
"Mention",
"s",
"ancestors",
"."
] | python | train |
all-umass/graphs | graphs/reorder.py | https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/reorder.py#L24-L30 | def permute_graph(G, order):
'''Reorder the graph's vertices, returning a copy of the input graph.
order : integer array-like, some permutation of range(G.num_vertices()).
'''
adj = G.matrix('dense')
adj = adj[np.ix_(order, order)]
return Graph.from_adj_matrix(adj) | [
"def",
"permute_graph",
"(",
"G",
",",
"order",
")",
":",
"adj",
"=",
"G",
".",
"matrix",
"(",
"'dense'",
")",
"adj",
"=",
"adj",
"[",
"np",
".",
"ix_",
"(",
"order",
",",
"order",
")",
"]",
"return",
"Graph",
".",
"from_adj_matrix",
"(",
"adj",
... | Reorder the graph's vertices, returning a copy of the input graph.
order : integer array-like, some permutation of range(G.num_vertices()). | [
"Reorder",
"the",
"graph",
"s",
"vertices",
"returning",
"a",
"copy",
"of",
"the",
"input",
"graph",
".",
"order",
":",
"integer",
"array",
"-",
"like",
"some",
"permutation",
"of",
"range",
"(",
"G",
".",
"num_vertices",
"()",
")",
"."
] | python | train |
softlayer/softlayer-python | SoftLayer/CLI/loadbal/detail.py | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/loadbal/detail.py#L15-L81 | def cli(env, identifier):
"""Get Load balancer details."""
mgr = SoftLayer.LoadBalancerManager(env.client)
_, loadbal_id = loadbal.parse_id(identifier)
load_balancer = mgr.get_local_lb(loadbal_id)
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'l'
table.align['v... | [
"def",
"cli",
"(",
"env",
",",
"identifier",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"LoadBalancerManager",
"(",
"env",
".",
"client",
")",
"_",
",",
"loadbal_id",
"=",
"loadbal",
".",
"parse_id",
"(",
"identifier",
")",
"load_balancer",
"=",
"mgr",
".",... | Get Load balancer details. | [
"Get",
"Load",
"balancer",
"details",
"."
] | python | train |
andy-z/ged4py | ged4py/model.py | https://github.com/andy-z/ged4py/blob/d0e0cceaadf0a84cbf052705e3c27303b12e1757/ged4py/model.py#L268-L272 | def given(self):
"""Given name could include both first and middle name"""
if self._primary.value[0] and self._primary.value[2]:
return self._primary.value[0] + ' ' + self._primary.value[2]
return self._primary.value[0] or self._primary.value[2] | [
"def",
"given",
"(",
"self",
")",
":",
"if",
"self",
".",
"_primary",
".",
"value",
"[",
"0",
"]",
"and",
"self",
".",
"_primary",
".",
"value",
"[",
"2",
"]",
":",
"return",
"self",
".",
"_primary",
".",
"value",
"[",
"0",
"]",
"+",
"' '",
"+"... | Given name could include both first and middle name | [
"Given",
"name",
"could",
"include",
"both",
"first",
"and",
"middle",
"name"
] | python | train |
yandex/yandex-tank | yandextank/aggregator/tank_aggregator.py | https://github.com/yandex/yandex-tank/blob/d71d63b6ab5de8b8a5ea2b728b6ab9ac0b1ba71b/yandextank/aggregator/tank_aggregator.py#L137-L140 | def __notify_listeners(self, data, stats):
""" notify all listeners about aggregate data and stats """
for listener in self.listeners:
listener.on_aggregated_data(data, stats) | [
"def",
"__notify_listeners",
"(",
"self",
",",
"data",
",",
"stats",
")",
":",
"for",
"listener",
"in",
"self",
".",
"listeners",
":",
"listener",
".",
"on_aggregated_data",
"(",
"data",
",",
"stats",
")"
] | notify all listeners about aggregate data and stats | [
"notify",
"all",
"listeners",
"about",
"aggregate",
"data",
"and",
"stats"
] | python | test |
UCBerkeleySETI/blimpy | blimpy/filterbank.py | https://github.com/UCBerkeleySETI/blimpy/blob/b8822d3e3e911944370d84371a91fa0c29e9772e/blimpy/filterbank.py#L186-L216 | def _setup_freqs(self, f_start=None, f_stop=None):
""" Setup frequency axis """
## Setup frequency axis
f0 = self.header[b'fch1']
f_delt = self.header[b'foff']
i_start, i_stop = 0, self.header[b'nchans']
if f_start:
i_start = int((f_start - f0) / f_delt)
... | [
"def",
"_setup_freqs",
"(",
"self",
",",
"f_start",
"=",
"None",
",",
"f_stop",
"=",
"None",
")",
":",
"## Setup frequency axis",
"f0",
"=",
"self",
".",
"header",
"[",
"b'fch1'",
"]",
"f_delt",
"=",
"self",
".",
"header",
"[",
"b'foff'",
"]",
"i_start",... | Setup frequency axis | [
"Setup",
"frequency",
"axis"
] | python | test |
Erotemic/utool | utool/_internal/meta_util_path.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/_internal/meta_util_path.py#L25-L35 | def unixjoin(*args):
"""
Like os.path.join, but uses forward slashes on win32
"""
isabs_list = list(map(isabs, args))
if any(isabs_list):
poslist = [count for count, flag in enumerate(isabs_list) if flag]
pos = poslist[-1]
return '/'.join(args[pos:])
else:
return ... | [
"def",
"unixjoin",
"(",
"*",
"args",
")",
":",
"isabs_list",
"=",
"list",
"(",
"map",
"(",
"isabs",
",",
"args",
")",
")",
"if",
"any",
"(",
"isabs_list",
")",
":",
"poslist",
"=",
"[",
"count",
"for",
"count",
",",
"flag",
"in",
"enumerate",
"(",
... | Like os.path.join, but uses forward slashes on win32 | [
"Like",
"os",
".",
"path",
".",
"join",
"but",
"uses",
"forward",
"slashes",
"on",
"win32"
] | python | train |
thomasdelaet/python-velbus | velbus/messages/module_type.py | https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/messages/module_type.py#L36-L51 | def populate(self, priority, address, rtr, data):
"""
:return: None
"""
assert isinstance(data, bytes)
self.needs_low_priority(priority)
self.needs_no_rtr(rtr)
self.needs_data(data, 4)
self.set_attributes(priority, address, rtr)
self.module_type = ... | [
"def",
"populate",
"(",
"self",
",",
"priority",
",",
"address",
",",
"rtr",
",",
"data",
")",
":",
"assert",
"isinstance",
"(",
"data",
",",
"bytes",
")",
"self",
".",
"needs_low_priority",
"(",
"priority",
")",
"self",
".",
"needs_no_rtr",
"(",
"rtr",
... | :return: None | [
":",
"return",
":",
"None"
] | python | train |
Othernet-Project/chainable-validators | validators/chain.py | https://github.com/Othernet-Project/chainable-validators/blob/8c0afebfaaa131440ffb2a960b9b38978f00d88f/validators/chain.py#L37-L57 | def make_chain(fns):
""" Take a list of chainable validators and return a chained validator
The functions should be decorated with ``chainable`` decorator.
Any exceptions raised by any of the validators are propagated except for
``ReturnEarly`` exception which is trapped. When ``ReturnEarly`` exceptio... | [
"def",
"make_chain",
"(",
"fns",
")",
":",
"chain",
"=",
"lambda",
"x",
":",
"x",
"for",
"fn",
"in",
"reversed",
"(",
"fns",
")",
":",
"chain",
"=",
"fn",
"(",
"chain",
")",
"def",
"validator",
"(",
"v",
")",
":",
"try",
":",
"return",
"chain",
... | Take a list of chainable validators and return a chained validator
The functions should be decorated with ``chainable`` decorator.
Any exceptions raised by any of the validators are propagated except for
``ReturnEarly`` exception which is trapped. When ``ReturnEarly`` exception
is trapped, the origina... | [
"Take",
"a",
"list",
"of",
"chainable",
"validators",
"and",
"return",
"a",
"chained",
"validator"
] | python | train |
Yelp/py_zipkin | py_zipkin/encoding/_decoders.py | https://github.com/Yelp/py_zipkin/blob/0944d9a3fb1f1798dbb276694aeed99f2b4283ba/py_zipkin/encoding/_decoders.py#L270-L288 | def _write_hex_long(self, data, pos, value):
"""
Writes an unsigned long value across a byte array.
:param data: the buffer to write the value to
:type data: bytearray
:param pos: the starting position
:type pos: int
:param value: the value to write
:type... | [
"def",
"_write_hex_long",
"(",
"self",
",",
"data",
",",
"pos",
",",
"value",
")",
":",
"self",
".",
"_write_hex_byte",
"(",
"data",
",",
"pos",
"+",
"0",
",",
"(",
"value",
">>",
"56",
")",
"&",
"0xff",
")",
"self",
".",
"_write_hex_byte",
"(",
"d... | Writes an unsigned long value across a byte array.
:param data: the buffer to write the value to
:type data: bytearray
:param pos: the starting position
:type pos: int
:param value: the value to write
:type value: unsigned long | [
"Writes",
"an",
"unsigned",
"long",
"value",
"across",
"a",
"byte",
"array",
"."
] | python | test |
matthewgilbert/mapping | mapping/util.py | https://github.com/matthewgilbert/mapping/blob/24ea21acfe37a0ee273f63a273b5d24ea405e70d/mapping/util.py#L6-L40 | def read_price_data(files, name_func=None):
"""
Convenience function for reading in pricing data from csv files
Parameters
----------
files: list
List of strings refering to csv files to read data in from, first
column should be dates
name_func: func
A function to apply ... | [
"def",
"read_price_data",
"(",
"files",
",",
"name_func",
"=",
"None",
")",
":",
"if",
"name_func",
"is",
"None",
":",
"def",
"name_func",
"(",
"x",
")",
":",
"return",
"os",
".",
"path",
".",
"split",
"(",
"x",
")",
"[",
"1",
"]",
".",
"split",
... | Convenience function for reading in pricing data from csv files
Parameters
----------
files: list
List of strings refering to csv files to read data in from, first
column should be dates
name_func: func
A function to apply to the file strings to infer the instrument name,
... | [
"Convenience",
"function",
"for",
"reading",
"in",
"pricing",
"data",
"from",
"csv",
"files"
] | python | train |
galactics/beyond | beyond/orbits/orbit.py | https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/orbits/orbit.py#L187-L198 | def maneuvers(self):
"""list of :py:class:`~beyond.orbits.man.Maneuver`: Maneuver descriptions usable by the
propagator. Not all propagators can handle maneuvers. Check their respective documentations
for more details.
"""
mans = self.complements.setdefault('maneuvers', [])
... | [
"def",
"maneuvers",
"(",
"self",
")",
":",
"mans",
"=",
"self",
".",
"complements",
".",
"setdefault",
"(",
"'maneuvers'",
",",
"[",
"]",
")",
"if",
"isinstance",
"(",
"mans",
",",
"Maneuver",
")",
":",
"mans",
"=",
"[",
"mans",
"]",
"self",
".",
"... | list of :py:class:`~beyond.orbits.man.Maneuver`: Maneuver descriptions usable by the
propagator. Not all propagators can handle maneuvers. Check their respective documentations
for more details. | [
"list",
"of",
":",
"py",
":",
"class",
":",
"~beyond",
".",
"orbits",
".",
"man",
".",
"Maneuver",
":",
"Maneuver",
"descriptions",
"usable",
"by",
"the",
"propagator",
".",
"Not",
"all",
"propagators",
"can",
"handle",
"maneuvers",
".",
"Check",
"their",
... | python | train |
honzamach/pynspect | pynspect/benchmark/bench_jpath.py | https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/benchmark/bench_jpath.py#L36-L49 | def random_jpath(depth = 3):
"""
Generate random JPath with given node depth.
"""
chunks = []
while depth > 0:
length = random.randint(5, 15)
ident = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase) for _ in range(length))
if random.choice((True, False)... | [
"def",
"random_jpath",
"(",
"depth",
"=",
"3",
")",
":",
"chunks",
"=",
"[",
"]",
"while",
"depth",
">",
"0",
":",
"length",
"=",
"random",
".",
"randint",
"(",
"5",
",",
"15",
")",
"ident",
"=",
"''",
".",
"join",
"(",
"random",
".",
"choice",
... | Generate random JPath with given node depth. | [
"Generate",
"random",
"JPath",
"with",
"given",
"node",
"depth",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.