nwo
stringlengths 5
106
| sha
stringlengths 40
40
| path
stringlengths 4
174
| language
stringclasses 1
value | identifier
stringlengths 1
140
| parameters
stringlengths 0
87.7k
| argument_list
stringclasses 1
value | return_statement
stringlengths 0
426k
| docstring
stringlengths 0
64.3k
| docstring_summary
stringlengths 0
26.3k
| docstring_tokens
list | function
stringlengths 18
4.83M
| function_tokens
list | url
stringlengths 83
304
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
opencobra/cobrapy
|
0b9ea70cb0ffe78568d445ce3361ad10ec6b02a2
|
src/cobra/core/dictlist.py
|
python
|
DictList._generate_index
|
(self)
|
rebuild the _dict index
|
rebuild the _dict index
|
[
"rebuild",
"the",
"_dict",
"index"
] |
def _generate_index(self):
"""rebuild the _dict index"""
self._dict = {v.id: k for k, v in enumerate(self)}
|
[
"def",
"_generate_index",
"(",
"self",
")",
":",
"self",
".",
"_dict",
"=",
"{",
"v",
".",
"id",
":",
"k",
"for",
"k",
",",
"v",
"in",
"enumerate",
"(",
"self",
")",
"}"
] |
https://github.com/opencobra/cobrapy/blob/0b9ea70cb0ffe78568d445ce3361ad10ec6b02a2/src/cobra/core/dictlist.py#L51-L53
|
||
googleads/google-ads-python
|
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
|
google/ads/googleads/v9/services/services/campaign_criterion_service/client.py
|
python
|
CampaignCriterionServiceClient._get_default_mtls_endpoint
|
(api_endpoint)
|
return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
|
Convert api endpoint to mTLS endpoint.
Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
"*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
Args:
api_endpoint (Optional[str]): the api endpoint to convert.
Returns:
str: converted mTLS api endpoint.
|
Convert api endpoint to mTLS endpoint.
Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
"*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
Args:
api_endpoint (Optional[str]): the api endpoint to convert.
Returns:
str: converted mTLS api endpoint.
|
[
"Convert",
"api",
"endpoint",
"to",
"mTLS",
"endpoint",
".",
"Convert",
"*",
".",
"sandbox",
".",
"googleapis",
".",
"com",
"and",
"*",
".",
"googleapis",
".",
"com",
"to",
"*",
".",
"mtls",
".",
"sandbox",
".",
"googleapis",
".",
"com",
"and",
"*",
".",
"mtls",
".",
"googleapis",
".",
"com",
"respectively",
".",
"Args",
":",
"api_endpoint",
"(",
"Optional",
"[",
"str",
"]",
")",
":",
"the",
"api",
"endpoint",
"to",
"convert",
".",
"Returns",
":",
"str",
":",
"converted",
"mTLS",
"api",
"endpoint",
"."
] |
def _get_default_mtls_endpoint(api_endpoint):
"""Convert api endpoint to mTLS endpoint.
Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
"*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
Args:
api_endpoint (Optional[str]): the api endpoint to convert.
Returns:
str: converted mTLS api endpoint.
"""
if not api_endpoint:
return api_endpoint
mtls_endpoint_re = re.compile(
r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?"
)
m = mtls_endpoint_re.match(api_endpoint)
name, mtls, sandbox, googledomain = m.groups()
if mtls or not googledomain:
return api_endpoint
if sandbox:
return api_endpoint.replace(
"sandbox.googleapis.com", "mtls.sandbox.googleapis.com"
)
return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
|
[
"def",
"_get_default_mtls_endpoint",
"(",
"api_endpoint",
")",
":",
"if",
"not",
"api_endpoint",
":",
"return",
"api_endpoint",
"mtls_endpoint_re",
"=",
"re",
".",
"compile",
"(",
"r\"(?P<name>[^.]+)(?P<mtls>\\.mtls)?(?P<sandbox>\\.sandbox)?(?P<googledomain>\\.googleapis\\.com)?\"",
")",
"m",
"=",
"mtls_endpoint_re",
".",
"match",
"(",
"api_endpoint",
")",
"name",
",",
"mtls",
",",
"sandbox",
",",
"googledomain",
"=",
"m",
".",
"groups",
"(",
")",
"if",
"mtls",
"or",
"not",
"googledomain",
":",
"return",
"api_endpoint",
"if",
"sandbox",
":",
"return",
"api_endpoint",
".",
"replace",
"(",
"\"sandbox.googleapis.com\"",
",",
"\"mtls.sandbox.googleapis.com\"",
")",
"return",
"api_endpoint",
".",
"replace",
"(",
"\".googleapis.com\"",
",",
"\".mtls.googleapis.com\"",
")"
] |
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v9/services/services/campaign_criterion_service/client.py#L85-L111
|
|
holzschu/Carnets
|
44effb10ddfc6aa5c8b0687582a724ba82c6b547
|
Library/lib/python3.7/site-packages/asn1crypto/core.py
|
python
|
Sequence._setup
|
(self)
|
Generates _field_map, _field_ids and _oid_nums for use in parsing
|
Generates _field_map, _field_ids and _oid_nums for use in parsing
|
[
"Generates",
"_field_map",
"_field_ids",
"and",
"_oid_nums",
"for",
"use",
"in",
"parsing"
] |
def _setup(self):
"""
Generates _field_map, _field_ids and _oid_nums for use in parsing
"""
cls = self.__class__
cls._field_map = {}
cls._field_ids = []
cls._precomputed_specs = []
for index, field in enumerate(cls._fields):
if len(field) < 3:
field = field + ({},)
cls._fields[index] = field
cls._field_map[field[0]] = index
cls._field_ids.append(_build_id_tuple(field[2], field[1]))
if cls._oid_pair is not None:
cls._oid_nums = (cls._field_map[cls._oid_pair[0]], cls._field_map[cls._oid_pair[1]])
for index, field in enumerate(cls._fields):
has_callback = cls._spec_callbacks is not None and field[0] in cls._spec_callbacks
is_mapped_oid = cls._oid_nums is not None and cls._oid_nums[1] == index
if has_callback or is_mapped_oid:
cls._precomputed_specs.append(None)
else:
cls._precomputed_specs.append((field[0], field[1], field[1], field[2], None))
|
[
"def",
"_setup",
"(",
"self",
")",
":",
"cls",
"=",
"self",
".",
"__class__",
"cls",
".",
"_field_map",
"=",
"{",
"}",
"cls",
".",
"_field_ids",
"=",
"[",
"]",
"cls",
".",
"_precomputed_specs",
"=",
"[",
"]",
"for",
"index",
",",
"field",
"in",
"enumerate",
"(",
"cls",
".",
"_fields",
")",
":",
"if",
"len",
"(",
"field",
")",
"<",
"3",
":",
"field",
"=",
"field",
"+",
"(",
"{",
"}",
",",
")",
"cls",
".",
"_fields",
"[",
"index",
"]",
"=",
"field",
"cls",
".",
"_field_map",
"[",
"field",
"[",
"0",
"]",
"]",
"=",
"index",
"cls",
".",
"_field_ids",
".",
"append",
"(",
"_build_id_tuple",
"(",
"field",
"[",
"2",
"]",
",",
"field",
"[",
"1",
"]",
")",
")",
"if",
"cls",
".",
"_oid_pair",
"is",
"not",
"None",
":",
"cls",
".",
"_oid_nums",
"=",
"(",
"cls",
".",
"_field_map",
"[",
"cls",
".",
"_oid_pair",
"[",
"0",
"]",
"]",
",",
"cls",
".",
"_field_map",
"[",
"cls",
".",
"_oid_pair",
"[",
"1",
"]",
"]",
")",
"for",
"index",
",",
"field",
"in",
"enumerate",
"(",
"cls",
".",
"_fields",
")",
":",
"has_callback",
"=",
"cls",
".",
"_spec_callbacks",
"is",
"not",
"None",
"and",
"field",
"[",
"0",
"]",
"in",
"cls",
".",
"_spec_callbacks",
"is_mapped_oid",
"=",
"cls",
".",
"_oid_nums",
"is",
"not",
"None",
"and",
"cls",
".",
"_oid_nums",
"[",
"1",
"]",
"==",
"index",
"if",
"has_callback",
"or",
"is_mapped_oid",
":",
"cls",
".",
"_precomputed_specs",
".",
"append",
"(",
"None",
")",
"else",
":",
"cls",
".",
"_precomputed_specs",
".",
"append",
"(",
"(",
"field",
"[",
"0",
"]",
",",
"field",
"[",
"1",
"]",
",",
"field",
"[",
"1",
"]",
",",
"field",
"[",
"2",
"]",
",",
"None",
")",
")"
] |
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/asn1crypto/core.py#L3426-L3451
|
||
Scifabric/pybossa
|
fd87953c067a94ae211cd8771d4eead130ef3c64
|
pybossa/ratelimit/__init__.py
|
python
|
get_view_rate_limit
|
()
|
return getattr(g, '_view_rate_limit', None)
|
Return the rate limit values.
|
Return the rate limit values.
|
[
"Return",
"the",
"rate",
"limit",
"values",
"."
] |
def get_view_rate_limit():
"""Return the rate limit values."""
return getattr(g, '_view_rate_limit', None)
|
[
"def",
"get_view_rate_limit",
"(",
")",
":",
"return",
"getattr",
"(",
"g",
",",
"'_view_rate_limit'",
",",
"None",
")"
] |
https://github.com/Scifabric/pybossa/blob/fd87953c067a94ae211cd8771d4eead130ef3c64/pybossa/ratelimit/__init__.py#L66-L68
|
|
AppScale/gts
|
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
|
AppServer/lib/django-1.2/django/contrib/gis/geos/point.py
|
python
|
Point._create_point
|
(self, ndim, coords)
|
return capi.create_point(cs)
|
Create a coordinate sequence, set X, Y, [Z], and create point
|
Create a coordinate sequence, set X, Y, [Z], and create point
|
[
"Create",
"a",
"coordinate",
"sequence",
"set",
"X",
"Y",
"[",
"Z",
"]",
"and",
"create",
"point"
] |
def _create_point(self, ndim, coords):
"""
Create a coordinate sequence, set X, Y, [Z], and create point
"""
if ndim < 2 or ndim > 3:
raise TypeError('Invalid point dimension: %s' % str(ndim))
cs = capi.create_cs(c_uint(1), c_uint(ndim))
i = iter(coords)
capi.cs_setx(cs, 0, i.next())
capi.cs_sety(cs, 0, i.next())
if ndim == 3: capi.cs_setz(cs, 0, i.next())
return capi.create_point(cs)
|
[
"def",
"_create_point",
"(",
"self",
",",
"ndim",
",",
"coords",
")",
":",
"if",
"ndim",
"<",
"2",
"or",
"ndim",
">",
"3",
":",
"raise",
"TypeError",
"(",
"'Invalid point dimension: %s'",
"%",
"str",
"(",
"ndim",
")",
")",
"cs",
"=",
"capi",
".",
"create_cs",
"(",
"c_uint",
"(",
"1",
")",
",",
"c_uint",
"(",
"ndim",
")",
")",
"i",
"=",
"iter",
"(",
"coords",
")",
"capi",
".",
"cs_setx",
"(",
"cs",
",",
"0",
",",
"i",
".",
"next",
"(",
")",
")",
"capi",
".",
"cs_sety",
"(",
"cs",
",",
"0",
",",
"i",
".",
"next",
"(",
")",
")",
"if",
"ndim",
"==",
"3",
":",
"capi",
".",
"cs_setz",
"(",
"cs",
",",
"0",
",",
"i",
".",
"next",
"(",
")",
")",
"return",
"capi",
".",
"create_point",
"(",
"cs",
")"
] |
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.2/django/contrib/gis/geos/point.py#L40-L53
|
|
googleads/google-ads-python
|
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
|
google/ads/googleads/v9/services/services/click_view_service/client.py
|
python
|
ClickViewServiceClient.__exit__
|
(self, type, value, traceback)
|
Releases underlying transport's resources.
.. warning::
ONLY use as a context manager if the transport is NOT shared
with other clients! Exiting the with block will CLOSE the transport
and may cause errors in other clients!
|
Releases underlying transport's resources.
|
[
"Releases",
"underlying",
"transport",
"s",
"resources",
"."
] |
def __exit__(self, type, value, traceback):
"""Releases underlying transport's resources.
.. warning::
ONLY use as a context manager if the transport is NOT shared
with other clients! Exiting the with block will CLOSE the transport
and may cause errors in other clients!
"""
self.transport.close()
|
[
"def",
"__exit__",
"(",
"self",
",",
"type",
",",
"value",
",",
"traceback",
")",
":",
"self",
".",
"transport",
".",
"close",
"(",
")"
] |
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v9/services/services/click_view_service/client.py#L164-L172
|
||
TencentCloud/tencentcloud-sdk-python
|
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
|
tencentcloud/ses/v20201002/models.py
|
python
|
UpdateEmailTemplateRequest.__init__
|
(self)
|
r"""
:param TemplateContent: 模板内容
:type TemplateContent: :class:`tencentcloud.ses.v20201002.models.TemplateContent`
:param TemplateID: 模板ID
:type TemplateID: int
:param TemplateName: 模版名字
:type TemplateName: str
|
r"""
:param TemplateContent: 模板内容
:type TemplateContent: :class:`tencentcloud.ses.v20201002.models.TemplateContent`
:param TemplateID: 模板ID
:type TemplateID: int
:param TemplateName: 模版名字
:type TemplateName: str
|
[
"r",
":",
"param",
"TemplateContent",
":",
"模板内容",
":",
"type",
"TemplateContent",
":",
":",
"class",
":",
"tencentcloud",
".",
"ses",
".",
"v20201002",
".",
"models",
".",
"TemplateContent",
":",
"param",
"TemplateID",
":",
"模板ID",
":",
"type",
"TemplateID",
":",
"int",
":",
"param",
"TemplateName",
":",
"模版名字",
":",
"type",
"TemplateName",
":",
"str"
] |
def __init__(self):
r"""
:param TemplateContent: 模板内容
:type TemplateContent: :class:`tencentcloud.ses.v20201002.models.TemplateContent`
:param TemplateID: 模板ID
:type TemplateID: int
:param TemplateName: 模版名字
:type TemplateName: str
"""
self.TemplateContent = None
self.TemplateID = None
self.TemplateName = None
|
[
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"TemplateContent",
"=",
"None",
"self",
".",
"TemplateID",
"=",
"None",
"self",
".",
"TemplateName",
"=",
"None"
] |
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/ses/v20201002/models.py#L1445-L1456
|
||
python-cmd2/cmd2
|
c1f6114d52161a3b8a32d3cee1c495d79052e1fb
|
cmd2/utils.py
|
python
|
align_center
|
(
text: str, *, fill_char: str = ' ', width: Optional[int] = None, tab_width: int = 4, truncate: bool = False
)
|
return align_text(text, TextAlignment.CENTER, fill_char=fill_char, width=width, tab_width=tab_width, truncate=truncate)
|
Center text for display within a given width. Supports characters with display widths greater than 1.
ANSI style sequences do not count toward the display width. If text has line breaks, then each line is aligned
independently.
:param text: text to center (can contain multiple lines)
:param fill_char: character that fills the alignment gap. Defaults to space. (Cannot be a line breaking character)
:param width: display width of the aligned text. Defaults to width of the terminal.
:param tab_width: any tabs in the text will be replaced with this many spaces. if fill_char is a tab, then it will
be converted to one space.
:param truncate: if True, then text will be shortened to fit within the display width. The truncated portion is
replaced by a '…' character. Defaults to False.
:return: centered text
:raises: TypeError if fill_char is more than one character (not including ANSI style sequences)
:raises: ValueError if text or fill_char contains an unprintable character
:raises: ValueError if width is less than 1
|
Center text for display within a given width. Supports characters with display widths greater than 1.
ANSI style sequences do not count toward the display width. If text has line breaks, then each line is aligned
independently.
|
[
"Center",
"text",
"for",
"display",
"within",
"a",
"given",
"width",
".",
"Supports",
"characters",
"with",
"display",
"widths",
"greater",
"than",
"1",
".",
"ANSI",
"style",
"sequences",
"do",
"not",
"count",
"toward",
"the",
"display",
"width",
".",
"If",
"text",
"has",
"line",
"breaks",
"then",
"each",
"line",
"is",
"aligned",
"independently",
"."
] |
def align_center(
text: str, *, fill_char: str = ' ', width: Optional[int] = None, tab_width: int = 4, truncate: bool = False
) -> str:
"""
Center text for display within a given width. Supports characters with display widths greater than 1.
ANSI style sequences do not count toward the display width. If text has line breaks, then each line is aligned
independently.
:param text: text to center (can contain multiple lines)
:param fill_char: character that fills the alignment gap. Defaults to space. (Cannot be a line breaking character)
:param width: display width of the aligned text. Defaults to width of the terminal.
:param tab_width: any tabs in the text will be replaced with this many spaces. if fill_char is a tab, then it will
be converted to one space.
:param truncate: if True, then text will be shortened to fit within the display width. The truncated portion is
replaced by a '…' character. Defaults to False.
:return: centered text
:raises: TypeError if fill_char is more than one character (not including ANSI style sequences)
:raises: ValueError if text or fill_char contains an unprintable character
:raises: ValueError if width is less than 1
"""
return align_text(text, TextAlignment.CENTER, fill_char=fill_char, width=width, tab_width=tab_width, truncate=truncate)
|
[
"def",
"align_center",
"(",
"text",
":",
"str",
",",
"*",
",",
"fill_char",
":",
"str",
"=",
"' '",
",",
"width",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"tab_width",
":",
"int",
"=",
"4",
",",
"truncate",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"return",
"align_text",
"(",
"text",
",",
"TextAlignment",
".",
"CENTER",
",",
"fill_char",
"=",
"fill_char",
",",
"width",
"=",
"width",
",",
"tab_width",
"=",
"tab_width",
",",
"truncate",
"=",
"truncate",
")"
] |
https://github.com/python-cmd2/cmd2/blob/c1f6114d52161a3b8a32d3cee1c495d79052e1fb/cmd2/utils.py#L902-L922
|
|
bytefish/facerec
|
4071e1e79a50dbf1d1f2e061d24448576e5ac37d
|
py/apps/videofacerec/helper/video.py
|
python
|
VideoSynthBase.__init__
|
(self, size=None, noise=0.0, bg = None, **params)
|
[] |
def __init__(self, size=None, noise=0.0, bg = None, **params):
self.bg = None
self.frame_size = (640, 480)
if bg is not None:
self.bg = cv2.imread(bg, 1)
h, w = self.bg.shape[:2]
self.frame_size = (w, h)
if size is not None:
w, h = map(int, size.split('x'))
self.frame_size = (w, h)
self.bg = cv2.resize(self.bg, self.frame_size)
self.noise = float(noise)
|
[
"def",
"__init__",
"(",
"self",
",",
"size",
"=",
"None",
",",
"noise",
"=",
"0.0",
",",
"bg",
"=",
"None",
",",
"*",
"*",
"params",
")",
":",
"self",
".",
"bg",
"=",
"None",
"self",
".",
"frame_size",
"=",
"(",
"640",
",",
"480",
")",
"if",
"bg",
"is",
"not",
"None",
":",
"self",
".",
"bg",
"=",
"cv2",
".",
"imread",
"(",
"bg",
",",
"1",
")",
"h",
",",
"w",
"=",
"self",
".",
"bg",
".",
"shape",
"[",
":",
"2",
"]",
"self",
".",
"frame_size",
"=",
"(",
"w",
",",
"h",
")",
"if",
"size",
"is",
"not",
"None",
":",
"w",
",",
"h",
"=",
"map",
"(",
"int",
",",
"size",
".",
"split",
"(",
"'x'",
")",
")",
"self",
".",
"frame_size",
"=",
"(",
"w",
",",
"h",
")",
"self",
".",
"bg",
"=",
"cv2",
".",
"resize",
"(",
"self",
".",
"bg",
",",
"self",
".",
"frame_size",
")",
"self",
".",
"noise",
"=",
"float",
"(",
"noise",
")"
] |
https://github.com/bytefish/facerec/blob/4071e1e79a50dbf1d1f2e061d24448576e5ac37d/py/apps/videofacerec/helper/video.py#L11-L24
|
||||
IronLanguages/ironpython3
|
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
|
Src/StdLib/Lib/idlelib/CallTipWindow.py
|
python
|
CallTip.is_active
|
(self)
|
return bool(self.tipwindow)
|
[] |
def is_active(self):
return bool(self.tipwindow)
|
[
"def",
"is_active",
"(",
"self",
")",
":",
"return",
"bool",
"(",
"self",
".",
"tipwindow",
")"
] |
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/idlelib/CallTipWindow.py#L132-L133
|
|||
hydroshare/hydroshare
|
7ba563b55412f283047fb3ef6da367d41dec58c6
|
hs_app_timeseries/receivers.py
|
python
|
pre_delete_file_from_resource_handler
|
(sender, **kwargs)
|
[] |
def pre_delete_file_from_resource_handler(sender, **kwargs):
# if any of the content files (sqlite or csv) is deleted then reset the 'is_dirty' attribute
# for all extracted metadata to False
resource = kwargs['resource']
def reset_metadata_elements_is_dirty(elements):
# filter out any non-dirty element
elements = [element for element in elements if element.is_dirty]
for element in elements:
element.is_dirty = False
element.save()
if resource.metadata.is_dirty:
TimeSeriesMetaData.objects.filter(id=resource.metadata.id).update(is_dirty=False)
# metadata object is_dirty attribute for some reason can't be set using the following
# 2 lines of code
# resource.metadata.is_dirty=False
# resource.metadata.save()
reset_metadata_elements_is_dirty(resource.metadata.sites.all())
reset_metadata_elements_is_dirty(resource.metadata.variables.all())
reset_metadata_elements_is_dirty(resource.metadata.methods.all())
reset_metadata_elements_is_dirty(resource.metadata.processing_levels.all())
reset_metadata_elements_is_dirty(resource.metadata.time_series_results.all())
reset_metadata_elements_is_dirty(resource.metadata.cv_variable_types.all())
reset_metadata_elements_is_dirty(resource.metadata.cv_variable_names.all())
reset_metadata_elements_is_dirty(resource.metadata.cv_speciations.all())
reset_metadata_elements_is_dirty(resource.metadata.cv_elevation_datums.all())
reset_metadata_elements_is_dirty(resource.metadata.cv_site_types.all())
reset_metadata_elements_is_dirty(resource.metadata.cv_method_types.all())
reset_metadata_elements_is_dirty(resource.metadata.cv_units_types.all())
reset_metadata_elements_is_dirty(resource.metadata.cv_statuses.all())
reset_metadata_elements_is_dirty(resource.metadata.cv_aggregation_statistics.all())
|
[
"def",
"pre_delete_file_from_resource_handler",
"(",
"sender",
",",
"*",
"*",
"kwargs",
")",
":",
"# if any of the content files (sqlite or csv) is deleted then reset the 'is_dirty' attribute",
"# for all extracted metadata to False",
"resource",
"=",
"kwargs",
"[",
"'resource'",
"]",
"def",
"reset_metadata_elements_is_dirty",
"(",
"elements",
")",
":",
"# filter out any non-dirty element",
"elements",
"=",
"[",
"element",
"for",
"element",
"in",
"elements",
"if",
"element",
".",
"is_dirty",
"]",
"for",
"element",
"in",
"elements",
":",
"element",
".",
"is_dirty",
"=",
"False",
"element",
".",
"save",
"(",
")",
"if",
"resource",
".",
"metadata",
".",
"is_dirty",
":",
"TimeSeriesMetaData",
".",
"objects",
".",
"filter",
"(",
"id",
"=",
"resource",
".",
"metadata",
".",
"id",
")",
".",
"update",
"(",
"is_dirty",
"=",
"False",
")",
"# metadata object is_dirty attribute for some reason can't be set using the following",
"# 2 lines of code",
"# resource.metadata.is_dirty=False",
"# resource.metadata.save()",
"reset_metadata_elements_is_dirty",
"(",
"resource",
".",
"metadata",
".",
"sites",
".",
"all",
"(",
")",
")",
"reset_metadata_elements_is_dirty",
"(",
"resource",
".",
"metadata",
".",
"variables",
".",
"all",
"(",
")",
")",
"reset_metadata_elements_is_dirty",
"(",
"resource",
".",
"metadata",
".",
"methods",
".",
"all",
"(",
")",
")",
"reset_metadata_elements_is_dirty",
"(",
"resource",
".",
"metadata",
".",
"processing_levels",
".",
"all",
"(",
")",
")",
"reset_metadata_elements_is_dirty",
"(",
"resource",
".",
"metadata",
".",
"time_series_results",
".",
"all",
"(",
")",
")",
"reset_metadata_elements_is_dirty",
"(",
"resource",
".",
"metadata",
".",
"cv_variable_types",
".",
"all",
"(",
")",
")",
"reset_metadata_elements_is_dirty",
"(",
"resource",
".",
"metadata",
".",
"cv_variable_names",
".",
"all",
"(",
")",
")",
"reset_metadata_elements_is_dirty",
"(",
"resource",
".",
"metadata",
".",
"cv_speciations",
".",
"all",
"(",
")",
")",
"reset_metadata_elements_is_dirty",
"(",
"resource",
".",
"metadata",
".",
"cv_elevation_datums",
".",
"all",
"(",
")",
")",
"reset_metadata_elements_is_dirty",
"(",
"resource",
".",
"metadata",
".",
"cv_site_types",
".",
"all",
"(",
")",
")",
"reset_metadata_elements_is_dirty",
"(",
"resource",
".",
"metadata",
".",
"cv_method_types",
".",
"all",
"(",
")",
")",
"reset_metadata_elements_is_dirty",
"(",
"resource",
".",
"metadata",
".",
"cv_units_types",
".",
"all",
"(",
")",
")",
"reset_metadata_elements_is_dirty",
"(",
"resource",
".",
"metadata",
".",
"cv_statuses",
".",
"all",
"(",
")",
")",
"reset_metadata_elements_is_dirty",
"(",
"resource",
".",
"metadata",
".",
"cv_aggregation_statistics",
".",
"all",
"(",
")",
")"
] |
https://github.com/hydroshare/hydroshare/blob/7ba563b55412f283047fb3ef6da367d41dec58c6/hs_app_timeseries/receivers.py#L48-L80
|
||||
TencentCloud/tencentcloud-sdk-python
|
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
|
tencentcloud/sqlserver/v20180328/models.py
|
python
|
DeletePublishSubscribeRequest.__init__
|
(self)
|
r"""
:param PublishSubscribeId: 发布订阅ID,可通过DescribePublishSubscribe接口获得
:type PublishSubscribeId: int
:param DatabaseTupleSet: 待删除的数据库的订阅发布关系集合
:type DatabaseTupleSet: list of DatabaseTuple
|
r"""
:param PublishSubscribeId: 发布订阅ID,可通过DescribePublishSubscribe接口获得
:type PublishSubscribeId: int
:param DatabaseTupleSet: 待删除的数据库的订阅发布关系集合
:type DatabaseTupleSet: list of DatabaseTuple
|
[
"r",
":",
"param",
"PublishSubscribeId",
":",
"发布订阅ID,可通过DescribePublishSubscribe接口获得",
":",
"type",
"PublishSubscribeId",
":",
"int",
":",
"param",
"DatabaseTupleSet",
":",
"待删除的数据库的订阅发布关系集合",
":",
"type",
"DatabaseTupleSet",
":",
"list",
"of",
"DatabaseTuple"
] |
def __init__(self):
r"""
:param PublishSubscribeId: 发布订阅ID,可通过DescribePublishSubscribe接口获得
:type PublishSubscribeId: int
:param DatabaseTupleSet: 待删除的数据库的订阅发布关系集合
:type DatabaseTupleSet: list of DatabaseTuple
"""
self.PublishSubscribeId = None
self.DatabaseTupleSet = None
|
[
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"PublishSubscribeId",
"=",
"None",
"self",
".",
"DatabaseTupleSet",
"=",
"None"
] |
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/sqlserver/v20180328/models.py#L2255-L2263
|
||
biolab/orange3
|
41685e1c7b1d1babe680113685a2d44bcc9fec0b
|
Orange/data/pandas_compat.py
|
python
|
table_to_frames
|
(table)
|
return xdf, ydf, mdf
|
[] |
def table_to_frames(table):
xdf = OrangeDataFrame(table, Role.Attribute)
ydf = OrangeDataFrame(table, Role.ClassAttribute)
mdf = OrangeDataFrame(table, Role.Meta)
return xdf, ydf, mdf
|
[
"def",
"table_to_frames",
"(",
"table",
")",
":",
"xdf",
"=",
"OrangeDataFrame",
"(",
"table",
",",
"Role",
".",
"Attribute",
")",
"ydf",
"=",
"OrangeDataFrame",
"(",
"table",
",",
"Role",
".",
"ClassAttribute",
")",
"mdf",
"=",
"OrangeDataFrame",
"(",
"table",
",",
"Role",
".",
"Meta",
")",
"return",
"xdf",
",",
"ydf",
",",
"mdf"
] |
https://github.com/biolab/orange3/blob/41685e1c7b1d1babe680113685a2d44bcc9fec0b/Orange/data/pandas_compat.py#L458-L463
|
|||
Zulko/easyAI
|
a5cbd0b600ebbeadc3730df9e7a211d7643cff8b
|
easyAI/games/ThreeMusketeers.py
|
python
|
ThreeMusketeers.make_move
|
(self, move)
|
move = [y1, x1, y2, x2]
|
move = [y1, x1, y2, x2]
|
[
"move",
"=",
"[",
"y1",
"x1",
"y2",
"x2",
"]"
] |
def make_move(self, move):
""" move = [y1, x1, y2, x2] """
if move == "None":
return
self.board[move[0], move[1]] = 0
self.board[move[2], move[3]] = self.current_player
if self.current_player == 1:
self.musketeers.remove((move[0], move[1]))
self.musketeers.append((move[2], move[3]))
|
[
"def",
"make_move",
"(",
"self",
",",
"move",
")",
":",
"if",
"move",
"==",
"\"None\"",
":",
"return",
"self",
".",
"board",
"[",
"move",
"[",
"0",
"]",
",",
"move",
"[",
"1",
"]",
"]",
"=",
"0",
"self",
".",
"board",
"[",
"move",
"[",
"2",
"]",
",",
"move",
"[",
"3",
"]",
"]",
"=",
"self",
".",
"current_player",
"if",
"self",
".",
"current_player",
"==",
"1",
":",
"self",
".",
"musketeers",
".",
"remove",
"(",
"(",
"move",
"[",
"0",
"]",
",",
"move",
"[",
"1",
"]",
")",
")",
"self",
".",
"musketeers",
".",
"append",
"(",
"(",
"move",
"[",
"2",
"]",
",",
"move",
"[",
"3",
"]",
")",
")"
] |
https://github.com/Zulko/easyAI/blob/a5cbd0b600ebbeadc3730df9e7a211d7643cff8b/easyAI/games/ThreeMusketeers.py#L50-L60
|
||
zeusees/License-Plate-Detector
|
59615d375ddd8e67b0c246d2b8997b0489760eef
|
hubconf.py
|
python
|
custom
|
(path_or_model='path/to/model.pt', autoshape=True)
|
return hub_model.autoshape() if autoshape else hub_model
|
YOLOv5-custom model from https://github.com/ultralytics/yolov5
Arguments (3 options):
path_or_model (str): 'path/to/model.pt'
path_or_model (dict): torch.load('path/to/model.pt')
path_or_model (nn.Module): torch.load('path/to/model.pt')['model']
Returns:
pytorch model
|
YOLOv5-custom model from https://github.com/ultralytics/yolov5
|
[
"YOLOv5",
"-",
"custom",
"model",
"from",
"https",
":",
"//",
"github",
".",
"com",
"/",
"ultralytics",
"/",
"yolov5"
] |
def custom(path_or_model='path/to/model.pt', autoshape=True):
"""YOLOv5-custom model from https://github.com/ultralytics/yolov5
Arguments (3 options):
path_or_model (str): 'path/to/model.pt'
path_or_model (dict): torch.load('path/to/model.pt')
path_or_model (nn.Module): torch.load('path/to/model.pt')['model']
Returns:
pytorch model
"""
model = torch.load(path_or_model) if isinstance(path_or_model, str) else path_or_model # load checkpoint
if isinstance(model, dict):
model = model['model'] # load model
hub_model = Model(model.yaml).to(next(model.parameters()).device) # create
hub_model.load_state_dict(model.float().state_dict()) # load state_dict
hub_model.names = model.names # class names
return hub_model.autoshape() if autoshape else hub_model
|
[
"def",
"custom",
"(",
"path_or_model",
"=",
"'path/to/model.pt'",
",",
"autoshape",
"=",
"True",
")",
":",
"model",
"=",
"torch",
".",
"load",
"(",
"path_or_model",
")",
"if",
"isinstance",
"(",
"path_or_model",
",",
"str",
")",
"else",
"path_or_model",
"# load checkpoint",
"if",
"isinstance",
"(",
"model",
",",
"dict",
")",
":",
"model",
"=",
"model",
"[",
"'model'",
"]",
"# load model",
"hub_model",
"=",
"Model",
"(",
"model",
".",
"yaml",
")",
".",
"to",
"(",
"next",
"(",
"model",
".",
"parameters",
"(",
")",
")",
".",
"device",
")",
"# create",
"hub_model",
".",
"load_state_dict",
"(",
"model",
".",
"float",
"(",
")",
".",
"state_dict",
"(",
")",
")",
"# load state_dict",
"hub_model",
".",
"names",
"=",
"model",
".",
"names",
"# class names",
"return",
"hub_model",
".",
"autoshape",
"(",
")",
"if",
"autoshape",
"else",
"hub_model"
] |
https://github.com/zeusees/License-Plate-Detector/blob/59615d375ddd8e67b0c246d2b8997b0489760eef/hubconf.py#L110-L128
|
|
progrium/ginkgo
|
440b75186506bf9a8badba038068dd97293ea4b8
|
ginkgo/async/gevent.py
|
python
|
AsyncManager.spawn
|
(self, func, *args, **kwargs)
|
return self._greenlets.spawn(func, *args, **kwargs)
|
Spawn a greenlet under this service
|
Spawn a greenlet under this service
|
[
"Spawn",
"a",
"greenlet",
"under",
"this",
"service"
] |
def spawn(self, func, *args, **kwargs):
"""Spawn a greenlet under this service"""
return self._greenlets.spawn(func, *args, **kwargs)
|
[
"def",
"spawn",
"(",
"self",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_greenlets",
".",
"spawn",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/progrium/ginkgo/blob/440b75186506bf9a8badba038068dd97293ea4b8/ginkgo/async/gevent.py#L48-L50
|
|
IronLanguages/ironpython3
|
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
|
Src/StdLib/Lib/encodings/charmap.py
|
python
|
StreamReader.decode
|
(self,input,errors='strict')
|
return Codec.decode(input,errors,self.mapping)
|
[] |
def decode(self,input,errors='strict'):
return Codec.decode(input,errors,self.mapping)
|
[
"def",
"decode",
"(",
"self",
",",
"input",
",",
"errors",
"=",
"'strict'",
")",
":",
"return",
"Codec",
".",
"decode",
"(",
"input",
",",
"errors",
",",
"self",
".",
"mapping",
")"
] |
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/encodings/charmap.py#L55-L56
|
|||
hzlzh/AlfredWorkflow.com
|
7055f14f6922c80ea5943839eb0caff11ae57255
|
Sources/Workflows/XLixian/iambus_xunlei_lixian/lixian_plugins/commands/extend_links.py
|
python
|
extend_links
|
(args)
|
usage: lx extend-links http://kuai.xunlei.com/d/... http://www.verycd.com/topics/...
parse and print links from pages
lx extend-links urls...
lx extend-links --name urls...
|
usage: lx extend-links http://kuai.xunlei.com/d/... http://www.verycd.com/topics/...
|
[
"usage",
":",
"lx",
"extend",
"-",
"links",
"http",
":",
"//",
"kuai",
".",
"xunlei",
".",
"com",
"/",
"d",
"/",
"...",
"http",
":",
"//",
"www",
".",
"verycd",
".",
"com",
"/",
"topics",
"/",
"..."
] |
def extend_links(args):
'''
usage: lx extend-links http://kuai.xunlei.com/d/... http://www.verycd.com/topics/...
parse and print links from pages
lx extend-links urls...
lx extend-links --name urls...
'''
from lixian_cli_parser import parse_command_line
from lixian_encoding import default_encoding
args = parse_command_line(args, [], ['name'])
import lixian_plugins.parsers
if args.name:
for x in lixian_plugins.parsers.extend_links_name(args):
print x.encode(default_encoding)
else:
for x in lixian_plugins.parsers.extend_links(args):
print x
|
[
"def",
"extend_links",
"(",
"args",
")",
":",
"from",
"lixian_cli_parser",
"import",
"parse_command_line",
"from",
"lixian_encoding",
"import",
"default_encoding",
"args",
"=",
"parse_command_line",
"(",
"args",
",",
"[",
"]",
",",
"[",
"'name'",
"]",
")",
"import",
"lixian_plugins",
".",
"parsers",
"if",
"args",
".",
"name",
":",
"for",
"x",
"in",
"lixian_plugins",
".",
"parsers",
".",
"extend_links_name",
"(",
"args",
")",
":",
"print",
"x",
".",
"encode",
"(",
"default_encoding",
")",
"else",
":",
"for",
"x",
"in",
"lixian_plugins",
".",
"parsers",
".",
"extend_links",
"(",
"args",
")",
":",
"print",
"x"
] |
https://github.com/hzlzh/AlfredWorkflow.com/blob/7055f14f6922c80ea5943839eb0caff11ae57255/Sources/Workflows/XLixian/iambus_xunlei_lixian/lixian_plugins/commands/extend_links.py#L5-L25
|
||
darkonhub/darkon
|
5f35a12585f5edb43ab1da5edd8d05243da65a64
|
darkon/gradcam/gradcam.py
|
python
|
Gradcam.gradcam
|
(self, sess, input_data, target_index=None, feed_options=dict())
|
return ret
|
Calculate Grad-CAM (class activation map) and Guided Grad-CAM for given input on target class
Parameters
----------
sess: tf.Session
Tensorflow session
input_data : numpy.ndarray
A single input instance
target_index : int
Target class index
If None, predicted class index is used
feed_options : dict
Optional parameters to graph
Returns
-------
dict
Note
----
Keys in return:
* gradcam_img: Heatmap overlayed on input
* guided_gradcam_img: Guided Grad-CAM result
* heatmap: Heatmap of input on the target class
* guided_backprop: Guided backprop result
|
Calculate Grad-CAM (class activation map) and Guided Grad-CAM for given input on target class
|
[
"Calculate",
"Grad",
"-",
"CAM",
"(",
"class",
"activation",
"map",
")",
"and",
"Guided",
"Grad",
"-",
"CAM",
"for",
"given",
"input",
"on",
"target",
"class"
] |
def gradcam(self, sess, input_data, target_index=None, feed_options=dict()):
""" Calculate Grad-CAM (class activation map) and Guided Grad-CAM for given input on target class
Parameters
----------
sess: tf.Session
Tensorflow session
input_data : numpy.ndarray
A single input instance
target_index : int
Target class index
If None, predicted class index is used
feed_options : dict
Optional parameters to graph
Returns
-------
dict
Note
----
Keys in return:
* gradcam_img: Heatmap overlayed on input
* guided_gradcam_img: Guided Grad-CAM result
* heatmap: Heatmap of input on the target class
* guided_backprop: Guided backprop result
"""
input_feed = np.expand_dims(input_data, axis=0)
if input_data.ndim == 3:
is_image = True
image_height, image_width = input_data.shape[:2]
if input_data.ndim == 1:
is_image = False
input_length = input_data.shape[0]
if target_index is not None:
feed_dict = {self._x_placeholder: input_feed, self._class_idx: target_index}
feed_dict.update(feed_options)
conv_out_eval, grad_eval = sess.run([self._target_ts, self._grad_by_idx], feed_dict=feed_dict)
else:
feed_dict = {self._x_placeholder: input_feed}
feed_dict.update(feed_options)
conv_out_eval, grad_eval = sess.run([self._target_ts, self._grad_by_top1], feed_dict=feed_dict)
weights = np.mean(grad_eval, axis=(0, 1, 2))
conv_out_eval = np.squeeze(conv_out_eval, axis=0)
cam = np.zeros(conv_out_eval.shape[:2], dtype=np.float32)
for i, w in enumerate(weights):
cam += w * conv_out_eval[:, :, i]
if is_image:
cam += 1
cam = cv2.resize(cam, (image_height, image_width))
saliency_val = sess.run(self._saliency_map, feed_dict={self._x_placeholder: input_feed})
saliency_val = np.squeeze(saliency_val, axis=0)
else:
cam = skimage_resize(cam, (input_length, 1), preserve_range=True, mode='reflect')
cam = np.transpose(cam)
cam = np.maximum(cam, 0)
heatmap = cam / np.max(cam)
ret = {'heatmap': heatmap}
if is_image:
ret.update({
'gradcam_img': self.overlay_gradcam(input_data, heatmap),
'guided_gradcam_img': _deprocess_image(saliency_val * heatmap[..., None]),
'guided_backprop': saliency_val
})
return ret
|
[
"def",
"gradcam",
"(",
"self",
",",
"sess",
",",
"input_data",
",",
"target_index",
"=",
"None",
",",
"feed_options",
"=",
"dict",
"(",
")",
")",
":",
"input_feed",
"=",
"np",
".",
"expand_dims",
"(",
"input_data",
",",
"axis",
"=",
"0",
")",
"if",
"input_data",
".",
"ndim",
"==",
"3",
":",
"is_image",
"=",
"True",
"image_height",
",",
"image_width",
"=",
"input_data",
".",
"shape",
"[",
":",
"2",
"]",
"if",
"input_data",
".",
"ndim",
"==",
"1",
":",
"is_image",
"=",
"False",
"input_length",
"=",
"input_data",
".",
"shape",
"[",
"0",
"]",
"if",
"target_index",
"is",
"not",
"None",
":",
"feed_dict",
"=",
"{",
"self",
".",
"_x_placeholder",
":",
"input_feed",
",",
"self",
".",
"_class_idx",
":",
"target_index",
"}",
"feed_dict",
".",
"update",
"(",
"feed_options",
")",
"conv_out_eval",
",",
"grad_eval",
"=",
"sess",
".",
"run",
"(",
"[",
"self",
".",
"_target_ts",
",",
"self",
".",
"_grad_by_idx",
"]",
",",
"feed_dict",
"=",
"feed_dict",
")",
"else",
":",
"feed_dict",
"=",
"{",
"self",
".",
"_x_placeholder",
":",
"input_feed",
"}",
"feed_dict",
".",
"update",
"(",
"feed_options",
")",
"conv_out_eval",
",",
"grad_eval",
"=",
"sess",
".",
"run",
"(",
"[",
"self",
".",
"_target_ts",
",",
"self",
".",
"_grad_by_top1",
"]",
",",
"feed_dict",
"=",
"feed_dict",
")",
"weights",
"=",
"np",
".",
"mean",
"(",
"grad_eval",
",",
"axis",
"=",
"(",
"0",
",",
"1",
",",
"2",
")",
")",
"conv_out_eval",
"=",
"np",
".",
"squeeze",
"(",
"conv_out_eval",
",",
"axis",
"=",
"0",
")",
"cam",
"=",
"np",
".",
"zeros",
"(",
"conv_out_eval",
".",
"shape",
"[",
":",
"2",
"]",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"for",
"i",
",",
"w",
"in",
"enumerate",
"(",
"weights",
")",
":",
"cam",
"+=",
"w",
"*",
"conv_out_eval",
"[",
":",
",",
":",
",",
"i",
"]",
"if",
"is_image",
":",
"cam",
"+=",
"1",
"cam",
"=",
"cv2",
".",
"resize",
"(",
"cam",
",",
"(",
"image_height",
",",
"image_width",
")",
")",
"saliency_val",
"=",
"sess",
".",
"run",
"(",
"self",
".",
"_saliency_map",
",",
"feed_dict",
"=",
"{",
"self",
".",
"_x_placeholder",
":",
"input_feed",
"}",
")",
"saliency_val",
"=",
"np",
".",
"squeeze",
"(",
"saliency_val",
",",
"axis",
"=",
"0",
")",
"else",
":",
"cam",
"=",
"skimage_resize",
"(",
"cam",
",",
"(",
"input_length",
",",
"1",
")",
",",
"preserve_range",
"=",
"True",
",",
"mode",
"=",
"'reflect'",
")",
"cam",
"=",
"np",
".",
"transpose",
"(",
"cam",
")",
"cam",
"=",
"np",
".",
"maximum",
"(",
"cam",
",",
"0",
")",
"heatmap",
"=",
"cam",
"/",
"np",
".",
"max",
"(",
"cam",
")",
"ret",
"=",
"{",
"'heatmap'",
":",
"heatmap",
"}",
"if",
"is_image",
":",
"ret",
".",
"update",
"(",
"{",
"'gradcam_img'",
":",
"self",
".",
"overlay_gradcam",
"(",
"input_data",
",",
"heatmap",
")",
",",
"'guided_gradcam_img'",
":",
"_deprocess_image",
"(",
"saliency_val",
"*",
"heatmap",
"[",
"...",
",",
"None",
"]",
")",
",",
"'guided_backprop'",
":",
"saliency_val",
"}",
")",
"return",
"ret"
] |
https://github.com/darkonhub/darkon/blob/5f35a12585f5edb43ab1da5edd8d05243da65a64/darkon/gradcam/gradcam.py#L99-L171
|
|
phonopy/phonopy
|
816586d0ba8177482ecf40e52f20cbdee2260d51
|
phonopy/structure/cells.py
|
python
|
get_smallest_vectors
|
(
supercell_bases, supercell_pos, primitive_pos, store_dense_svecs=False, symprec=1e-5
)
|
return spairs.shortest_vectors, spairs.multiplicities
|
Return shortest vectors and multiplicities.
See the details at `ShortestPairs`.
|
Return shortest vectors and multiplicities.
|
[
"Return",
"shortest",
"vectors",
"and",
"multiplicities",
"."
] |
def get_smallest_vectors(
supercell_bases, supercell_pos, primitive_pos, store_dense_svecs=False, symprec=1e-5
):
"""Return shortest vectors and multiplicities.
See the details at `ShortestPairs`.
"""
spairs = ShortestPairs(
supercell_bases,
supercell_pos,
primitive_pos,
store_dense_svecs=store_dense_svecs,
symprec=symprec,
)
return spairs.shortest_vectors, spairs.multiplicities
|
[
"def",
"get_smallest_vectors",
"(",
"supercell_bases",
",",
"supercell_pos",
",",
"primitive_pos",
",",
"store_dense_svecs",
"=",
"False",
",",
"symprec",
"=",
"1e-5",
")",
":",
"spairs",
"=",
"ShortestPairs",
"(",
"supercell_bases",
",",
"supercell_pos",
",",
"primitive_pos",
",",
"store_dense_svecs",
"=",
"store_dense_svecs",
",",
"symprec",
"=",
"symprec",
",",
")",
"return",
"spairs",
".",
"shortest_vectors",
",",
"spairs",
".",
"multiplicities"
] |
https://github.com/phonopy/phonopy/blob/816586d0ba8177482ecf40e52f20cbdee2260d51/phonopy/structure/cells.py#L935-L950
|
|
Tautulli/Tautulli
|
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
|
lib/future/backports/email/_header_value_parser.py
|
python
|
_validate_xtext
|
(xtext)
|
If input token contains ASCII non-printables, register a defect.
|
If input token contains ASCII non-printables, register a defect.
|
[
"If",
"input",
"token",
"contains",
"ASCII",
"non",
"-",
"printables",
"register",
"a",
"defect",
"."
] |
def _validate_xtext(xtext):
"""If input token contains ASCII non-printables, register a defect."""
non_printables = _non_printable_finder(xtext)
if non_printables:
xtext.defects.append(errors.NonPrintableDefect(non_printables))
if utils._has_surrogates(xtext):
xtext.defects.append(errors.UndecodableBytesDefect(
"Non-ASCII characters found in header token"))
|
[
"def",
"_validate_xtext",
"(",
"xtext",
")",
":",
"non_printables",
"=",
"_non_printable_finder",
"(",
"xtext",
")",
"if",
"non_printables",
":",
"xtext",
".",
"defects",
".",
"append",
"(",
"errors",
".",
"NonPrintableDefect",
"(",
"non_printables",
")",
")",
"if",
"utils",
".",
"_has_surrogates",
"(",
"xtext",
")",
":",
"xtext",
".",
"defects",
".",
"append",
"(",
"errors",
".",
"UndecodableBytesDefect",
"(",
"\"Non-ASCII characters found in header token\"",
")",
")"
] |
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/future/backports/email/_header_value_parser.py#L1359-L1367
|
||
sartography/SpiffWorkflow
|
764be6c276a278d372b96de470e39b29248a86d4
|
SpiffWorkflow/workflow.py
|
python
|
Workflow.complete_task_from_id
|
(self, task_id)
|
Runs the task with the given id.
:type task_id: integer
:param task_id: The id of the Task object.
|
Runs the task with the given id.
|
[
"Runs",
"the",
"task",
"with",
"the",
"given",
"id",
"."
] |
def complete_task_from_id(self, task_id):
"""
Runs the task with the given id.
:type task_id: integer
:param task_id: The id of the Task object.
"""
if task_id is None:
raise WorkflowException(self.spec, 'task_id is None')
for task in self.task_tree:
if task.id == task_id:
return task.complete()
msg = 'A task with the given task_id (%s) was not found' % task_id
raise WorkflowException(self.spec, msg)
|
[
"def",
"complete_task_from_id",
"(",
"self",
",",
"task_id",
")",
":",
"if",
"task_id",
"is",
"None",
":",
"raise",
"WorkflowException",
"(",
"self",
".",
"spec",
",",
"'task_id is None'",
")",
"for",
"task",
"in",
"self",
".",
"task_tree",
":",
"if",
"task",
".",
"id",
"==",
"task_id",
":",
"return",
"task",
".",
"complete",
"(",
")",
"msg",
"=",
"'A task with the given task_id (%s) was not found'",
"%",
"task_id",
"raise",
"WorkflowException",
"(",
"self",
".",
"spec",
",",
"msg",
")"
] |
https://github.com/sartography/SpiffWorkflow/blob/764be6c276a278d372b96de470e39b29248a86d4/SpiffWorkflow/workflow.py#L361-L374
|
||
holzschu/Carnets
|
44effb10ddfc6aa5c8b0687582a724ba82c6b547
|
Library/lib/python3.7/site-packages/pandas-0.24.2-py3.7-macosx-10.9-x86_64.egg/pandas/core/nanops.py
|
python
|
nansem
|
(values, axis=None, skipna=True, ddof=1, mask=None)
|
return np.sqrt(var) / np.sqrt(count)
|
Compute the standard error in the mean along given axis while ignoring NaNs
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
ddof : int, default 1
Delta Degrees of Freedom. The divisor used in calculations is N - ddof,
where N represents the number of elements.
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : float64
Unless input is a float array, in which case use the same
precision as the input array.
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, np.nan, 2, 3])
>>> nanops.nansem(s)
0.5773502691896258
|
Compute the standard error in the mean along given axis while ignoring NaNs
|
[
"Compute",
"the",
"standard",
"error",
"in",
"the",
"mean",
"along",
"given",
"axis",
"while",
"ignoring",
"NaNs"
] |
def nansem(values, axis=None, skipna=True, ddof=1, mask=None):
"""
Compute the standard error in the mean along given axis while ignoring NaNs
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
ddof : int, default 1
Delta Degrees of Freedom. The divisor used in calculations is N - ddof,
where N represents the number of elements.
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : float64
Unless input is a float array, in which case use the same
precision as the input array.
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, np.nan, 2, 3])
>>> nanops.nansem(s)
0.5773502691896258
"""
# This checks if non-numeric-like data is passed with numeric_only=False
# and raises a TypeError otherwise
nanvar(values, axis, skipna, ddof=ddof, mask=mask)
if mask is None:
mask = isna(values)
if not is_float_dtype(values.dtype):
values = values.astype('f8')
count, _ = _get_counts_nanvar(mask, axis, ddof, values.dtype)
var = nanvar(values, axis, skipna, ddof=ddof)
return np.sqrt(var) / np.sqrt(count)
|
[
"def",
"nansem",
"(",
"values",
",",
"axis",
"=",
"None",
",",
"skipna",
"=",
"True",
",",
"ddof",
"=",
"1",
",",
"mask",
"=",
"None",
")",
":",
"# This checks if non-numeric-like data is passed with numeric_only=False",
"# and raises a TypeError otherwise",
"nanvar",
"(",
"values",
",",
"axis",
",",
"skipna",
",",
"ddof",
"=",
"ddof",
",",
"mask",
"=",
"mask",
")",
"if",
"mask",
"is",
"None",
":",
"mask",
"=",
"isna",
"(",
"values",
")",
"if",
"not",
"is_float_dtype",
"(",
"values",
".",
"dtype",
")",
":",
"values",
"=",
"values",
".",
"astype",
"(",
"'f8'",
")",
"count",
",",
"_",
"=",
"_get_counts_nanvar",
"(",
"mask",
",",
"axis",
",",
"ddof",
",",
"values",
".",
"dtype",
")",
"var",
"=",
"nanvar",
"(",
"values",
",",
"axis",
",",
"skipna",
",",
"ddof",
"=",
"ddof",
")",
"return",
"np",
".",
"sqrt",
"(",
"var",
")",
"/",
"np",
".",
"sqrt",
"(",
"count",
")"
] |
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/pandas-0.24.2-py3.7-macosx-10.9-x86_64.egg/pandas/core/nanops.py#L683-L723
|
|
meliketoy/gradcam.pytorch
|
7b71c55b1debf633918793bd7db5ac4533647eb0
|
3_detector/networks/resnet.py
|
python
|
resnet
|
(pretrained=False, depth=18, **kwargs)
|
return model
|
Constructs ResNet models for various depths
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
depth (int) : Integer input of either 18, 34, 50, 101, 152
|
Constructs ResNet models for various depths
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
depth (int) : Integer input of either 18, 34, 50, 101, 152
|
[
"Constructs",
"ResNet",
"models",
"for",
"various",
"depths",
"Args",
":",
"pretrained",
"(",
"bool",
")",
":",
"If",
"True",
"returns",
"a",
"model",
"pre",
"-",
"trained",
"on",
"ImageNet",
"depth",
"(",
"int",
")",
":",
"Integer",
"input",
"of",
"either",
"18",
"34",
"50",
"101",
"152"
] |
def resnet(pretrained=False, depth=18, **kwargs):
"""Constructs ResNet models for various depths
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
depth (int) : Integer input of either 18, 34, 50, 101, 152
"""
block, num_blocks = cfg(depth)
model = ResNet(block, num_blocks, **kwargs)
if (pretrained):
print("| Downloading ImageNet fine-tuned ResNet-%d..." %depth)
model.load_state_dict(model_zoo.load_url(model_urls['resnet%d' %depth]))
return model
|
[
"def",
"resnet",
"(",
"pretrained",
"=",
"False",
",",
"depth",
"=",
"18",
",",
"*",
"*",
"kwargs",
")",
":",
"block",
",",
"num_blocks",
"=",
"cfg",
"(",
"depth",
")",
"model",
"=",
"ResNet",
"(",
"block",
",",
"num_blocks",
",",
"*",
"*",
"kwargs",
")",
"if",
"(",
"pretrained",
")",
":",
"print",
"(",
"\"| Downloading ImageNet fine-tuned ResNet-%d...\"",
"%",
"depth",
")",
"model",
".",
"load_state_dict",
"(",
"model_zoo",
".",
"load_url",
"(",
"model_urls",
"[",
"'resnet%d'",
"%",
"depth",
"]",
")",
")",
"return",
"model"
] |
https://github.com/meliketoy/gradcam.pytorch/blob/7b71c55b1debf633918793bd7db5ac4533647eb0/3_detector/networks/resnet.py#L165-L176
|
|
slashmili/python-jalali
|
468e7c687fe83af51ed957958374f1acc5245299
|
jdatetime/__init__.py
|
python
|
datetime.fromtimestamp
|
(timestamp, tz=None)
|
return datetime(
now.year,
now.month,
now.day,
now_datetime.hour,
now_datetime.minute,
now_datetime.second,
now_datetime.microsecond,
tz,
)
|
timestamp[, tz] -> tz's local time from POSIX timestamp.
|
timestamp[, tz] -> tz's local time from POSIX timestamp.
|
[
"timestamp",
"[",
"tz",
"]",
"-",
">",
"tz",
"s",
"local",
"time",
"from",
"POSIX",
"timestamp",
"."
] |
def fromtimestamp(timestamp, tz=None):
"""timestamp[, tz] -> tz's local time from POSIX timestamp."""
now_datetime = py_datetime.datetime.fromtimestamp(timestamp, tz)
now = date.fromgregorian(date=now_datetime.date())
return datetime(
now.year,
now.month,
now.day,
now_datetime.hour,
now_datetime.minute,
now_datetime.second,
now_datetime.microsecond,
tz,
)
|
[
"def",
"fromtimestamp",
"(",
"timestamp",
",",
"tz",
"=",
"None",
")",
":",
"now_datetime",
"=",
"py_datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"timestamp",
",",
"tz",
")",
"now",
"=",
"date",
".",
"fromgregorian",
"(",
"date",
"=",
"now_datetime",
".",
"date",
"(",
")",
")",
"return",
"datetime",
"(",
"now",
".",
"year",
",",
"now",
".",
"month",
",",
"now",
".",
"day",
",",
"now_datetime",
".",
"hour",
",",
"now_datetime",
".",
"minute",
",",
"now_datetime",
".",
"second",
",",
"now_datetime",
".",
"microsecond",
",",
"tz",
",",
")"
] |
https://github.com/slashmili/python-jalali/blob/468e7c687fe83af51ed957958374f1acc5245299/jdatetime/__init__.py#L771-L784
|
|
fossasia/x-mario-center
|
fe67afe28d995dcf4e2498e305825a4859566172
|
build/lib.linux-i686-2.7/softwarecenter/utils.py
|
python
|
get_http_proxy_string_from_gsettings
|
()
|
return None
|
Helper that gets the http proxy from gsettings
May raise a exception if there is no schema for the proxy
(e.g. on non-gnome systems)
Returns: string with http://auth:pw@proxy:port/, None
|
Helper that gets the http proxy from gsettings
|
[
"Helper",
"that",
"gets",
"the",
"http",
"proxy",
"from",
"gsettings"
] |
def get_http_proxy_string_from_gsettings():
"""Helper that gets the http proxy from gsettings
May raise a exception if there is no schema for the proxy
(e.g. on non-gnome systems)
Returns: string with http://auth:pw@proxy:port/, None
"""
# check if this is actually available and usable. if not
# well ... it segfaults (thanks pygi)
schemas = ["org.gnome.system.proxy", "org.gnome.system.proxy.http"]
for schema in schemas:
if not schema in Gio.Settings.list_schemas():
raise ValueError("no schema '%s'" % schema)
# Check to see if proxy mode is set to none before checking for host
# (LP: #982567)
psettings = Gio.Settings.new("org.gnome.system.proxy")
if "none" in psettings.get_string("mode"):
return None
# If proxy mode isn't "none" check to see if host and port is set
settings = Gio.Settings.new("org.gnome.system.proxy.http")
if settings.get_string("host"):
authentication = ""
if settings.get_boolean("use-authentication"):
user = settings.get_string("authentication-user")
password = settings.get_string("authentication-password")
authentication = "%s:%s@" % (user, password)
host = settings.get_string("host")
port = settings.get_int("port")
# strip leading http (if there is one)
if host.startswith("http://"):
host = host[len("http://"):]
http_proxy = "http://%s%s:%s/" % (authentication, host, port)
if host:
return http_proxy
# no proxy
return None
|
[
"def",
"get_http_proxy_string_from_gsettings",
"(",
")",
":",
"# check if this is actually available and usable. if not",
"# well ... it segfaults (thanks pygi)",
"schemas",
"=",
"[",
"\"org.gnome.system.proxy\"",
",",
"\"org.gnome.system.proxy.http\"",
"]",
"for",
"schema",
"in",
"schemas",
":",
"if",
"not",
"schema",
"in",
"Gio",
".",
"Settings",
".",
"list_schemas",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"no schema '%s'\"",
"%",
"schema",
")",
"# Check to see if proxy mode is set to none before checking for host",
"# (LP: #982567)",
"psettings",
"=",
"Gio",
".",
"Settings",
".",
"new",
"(",
"\"org.gnome.system.proxy\"",
")",
"if",
"\"none\"",
"in",
"psettings",
".",
"get_string",
"(",
"\"mode\"",
")",
":",
"return",
"None",
"# If proxy mode isn't \"none\" check to see if host and port is set",
"settings",
"=",
"Gio",
".",
"Settings",
".",
"new",
"(",
"\"org.gnome.system.proxy.http\"",
")",
"if",
"settings",
".",
"get_string",
"(",
"\"host\"",
")",
":",
"authentication",
"=",
"\"\"",
"if",
"settings",
".",
"get_boolean",
"(",
"\"use-authentication\"",
")",
":",
"user",
"=",
"settings",
".",
"get_string",
"(",
"\"authentication-user\"",
")",
"password",
"=",
"settings",
".",
"get_string",
"(",
"\"authentication-password\"",
")",
"authentication",
"=",
"\"%s:%s@\"",
"%",
"(",
"user",
",",
"password",
")",
"host",
"=",
"settings",
".",
"get_string",
"(",
"\"host\"",
")",
"port",
"=",
"settings",
".",
"get_int",
"(",
"\"port\"",
")",
"# strip leading http (if there is one)",
"if",
"host",
".",
"startswith",
"(",
"\"http://\"",
")",
":",
"host",
"=",
"host",
"[",
"len",
"(",
"\"http://\"",
")",
":",
"]",
"http_proxy",
"=",
"\"http://%s%s:%s/\"",
"%",
"(",
"authentication",
",",
"host",
",",
"port",
")",
"if",
"host",
":",
"return",
"http_proxy",
"# no proxy",
"return",
"None"
] |
https://github.com/fossasia/x-mario-center/blob/fe67afe28d995dcf4e2498e305825a4859566172/build/lib.linux-i686-2.7/softwarecenter/utils.py#L248-L286
|
|
arsenetar/dupeguru
|
eb57d269fcc1392fac9d49eb10d597a9c66fcc82
|
core/app.py
|
python
|
DupeGuru.save_as
|
(self, filename)
|
Save results in ``filename``.
:param str filename: path of the file to save results (as XML) to.
|
Save results in ``filename``.
|
[
"Save",
"results",
"in",
"filename",
"."
] |
def save_as(self, filename):
"""Save results in ``filename``.
:param str filename: path of the file to save results (as XML) to.
"""
try:
self.results.save_to_xml(filename)
except OSError as e:
self.view.show_message(tr("Couldn't write to file: {}").format(str(e)))
|
[
"def",
"save_as",
"(",
"self",
",",
"filename",
")",
":",
"try",
":",
"self",
".",
"results",
".",
"save_to_xml",
"(",
"filename",
")",
"except",
"OSError",
"as",
"e",
":",
"self",
".",
"view",
".",
"show_message",
"(",
"tr",
"(",
"\"Couldn't write to file: {}\"",
")",
".",
"format",
"(",
"str",
"(",
"e",
")",
")",
")"
] |
https://github.com/arsenetar/dupeguru/blob/eb57d269fcc1392fac9d49eb10d597a9c66fcc82/core/app.py#L763-L771
|
||
polakowo/vectorbt
|
6638735c131655760474d72b9f045d1dbdbd8fe9
|
vectorbt/returns/nb.py
|
python
|
rolling_annualized_return_nb
|
(returns: tp.Array2d,
window: int,
minp: tp.Optional[int],
ann_factor: float)
|
return generic_nb.rolling_apply_nb(
returns, window, minp, _apply_func_nb, ann_factor)
|
Rolling version of `annualized_return_nb`.
|
Rolling version of `annualized_return_nb`.
|
[
"Rolling",
"version",
"of",
"annualized_return_nb",
"."
] |
def rolling_annualized_return_nb(returns: tp.Array2d,
window: int,
minp: tp.Optional[int],
ann_factor: float) -> tp.Array2d:
"""Rolling version of `annualized_return_nb`."""
def _apply_func_nb(i, col, _returns, _ann_factor):
return annualized_return_1d_nb(_returns, _ann_factor)
return generic_nb.rolling_apply_nb(
returns, window, minp, _apply_func_nb, ann_factor)
|
[
"def",
"rolling_annualized_return_nb",
"(",
"returns",
":",
"tp",
".",
"Array2d",
",",
"window",
":",
"int",
",",
"minp",
":",
"tp",
".",
"Optional",
"[",
"int",
"]",
",",
"ann_factor",
":",
"float",
")",
"->",
"tp",
".",
"Array2d",
":",
"def",
"_apply_func_nb",
"(",
"i",
",",
"col",
",",
"_returns",
",",
"_ann_factor",
")",
":",
"return",
"annualized_return_1d_nb",
"(",
"_returns",
",",
"_ann_factor",
")",
"return",
"generic_nb",
".",
"rolling_apply_nb",
"(",
"returns",
",",
"window",
",",
"minp",
",",
"_apply_func_nb",
",",
"ann_factor",
")"
] |
https://github.com/polakowo/vectorbt/blob/6638735c131655760474d72b9f045d1dbdbd8fe9/vectorbt/returns/nb.py#L149-L159
|
|
eirannejad/pyRevit
|
49c0b7eb54eb343458ce1365425e6552d0c47d44
|
site-packages/werkzeug/routing.py
|
python
|
Map.update
|
(self)
|
Called before matching and building to keep the compiled rules
in the correct order after things changed.
|
Called before matching and building to keep the compiled rules
in the correct order after things changed.
|
[
"Called",
"before",
"matching",
"and",
"building",
"to",
"keep",
"the",
"compiled",
"rules",
"in",
"the",
"correct",
"order",
"after",
"things",
"changed",
"."
] |
def update(self):
"""Called before matching and building to keep the compiled rules
in the correct order after things changed.
"""
if not self._remap:
return
with self._remap_lock:
if not self._remap:
return
self._rules.sort(key=lambda x: x.match_compare_key())
for rules in itervalues(self._rules_by_endpoint):
rules.sort(key=lambda x: x.build_compare_key())
self._remap = False
|
[
"def",
"update",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_remap",
":",
"return",
"with",
"self",
".",
"_remap_lock",
":",
"if",
"not",
"self",
".",
"_remap",
":",
"return",
"self",
".",
"_rules",
".",
"sort",
"(",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"match_compare_key",
"(",
")",
")",
"for",
"rules",
"in",
"itervalues",
"(",
"self",
".",
"_rules_by_endpoint",
")",
":",
"rules",
".",
"sort",
"(",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"build_compare_key",
"(",
")",
")",
"self",
".",
"_remap",
"=",
"False"
] |
https://github.com/eirannejad/pyRevit/blob/49c0b7eb54eb343458ce1365425e6552d0c47d44/site-packages/werkzeug/routing.py#L1339-L1353
|
||
tasmota/tasmotizer
|
ea8484060f7451fde8b80dbabb83e9ec5faf7d87
|
tasmotizer_esptool.py
|
python
|
expand_file_arguments
|
()
|
Any argument starting with "@" gets replaced with all values read from a text file.
Text file arguments can be split by newline or by space.
Values are added "as-is", as if they were specified in this order on the command line.
|
Any argument starting with "
|
[
"Any",
"argument",
"starting",
"with"
] |
def expand_file_arguments():
""" Any argument starting with "@" gets replaced with all values read from a text file.
Text file arguments can be split by newline or by space.
Values are added "as-is", as if they were specified in this order on the command line.
"""
new_args = []
expanded = False
for arg in sys.argv:
if arg.startswith("@"):
expanded = True
with open(arg[1:],"r") as f:
for line in f.readlines():
new_args += shlex.split(line)
else:
new_args.append(arg)
if expanded:
print("esptool.py %s" % (" ".join(new_args[1:])))
sys.argv = new_args
|
[
"def",
"expand_file_arguments",
"(",
")",
":",
"new_args",
"=",
"[",
"]",
"expanded",
"=",
"False",
"for",
"arg",
"in",
"sys",
".",
"argv",
":",
"if",
"arg",
".",
"startswith",
"(",
"\"@\"",
")",
":",
"expanded",
"=",
"True",
"with",
"open",
"(",
"arg",
"[",
"1",
":",
"]",
",",
"\"r\"",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
".",
"readlines",
"(",
")",
":",
"new_args",
"+=",
"shlex",
".",
"split",
"(",
"line",
")",
"else",
":",
"new_args",
".",
"append",
"(",
"arg",
")",
"if",
"expanded",
":",
"print",
"(",
"\"esptool.py %s\"",
"%",
"(",
"\" \"",
".",
"join",
"(",
"new_args",
"[",
"1",
":",
"]",
")",
")",
")",
"sys",
".",
"argv",
"=",
"new_args"
] |
https://github.com/tasmota/tasmotizer/blob/ea8484060f7451fde8b80dbabb83e9ec5faf7d87/tasmotizer_esptool.py#L3001-L3018
|
||
qfpl/hpython
|
4c608ebbcfaee56ad386666d27e67cd4c77b0b4f
|
benchmarks/pypy.py
|
python
|
Decimal._compare_check_nans
|
(self, other, context)
|
return 0
|
Version of _check_nans used for the signaling comparisons
compare_signal, __le__, __lt__, __ge__, __gt__.
Signal InvalidOperation if either self or other is a (quiet
or signaling) NaN. Signaling NaNs take precedence over quiet
NaNs.
Return 0 if neither operand is a NaN.
|
Version of _check_nans used for the signaling comparisons
compare_signal, __le__, __lt__, __ge__, __gt__.
|
[
"Version",
"of",
"_check_nans",
"used",
"for",
"the",
"signaling",
"comparisons",
"compare_signal",
"__le__",
"__lt__",
"__ge__",
"__gt__",
"."
] |
def _compare_check_nans(self, other, context):
"""Version of _check_nans used for the signaling comparisons
compare_signal, __le__, __lt__, __ge__, __gt__.
Signal InvalidOperation if either self or other is a (quiet
or signaling) NaN. Signaling NaNs take precedence over quiet
NaNs.
Return 0 if neither operand is a NaN.
"""
if context is None:
context = getcontext()
if self._is_special or other._is_special:
if self.is_snan():
return context._raise_error(InvalidOperation,
'comparison involving sNaN',
self)
elif other.is_snan():
return context._raise_error(InvalidOperation,
'comparison involving sNaN',
other)
elif self.is_qnan():
return context._raise_error(InvalidOperation,
'comparison involving NaN',
self)
elif other.is_qnan():
return context._raise_error(InvalidOperation,
'comparison involving NaN',
other)
return 0
|
[
"def",
"_compare_check_nans",
"(",
"self",
",",
"other",
",",
"context",
")",
":",
"if",
"context",
"is",
"None",
":",
"context",
"=",
"getcontext",
"(",
")",
"if",
"self",
".",
"_is_special",
"or",
"other",
".",
"_is_special",
":",
"if",
"self",
".",
"is_snan",
"(",
")",
":",
"return",
"context",
".",
"_raise_error",
"(",
"InvalidOperation",
",",
"'comparison involving sNaN'",
",",
"self",
")",
"elif",
"other",
".",
"is_snan",
"(",
")",
":",
"return",
"context",
".",
"_raise_error",
"(",
"InvalidOperation",
",",
"'comparison involving sNaN'",
",",
"other",
")",
"elif",
"self",
".",
"is_qnan",
"(",
")",
":",
"return",
"context",
".",
"_raise_error",
"(",
"InvalidOperation",
",",
"'comparison involving NaN'",
",",
"self",
")",
"elif",
"other",
".",
"is_qnan",
"(",
")",
":",
"return",
"context",
".",
"_raise_error",
"(",
"InvalidOperation",
",",
"'comparison involving NaN'",
",",
"other",
")",
"return",
"0"
] |
https://github.com/qfpl/hpython/blob/4c608ebbcfaee56ad386666d27e67cd4c77b0b4f/benchmarks/pypy.py#L814-L845
|
|
jliljebl/flowblade
|
995313a509b80e99eb1ad550d945bdda5995093b
|
flowblade-trunk/Flowblade/shortcuts.py
|
python
|
_get_shortcut_file_fullpath
|
(f)
|
return full_path
|
[] |
def _get_shortcut_file_fullpath(f):
full_path = respaths.SHORTCUTS_PATH + f
if os.path.isfile(full_path) == False:
full_path = userfolders.get_data_dir() + "/" + appconsts.USER_SHORTCUTS_DIR + f
return full_path
|
[
"def",
"_get_shortcut_file_fullpath",
"(",
"f",
")",
":",
"full_path",
"=",
"respaths",
".",
"SHORTCUTS_PATH",
"+",
"f",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"full_path",
")",
"==",
"False",
":",
"full_path",
"=",
"userfolders",
".",
"get_data_dir",
"(",
")",
"+",
"\"/\"",
"+",
"appconsts",
".",
"USER_SHORTCUTS_DIR",
"+",
"f",
"return",
"full_path"
] |
https://github.com/jliljebl/flowblade/blob/995313a509b80e99eb1ad550d945bdda5995093b/flowblade-trunk/Flowblade/shortcuts.py#L357-L361
|
|||
ctxis/canape
|
5f0e03424577296bcc60c2008a60a98ec5307e4b
|
CANAPE.Scripting/Lib/cmd.py
|
python
|
Cmd.columnize
|
(self, list, displaywidth=80)
|
Display a list of strings as a compact set of columns.
Each column is only as wide as necessary.
Columns are separated by two spaces (one was not legible enough).
|
Display a list of strings as a compact set of columns.
|
[
"Display",
"a",
"list",
"of",
"strings",
"as",
"a",
"compact",
"set",
"of",
"columns",
"."
] |
def columnize(self, list, displaywidth=80):
"""Display a list of strings as a compact set of columns.
Each column is only as wide as necessary.
Columns are separated by two spaces (one was not legible enough).
"""
if not list:
self.stdout.write("<empty>\n")
return
nonstrings = [i for i in range(len(list))
if not isinstance(list[i], str)]
if nonstrings:
raise TypeError, ("list[i] not a string for i in %s" %
", ".join(map(str, nonstrings)))
size = len(list)
if size == 1:
self.stdout.write('%s\n'%str(list[0]))
return
# Try every row count from 1 upwards
for nrows in range(1, len(list)):
ncols = (size+nrows-1) // nrows
colwidths = []
totwidth = -2
for col in range(ncols):
colwidth = 0
for row in range(nrows):
i = row + nrows*col
if i >= size:
break
x = list[i]
colwidth = max(colwidth, len(x))
colwidths.append(colwidth)
totwidth += colwidth + 2
if totwidth > displaywidth:
break
if totwidth <= displaywidth:
break
else:
nrows = len(list)
ncols = 1
colwidths = [0]
for row in range(nrows):
texts = []
for col in range(ncols):
i = row + nrows*col
if i >= size:
x = ""
else:
x = list[i]
texts.append(x)
while texts and not texts[-1]:
del texts[-1]
for col in range(len(texts)):
texts[col] = texts[col].ljust(colwidths[col])
self.stdout.write("%s\n"%str(" ".join(texts)))
|
[
"def",
"columnize",
"(",
"self",
",",
"list",
",",
"displaywidth",
"=",
"80",
")",
":",
"if",
"not",
"list",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"\"<empty>\\n\"",
")",
"return",
"nonstrings",
"=",
"[",
"i",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"list",
")",
")",
"if",
"not",
"isinstance",
"(",
"list",
"[",
"i",
"]",
",",
"str",
")",
"]",
"if",
"nonstrings",
":",
"raise",
"TypeError",
",",
"(",
"\"list[i] not a string for i in %s\"",
"%",
"\", \"",
".",
"join",
"(",
"map",
"(",
"str",
",",
"nonstrings",
")",
")",
")",
"size",
"=",
"len",
"(",
"list",
")",
"if",
"size",
"==",
"1",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"'%s\\n'",
"%",
"str",
"(",
"list",
"[",
"0",
"]",
")",
")",
"return",
"# Try every row count from 1 upwards",
"for",
"nrows",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"list",
")",
")",
":",
"ncols",
"=",
"(",
"size",
"+",
"nrows",
"-",
"1",
")",
"//",
"nrows",
"colwidths",
"=",
"[",
"]",
"totwidth",
"=",
"-",
"2",
"for",
"col",
"in",
"range",
"(",
"ncols",
")",
":",
"colwidth",
"=",
"0",
"for",
"row",
"in",
"range",
"(",
"nrows",
")",
":",
"i",
"=",
"row",
"+",
"nrows",
"*",
"col",
"if",
"i",
">=",
"size",
":",
"break",
"x",
"=",
"list",
"[",
"i",
"]",
"colwidth",
"=",
"max",
"(",
"colwidth",
",",
"len",
"(",
"x",
")",
")",
"colwidths",
".",
"append",
"(",
"colwidth",
")",
"totwidth",
"+=",
"colwidth",
"+",
"2",
"if",
"totwidth",
">",
"displaywidth",
":",
"break",
"if",
"totwidth",
"<=",
"displaywidth",
":",
"break",
"else",
":",
"nrows",
"=",
"len",
"(",
"list",
")",
"ncols",
"=",
"1",
"colwidths",
"=",
"[",
"0",
"]",
"for",
"row",
"in",
"range",
"(",
"nrows",
")",
":",
"texts",
"=",
"[",
"]",
"for",
"col",
"in",
"range",
"(",
"ncols",
")",
":",
"i",
"=",
"row",
"+",
"nrows",
"*",
"col",
"if",
"i",
">=",
"size",
":",
"x",
"=",
"\"\"",
"else",
":",
"x",
"=",
"list",
"[",
"i",
"]",
"texts",
".",
"append",
"(",
"x",
")",
"while",
"texts",
"and",
"not",
"texts",
"[",
"-",
"1",
"]",
":",
"del",
"texts",
"[",
"-",
"1",
"]",
"for",
"col",
"in",
"range",
"(",
"len",
"(",
"texts",
")",
")",
":",
"texts",
"[",
"col",
"]",
"=",
"texts",
"[",
"col",
"]",
".",
"ljust",
"(",
"colwidths",
"[",
"col",
"]",
")",
"self",
".",
"stdout",
".",
"write",
"(",
"\"%s\\n\"",
"%",
"str",
"(",
"\" \"",
".",
"join",
"(",
"texts",
")",
")",
")"
] |
https://github.com/ctxis/canape/blob/5f0e03424577296bcc60c2008a60a98ec5307e4b/CANAPE.Scripting/Lib/cmd.py#L347-L401
|
||
freqtrade/freqtrade
|
13651fd3be8d5ce8dcd7c94b920bda4e00b75aca
|
freqtrade/exchange/binance.py
|
python
|
Binance.stoploss_adjust
|
(self, stop_loss: float, order: Dict)
|
return order['type'] == 'stop_loss_limit' and stop_loss > float(order['info']['stopPrice'])
|
Verify stop_loss against stoploss-order value (limit or price)
Returns True if adjustment is necessary.
|
Verify stop_loss against stoploss-order value (limit or price)
Returns True if adjustment is necessary.
|
[
"Verify",
"stop_loss",
"against",
"stoploss",
"-",
"order",
"value",
"(",
"limit",
"or",
"price",
")",
"Returns",
"True",
"if",
"adjustment",
"is",
"necessary",
"."
] |
def stoploss_adjust(self, stop_loss: float, order: Dict) -> bool:
"""
Verify stop_loss against stoploss-order value (limit or price)
Returns True if adjustment is necessary.
"""
return order['type'] == 'stop_loss_limit' and stop_loss > float(order['info']['stopPrice'])
|
[
"def",
"stoploss_adjust",
"(",
"self",
",",
"stop_loss",
":",
"float",
",",
"order",
":",
"Dict",
")",
"->",
"bool",
":",
"return",
"order",
"[",
"'type'",
"]",
"==",
"'stop_loss_limit'",
"and",
"stop_loss",
">",
"float",
"(",
"order",
"[",
"'info'",
"]",
"[",
"'stopPrice'",
"]",
")"
] |
https://github.com/freqtrade/freqtrade/blob/13651fd3be8d5ce8dcd7c94b920bda4e00b75aca/freqtrade/exchange/binance.py#L29-L34
|
|
holzschu/Carnets
|
44effb10ddfc6aa5c8b0687582a724ba82c6b547
|
Library/lib/python3.7/site-packages/pip/_internal/cli/parser.py
|
python
|
CustomOptionParser.insert_option_group
|
(self, idx, *args, **kwargs)
|
return group
|
Insert an OptionGroup at a given position.
|
Insert an OptionGroup at a given position.
|
[
"Insert",
"an",
"OptionGroup",
"at",
"a",
"given",
"position",
"."
] |
def insert_option_group(self, idx, *args, **kwargs):
"""Insert an OptionGroup at a given position."""
group = self.add_option_group(*args, **kwargs)
self.option_groups.pop()
self.option_groups.insert(idx, group)
return group
|
[
"def",
"insert_option_group",
"(",
"self",
",",
"idx",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"group",
"=",
"self",
".",
"add_option_group",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"option_groups",
".",
"pop",
"(",
")",
"self",
".",
"option_groups",
".",
"insert",
"(",
"idx",
",",
"group",
")",
"return",
"group"
] |
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/pip/_internal/cli/parser.py#L113-L120
|
|
LexPredict/lexpredict-contraxsuite
|
1d5a2540d31f8f3f1adc442cfa13a7c007319899
|
sdk/python/sdk/openapi_client/model/document_type_create.py
|
python
|
DocumentTypeCreate._from_openapi_data
|
(cls, title, code, editor_type, *args, **kwargs)
|
return self
|
DocumentTypeCreate - a model defined in OpenAPI
Args:
title (str):
code (str): Field codes must be lowercase, should start with a Latin letter, and contain only Latin letters, digits, and underscores.
editor_type (str):
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_visited_composed_classes (tuple): This stores a tuple of
classes that we have traveled through so that
if we see that class again we will not use its
discriminator again.
When traveling through a discriminator, the
composed schema that is
is traveled through is added to this set.
For example if Animal has a discriminator
petType and we pass in "Dog", and the class Dog
allOf includes Animal, we move through Animal
once using the discriminator, and pick Dog.
Then in Dog, we will make an instance of the
Animal class but this time we won't travel
through its discriminator because we passed in
_visited_composed_classes = (Animal,)
uid (str): [optional] # noqa: E501
categories ([DocumentTypeDetailCategories]): [optional] # noqa: E501
managers ([int]): Choose which users can modify this Document Type. Users chosen as Managers can be of any System-Level Permission.. [optional] # noqa: E501
fields ([DocumentFieldCategoryListFields]): [optional] # noqa: E501
search_fields ([str]): [optional] # noqa: E501
field_code_aliases ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type): [optional] # noqa: E501
metadata ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type): [optional] # noqa: E501
warning_message (str): [optional] # noqa: E501
|
DocumentTypeCreate - a model defined in OpenAPI
|
[
"DocumentTypeCreate",
"-",
"a",
"model",
"defined",
"in",
"OpenAPI"
] |
def _from_openapi_data(cls, title, code, editor_type, *args, **kwargs): # noqa: E501
"""DocumentTypeCreate - a model defined in OpenAPI
Args:
title (str):
code (str): Field codes must be lowercase, should start with a Latin letter, and contain only Latin letters, digits, and underscores.
editor_type (str):
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_visited_composed_classes (tuple): This stores a tuple of
classes that we have traveled through so that
if we see that class again we will not use its
discriminator again.
When traveling through a discriminator, the
composed schema that is
is traveled through is added to this set.
For example if Animal has a discriminator
petType and we pass in "Dog", and the class Dog
allOf includes Animal, we move through Animal
once using the discriminator, and pick Dog.
Then in Dog, we will make an instance of the
Animal class but this time we won't travel
through its discriminator because we passed in
_visited_composed_classes = (Animal,)
uid (str): [optional] # noqa: E501
categories ([DocumentTypeDetailCategories]): [optional] # noqa: E501
managers ([int]): Choose which users can modify this Document Type. Users chosen as Managers can be of any System-Level Permission.. [optional] # noqa: E501
fields ([DocumentFieldCategoryListFields]): [optional] # noqa: E501
search_fields ([str]): [optional] # noqa: E501
field_code_aliases ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type): [optional] # noqa: E501
metadata ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type): [optional] # noqa: E501
warning_message (str): [optional] # noqa: E501
"""
_check_type = kwargs.pop('_check_type', True)
_spec_property_naming = kwargs.pop('_spec_property_naming', False)
_path_to_item = kwargs.pop('_path_to_item', ())
_configuration = kwargs.pop('_configuration', None)
_visited_composed_classes = kwargs.pop('_visited_composed_classes', ())
self = super(OpenApiModel, cls).__new__(cls)
if args:
raise ApiTypeError(
"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % (
args,
self.__class__.__name__,
),
path_to_item=_path_to_item,
valid_classes=(self.__class__,),
)
self._data_store = {}
self._check_type = _check_type
self._spec_property_naming = _spec_property_naming
self._path_to_item = _path_to_item
self._configuration = _configuration
self._visited_composed_classes = _visited_composed_classes + (self.__class__,)
self.title = title
self.code = code
self.editor_type = editor_type
for var_name, var_value in kwargs.items():
if var_name not in self.attribute_map and \
self._configuration is not None and \
self._configuration.discard_unknown_keys and \
self.additional_properties_type is None:
# discard variable.
continue
setattr(self, var_name, var_value)
return self
|
[
"def",
"_from_openapi_data",
"(",
"cls",
",",
"title",
",",
"code",
",",
"editor_type",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"_check_type",
"=",
"kwargs",
".",
"pop",
"(",
"'_check_type'",
",",
"True",
")",
"_spec_property_naming",
"=",
"kwargs",
".",
"pop",
"(",
"'_spec_property_naming'",
",",
"False",
")",
"_path_to_item",
"=",
"kwargs",
".",
"pop",
"(",
"'_path_to_item'",
",",
"(",
")",
")",
"_configuration",
"=",
"kwargs",
".",
"pop",
"(",
"'_configuration'",
",",
"None",
")",
"_visited_composed_classes",
"=",
"kwargs",
".",
"pop",
"(",
"'_visited_composed_classes'",
",",
"(",
")",
")",
"self",
"=",
"super",
"(",
"OpenApiModel",
",",
"cls",
")",
".",
"__new__",
"(",
"cls",
")",
"if",
"args",
":",
"raise",
"ApiTypeError",
"(",
"\"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments.\"",
"%",
"(",
"args",
",",
"self",
".",
"__class__",
".",
"__name__",
",",
")",
",",
"path_to_item",
"=",
"_path_to_item",
",",
"valid_classes",
"=",
"(",
"self",
".",
"__class__",
",",
")",
",",
")",
"self",
".",
"_data_store",
"=",
"{",
"}",
"self",
".",
"_check_type",
"=",
"_check_type",
"self",
".",
"_spec_property_naming",
"=",
"_spec_property_naming",
"self",
".",
"_path_to_item",
"=",
"_path_to_item",
"self",
".",
"_configuration",
"=",
"_configuration",
"self",
".",
"_visited_composed_classes",
"=",
"_visited_composed_classes",
"+",
"(",
"self",
".",
"__class__",
",",
")",
"self",
".",
"title",
"=",
"title",
"self",
".",
"code",
"=",
"code",
"self",
".",
"editor_type",
"=",
"editor_type",
"for",
"var_name",
",",
"var_value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"var_name",
"not",
"in",
"self",
".",
"attribute_map",
"and",
"self",
".",
"_configuration",
"is",
"not",
"None",
"and",
"self",
".",
"_configuration",
".",
"discard_unknown_keys",
"and",
"self",
".",
"additional_properties_type",
"is",
"None",
":",
"# discard variable.",
"continue",
"setattr",
"(",
"self",
",",
"var_name",
",",
"var_value",
")",
"return",
"self"
] |
https://github.com/LexPredict/lexpredict-contraxsuite/blob/1d5a2540d31f8f3f1adc442cfa13a7c007319899/sdk/python/sdk/openapi_client/model/document_type_create.py#L145-L230
|
|
makerbot/ReplicatorG
|
d6f2b07785a5a5f1e172fb87cb4303b17c575d5d
|
skein_engines/skeinforge-47/skeinforge_application/skeinforge_plugins/craft_plugins/widen.py
|
python
|
getCraftedText
|
(fileName, text='', repository=None)
|
return getCraftedTextFromText(archive.getTextIfEmpty(fileName, text), repository)
|
Widen the preface file or text.
|
Widen the preface file or text.
|
[
"Widen",
"the",
"preface",
"file",
"or",
"text",
"."
] |
def getCraftedText(fileName, text='', repository=None):
'Widen the preface file or text.'
return getCraftedTextFromText(archive.getTextIfEmpty(fileName, text), repository)
|
[
"def",
"getCraftedText",
"(",
"fileName",
",",
"text",
"=",
"''",
",",
"repository",
"=",
"None",
")",
":",
"return",
"getCraftedTextFromText",
"(",
"archive",
".",
"getTextIfEmpty",
"(",
"fileName",
",",
"text",
")",
",",
"repository",
")"
] |
https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-47/skeinforge_application/skeinforge_plugins/craft_plugins/widen.py#L60-L62
|
|
graalvm/mx
|
29c0debab406352df3af246be2f8973be5db69ae
|
mx.py
|
python
|
JdkLibrary.is_provided_by
|
(self, jdk)
|
return jdk.javaCompliance >= self.jdkStandardizedSince or exists(self.get_jdk_path(jdk, self.path))
|
Determines if this library is provided by `jdk`.
:param JDKConfig jdk: the JDK to test
|
Determines if this library is provided by `jdk`.
|
[
"Determines",
"if",
"this",
"library",
"is",
"provided",
"by",
"jdk",
"."
] |
def is_provided_by(self, jdk):
"""
Determines if this library is provided by `jdk`.
:param JDKConfig jdk: the JDK to test
"""
return jdk.javaCompliance >= self.jdkStandardizedSince or exists(self.get_jdk_path(jdk, self.path))
|
[
"def",
"is_provided_by",
"(",
"self",
",",
"jdk",
")",
":",
"return",
"jdk",
".",
"javaCompliance",
">=",
"self",
".",
"jdkStandardizedSince",
"or",
"exists",
"(",
"self",
".",
"get_jdk_path",
"(",
"jdk",
",",
"self",
".",
"path",
")",
")"
] |
https://github.com/graalvm/mx/blob/29c0debab406352df3af246be2f8973be5db69ae/mx.py#L8720-L8726
|
|
bytedance/byteps
|
d0bcf1a87ee87539ceb29bcc976d4da063ffc47b
|
byteps/mxnet/__init__.py
|
python
|
DistributedOptimizer._do_push_pull
|
(self, index, grad)
|
[] |
def _do_push_pull(self, index, grad):
if isinstance(index, (tuple, list)):
for i in range(len(index)):
byteps_declare_tensor("gradient_" + str(index[i]))
byteps_push_pull(grad[i], version=0, priority=-index[i],
name="gradient_" + str(index[i]), is_average=True)
else:
byteps_declare_tensor("gradient_" + str(index))
byteps_push_pull(grad, version=0, priority=-index,
name="gradient_" + str(index), is_average=True)
|
[
"def",
"_do_push_pull",
"(",
"self",
",",
"index",
",",
"grad",
")",
":",
"if",
"isinstance",
"(",
"index",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"index",
")",
")",
":",
"byteps_declare_tensor",
"(",
"\"gradient_\"",
"+",
"str",
"(",
"index",
"[",
"i",
"]",
")",
")",
"byteps_push_pull",
"(",
"grad",
"[",
"i",
"]",
",",
"version",
"=",
"0",
",",
"priority",
"=",
"-",
"index",
"[",
"i",
"]",
",",
"name",
"=",
"\"gradient_\"",
"+",
"str",
"(",
"index",
"[",
"i",
"]",
")",
",",
"is_average",
"=",
"True",
")",
"else",
":",
"byteps_declare_tensor",
"(",
"\"gradient_\"",
"+",
"str",
"(",
"index",
")",
")",
"byteps_push_pull",
"(",
"grad",
",",
"version",
"=",
"0",
",",
"priority",
"=",
"-",
"index",
",",
"name",
"=",
"\"gradient_\"",
"+",
"str",
"(",
"index",
")",
",",
"is_average",
"=",
"True",
")"
] |
https://github.com/bytedance/byteps/blob/d0bcf1a87ee87539ceb29bcc976d4da063ffc47b/byteps/mxnet/__init__.py#L52-L61
|
||||
oracle/graalpython
|
577e02da9755d916056184ec441c26e00b70145c
|
graalpython/lib-python/3/encodings/ascii.py
|
python
|
IncrementalEncoder.encode
|
(self, input, final=False)
|
return codecs.ascii_encode(input, self.errors)[0]
|
[] |
def encode(self, input, final=False):
return codecs.ascii_encode(input, self.errors)[0]
|
[
"def",
"encode",
"(",
"self",
",",
"input",
",",
"final",
"=",
"False",
")",
":",
"return",
"codecs",
".",
"ascii_encode",
"(",
"input",
",",
"self",
".",
"errors",
")",
"[",
"0",
"]"
] |
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/encodings/ascii.py#L21-L22
|
|||
beringresearch/ivis
|
690d610d62be786b7a9a98debe57129bae678095
|
ivis/nn/losses.py
|
python
|
semi_supervised_loss
|
(loss_function)
|
return new_loss_function
|
Wraps the provided ivis supervised loss function to deal with the partially
labeled data. Returns a new 'semi-supervised' loss function that masks the
loss on examples where label information is missing.
Missing labels are assumed to be marked with -1.
|
Wraps the provided ivis supervised loss function to deal with the partially
labeled data. Returns a new 'semi-supervised' loss function that masks the
loss on examples where label information is missing.
|
[
"Wraps",
"the",
"provided",
"ivis",
"supervised",
"loss",
"function",
"to",
"deal",
"with",
"the",
"partially",
"labeled",
"data",
".",
"Returns",
"a",
"new",
"semi",
"-",
"supervised",
"loss",
"function",
"that",
"masks",
"the",
"loss",
"on",
"examples",
"where",
"label",
"information",
"is",
"missing",
"."
] |
def semi_supervised_loss(loss_function):
"""Wraps the provided ivis supervised loss function to deal with the partially
labeled data. Returns a new 'semi-supervised' loss function that masks the
loss on examples where label information is missing.
Missing labels are assumed to be marked with -1."""
@functools.wraps(loss_function)
def new_loss_function(y_true, y_pred):
mask = tf.cast(~tf.math.equal(y_true, -1), tf.float32)
y_true_pos = tf.nn.relu(y_true)
loss = loss_function(y_true_pos, y_pred)
masked_loss = loss * mask
return masked_loss
return new_loss_function
|
[
"def",
"semi_supervised_loss",
"(",
"loss_function",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"loss_function",
")",
"def",
"new_loss_function",
"(",
"y_true",
",",
"y_pred",
")",
":",
"mask",
"=",
"tf",
".",
"cast",
"(",
"~",
"tf",
".",
"math",
".",
"equal",
"(",
"y_true",
",",
"-",
"1",
")",
",",
"tf",
".",
"float32",
")",
"y_true_pos",
"=",
"tf",
".",
"nn",
".",
"relu",
"(",
"y_true",
")",
"loss",
"=",
"loss_function",
"(",
"y_true_pos",
",",
"y_pred",
")",
"masked_loss",
"=",
"loss",
"*",
"mask",
"return",
"masked_loss",
"return",
"new_loss_function"
] |
https://github.com/beringresearch/ivis/blob/690d610d62be786b7a9a98debe57129bae678095/ivis/nn/losses.py#L230-L245
|
|
hugsy/gef
|
2975d5fc0307bdb4318d4d1c5e84f1d53246717e
|
gef.py
|
python
|
open_file
|
(path, use_cache=False)
|
return open(path, "r")
|
Attempt to open the given file, if remote debugging is active, download
it first to the mirror in /tmp/.
|
Attempt to open the given file, if remote debugging is active, download
it first to the mirror in /tmp/.
|
[
"Attempt",
"to",
"open",
"the",
"given",
"file",
"if",
"remote",
"debugging",
"is",
"active",
"download",
"it",
"first",
"to",
"the",
"mirror",
"in",
"/",
"tmp",
"/",
"."
] |
def open_file(path, use_cache=False):
"""Attempt to open the given file, if remote debugging is active, download
it first to the mirror in /tmp/."""
if is_remote_debug() and not __gef_qemu_mode__:
lpath = download_file(path, use_cache)
if not lpath:
raise IOError("cannot open remote path {:s}".format(path))
path = lpath
return open(path, "r")
|
[
"def",
"open_file",
"(",
"path",
",",
"use_cache",
"=",
"False",
")",
":",
"if",
"is_remote_debug",
"(",
")",
"and",
"not",
"__gef_qemu_mode__",
":",
"lpath",
"=",
"download_file",
"(",
"path",
",",
"use_cache",
")",
"if",
"not",
"lpath",
":",
"raise",
"IOError",
"(",
"\"cannot open remote path {:s}\"",
".",
"format",
"(",
"path",
")",
")",
"path",
"=",
"lpath",
"return",
"open",
"(",
"path",
",",
"\"r\"",
")"
] |
https://github.com/hugsy/gef/blob/2975d5fc0307bdb4318d4d1c5e84f1d53246717e/gef.py#L3213-L3222
|
|
Source-Python-Dev-Team/Source.Python
|
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
|
addons/source-python/packages/site-packages/docutils/utils/math/math2html.py
|
python
|
Cloner.clone
|
(cls, original)
|
return cls.create(original.__class__)
|
Return an exact copy of an object.
|
Return an exact copy of an object.
|
[
"Return",
"an",
"exact",
"copy",
"of",
"an",
"object",
"."
] |
def clone(cls, original):
"Return an exact copy of an object."
"The original object must have an empty constructor."
return cls.create(original.__class__)
|
[
"def",
"clone",
"(",
"cls",
",",
"original",
")",
":",
"\"The original object must have an empty constructor.\"",
"return",
"cls",
".",
"create",
"(",
"original",
".",
"__class__",
")"
] |
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/packages/site-packages/docutils/utils/math/math2html.py#L1219-L1222
|
|
aws/sagemaker-python-sdk
|
9d259b316f7f43838c16f35c10e98a110b56735b
|
src/sagemaker/transformer.py
|
python
|
_TransformJob.start_new
|
(
cls,
transformer,
data,
data_type,
content_type,
compression_type,
split_type,
input_filter,
output_filter,
join_source,
experiment_config,
model_client_config,
)
|
return cls(transformer.sagemaker_session, transformer._current_job_name)
|
Placeholder docstring
|
Placeholder docstring
|
[
"Placeholder",
"docstring"
] |
def start_new(
cls,
transformer,
data,
data_type,
content_type,
compression_type,
split_type,
input_filter,
output_filter,
join_source,
experiment_config,
model_client_config,
):
"""Placeholder docstring"""
transform_args = cls._get_transform_args(
transformer,
data,
data_type,
content_type,
compression_type,
split_type,
input_filter,
output_filter,
join_source,
experiment_config,
model_client_config,
)
transformer.sagemaker_session.transform(**transform_args)
return cls(transformer.sagemaker_session, transformer._current_job_name)
|
[
"def",
"start_new",
"(",
"cls",
",",
"transformer",
",",
"data",
",",
"data_type",
",",
"content_type",
",",
"compression_type",
",",
"split_type",
",",
"input_filter",
",",
"output_filter",
",",
"join_source",
",",
"experiment_config",
",",
"model_client_config",
",",
")",
":",
"transform_args",
"=",
"cls",
".",
"_get_transform_args",
"(",
"transformer",
",",
"data",
",",
"data_type",
",",
"content_type",
",",
"compression_type",
",",
"split_type",
",",
"input_filter",
",",
"output_filter",
",",
"join_source",
",",
"experiment_config",
",",
"model_client_config",
",",
")",
"transformer",
".",
"sagemaker_session",
".",
"transform",
"(",
"*",
"*",
"transform_args",
")",
"return",
"cls",
"(",
"transformer",
".",
"sagemaker_session",
",",
"transformer",
".",
"_current_job_name",
")"
] |
https://github.com/aws/sagemaker-python-sdk/blob/9d259b316f7f43838c16f35c10e98a110b56735b/src/sagemaker/transformer.py#L344-L375
|
|
ansible-collections/community.general
|
3faffe8f47968a2400ba3c896c8901c03001a194
|
plugins/modules/consul_acl.py
|
python
|
decode_rules_as_hcl_string
|
(rules_as_hcl)
|
return decode_rules_as_json(rules_as_json)
|
Converts the given HCL (string) representation of rules into a list of rule domain models.
:param rules_as_hcl: the HCL (string) representation of a collection of rules
:return: the equivalent domain model to the given rules
|
Converts the given HCL (string) representation of rules into a list of rule domain models.
:param rules_as_hcl: the HCL (string) representation of a collection of rules
:return: the equivalent domain model to the given rules
|
[
"Converts",
"the",
"given",
"HCL",
"(",
"string",
")",
"representation",
"of",
"rules",
"into",
"a",
"list",
"of",
"rule",
"domain",
"models",
".",
":",
"param",
"rules_as_hcl",
":",
"the",
"HCL",
"(",
"string",
")",
"representation",
"of",
"a",
"collection",
"of",
"rules",
":",
"return",
":",
"the",
"equivalent",
"domain",
"model",
"to",
"the",
"given",
"rules"
] |
def decode_rules_as_hcl_string(rules_as_hcl):
"""
Converts the given HCL (string) representation of rules into a list of rule domain models.
:param rules_as_hcl: the HCL (string) representation of a collection of rules
:return: the equivalent domain model to the given rules
"""
rules_as_hcl = to_text(rules_as_hcl)
rules_as_json = hcl.loads(rules_as_hcl)
return decode_rules_as_json(rules_as_json)
|
[
"def",
"decode_rules_as_hcl_string",
"(",
"rules_as_hcl",
")",
":",
"rules_as_hcl",
"=",
"to_text",
"(",
"rules_as_hcl",
")",
"rules_as_json",
"=",
"hcl",
".",
"loads",
"(",
"rules_as_hcl",
")",
"return",
"decode_rules_as_json",
"(",
"rules_as_json",
")"
] |
https://github.com/ansible-collections/community.general/blob/3faffe8f47968a2400ba3c896c8901c03001a194/plugins/modules/consul_acl.py#L376-L384
|
|
hzlzh/AlfredWorkflow.com
|
7055f14f6922c80ea5943839eb0caff11ae57255
|
Sources/Workflows/delicious/BeautifulSoup.py
|
python
|
Tag.__len__
|
(self)
|
return len(self.contents)
|
The length of a tag is the length of its list of contents.
|
The length of a tag is the length of its list of contents.
|
[
"The",
"length",
"of",
"a",
"tag",
"is",
"the",
"length",
"of",
"its",
"list",
"of",
"contents",
"."
] |
def __len__(self):
"The length of a tag is the length of its list of contents."
return len(self.contents)
|
[
"def",
"__len__",
"(",
"self",
")",
":",
"return",
"len",
"(",
"self",
".",
"contents",
")"
] |
https://github.com/hzlzh/AlfredWorkflow.com/blob/7055f14f6922c80ea5943839eb0caff11ae57255/Sources/Workflows/delicious/BeautifulSoup.py#L619-L621
|
|
JacquesLucke/animation_nodes
|
b1e3ace8dcb0a771fd882fc3ac4e490b009fa0d1
|
animation_nodes/nodes/rotation/wiggle_euler.py
|
python
|
EulerWiggleNode.draw
|
(self, layout)
|
[] |
def draw(self, layout):
row = layout.row(align = True)
row.prop(self, "nodeSeed", text = "Node Seed")
row.prop(self, "createList", text = "", icon = "LINENUMBERS_ON")
|
[
"def",
"draw",
"(",
"self",
",",
"layout",
")",
":",
"row",
"=",
"layout",
".",
"row",
"(",
"align",
"=",
"True",
")",
"row",
".",
"prop",
"(",
"self",
",",
"\"nodeSeed\"",
",",
"text",
"=",
"\"Node Seed\"",
")",
"row",
".",
"prop",
"(",
"self",
",",
"\"createList\"",
",",
"text",
"=",
"\"\"",
",",
"icon",
"=",
"\"LINENUMBERS_ON\"",
")"
] |
https://github.com/JacquesLucke/animation_nodes/blob/b1e3ace8dcb0a771fd882fc3ac4e490b009fa0d1/animation_nodes/nodes/rotation/wiggle_euler.py#L36-L39
|
||||
XX-net/XX-Net
|
a9898cfcf0084195fb7e69b6bc834e59aecdf14f
|
python3.8.2/Lib/uuid.py
|
python
|
getnode
|
(*, getters=None)
|
Get the hardware address as a 48-bit positive integer.
The first time this runs, it may launch a separate program, which could
be quite slow. If all attempts to obtain the hardware address fail, we
choose a random 48-bit number with its eighth bit set to 1 as recommended
in RFC 4122.
|
Get the hardware address as a 48-bit positive integer.
|
[
"Get",
"the",
"hardware",
"address",
"as",
"a",
"48",
"-",
"bit",
"positive",
"integer",
"."
] |
def getnode(*, getters=None):
"""Get the hardware address as a 48-bit positive integer.
The first time this runs, it may launch a separate program, which could
be quite slow. If all attempts to obtain the hardware address fail, we
choose a random 48-bit number with its eighth bit set to 1 as recommended
in RFC 4122.
"""
global _node
if _node is not None:
return _node
for getter in _GETTERS + [_random_getnode]:
try:
_node = getter()
except:
continue
if (_node is not None) and (0 <= _node < (1 << 48)):
return _node
assert False, '_random_getnode() returned invalid value: {}'.format(_node)
|
[
"def",
"getnode",
"(",
"*",
",",
"getters",
"=",
"None",
")",
":",
"global",
"_node",
"if",
"_node",
"is",
"not",
"None",
":",
"return",
"_node",
"for",
"getter",
"in",
"_GETTERS",
"+",
"[",
"_random_getnode",
"]",
":",
"try",
":",
"_node",
"=",
"getter",
"(",
")",
"except",
":",
"continue",
"if",
"(",
"_node",
"is",
"not",
"None",
")",
"and",
"(",
"0",
"<=",
"_node",
"<",
"(",
"1",
"<<",
"48",
")",
")",
":",
"return",
"_node",
"assert",
"False",
",",
"'_random_getnode() returned invalid value: {}'",
".",
"format",
"(",
"_node",
")"
] |
https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/python3.8.2/Lib/uuid.py#L709-L728
|
||
rcorcs/NatI
|
fdf014f4292afdc95250add7b6658468043228e1
|
psw.py
|
python
|
play
|
(filename)
|
Plays an mp3 depending on the system.
|
Plays an mp3 depending on the system.
|
[
"Plays",
"an",
"mp3",
"depending",
"on",
"the",
"system",
"."
] |
def play(filename):
"""
Plays an mp3 depending on the system.
"""
import sys
import subprocess
if sys.platform == "linux" or sys.platform == "linux2":
# linux
subprocess.call(["play", '-q', filename])
elif sys.platform == "darwin":
# OS X
subprocess.call(["afplay", filename])
# only 32 bit windows, but a lot of win x86_64
# py installs are 32bit. Too much work for _64 fix
elif sys.platform == 'win32':
print ("trying windows default")
subprocess.call(["WMPlayer", filename])
|
[
"def",
"play",
"(",
"filename",
")",
":",
"import",
"sys",
"import",
"subprocess",
"if",
"sys",
".",
"platform",
"==",
"\"linux\"",
"or",
"sys",
".",
"platform",
"==",
"\"linux2\"",
":",
"# linux",
"subprocess",
".",
"call",
"(",
"[",
"\"play\"",
",",
"'-q'",
",",
"filename",
"]",
")",
"elif",
"sys",
".",
"platform",
"==",
"\"darwin\"",
":",
"# OS X",
"subprocess",
".",
"call",
"(",
"[",
"\"afplay\"",
",",
"filename",
"]",
")",
"# only 32 bit windows, but a lot of win x86_64",
"# py installs are 32bit. Too much work for _64 fix",
"elif",
"sys",
".",
"platform",
"==",
"'win32'",
":",
"print",
"(",
"\"trying windows default\"",
")",
"subprocess",
".",
"call",
"(",
"[",
"\"WMPlayer\"",
",",
"filename",
"]",
")"
] |
https://github.com/rcorcs/NatI/blob/fdf014f4292afdc95250add7b6658468043228e1/psw.py#L19-L36
|
||
pyqteval/evlal_win
|
ce7fc77ac5cdf864cd6aa9b04b5329501f8f4c92
|
pyinstaller-2.0/PyInstaller/lib/six.py
|
python
|
_add_doc
|
(func, doc)
|
Add documentation to a function.
|
Add documentation to a function.
|
[
"Add",
"documentation",
"to",
"a",
"function",
"."
] |
def _add_doc(func, doc):
"""Add documentation to a function."""
func.__doc__ = doc
|
[
"def",
"_add_doc",
"(",
"func",
",",
"doc",
")",
":",
"func",
".",
"__doc__",
"=",
"doc"
] |
https://github.com/pyqteval/evlal_win/blob/ce7fc77ac5cdf864cd6aa9b04b5329501f8f4c92/pyinstaller-2.0/PyInstaller/lib/six.py#L31-L33
|
||
JamesRamm/longclaw
|
f570918530db010ed842d795135e6d7e9196eb95
|
longclaw/checkout/api.py
|
python
|
create_token
|
(request)
|
return Response({'token': token}, status=status.HTTP_200_OK)
|
Generic function for creating a payment token from the
payment backend. Some payment backends (e.g. braintree) support creating a payment
token, which should be imported from the backend as 'get_token'
|
Generic function for creating a payment token from the
payment backend. Some payment backends (e.g. braintree) support creating a payment
token, which should be imported from the backend as 'get_token'
|
[
"Generic",
"function",
"for",
"creating",
"a",
"payment",
"token",
"from",
"the",
"payment",
"backend",
".",
"Some",
"payment",
"backends",
"(",
"e",
".",
"g",
".",
"braintree",
")",
"support",
"creating",
"a",
"payment",
"token",
"which",
"should",
"be",
"imported",
"from",
"the",
"backend",
"as",
"get_token"
] |
def create_token(request):
""" Generic function for creating a payment token from the
payment backend. Some payment backends (e.g. braintree) support creating a payment
token, which should be imported from the backend as 'get_token'
"""
token = GATEWAY.get_token(request)
return Response({'token': token}, status=status.HTTP_200_OK)
|
[
"def",
"create_token",
"(",
"request",
")",
":",
"token",
"=",
"GATEWAY",
".",
"get_token",
"(",
"request",
")",
"return",
"Response",
"(",
"{",
"'token'",
":",
"token",
"}",
",",
"status",
"=",
"status",
".",
"HTTP_200_OK",
")"
] |
https://github.com/JamesRamm/longclaw/blob/f570918530db010ed842d795135e6d7e9196eb95/longclaw/checkout/api.py#L15-L21
|
|
pymedusa/Medusa
|
1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38
|
ext/tornado/web.py
|
python
|
RequestHandler._log
|
(self)
|
Logs the current request.
Sort of deprecated since this functionality was moved to the
Application, but left in place for the benefit of existing apps
that have overridden this method.
|
Logs the current request.
|
[
"Logs",
"the",
"current",
"request",
"."
] |
def _log(self) -> None:
"""Logs the current request.
Sort of deprecated since this functionality was moved to the
Application, but left in place for the benefit of existing apps
that have overridden this method.
"""
self.application.log_request(self)
|
[
"def",
"_log",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"application",
".",
"log_request",
"(",
"self",
")"
] |
https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/ext/tornado/web.py#L1730-L1737
|
||
cuthbertLab/music21
|
bd30d4663e52955ed922c10fdf541419d8c67671
|
music21/tree/trees.py
|
python
|
ElementTree.__setitem__
|
(self, i, new)
|
r'''
Sets elements at index `i` to `new`, but keeping the old position
of the element there. (This is different from OffsetTrees, where things can move around).
>>> score = tree.makeExampleScore()
>>> scoreTree = score.asTree(flatten=True)
>>> n = scoreTree[10]
>>> n
<music21.note.Note G#>
>>> scoreTree.getNodeByIndex(10)
<ElementNode: Start:2.0 <0.20...> Indices:(l:10 *10* r:11)
Payload:<music21.note.Note G#>>
>>> scoreTree[10] = note.Note('F#')
>>> scoreTree[10]
<music21.note.Note F#>
>>> scoreTree.getNodeByIndex(10)
<ElementNode: Start:2.0 <0.20...> Indices:(l:10 *10* r:11)
Payload:<music21.note.Note F#>>
>>> scoreTree[10:13]
[<music21.note.Note F#>, <music21.note.Note F>, <music21.note.Note G>]
>>> scoreTree[10:14:2] = [note.Note('E#'), note.Note('F-')]
>>> scoreTree[10:13]
[<music21.note.Note E#>, <music21.note.Note F>, <music21.note.Note F->]
|
r'''
Sets elements at index `i` to `new`, but keeping the old position
of the element there. (This is different from OffsetTrees, where things can move around).
|
[
"r",
"Sets",
"elements",
"at",
"index",
"i",
"to",
"new",
"but",
"keeping",
"the",
"old",
"position",
"of",
"the",
"element",
"there",
".",
"(",
"This",
"is",
"different",
"from",
"OffsetTrees",
"where",
"things",
"can",
"move",
"around",
")",
"."
] |
def __setitem__(self, i, new):
# noinspection PyShadowingNames
r'''
Sets elements at index `i` to `new`, but keeping the old position
of the element there. (This is different from OffsetTrees, where things can move around).
>>> score = tree.makeExampleScore()
>>> scoreTree = score.asTree(flatten=True)
>>> n = scoreTree[10]
>>> n
<music21.note.Note G#>
>>> scoreTree.getNodeByIndex(10)
<ElementNode: Start:2.0 <0.20...> Indices:(l:10 *10* r:11)
Payload:<music21.note.Note G#>>
>>> scoreTree[10] = note.Note('F#')
>>> scoreTree[10]
<music21.note.Note F#>
>>> scoreTree.getNodeByIndex(10)
<ElementNode: Start:2.0 <0.20...> Indices:(l:10 *10* r:11)
Payload:<music21.note.Note F#>>
>>> scoreTree[10:13]
[<music21.note.Note F#>, <music21.note.Note F>, <music21.note.Note G>]
>>> scoreTree[10:14:2] = [note.Note('E#'), note.Note('F-')]
>>> scoreTree[10:13]
[<music21.note.Note E#>, <music21.note.Note F>, <music21.note.Note F->]
'''
if isinstance(i, int):
n = self.getNodeByIndex(i)
if n is None:
message = f'Index must be less than {len(self)}'
raise TypeError(message)
n.payload = new
elif isinstance(i, slice):
if not isinstance(new, list):
message = f'If {i} is a slice, then {new} must be a list'
raise TypeError(message)
sliceLen = (i.stop - i.start) / i.step
if sliceLen != len(new):
message = f'{i} is a slice of len {sliceLen}, so {new} cannot have len {len(new)}'
raise TypeError(message)
for j, sliceIter in enumerate(range(i.start, i.stop, i.step)):
self[sliceIter] = new[j] # recursive.
else:
message = f'Indices must be ints or slices, got {i}'
raise TypeError(message)
|
[
"def",
"__setitem__",
"(",
"self",
",",
"i",
",",
"new",
")",
":",
"# noinspection PyShadowingNames",
"if",
"isinstance",
"(",
"i",
",",
"int",
")",
":",
"n",
"=",
"self",
".",
"getNodeByIndex",
"(",
"i",
")",
"if",
"n",
"is",
"None",
":",
"message",
"=",
"f'Index must be less than {len(self)}'",
"raise",
"TypeError",
"(",
"message",
")",
"n",
".",
"payload",
"=",
"new",
"elif",
"isinstance",
"(",
"i",
",",
"slice",
")",
":",
"if",
"not",
"isinstance",
"(",
"new",
",",
"list",
")",
":",
"message",
"=",
"f'If {i} is a slice, then {new} must be a list'",
"raise",
"TypeError",
"(",
"message",
")",
"sliceLen",
"=",
"(",
"i",
".",
"stop",
"-",
"i",
".",
"start",
")",
"/",
"i",
".",
"step",
"if",
"sliceLen",
"!=",
"len",
"(",
"new",
")",
":",
"message",
"=",
"f'{i} is a slice of len {sliceLen}, so {new} cannot have len {len(new)}'",
"raise",
"TypeError",
"(",
"message",
")",
"for",
"j",
",",
"sliceIter",
"in",
"enumerate",
"(",
"range",
"(",
"i",
".",
"start",
",",
"i",
".",
"stop",
",",
"i",
".",
"step",
")",
")",
":",
"self",
"[",
"sliceIter",
"]",
"=",
"new",
"[",
"j",
"]",
"# recursive.",
"else",
":",
"message",
"=",
"f'Indices must be ints or slices, got {i}'",
"raise",
"TypeError",
"(",
"message",
")"
] |
https://github.com/cuthbertLab/music21/blob/bd30d4663e52955ed922c10fdf541419d8c67671/music21/tree/trees.py#L298-L345
|
||
kakao/khaiii
|
328d5a8af456a5941130383354c07d1cd0e47cf5
|
src/main/python/khaiii/resource/char_align.py
|
python
|
Aligner._align_backward
|
(cls, raw_word: str, mrp_chrs: List[MrpChr])
|
return word_idx+1, mrp_chrs_idx+1
|
align from back of word
Args:
raw_word: raw word
mrp_chrs: list of MrpChr object
Returns:
word index
mrp_chrs index
|
align from back of word
Args:
raw_word: raw word
mrp_chrs: list of MrpChr object
Returns:
word index
mrp_chrs index
|
[
"align",
"from",
"back",
"of",
"word",
"Args",
":",
"raw_word",
":",
"raw",
"word",
"mrp_chrs",
":",
"list",
"of",
"MrpChr",
"object",
"Returns",
":",
"word",
"index",
"mrp_chrs",
"index"
] |
def _align_backward(cls, raw_word: str, mrp_chrs: List[MrpChr]) -> Tuple[int, int]:
"""
align from back of word
Args:
raw_word: raw word
mrp_chrs: list of MrpChr object
Returns:
word index
mrp_chrs index
"""
word_idx = len(raw_word) - 1
mrp_chrs_idx = len(mrp_chrs) - 1
while word_idx >= 0:
word_char = raw_word[word_idx]
morph_char = mrp_chrs[mrp_chrs_idx].char
if word_char != morph_char:
word_norm = cls._norm(word_char)
char_norm = cls._norm(morph_char)
if word_norm == char_norm:
pass
elif mrp_chrs_idx+1 >= 0 and \
word_norm == cls._norm(mrp_chrs[mrp_chrs_idx - 1].char + morph_char):
mrp_chrs_idx -= 1
elif (word_char == '㈜' and mrp_chrs_idx-2 >= 0 and morph_char == ')'
and mrp_chrs[mrp_chrs_idx-1].char == '주'
and mrp_chrs[mrp_chrs_idx-2].char == '('):
mrp_chrs_idx -= 2
else:
return word_idx+1, mrp_chrs_idx+1
word_idx -= 1
mrp_chrs_idx -= 1
return word_idx+1, mrp_chrs_idx+1
|
[
"def",
"_align_backward",
"(",
"cls",
",",
"raw_word",
":",
"str",
",",
"mrp_chrs",
":",
"List",
"[",
"MrpChr",
"]",
")",
"->",
"Tuple",
"[",
"int",
",",
"int",
"]",
":",
"word_idx",
"=",
"len",
"(",
"raw_word",
")",
"-",
"1",
"mrp_chrs_idx",
"=",
"len",
"(",
"mrp_chrs",
")",
"-",
"1",
"while",
"word_idx",
">=",
"0",
":",
"word_char",
"=",
"raw_word",
"[",
"word_idx",
"]",
"morph_char",
"=",
"mrp_chrs",
"[",
"mrp_chrs_idx",
"]",
".",
"char",
"if",
"word_char",
"!=",
"morph_char",
":",
"word_norm",
"=",
"cls",
".",
"_norm",
"(",
"word_char",
")",
"char_norm",
"=",
"cls",
".",
"_norm",
"(",
"morph_char",
")",
"if",
"word_norm",
"==",
"char_norm",
":",
"pass",
"elif",
"mrp_chrs_idx",
"+",
"1",
">=",
"0",
"and",
"word_norm",
"==",
"cls",
".",
"_norm",
"(",
"mrp_chrs",
"[",
"mrp_chrs_idx",
"-",
"1",
"]",
".",
"char",
"+",
"morph_char",
")",
":",
"mrp_chrs_idx",
"-=",
"1",
"elif",
"(",
"word_char",
"==",
"'㈜' a",
"d m",
"p_chrs_idx-2",
" ",
">",
" 0",
"a",
"d m",
"rph_char =",
" '",
"'",
"and",
"mrp_chrs",
"[",
"mrp_chrs_idx",
"-",
"1",
"]",
".",
"char",
"==",
"'주'",
"and",
"mrp_chrs",
"[",
"mrp_chrs_idx",
"-",
"2",
"]",
".",
"char",
"==",
"'('",
")",
":",
"mrp_chrs_idx",
"-=",
"2",
"else",
":",
"return",
"word_idx",
"+",
"1",
",",
"mrp_chrs_idx",
"+",
"1",
"word_idx",
"-=",
"1",
"mrp_chrs_idx",
"-=",
"1",
"return",
"word_idx",
"+",
"1",
",",
"mrp_chrs_idx",
"+",
"1"
] |
https://github.com/kakao/khaiii/blob/328d5a8af456a5941130383354c07d1cd0e47cf5/src/main/python/khaiii/resource/char_align.py#L239-L270
|
|
Axelrod-Python/Axelrod
|
00e18323c1b1af74df873773e44f31e1b9a299c6
|
axelrod/strategies/cycler.py
|
python
|
EvolvableCycler._normalize_parameters
|
(
self, cycle=None, cycle_length=None
)
|
return cycle, cycle_length
|
Compute other parameters from those that may be missing, to ensure proper cloning.
|
Compute other parameters from those that may be missing, to ensure proper cloning.
|
[
"Compute",
"other",
"parameters",
"from",
"those",
"that",
"may",
"be",
"missing",
"to",
"ensure",
"proper",
"cloning",
"."
] |
def _normalize_parameters(
self, cycle=None, cycle_length=None
) -> Tuple[str, int]:
"""Compute other parameters from those that may be missing, to ensure proper cloning."""
if not cycle:
if not cycle_length:
raise InsufficientParametersError(
"Insufficient Parameters to instantiate EvolvableCycler"
)
cycle = self._generate_random_cycle(cycle_length)
cycle_length = len(cycle)
return cycle, cycle_length
|
[
"def",
"_normalize_parameters",
"(",
"self",
",",
"cycle",
"=",
"None",
",",
"cycle_length",
"=",
"None",
")",
"->",
"Tuple",
"[",
"str",
",",
"int",
"]",
":",
"if",
"not",
"cycle",
":",
"if",
"not",
"cycle_length",
":",
"raise",
"InsufficientParametersError",
"(",
"\"Insufficient Parameters to instantiate EvolvableCycler\"",
")",
"cycle",
"=",
"self",
".",
"_generate_random_cycle",
"(",
"cycle_length",
")",
"cycle_length",
"=",
"len",
"(",
"cycle",
")",
"return",
"cycle",
",",
"cycle_length"
] |
https://github.com/Axelrod-Python/Axelrod/blob/00e18323c1b1af74df873773e44f31e1b9a299c6/axelrod/strategies/cycler.py#L126-L137
|
|
git-cola/git-cola
|
b48b8028e0c3baf47faf7b074b9773737358163d
|
cola/widgets/submodules.py
|
python
|
SubmodulesTreeWidgetItem.__init__
|
(self, name, path, tip, icon)
|
[] |
def __init__(self, name, path, tip, icon):
QtWidgets.QTreeWidgetItem.__init__(self)
self.path = path
self.setIcon(0, icon)
self.setText(0, name)
self.setToolTip(0, tip)
|
[
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"path",
",",
"tip",
",",
"icon",
")",
":",
"QtWidgets",
".",
"QTreeWidgetItem",
".",
"__init__",
"(",
"self",
")",
"self",
".",
"path",
"=",
"path",
"self",
".",
"setIcon",
"(",
"0",
",",
"icon",
")",
"self",
".",
"setText",
"(",
"0",
",",
"name",
")",
"self",
".",
"setToolTip",
"(",
"0",
",",
"tip",
")"
] |
https://github.com/git-cola/git-cola/blob/b48b8028e0c3baf47faf7b074b9773737358163d/cola/widgets/submodules.py#L223-L229
|
||||
home-assistant/core
|
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
|
homeassistant/components/nest/api.py
|
python
|
AsyncConfigEntryAuth.async_get_access_token
|
(self)
|
return cast(str, self._oauth_session.token["access_token"])
|
Return a valid access token for SDM API.
|
Return a valid access token for SDM API.
|
[
"Return",
"a",
"valid",
"access",
"token",
"for",
"SDM",
"API",
"."
] |
async def async_get_access_token(self) -> str:
"""Return a valid access token for SDM API."""
if not self._oauth_session.valid_token:
await self._oauth_session.async_ensure_token_valid()
return cast(str, self._oauth_session.token["access_token"])
|
[
"async",
"def",
"async_get_access_token",
"(",
"self",
")",
"->",
"str",
":",
"if",
"not",
"self",
".",
"_oauth_session",
".",
"valid_token",
":",
"await",
"self",
".",
"_oauth_session",
".",
"async_ensure_token_valid",
"(",
")",
"return",
"cast",
"(",
"str",
",",
"self",
".",
"_oauth_session",
".",
"token",
"[",
"\"access_token\"",
"]",
")"
] |
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/nest/api.py#L48-L52
|
|
chribsen/simple-machine-learning-examples
|
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
|
venv/lib/python2.7/site-packages/deap/gp.py
|
python
|
PrimitiveTree.searchSubtree
|
(self, begin)
|
return slice(begin, end)
|
Return a slice object that corresponds to the
range of values that defines the subtree which has the
element with index *begin* as its root.
|
Return a slice object that corresponds to the
range of values that defines the subtree which has the
element with index *begin* as its root.
|
[
"Return",
"a",
"slice",
"object",
"that",
"corresponds",
"to",
"the",
"range",
"of",
"values",
"that",
"defines",
"the",
"subtree",
"which",
"has",
"the",
"element",
"with",
"index",
"*",
"begin",
"*",
"as",
"its",
"root",
"."
] |
def searchSubtree(self, begin):
"""Return a slice object that corresponds to the
range of values that defines the subtree which has the
element with index *begin* as its root.
"""
end = begin + 1
total = self[begin].arity
while total > 0:
total += self[end].arity - 1
end += 1
return slice(begin, end)
|
[
"def",
"searchSubtree",
"(",
"self",
",",
"begin",
")",
":",
"end",
"=",
"begin",
"+",
"1",
"total",
"=",
"self",
"[",
"begin",
"]",
".",
"arity",
"while",
"total",
">",
"0",
":",
"total",
"+=",
"self",
"[",
"end",
"]",
".",
"arity",
"-",
"1",
"end",
"+=",
"1",
"return",
"slice",
"(",
"begin",
",",
"end",
")"
] |
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/deap/gp.py#L167-L177
|
|
Thriftpy/thriftpy
|
0e606f82a3c900e663b63d69f68fc304c5d58dee
|
thriftpy/transport/socket.py
|
python
|
TSocket.close
|
(self)
|
[] |
def close(self):
if not self.sock:
return
try:
self.sock.shutdown(socket.SHUT_RDWR)
self.sock.close()
self.sock = None
except (socket.error, OSError):
pass
|
[
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"sock",
":",
"return",
"try",
":",
"self",
".",
"sock",
".",
"shutdown",
"(",
"socket",
".",
"SHUT_RDWR",
")",
"self",
".",
"sock",
".",
"close",
"(",
")",
"self",
".",
"sock",
"=",
"None",
"except",
"(",
"socket",
".",
"error",
",",
"OSError",
")",
":",
"pass"
] |
https://github.com/Thriftpy/thriftpy/blob/0e606f82a3c900e663b63d69f68fc304c5d58dee/thriftpy/transport/socket.py#L134-L143
|
||||
sagemath/sage
|
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
|
src/sage/combinat/designs/database.py
|
python
|
RBIBD_120_8_1
|
()
|
return [B for S in equiv for B in S]
|
r"""
Return a resolvable `BIBD(120,8,1)`
This function output a list ``L`` of `17\times 15` blocks such that
``L[i*15:(i+1)*15]`` is a partition of `120`.
Construction shared by Julian R. Abel:
Seiden's method: Start with a cyclic `(273,17,1)-BIBD` and let `B` be an
hyperoval, i.e. a set of 18 points which intersects any block of the
BIBD in either 0 points (153 blocks) or 2 points (120 blocks). Dualise
this design and take these last 120 blocks as points in the design;
blocks in the design will correspond to the `273-18=255` non-hyperoval
points.
The design is also resolvable. In the original `PG(2,16)` take any
point `T` in the hyperoval and consider a block `B1` containing `T`.
The `15` points in `B1` that do not belong to the hyperoval correspond
to `15` blocks forming a parallel class in the dualised design. The
other `16` parallel classes come in a similar way, by using point `T`
and the other `16` blocks containing `T`.
.. SEEALSO::
:func:`OA_9_120`
EXAMPLES::
sage: from sage.combinat.designs.database import RBIBD_120_8_1
sage: from sage.combinat.designs.bibd import is_pairwise_balanced_design
sage: RBIBD = RBIBD_120_8_1()
sage: is_pairwise_balanced_design(RBIBD,120,[8])
True
It is indeed resolvable, and the parallel classes are given by 17 slices of
consecutive 15 blocks::
sage: for i in range(17):
....: assert len(set(sum(RBIBD[i*15:(i+1)*15],[]))) == 120
The BIBD is available from the constructor::
sage: _ = designs.balanced_incomplete_block_design(120,8)
|
r"""
Return a resolvable `BIBD(120,8,1)`
|
[
"r",
"Return",
"a",
"resolvable",
"BIBD",
"(",
"120",
"8",
"1",
")"
] |
def RBIBD_120_8_1():
r"""
Return a resolvable `BIBD(120,8,1)`
This function output a list ``L`` of `17\times 15` blocks such that
``L[i*15:(i+1)*15]`` is a partition of `120`.
Construction shared by Julian R. Abel:
Seiden's method: Start with a cyclic `(273,17,1)-BIBD` and let `B` be an
hyperoval, i.e. a set of 18 points which intersects any block of the
BIBD in either 0 points (153 blocks) or 2 points (120 blocks). Dualise
this design and take these last 120 blocks as points in the design;
blocks in the design will correspond to the `273-18=255` non-hyperoval
points.
The design is also resolvable. In the original `PG(2,16)` take any
point `T` in the hyperoval and consider a block `B1` containing `T`.
The `15` points in `B1` that do not belong to the hyperoval correspond
to `15` blocks forming a parallel class in the dualised design. The
other `16` parallel classes come in a similar way, by using point `T`
and the other `16` blocks containing `T`.
.. SEEALSO::
:func:`OA_9_120`
EXAMPLES::
sage: from sage.combinat.designs.database import RBIBD_120_8_1
sage: from sage.combinat.designs.bibd import is_pairwise_balanced_design
sage: RBIBD = RBIBD_120_8_1()
sage: is_pairwise_balanced_design(RBIBD,120,[8])
True
It is indeed resolvable, and the parallel classes are given by 17 slices of
consecutive 15 blocks::
sage: for i in range(17):
....: assert len(set(sum(RBIBD[i*15:(i+1)*15],[]))) == 120
The BIBD is available from the constructor::
sage: _ = designs.balanced_incomplete_block_design(120,8)
"""
from .incidence_structures import IncidenceStructure
n=273
# Base block of a cyclic BIBD(273,16,1)
B = [1,2,4,8,16,32,64,91,117,128,137,182,195,205,234,239,256]
BIBD = [[(x+c)%n for x in B] for c in range(n)]
# A (precomputed) set that every block of the BIBD intersects on 0 or 2 points
hyperoval = [128, 192, 194, 4, 262, 140, 175, 48, 81, 180, 245, 271, 119, 212, 249, 189, 62, 255]
#for B in BIBD:
# len_trace = sum(x in hyperoval for x in B)
# assert len_trace == 0 or len_trace == 2
# Equivalence classes
p = hyperoval[0]
equiv = []
new_BIBD = []
for B in BIBD:
if any(x in hyperoval for x in B):
if p in B:
equiv.append([x for x in B if x not in hyperoval])
else:
new_BIBD.append([x for x in B])
BIBD = new_BIBD
r = {v:i for i,v in enumerate(x for x in range(n) if x not in hyperoval)}
BIBD = [[r[x] for x in B] for B in BIBD ]
equiv = [[r[x] for x in B] for B in equiv]
BIBD = IncidenceStructure(range(255),BIBD)
M = BIBD.incidence_matrix()
equiv = [[M.nonzero_positions_in_row(x) for x in S] for S in equiv]
return [B for S in equiv for B in S]
|
[
"def",
"RBIBD_120_8_1",
"(",
")",
":",
"from",
".",
"incidence_structures",
"import",
"IncidenceStructure",
"n",
"=",
"273",
"# Base block of a cyclic BIBD(273,16,1)",
"B",
"=",
"[",
"1",
",",
"2",
",",
"4",
",",
"8",
",",
"16",
",",
"32",
",",
"64",
",",
"91",
",",
"117",
",",
"128",
",",
"137",
",",
"182",
",",
"195",
",",
"205",
",",
"234",
",",
"239",
",",
"256",
"]",
"BIBD",
"=",
"[",
"[",
"(",
"x",
"+",
"c",
")",
"%",
"n",
"for",
"x",
"in",
"B",
"]",
"for",
"c",
"in",
"range",
"(",
"n",
")",
"]",
"# A (precomputed) set that every block of the BIBD intersects on 0 or 2 points",
"hyperoval",
"=",
"[",
"128",
",",
"192",
",",
"194",
",",
"4",
",",
"262",
",",
"140",
",",
"175",
",",
"48",
",",
"81",
",",
"180",
",",
"245",
",",
"271",
",",
"119",
",",
"212",
",",
"249",
",",
"189",
",",
"62",
",",
"255",
"]",
"#for B in BIBD:",
"# len_trace = sum(x in hyperoval for x in B)",
"# assert len_trace == 0 or len_trace == 2",
"# Equivalence classes",
"p",
"=",
"hyperoval",
"[",
"0",
"]",
"equiv",
"=",
"[",
"]",
"new_BIBD",
"=",
"[",
"]",
"for",
"B",
"in",
"BIBD",
":",
"if",
"any",
"(",
"x",
"in",
"hyperoval",
"for",
"x",
"in",
"B",
")",
":",
"if",
"p",
"in",
"B",
":",
"equiv",
".",
"append",
"(",
"[",
"x",
"for",
"x",
"in",
"B",
"if",
"x",
"not",
"in",
"hyperoval",
"]",
")",
"else",
":",
"new_BIBD",
".",
"append",
"(",
"[",
"x",
"for",
"x",
"in",
"B",
"]",
")",
"BIBD",
"=",
"new_BIBD",
"r",
"=",
"{",
"v",
":",
"i",
"for",
"i",
",",
"v",
"in",
"enumerate",
"(",
"x",
"for",
"x",
"in",
"range",
"(",
"n",
")",
"if",
"x",
"not",
"in",
"hyperoval",
")",
"}",
"BIBD",
"=",
"[",
"[",
"r",
"[",
"x",
"]",
"for",
"x",
"in",
"B",
"]",
"for",
"B",
"in",
"BIBD",
"]",
"equiv",
"=",
"[",
"[",
"r",
"[",
"x",
"]",
"for",
"x",
"in",
"B",
"]",
"for",
"B",
"in",
"equiv",
"]",
"BIBD",
"=",
"IncidenceStructure",
"(",
"range",
"(",
"255",
")",
",",
"BIBD",
")",
"M",
"=",
"BIBD",
".",
"incidence_matrix",
"(",
")",
"equiv",
"=",
"[",
"[",
"M",
".",
"nonzero_positions_in_row",
"(",
"x",
")",
"for",
"x",
"in",
"S",
"]",
"for",
"S",
"in",
"equiv",
"]",
"return",
"[",
"B",
"for",
"S",
"in",
"equiv",
"for",
"B",
"in",
"S",
"]"
] |
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/designs/database.py#L4053-L4132
|
|
aliyun/aliyun-openapi-python-sdk
|
bda53176cc9cf07605b1cf769f0df444cca626a0
|
aliyun-python-sdk-core/aliyunsdkcore/vendored/requests/packages/urllib3/packages/ordered_dict.py
|
python
|
OrderedDict.iteritems
|
(self)
|
od.iteritems -> an iterator over the (key, value) items in od
|
od.iteritems -> an iterator over the (key, value) items in od
|
[
"od",
".",
"iteritems",
"-",
">",
"an",
"iterator",
"over",
"the",
"(",
"key",
"value",
")",
"items",
"in",
"od"
] |
def iteritems(self):
'od.iteritems -> an iterator over the (key, value) items in od'
for k in self:
yield (k, self[k])
|
[
"def",
"iteritems",
"(",
"self",
")",
":",
"for",
"k",
"in",
"self",
":",
"yield",
"(",
"k",
",",
"self",
"[",
"k",
"]",
")"
] |
https://github.com/aliyun/aliyun-openapi-python-sdk/blob/bda53176cc9cf07605b1cf769f0df444cca626a0/aliyun-python-sdk-core/aliyunsdkcore/vendored/requests/packages/urllib3/packages/ordered_dict.py#L137-L140
|
||
awesto/django-shop
|
13d9a77aff7eede74a5f363c1d540e005d88dbcd
|
shop/admin/order.py
|
python
|
OrderPaymentInline.get_amount
|
(self, obj)
|
return obj.amount
|
Return amount using correct local format
|
Return amount using correct local format
|
[
"Return",
"amount",
"using",
"correct",
"local",
"format"
] |
def get_amount(self, obj):
"""Return amount using correct local format"""
return obj.amount
|
[
"def",
"get_amount",
"(",
"self",
",",
"obj",
")",
":",
"return",
"obj",
".",
"amount"
] |
https://github.com/awesto/django-shop/blob/13d9a77aff7eede74a5f363c1d540e005d88dbcd/shop/admin/order.py#L59-L61
|
|
PacktPublishing/Deep-Reinforcement-Learning-Hands-On
|
baa9d013596ea8ea8ed6826b9de6679d98b897ca
|
Chapter10/03_pong_a2c_rollouts.py
|
python
|
unpack_batch
|
(batch, net, device="cpu")
|
return states_v, actions_t, ref_vals_v
|
Convert batch into training tensors
:param batch:
:param net:
:return: states variable, actions tensor, reference values variable
|
Convert batch into training tensors
:param batch:
:param net:
:return: states variable, actions tensor, reference values variable
|
[
"Convert",
"batch",
"into",
"training",
"tensors",
":",
"param",
"batch",
":",
":",
"param",
"net",
":",
":",
"return",
":",
"states",
"variable",
"actions",
"tensor",
"reference",
"values",
"variable"
] |
def unpack_batch(batch, net, device="cpu"):
"""
Convert batch into training tensors
:param batch:
:param net:
:return: states variable, actions tensor, reference values variable
"""
states = []
actions = []
rewards = []
not_done_idx = []
last_states = []
for idx, exp in enumerate(batch):
states.append(np.array(exp.state, copy=False))
actions.append(int(exp.action))
rewards.append(exp.reward)
if exp.last_state is not None:
not_done_idx.append(idx)
last_states.append(np.array(exp.last_state, copy=False))
states_v = torch.FloatTensor(states).to(device)
actions_t = torch.LongTensor(actions).to(device)
# handle rewards
rewards_np = np.array(rewards, dtype=np.float32)
if not_done_idx:
last_states_v = torch.FloatTensor(last_states).to(device)
last_vals_v = net(last_states_v)[1]
last_vals_np = last_vals_v.data.cpu().numpy()[:, 0]
rewards_np[not_done_idx] += GAMMA ** REWARD_STEPS * last_vals_np
ref_vals_v = torch.FloatTensor(rewards_np).to(device)
return states_v, actions_t, ref_vals_v
|
[
"def",
"unpack_batch",
"(",
"batch",
",",
"net",
",",
"device",
"=",
"\"cpu\"",
")",
":",
"states",
"=",
"[",
"]",
"actions",
"=",
"[",
"]",
"rewards",
"=",
"[",
"]",
"not_done_idx",
"=",
"[",
"]",
"last_states",
"=",
"[",
"]",
"for",
"idx",
",",
"exp",
"in",
"enumerate",
"(",
"batch",
")",
":",
"states",
".",
"append",
"(",
"np",
".",
"array",
"(",
"exp",
".",
"state",
",",
"copy",
"=",
"False",
")",
")",
"actions",
".",
"append",
"(",
"int",
"(",
"exp",
".",
"action",
")",
")",
"rewards",
".",
"append",
"(",
"exp",
".",
"reward",
")",
"if",
"exp",
".",
"last_state",
"is",
"not",
"None",
":",
"not_done_idx",
".",
"append",
"(",
"idx",
")",
"last_states",
".",
"append",
"(",
"np",
".",
"array",
"(",
"exp",
".",
"last_state",
",",
"copy",
"=",
"False",
")",
")",
"states_v",
"=",
"torch",
".",
"FloatTensor",
"(",
"states",
")",
".",
"to",
"(",
"device",
")",
"actions_t",
"=",
"torch",
".",
"LongTensor",
"(",
"actions",
")",
".",
"to",
"(",
"device",
")",
"# handle rewards",
"rewards_np",
"=",
"np",
".",
"array",
"(",
"rewards",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"if",
"not_done_idx",
":",
"last_states_v",
"=",
"torch",
".",
"FloatTensor",
"(",
"last_states",
")",
".",
"to",
"(",
"device",
")",
"last_vals_v",
"=",
"net",
"(",
"last_states_v",
")",
"[",
"1",
"]",
"last_vals_np",
"=",
"last_vals_v",
".",
"data",
".",
"cpu",
"(",
")",
".",
"numpy",
"(",
")",
"[",
":",
",",
"0",
"]",
"rewards_np",
"[",
"not_done_idx",
"]",
"+=",
"GAMMA",
"**",
"REWARD_STEPS",
"*",
"last_vals_np",
"ref_vals_v",
"=",
"torch",
".",
"FloatTensor",
"(",
"rewards_np",
")",
".",
"to",
"(",
"device",
")",
"return",
"states_v",
",",
"actions_t",
",",
"ref_vals_v"
] |
https://github.com/PacktPublishing/Deep-Reinforcement-Learning-Hands-On/blob/baa9d013596ea8ea8ed6826b9de6679d98b897ca/Chapter10/03_pong_a2c_rollouts.py#L61-L92
|
|
open-mmlab/mmsegmentation
|
af9ccd3d47fda8c7b50eee3675072692e3e54da5
|
.dev/benchmark_inference.py
|
python
|
download_checkpoint
|
(checkpoint_name, model_name, config_name, collect_dir)
|
Download checkpoint and check if hash code is true.
|
Download checkpoint and check if hash code is true.
|
[
"Download",
"checkpoint",
"and",
"check",
"if",
"hash",
"code",
"is",
"true",
"."
] |
def download_checkpoint(checkpoint_name, model_name, config_name, collect_dir):
"""Download checkpoint and check if hash code is true."""
url = f'https://download.openmmlab.com/mmsegmentation/v0.5/{model_name}/{config_name}/{checkpoint_name}' # noqa
r = requests.get(url)
assert r.status_code != 403, f'{url} Access denied.'
with open(osp.join(collect_dir, checkpoint_name), 'wb') as code:
code.write(r.content)
true_hash_code = osp.splitext(checkpoint_name)[0].split('-')[1]
# check hash code
with open(osp.join(collect_dir, checkpoint_name), 'rb') as fp:
sha256_cal = hashlib.sha256()
sha256_cal.update(fp.read())
cur_hash_code = sha256_cal.hexdigest()[:8]
assert true_hash_code == cur_hash_code, f'{url} download failed, '
'incomplete downloaded file or url invalid.'
if cur_hash_code != true_hash_code:
os.remove(osp.join(collect_dir, checkpoint_name))
|
[
"def",
"download_checkpoint",
"(",
"checkpoint_name",
",",
"model_name",
",",
"config_name",
",",
"collect_dir",
")",
":",
"url",
"=",
"f'https://download.openmmlab.com/mmsegmentation/v0.5/{model_name}/{config_name}/{checkpoint_name}'",
"# noqa",
"r",
"=",
"requests",
".",
"get",
"(",
"url",
")",
"assert",
"r",
".",
"status_code",
"!=",
"403",
",",
"f'{url} Access denied.'",
"with",
"open",
"(",
"osp",
".",
"join",
"(",
"collect_dir",
",",
"checkpoint_name",
")",
",",
"'wb'",
")",
"as",
"code",
":",
"code",
".",
"write",
"(",
"r",
".",
"content",
")",
"true_hash_code",
"=",
"osp",
".",
"splitext",
"(",
"checkpoint_name",
")",
"[",
"0",
"]",
".",
"split",
"(",
"'-'",
")",
"[",
"1",
"]",
"# check hash code",
"with",
"open",
"(",
"osp",
".",
"join",
"(",
"collect_dir",
",",
"checkpoint_name",
")",
",",
"'rb'",
")",
"as",
"fp",
":",
"sha256_cal",
"=",
"hashlib",
".",
"sha256",
"(",
")",
"sha256_cal",
".",
"update",
"(",
"fp",
".",
"read",
"(",
")",
")",
"cur_hash_code",
"=",
"sha256_cal",
".",
"hexdigest",
"(",
")",
"[",
":",
"8",
"]",
"assert",
"true_hash_code",
"==",
"cur_hash_code",
",",
"f'{url} download failed, '",
"'incomplete downloaded file or url invalid.'",
"if",
"cur_hash_code",
"!=",
"true_hash_code",
":",
"os",
".",
"remove",
"(",
"osp",
".",
"join",
"(",
"collect_dir",
",",
"checkpoint_name",
")",
")"
] |
https://github.com/open-mmlab/mmsegmentation/blob/af9ccd3d47fda8c7b50eee3675072692e3e54da5/.dev/benchmark_inference.py#L19-L41
|
||
robhagemans/pcbasic
|
c3a043b46af66623a801e18a38175be077251ada
|
pcbasic/basic/interpreter.py
|
python
|
Interpreter.read_
|
(self, args)
|
READ: read values from DATA statement.
|
READ: read values from DATA statement.
|
[
"READ",
":",
"read",
"values",
"from",
"DATA",
"statement",
"."
] |
def read_(self, args):
"""READ: read values from DATA statement."""
data_error = False
for name, indices in args:
name = self._memory.complete_name(name)
current = self._program_code.tell()
self._program_code.seek(self.data_pos)
if self._program_code.peek() in tk.END_STATEMENT:
# initialise - find first DATA
self._program_code.skip_to_token(tk.DATA,)
if self._program_code.read(1) not in (tk.DATA, b','):
self._program_code.seek(current)
raise error.BASICError(error.OUT_OF_DATA)
self._program_code.skip_blank()
if name[-1:] == values.STR:
# for unquoted strings, payload starts at the first non-empty character
address = self._program_code.tell_address()
word = self._program_code.read_to((b',', b'"',) + tk.END_STATEMENT)
if self._program_code.peek() == b'"':
if word == b'':
# nothing before the quotes, so this is a quoted string literal
# string payload starts after quote
address = self._program_code.tell_address() + 1
word = self._program_code.read_string().strip(b'"')
else:
# complete unquoted string literal
word += self._program_code.read_string()
if (self._program_code.skip_blank() not in (tk.END_STATEMENT + (b',',))):
raise error.BASICError(error.STX)
else:
word = word.strip(self._program_code.blanks)
value = self._values.from_str_at(word, address)
else:
word = self._program_code.read_number()
value = self._values.from_repr(word, allow_nonnum=False)
# anything after the number is a syntax error, but assignment has taken place)
if (self._program_code.skip_blank() not in (tk.END_STATEMENT + (b',',))):
data_error = True
# restore to current program location
# to ensure any other errors in set_variable get the correct line number
data_pos = self._program_code.tell()
self._program_code.seek(current)
self._memory.set_variable(name, indices, value=value)
if data_error:
self._program_code.seek(self.data_pos)
raise error.BASICError(error.STX)
else:
self.data_pos = data_pos
|
[
"def",
"read_",
"(",
"self",
",",
"args",
")",
":",
"data_error",
"=",
"False",
"for",
"name",
",",
"indices",
"in",
"args",
":",
"name",
"=",
"self",
".",
"_memory",
".",
"complete_name",
"(",
"name",
")",
"current",
"=",
"self",
".",
"_program_code",
".",
"tell",
"(",
")",
"self",
".",
"_program_code",
".",
"seek",
"(",
"self",
".",
"data_pos",
")",
"if",
"self",
".",
"_program_code",
".",
"peek",
"(",
")",
"in",
"tk",
".",
"END_STATEMENT",
":",
"# initialise - find first DATA",
"self",
".",
"_program_code",
".",
"skip_to_token",
"(",
"tk",
".",
"DATA",
",",
")",
"if",
"self",
".",
"_program_code",
".",
"read",
"(",
"1",
")",
"not",
"in",
"(",
"tk",
".",
"DATA",
",",
"b','",
")",
":",
"self",
".",
"_program_code",
".",
"seek",
"(",
"current",
")",
"raise",
"error",
".",
"BASICError",
"(",
"error",
".",
"OUT_OF_DATA",
")",
"self",
".",
"_program_code",
".",
"skip_blank",
"(",
")",
"if",
"name",
"[",
"-",
"1",
":",
"]",
"==",
"values",
".",
"STR",
":",
"# for unquoted strings, payload starts at the first non-empty character",
"address",
"=",
"self",
".",
"_program_code",
".",
"tell_address",
"(",
")",
"word",
"=",
"self",
".",
"_program_code",
".",
"read_to",
"(",
"(",
"b','",
",",
"b'\"'",
",",
")",
"+",
"tk",
".",
"END_STATEMENT",
")",
"if",
"self",
".",
"_program_code",
".",
"peek",
"(",
")",
"==",
"b'\"'",
":",
"if",
"word",
"==",
"b''",
":",
"# nothing before the quotes, so this is a quoted string literal",
"# string payload starts after quote",
"address",
"=",
"self",
".",
"_program_code",
".",
"tell_address",
"(",
")",
"+",
"1",
"word",
"=",
"self",
".",
"_program_code",
".",
"read_string",
"(",
")",
".",
"strip",
"(",
"b'\"'",
")",
"else",
":",
"# complete unquoted string literal",
"word",
"+=",
"self",
".",
"_program_code",
".",
"read_string",
"(",
")",
"if",
"(",
"self",
".",
"_program_code",
".",
"skip_blank",
"(",
")",
"not",
"in",
"(",
"tk",
".",
"END_STATEMENT",
"+",
"(",
"b','",
",",
")",
")",
")",
":",
"raise",
"error",
".",
"BASICError",
"(",
"error",
".",
"STX",
")",
"else",
":",
"word",
"=",
"word",
".",
"strip",
"(",
"self",
".",
"_program_code",
".",
"blanks",
")",
"value",
"=",
"self",
".",
"_values",
".",
"from_str_at",
"(",
"word",
",",
"address",
")",
"else",
":",
"word",
"=",
"self",
".",
"_program_code",
".",
"read_number",
"(",
")",
"value",
"=",
"self",
".",
"_values",
".",
"from_repr",
"(",
"word",
",",
"allow_nonnum",
"=",
"False",
")",
"# anything after the number is a syntax error, but assignment has taken place)",
"if",
"(",
"self",
".",
"_program_code",
".",
"skip_blank",
"(",
")",
"not",
"in",
"(",
"tk",
".",
"END_STATEMENT",
"+",
"(",
"b','",
",",
")",
")",
")",
":",
"data_error",
"=",
"True",
"# restore to current program location",
"# to ensure any other errors in set_variable get the correct line number",
"data_pos",
"=",
"self",
".",
"_program_code",
".",
"tell",
"(",
")",
"self",
".",
"_program_code",
".",
"seek",
"(",
"current",
")",
"self",
".",
"_memory",
".",
"set_variable",
"(",
"name",
",",
"indices",
",",
"value",
"=",
"value",
")",
"if",
"data_error",
":",
"self",
".",
"_program_code",
".",
"seek",
"(",
"self",
".",
"data_pos",
")",
"raise",
"error",
".",
"BASICError",
"(",
"error",
".",
"STX",
")",
"else",
":",
"self",
".",
"data_pos",
"=",
"data_pos"
] |
https://github.com/robhagemans/pcbasic/blob/c3a043b46af66623a801e18a38175be077251ada/pcbasic/basic/interpreter.py#L521-L568
|
||
leapcode/bitmask_client
|
d2fe20df24fc6eaf146fa5ce1e847de6ab515688
|
pkg/pyinst/bitmask.py
|
python
|
log_lsb_release_info
|
(logger)
|
Attempt to log distribution info from the lsb_release utility
|
Attempt to log distribution info from the lsb_release utility
|
[
"Attempt",
"to",
"log",
"distribution",
"info",
"from",
"the",
"lsb_release",
"utility"
] |
def log_lsb_release_info(logger):
"""
Attempt to log distribution info from the lsb_release utility
"""
if commands.getoutput('which lsb_release'):
distro_info = commands.getoutput('lsb_release -a').split('\n')[-4:]
logger.info("LSB Release info:")
for line in distro_info:
logger.info(line)
|
[
"def",
"log_lsb_release_info",
"(",
"logger",
")",
":",
"if",
"commands",
".",
"getoutput",
"(",
"'which lsb_release'",
")",
":",
"distro_info",
"=",
"commands",
".",
"getoutput",
"(",
"'lsb_release -a'",
")",
".",
"split",
"(",
"'\\n'",
")",
"[",
"-",
"4",
":",
"]",
"logger",
".",
"info",
"(",
"\"LSB Release info:\"",
")",
"for",
"line",
"in",
"distro_info",
":",
"logger",
".",
"info",
"(",
"line",
")"
] |
https://github.com/leapcode/bitmask_client/blob/d2fe20df24fc6eaf146fa5ce1e847de6ab515688/pkg/pyinst/bitmask.py#L138-L146
|
||
smart-mobile-software/gitstack
|
d9fee8f414f202143eb6e620529e8e5539a2af56
|
python/Lib/calendar.py
|
python
|
TextCalendar.pryear
|
(self, theyear, w=0, l=0, c=6, m=3)
|
Print a year's calendar.
|
Print a year's calendar.
|
[
"Print",
"a",
"year",
"s",
"calendar",
"."
] |
def pryear(self, theyear, w=0, l=0, c=6, m=3):
"""Print a year's calendar."""
print self.formatyear(theyear, w, l, c, m)
|
[
"def",
"pryear",
"(",
"self",
",",
"theyear",
",",
"w",
"=",
"0",
",",
"l",
"=",
"0",
",",
"c",
"=",
"6",
",",
"m",
"=",
"3",
")",
":",
"print",
"self",
".",
"formatyear",
"(",
"theyear",
",",
"w",
",",
"l",
",",
"c",
",",
"m",
")"
] |
https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/calendar.py#L367-L369
|
||
scanny/python-pptx
|
71d1ca0b2b3b9178d64cdab565e8503a25a54e0b
|
pptx/opc/package.py
|
python
|
_Relationships._rels
|
(self)
|
return dict()
|
dict {rId: _Relationship} containing relationships of this collection.
|
dict {rId: _Relationship} containing relationships of this collection.
|
[
"dict",
"{",
"rId",
":",
"_Relationship",
"}",
"containing",
"relationships",
"of",
"this",
"collection",
"."
] |
def _rels(self):
"""dict {rId: _Relationship} containing relationships of this collection."""
return dict()
|
[
"def",
"_rels",
"(",
"self",
")",
":",
"return",
"dict",
"(",
")"
] |
https://github.com/scanny/python-pptx/blob/71d1ca0b2b3b9178d64cdab565e8503a25a54e0b/pptx/opc/package.py#L643-L645
|
|
karanchahal/distiller
|
a17ec06cbeafcdd2aea19d7c7663033c951392f5
|
models/wide_resnet/wide_resnet_ab.py
|
python
|
BasicBlock.forward
|
(self, x)
|
return torch.add(x if self.equalInOut else self.convShortcut(x), out)
|
[] |
def forward(self, x):
if not self.equalInOut:
x = self.relu1(self.bn1(x))
else:
out = self.relu1(self.bn1(x))
out = self.relu2(self.bn2(self.conv1(out if self.equalInOut else x)))
if self.droprate > 0:
out = F.dropout(out, p=self.droprate, training=self.training)
out = self.conv2(out)
return torch.add(x if self.equalInOut else self.convShortcut(x), out)
|
[
"def",
"forward",
"(",
"self",
",",
"x",
")",
":",
"if",
"not",
"self",
".",
"equalInOut",
":",
"x",
"=",
"self",
".",
"relu1",
"(",
"self",
".",
"bn1",
"(",
"x",
")",
")",
"else",
":",
"out",
"=",
"self",
".",
"relu1",
"(",
"self",
".",
"bn1",
"(",
"x",
")",
")",
"out",
"=",
"self",
".",
"relu2",
"(",
"self",
".",
"bn2",
"(",
"self",
".",
"conv1",
"(",
"out",
"if",
"self",
".",
"equalInOut",
"else",
"x",
")",
")",
")",
"if",
"self",
".",
"droprate",
">",
"0",
":",
"out",
"=",
"F",
".",
"dropout",
"(",
"out",
",",
"p",
"=",
"self",
".",
"droprate",
",",
"training",
"=",
"self",
".",
"training",
")",
"out",
"=",
"self",
".",
"conv2",
"(",
"out",
")",
"return",
"torch",
".",
"add",
"(",
"x",
"if",
"self",
".",
"equalInOut",
"else",
"self",
".",
"convShortcut",
"(",
"x",
")",
",",
"out",
")"
] |
https://github.com/karanchahal/distiller/blob/a17ec06cbeafcdd2aea19d7c7663033c951392f5/models/wide_resnet/wide_resnet_ab.py#L24-L33
|
|||
pyansys/pymapdl
|
c07291fc062b359abf0e92b95a92d753a95ef3d7
|
ansys/mapdl/core/mapdl_geometry.py
|
python
|
Geometry.anum
|
(self)
|
return self._mapdl.get_array("AREA", item1="ALIST").astype(np.int32)
|
Array of area numbers.
Examples
--------
>>> mapdl.block(0, 1, 0, 1, 0, 1)
>>> mapdl.anum
array([1, 2, 3, 4, 5, 6], dtype=int32)
|
Array of area numbers.
Examples
--------
>>> mapdl.block(0, 1, 0, 1, 0, 1)
>>> mapdl.anum
array([1, 2, 3, 4, 5, 6], dtype=int32)
|
[
"Array",
"of",
"area",
"numbers",
".",
"Examples",
"--------",
">>>",
"mapdl",
".",
"block",
"(",
"0",
"1",
"0",
"1",
"0",
"1",
")",
">>>",
"mapdl",
".",
"anum",
"array",
"(",
"[",
"1",
"2",
"3",
"4",
"5",
"6",
"]",
"dtype",
"=",
"int32",
")"
] |
def anum(self):
"""Array of area numbers.
Examples
--------
>>> mapdl.block(0, 1, 0, 1, 0, 1)
>>> mapdl.anum
array([1, 2, 3, 4, 5, 6], dtype=int32)
"""
return self._mapdl.get_array("AREA", item1="ALIST").astype(np.int32)
|
[
"def",
"anum",
"(",
"self",
")",
":",
"return",
"self",
".",
"_mapdl",
".",
"get_array",
"(",
"\"AREA\"",
",",
"item1",
"=",
"\"ALIST\"",
")",
".",
"astype",
"(",
"np",
".",
"int32",
")"
] |
https://github.com/pyansys/pymapdl/blob/c07291fc062b359abf0e92b95a92d753a95ef3d7/ansys/mapdl/core/mapdl_geometry.py#L405-L413
|
|
oracle/graalpython
|
577e02da9755d916056184ec441c26e00b70145c
|
graalpython/lib-python/3/distutils/command/bdist.py
|
python
|
bdist.finalize_options
|
(self)
|
[] |
def finalize_options(self):
# have to finalize 'plat_name' before 'bdist_base'
if self.plat_name is None:
if self.skip_build:
self.plat_name = get_platform()
else:
self.plat_name = self.get_finalized_command('build').plat_name
# 'bdist_base' -- parent of per-built-distribution-format
# temporary directories (eg. we'll probably have
# "build/bdist.<plat>/dumb", "build/bdist.<plat>/rpm", etc.)
if self.bdist_base is None:
build_base = self.get_finalized_command('build').build_base
self.bdist_base = os.path.join(build_base,
'bdist.' + self.plat_name)
self.ensure_string_list('formats')
if self.formats is None:
try:
self.formats = [self.default_format[os.name]]
except KeyError:
raise DistutilsPlatformError(
"don't know how to create built distributions "
"on platform %s" % os.name)
if self.dist_dir is None:
self.dist_dir = "dist"
|
[
"def",
"finalize_options",
"(",
"self",
")",
":",
"# have to finalize 'plat_name' before 'bdist_base'",
"if",
"self",
".",
"plat_name",
"is",
"None",
":",
"if",
"self",
".",
"skip_build",
":",
"self",
".",
"plat_name",
"=",
"get_platform",
"(",
")",
"else",
":",
"self",
".",
"plat_name",
"=",
"self",
".",
"get_finalized_command",
"(",
"'build'",
")",
".",
"plat_name",
"# 'bdist_base' -- parent of per-built-distribution-format",
"# temporary directories (eg. we'll probably have",
"# \"build/bdist.<plat>/dumb\", \"build/bdist.<plat>/rpm\", etc.)",
"if",
"self",
".",
"bdist_base",
"is",
"None",
":",
"build_base",
"=",
"self",
".",
"get_finalized_command",
"(",
"'build'",
")",
".",
"build_base",
"self",
".",
"bdist_base",
"=",
"os",
".",
"path",
".",
"join",
"(",
"build_base",
",",
"'bdist.'",
"+",
"self",
".",
"plat_name",
")",
"self",
".",
"ensure_string_list",
"(",
"'formats'",
")",
"if",
"self",
".",
"formats",
"is",
"None",
":",
"try",
":",
"self",
".",
"formats",
"=",
"[",
"self",
".",
"default_format",
"[",
"os",
".",
"name",
"]",
"]",
"except",
"KeyError",
":",
"raise",
"DistutilsPlatformError",
"(",
"\"don't know how to create built distributions \"",
"\"on platform %s\"",
"%",
"os",
".",
"name",
")",
"if",
"self",
".",
"dist_dir",
"is",
"None",
":",
"self",
".",
"dist_dir",
"=",
"\"dist\""
] |
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/distutils/command/bdist.py#L90-L116
|
||||
jerryli27/TwinGAN
|
4e5593445778dfb77af9f815b3f4fcafc35758dc
|
nets/pggan_utils.py
|
python
|
pggan_generator_arg_scope
|
(norm_type=None,
conditional_layer=None,
conditional_layer_var_scope_postfix='',
weights_init_stddev=0.02,
weight_decay=0.0,
is_training=False,
reuse=None)
|
return pggan_arg_scope(norm_type=norm_type, conditional_layer=conditional_layer,
norm_var_scope_postfix=conditional_layer_var_scope_postfix,
weights_init_stddev=weights_init_stddev, weight_decay=weight_decay,
is_training=is_training, reuse=reuse)
|
Wrapper around `pggan_arg_scope` for the generator/encoder. The difference is in the `norm_type`.
|
Wrapper around `pggan_arg_scope` for the generator/encoder. The difference is in the `norm_type`.
|
[
"Wrapper",
"around",
"pggan_arg_scope",
"for",
"the",
"generator",
"/",
"encoder",
".",
"The",
"difference",
"is",
"in",
"the",
"norm_type",
"."
] |
def pggan_generator_arg_scope(norm_type=None,
conditional_layer=None,
conditional_layer_var_scope_postfix='',
weights_init_stddev=0.02,
weight_decay=0.0,
is_training=False,
reuse=None):
"""Wrapper around `pggan_arg_scope` for the generator/encoder. The difference is in the `norm_type`."""
return pggan_arg_scope(norm_type=norm_type, conditional_layer=conditional_layer,
norm_var_scope_postfix=conditional_layer_var_scope_postfix,
weights_init_stddev=weights_init_stddev, weight_decay=weight_decay,
is_training=is_training, reuse=reuse)
|
[
"def",
"pggan_generator_arg_scope",
"(",
"norm_type",
"=",
"None",
",",
"conditional_layer",
"=",
"None",
",",
"conditional_layer_var_scope_postfix",
"=",
"''",
",",
"weights_init_stddev",
"=",
"0.02",
",",
"weight_decay",
"=",
"0.0",
",",
"is_training",
"=",
"False",
",",
"reuse",
"=",
"None",
")",
":",
"return",
"pggan_arg_scope",
"(",
"norm_type",
"=",
"norm_type",
",",
"conditional_layer",
"=",
"conditional_layer",
",",
"norm_var_scope_postfix",
"=",
"conditional_layer_var_scope_postfix",
",",
"weights_init_stddev",
"=",
"weights_init_stddev",
",",
"weight_decay",
"=",
"weight_decay",
",",
"is_training",
"=",
"is_training",
",",
"reuse",
"=",
"reuse",
")"
] |
https://github.com/jerryli27/TwinGAN/blob/4e5593445778dfb77af9f815b3f4fcafc35758dc/nets/pggan_utils.py#L102-L113
|
|
securesystemslab/zippy
|
ff0e84ac99442c2c55fe1d285332cfd4e185e089
|
zippy/benchmarks/src/benchmarks/sympy/sympy/stats/crv.py
|
python
|
_reduce_inequalities
|
(conditions, var, **kwargs)
|
[] |
def _reduce_inequalities(conditions, var, **kwargs):
try:
return reduce_rational_inequalities(conditions, var, **kwargs)
except PolynomialError:
raise ValueError("Reduction of condition failed %s\n" % conditions[0])
|
[
"def",
"_reduce_inequalities",
"(",
"conditions",
",",
"var",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"reduce_rational_inequalities",
"(",
"conditions",
",",
"var",
",",
"*",
"*",
"kwargs",
")",
"except",
"PolynomialError",
":",
"raise",
"ValueError",
"(",
"\"Reduction of condition failed %s\\n\"",
"%",
"conditions",
"[",
"0",
"]",
")"
] |
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/stats/crv.py#L404-L408
|
||||
securesystemslab/zippy
|
ff0e84ac99442c2c55fe1d285332cfd4e185e089
|
zippy/lib-python/3/tkinter/tix.py
|
python
|
OptionMenu.add_command
|
(self, name, cnf={}, **kw)
|
[] |
def add_command(self, name, cnf={}, **kw):
self.tk.call(self._w, 'add', 'command', name, *self._options(cnf, kw))
|
[
"def",
"add_command",
"(",
"self",
",",
"name",
",",
"cnf",
"=",
"{",
"}",
",",
"*",
"*",
"kw",
")",
":",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"'add'",
",",
"'command'",
",",
"name",
",",
"*",
"self",
".",
"_options",
"(",
"cnf",
",",
"kw",
")",
")"
] |
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/tkinter/tix.py#L1208-L1209
|
||||
apple/ccs-calendarserver
|
13c706b985fb728b9aab42dc0fef85aae21921c3
|
contrib/performance/stats.py
|
python
|
UniformDiscreteDistribution.__init__
|
(self, values, randomize=True)
|
[] |
def __init__(self, values, randomize=True):
self._values = values
self._randomize = randomize
self._refill()
|
[
"def",
"__init__",
"(",
"self",
",",
"values",
",",
"randomize",
"=",
"True",
")",
":",
"self",
".",
"_values",
"=",
"values",
"self",
".",
"_randomize",
"=",
"randomize",
"self",
".",
"_refill",
"(",
")"
] |
https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/contrib/performance/stats.py#L230-L233
|
||||
1040003585/WebScrapingWithPython
|
a770fa5b03894076c8c9539b1ffff34424ffc016
|
portia_examle/lib/python2.7/site-packages/pkg_resources/__init__.py
|
python
|
EntryPoint.parse
|
(cls, src, dist=None)
|
return cls(res['name'], res['module'], attrs, extras, dist)
|
Parse a single entry point from string `src`
Entry point syntax follows the form::
name = some.module:some.attr [extra1, extra2]
The entry name and module name are required, but the ``:attrs`` and
``[extras]`` parts are optional
|
Parse a single entry point from string `src`
|
[
"Parse",
"a",
"single",
"entry",
"point",
"from",
"string",
"src"
] |
def parse(cls, src, dist=None):
"""Parse a single entry point from string `src`
Entry point syntax follows the form::
name = some.module:some.attr [extra1, extra2]
The entry name and module name are required, but the ``:attrs`` and
``[extras]`` parts are optional
"""
m = cls.pattern.match(src)
if not m:
msg = "EntryPoint must be in 'name=module:attrs [extras]' format"
raise ValueError(msg, src)
res = m.groupdict()
extras = cls._parse_extras(res['extras'])
attrs = res['attr'].split('.') if res['attr'] else ()
return cls(res['name'], res['module'], attrs, extras, dist)
|
[
"def",
"parse",
"(",
"cls",
",",
"src",
",",
"dist",
"=",
"None",
")",
":",
"m",
"=",
"cls",
".",
"pattern",
".",
"match",
"(",
"src",
")",
"if",
"not",
"m",
":",
"msg",
"=",
"\"EntryPoint must be in 'name=module:attrs [extras]' format\"",
"raise",
"ValueError",
"(",
"msg",
",",
"src",
")",
"res",
"=",
"m",
".",
"groupdict",
"(",
")",
"extras",
"=",
"cls",
".",
"_parse_extras",
"(",
"res",
"[",
"'extras'",
"]",
")",
"attrs",
"=",
"res",
"[",
"'attr'",
"]",
".",
"split",
"(",
"'.'",
")",
"if",
"res",
"[",
"'attr'",
"]",
"else",
"(",
")",
"return",
"cls",
"(",
"res",
"[",
"'name'",
"]",
",",
"res",
"[",
"'module'",
"]",
",",
"attrs",
",",
"extras",
",",
"dist",
")"
] |
https://github.com/1040003585/WebScrapingWithPython/blob/a770fa5b03894076c8c9539b1ffff34424ffc016/portia_examle/lib/python2.7/site-packages/pkg_resources/__init__.py#L2320-L2337
|
|
nats-io/nats.py
|
49635bf58b1c888c66fa37569a9248b1a83a6c0a
|
nats/aio/client.py
|
python
|
Client.request
|
(
self,
subject: str,
payload: bytes = b'',
timeout: float = 0.5,
old_style: bool = False,
headers: dict = None,
)
|
return msg
|
Implements the request/response pattern via pub/sub
using a single wildcard subscription that handles
the responses.
|
Implements the request/response pattern via pub/sub
using a single wildcard subscription that handles
the responses.
|
[
"Implements",
"the",
"request",
"/",
"response",
"pattern",
"via",
"pub",
"/",
"sub",
"using",
"a",
"single",
"wildcard",
"subscription",
"that",
"handles",
"the",
"responses",
"."
] |
async def request(
self,
subject: str,
payload: bytes = b'',
timeout: float = 0.5,
old_style: bool = False,
headers: dict = None,
) -> Msg:
"""
Implements the request/response pattern via pub/sub
using a single wildcard subscription that handles
the responses.
"""
if old_style:
# FIXME: Support headers in old style requests.
return await self._request_old_style(
subject, payload, timeout=timeout
)
else:
msg = await self._request_new_style(
subject, payload, timeout=timeout, headers=headers
)
if msg.headers and msg.headers.get(STATUS_HDR) == NO_RESPONDERS_STATUS:
raise NoRespondersError
return msg
|
[
"async",
"def",
"request",
"(",
"self",
",",
"subject",
":",
"str",
",",
"payload",
":",
"bytes",
"=",
"b''",
",",
"timeout",
":",
"float",
"=",
"0.5",
",",
"old_style",
":",
"bool",
"=",
"False",
",",
"headers",
":",
"dict",
"=",
"None",
",",
")",
"->",
"Msg",
":",
"if",
"old_style",
":",
"# FIXME: Support headers in old style requests.",
"return",
"await",
"self",
".",
"_request_old_style",
"(",
"subject",
",",
"payload",
",",
"timeout",
"=",
"timeout",
")",
"else",
":",
"msg",
"=",
"await",
"self",
".",
"_request_new_style",
"(",
"subject",
",",
"payload",
",",
"timeout",
"=",
"timeout",
",",
"headers",
"=",
"headers",
")",
"if",
"msg",
".",
"headers",
"and",
"msg",
".",
"headers",
".",
"get",
"(",
"STATUS_HDR",
")",
"==",
"NO_RESPONDERS_STATUS",
":",
"raise",
"NoRespondersError",
"return",
"msg"
] |
https://github.com/nats-io/nats.py/blob/49635bf58b1c888c66fa37569a9248b1a83a6c0a/nats/aio/client.py#L805-L830
|
|
rbarrois/python-semanticversion
|
81a4730778fba6b5c76242d3c8da6dace7e2ec0a
|
semantic_version/base.py
|
python
|
Clause.__ne__
|
(self, other)
|
return not self == other
|
[] |
def __ne__(self, other):
return not self == other
|
[
"def",
"__ne__",
"(",
"self",
",",
"other",
")",
":",
"return",
"not",
"self",
"==",
"other"
] |
https://github.com/rbarrois/python-semanticversion/blob/81a4730778fba6b5c76242d3c8da6dace7e2ec0a/semantic_version/base.py#L697-L698
|
|||
DataDog/integrations-core
|
934674b29d94b70ccc008f76ea172d0cdae05e1e
|
tokumx/datadog_checks/tokumx/vendor/pymongo/periodic_executor.py
|
python
|
_register_executor
|
(executor)
|
[] |
def _register_executor(executor):
ref = weakref.ref(executor, _on_executor_deleted)
_EXECUTORS.add(ref)
|
[
"def",
"_register_executor",
"(",
"executor",
")",
":",
"ref",
"=",
"weakref",
".",
"ref",
"(",
"executor",
",",
"_on_executor_deleted",
")",
"_EXECUTORS",
".",
"add",
"(",
"ref",
")"
] |
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/tokumx/datadog_checks/tokumx/vendor/pymongo/periodic_executor.py#L144-L146
|
||||
hupili/snsapi
|
129529b89f38cbee253a23e5ed31dae2a0ea4254
|
snsapi/plugin_trial/emails.py
|
python
|
Email.update
|
(self, text, title = None)
|
return self._send_to_all_buddy(title, msg)
|
:title:
The unique field of email. Other platforms do not use it. If not supplied,
we'll format a title according to SNSAPI convention.
|
:title:
The unique field of email. Other platforms do not use it. If not supplied,
we'll format a title according to SNSAPI convention.
|
[
":",
"title",
":",
"The",
"unique",
"field",
"of",
"email",
".",
"Other",
"platforms",
"do",
"not",
"use",
"it",
".",
"If",
"not",
"supplied",
"we",
"ll",
"format",
"a",
"title",
"according",
"to",
"SNSAPI",
"convention",
"."
] |
def update(self, text, title = None):
'''
:title:
The unique field of email. Other platforms do not use it. If not supplied,
we'll format a title according to SNSAPI convention.
'''
msg = MIMEText(text, _charset = 'utf-8')
if not title:
#title = '[snsapi][status][from:%s][timestamp:%s]' % (self.jsonconf['address'], str(self.time()))
title = '[snsapi][status]%s' % (text[0:10])
return self._send_to_all_buddy(title, msg)
|
[
"def",
"update",
"(",
"self",
",",
"text",
",",
"title",
"=",
"None",
")",
":",
"msg",
"=",
"MIMEText",
"(",
"text",
",",
"_charset",
"=",
"'utf-8'",
")",
"if",
"not",
"title",
":",
"#title = '[snsapi][status][from:%s][timestamp:%s]' % (self.jsonconf['address'], str(self.time()))",
"title",
"=",
"'[snsapi][status]%s'",
"%",
"(",
"text",
"[",
"0",
":",
"10",
"]",
")",
"return",
"self",
".",
"_send_to_all_buddy",
"(",
"title",
",",
"msg",
")"
] |
https://github.com/hupili/snsapi/blob/129529b89f38cbee253a23e5ed31dae2a0ea4254/snsapi/plugin_trial/emails.py#L461-L471
|
|
openshift/openshift-tools
|
1188778e728a6e4781acf728123e5b356380fe6f
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/src/class/oc_configmap.py
|
python
|
OCConfigMap.needs_update
|
(self)
|
return not Utils.check_def_equal(self.inc_configmap, self.configmap, debug=self.verbose)
|
compare the current configmap with the proposed and return if they are equal
|
compare the current configmap with the proposed and return if they are equal
|
[
"compare",
"the",
"current",
"configmap",
"with",
"the",
"proposed",
"and",
"return",
"if",
"they",
"are",
"equal"
] |
def needs_update(self):
'''compare the current configmap with the proposed and return if they are equal'''
return not Utils.check_def_equal(self.inc_configmap, self.configmap, debug=self.verbose)
|
[
"def",
"needs_update",
"(",
"self",
")",
":",
"return",
"not",
"Utils",
".",
"check_def_equal",
"(",
"self",
".",
"inc_configmap",
",",
"self",
".",
"configmap",
",",
"debug",
"=",
"self",
".",
"verbose",
")"
] |
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/src/class/oc_configmap.py#L99-L101
|
|
astropy/photutils
|
3caa48e4e4d139976ed7457dc41583fb2c56ba20
|
photutils/segmentation/catalog.py
|
python
|
SourceCatalog._slices_iter
|
(self)
|
return _slices
|
A tuple of slice objects defining the minimal bounding box of
the source, always as an iterable.
|
A tuple of slice objects defining the minimal bounding box of
the source, always as an iterable.
|
[
"A",
"tuple",
"of",
"slice",
"objects",
"defining",
"the",
"minimal",
"bounding",
"box",
"of",
"the",
"source",
"always",
"as",
"an",
"iterable",
"."
] |
def _slices_iter(self):
"""
A tuple of slice objects defining the minimal bounding box of
the source, always as an iterable.
"""
_slices = self.slices
if self.isscalar:
_slices = (_slices,)
return _slices
|
[
"def",
"_slices_iter",
"(",
"self",
")",
":",
"_slices",
"=",
"self",
".",
"slices",
"if",
"self",
".",
"isscalar",
":",
"_slices",
"=",
"(",
"_slices",
",",
")",
"return",
"_slices"
] |
https://github.com/astropy/photutils/blob/3caa48e4e4d139976ed7457dc41583fb2c56ba20/photutils/segmentation/catalog.py#L847-L855
|
|
wxWidgets/Phoenix
|
b2199e299a6ca6d866aa6f3d0888499136ead9d6
|
wx/lib/agw/flatnotebook.py
|
python
|
FlatNotebook.SetActiveTabTextColour
|
(self, textColour)
|
Sets the text colour for the active tab.
:param `textColour`: a valid :class:`wx.Colour` object or any typemap supported by wxWidgets/wxPython
to generate a colour (i.e., a hex string, a colour name, a 3 or 4 integer tuple).
|
Sets the text colour for the active tab.
|
[
"Sets",
"the",
"text",
"colour",
"for",
"the",
"active",
"tab",
"."
] |
def SetActiveTabTextColour(self, textColour):
"""
Sets the text colour for the active tab.
:param `textColour`: a valid :class:`wx.Colour` object or any typemap supported by wxWidgets/wxPython
to generate a colour (i.e., a hex string, a colour name, a 3 or 4 integer tuple).
"""
self._pages._activeTextColour = FormatColour(textColour)
|
[
"def",
"SetActiveTabTextColour",
"(",
"self",
",",
"textColour",
")",
":",
"self",
".",
"_pages",
".",
"_activeTextColour",
"=",
"FormatColour",
"(",
"textColour",
")"
] |
https://github.com/wxWidgets/Phoenix/blob/b2199e299a6ca6d866aa6f3d0888499136ead9d6/wx/lib/agw/flatnotebook.py#L4144-L4152
|
||
facebookresearch/ParlAI
|
e4d59c30eef44f1f67105961b82a83fd28d7d78b
|
parlai/utils/fp16.py
|
python
|
SafeFP16Optimizer.clip_main_grads
|
(self, max_norm)
|
return grad_norm
|
Clips gradient norm and updates dynamic loss scaler.
|
Clips gradient norm and updates dynamic loss scaler.
|
[
"Clips",
"gradient",
"norm",
"and",
"updates",
"dynamic",
"loss",
"scaler",
"."
] |
def clip_main_grads(self, max_norm):
"""
Clips gradient norm and updates dynamic loss scaler.
"""
self._sync_fp16_grads_to_fp32()
grad_norm = clip_grad_norm(
self.fp32_params, max_norm, sync=self._aggregate_gnorms
)
# detect overflow and adjust loss scale
if self.scaler is not None:
overflow = has_overflow(grad_norm)
prev_scale = self.scaler.loss_scale
self.scaler.update_scale(overflow)
if overflow:
self.zero_grad()
if self.scaler.loss_scale <= self.min_loss_scale:
# Use FloatingPointError as an uncommon error that parent
# functions can safely catch to stop training.
self.scaler.loss_scale = prev_scale
raise FloatingPointError(
(
'Minimum loss scale reached ({}). Your loss is probably exploding. '
'Try lowering the learning rate, using gradient clipping or '
'increasing the batch size.'
).format(self.min_loss_scale)
)
logging.info(
f'Overflow: setting loss scale to {self.scaler.loss_scale}'
)
return grad_norm
|
[
"def",
"clip_main_grads",
"(",
"self",
",",
"max_norm",
")",
":",
"self",
".",
"_sync_fp16_grads_to_fp32",
"(",
")",
"grad_norm",
"=",
"clip_grad_norm",
"(",
"self",
".",
"fp32_params",
",",
"max_norm",
",",
"sync",
"=",
"self",
".",
"_aggregate_gnorms",
")",
"# detect overflow and adjust loss scale",
"if",
"self",
".",
"scaler",
"is",
"not",
"None",
":",
"overflow",
"=",
"has_overflow",
"(",
"grad_norm",
")",
"prev_scale",
"=",
"self",
".",
"scaler",
".",
"loss_scale",
"self",
".",
"scaler",
".",
"update_scale",
"(",
"overflow",
")",
"if",
"overflow",
":",
"self",
".",
"zero_grad",
"(",
")",
"if",
"self",
".",
"scaler",
".",
"loss_scale",
"<=",
"self",
".",
"min_loss_scale",
":",
"# Use FloatingPointError as an uncommon error that parent",
"# functions can safely catch to stop training.",
"self",
".",
"scaler",
".",
"loss_scale",
"=",
"prev_scale",
"raise",
"FloatingPointError",
"(",
"(",
"'Minimum loss scale reached ({}). Your loss is probably exploding. '",
"'Try lowering the learning rate, using gradient clipping or '",
"'increasing the batch size.'",
")",
".",
"format",
"(",
"self",
".",
"min_loss_scale",
")",
")",
"logging",
".",
"info",
"(",
"f'Overflow: setting loss scale to {self.scaler.loss_scale}'",
")",
"return",
"grad_norm"
] |
https://github.com/facebookresearch/ParlAI/blob/e4d59c30eef44f1f67105961b82a83fd28d7d78b/parlai/utils/fp16.py#L230-L261
|
|
robotlearn/pyrobolearn
|
9cd7c060723fda7d2779fa255ac998c2c82b8436
|
pyrobolearn/tools/interfaces/controllers/playstation.py
|
python
|
PSControllerInterface.set_vibration
|
(self, time_msec)
|
Set the vibration for both motors
|
Set the vibration for both motors
|
[
"Set",
"the",
"vibration",
"for",
"both",
"motors"
] |
def set_vibration(self, time_msec):
"""Set the vibration for both motors"""
self.gamepad.set_vibration(1, 1, time_msec)
# display info
if self.verbose:
print("Set vibration to both motors for {} msec".format(time_msec))
|
[
"def",
"set_vibration",
"(",
"self",
",",
"time_msec",
")",
":",
"self",
".",
"gamepad",
".",
"set_vibration",
"(",
"1",
",",
"1",
",",
"time_msec",
")",
"# display info",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"\"Set vibration to both motors for {} msec\"",
".",
"format",
"(",
"time_msec",
")",
")"
] |
https://github.com/robotlearn/pyrobolearn/blob/9cd7c060723fda7d2779fa255ac998c2c82b8436/pyrobolearn/tools/interfaces/controllers/playstation.py#L324-L329
|
||
sympy/sympy
|
d822fcba181155b85ff2b29fe525adbafb22b448
|
sympy/utilities/iterables.py
|
python
|
generate_involutions
|
(n)
|
Generates involutions.
An involution is a permutation that when multiplied
by itself equals the identity permutation. In this
implementation the involutions are generated using
Fixed Points.
Alternatively, an involution can be considered as
a permutation that does not contain any cycles with
a length that is greater than two.
Examples
========
>>> from sympy.utilities.iterables import generate_involutions
>>> list(generate_involutions(3))
[(0, 1, 2), (0, 2, 1), (1, 0, 2), (2, 1, 0)]
>>> len(list(generate_involutions(4)))
10
References
==========
.. [1] http://mathworld.wolfram.com/PermutationInvolution.html
|
Generates involutions.
|
[
"Generates",
"involutions",
"."
] |
def generate_involutions(n):
"""
Generates involutions.
An involution is a permutation that when multiplied
by itself equals the identity permutation. In this
implementation the involutions are generated using
Fixed Points.
Alternatively, an involution can be considered as
a permutation that does not contain any cycles with
a length that is greater than two.
Examples
========
>>> from sympy.utilities.iterables import generate_involutions
>>> list(generate_involutions(3))
[(0, 1, 2), (0, 2, 1), (1, 0, 2), (2, 1, 0)]
>>> len(list(generate_involutions(4)))
10
References
==========
.. [1] http://mathworld.wolfram.com/PermutationInvolution.html
"""
idx = list(range(n))
for p in permutations(idx):
for i in idx:
if p[p[i]] != i:
break
else:
yield p
|
[
"def",
"generate_involutions",
"(",
"n",
")",
":",
"idx",
"=",
"list",
"(",
"range",
"(",
"n",
")",
")",
"for",
"p",
"in",
"permutations",
"(",
"idx",
")",
":",
"for",
"i",
"in",
"idx",
":",
"if",
"p",
"[",
"p",
"[",
"i",
"]",
"]",
"!=",
"i",
":",
"break",
"else",
":",
"yield",
"p"
] |
https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/utilities/iterables.py#L2134-L2168
|
||
Tencent/bk-bcs-saas
|
2b437bf2f5fd5ce2078f7787c3a12df609f7679d
|
bcs-app/backend/uniapps/application/base_views.py
|
python
|
BaseAPI.get_namespaces
|
(self, request, project_id)
|
return True, resp["data"]
|
获取namespace
|
获取namespace
|
[
"获取namespace"
] |
def get_namespaces(self, request, project_id):
"""获取namespace"""
resp = paas_cc.get_namespace_list(request.user.token.access_token, project_id, limit=10000, offset=0)
if resp.get("code") != ErrorCode.NoError:
return False, APIResponse({"code": resp.get("code", DEFAULT_ERROR_CODE), "message": resp.get("message")})
return True, resp["data"]
|
[
"def",
"get_namespaces",
"(",
"self",
",",
"request",
",",
"project_id",
")",
":",
"resp",
"=",
"paas_cc",
".",
"get_namespace_list",
"(",
"request",
".",
"user",
".",
"token",
".",
"access_token",
",",
"project_id",
",",
"limit",
"=",
"10000",
",",
"offset",
"=",
"0",
")",
"if",
"resp",
".",
"get",
"(",
"\"code\"",
")",
"!=",
"ErrorCode",
".",
"NoError",
":",
"return",
"False",
",",
"APIResponse",
"(",
"{",
"\"code\"",
":",
"resp",
".",
"get",
"(",
"\"code\"",
",",
"DEFAULT_ERROR_CODE",
")",
",",
"\"message\"",
":",
"resp",
".",
"get",
"(",
"\"message\"",
")",
"}",
")",
"return",
"True",
",",
"resp",
"[",
"\"data\"",
"]"
] |
https://github.com/Tencent/bk-bcs-saas/blob/2b437bf2f5fd5ce2078f7787c3a12df609f7679d/bcs-app/backend/uniapps/application/base_views.py#L135-L140
|
|
gpodder/mygpo
|
7a028ad621d05d4ca0d58fd22fb92656c8835e43
|
mygpo/podcasts/models.py
|
python
|
Podcast.next_update
|
(self)
|
return self.last_update + interval
|
[] |
def next_update(self):
if not self.last_update:
return None
interval = timedelta(hours=self.update_interval) * self.update_interval_factor
return self.last_update + interval
|
[
"def",
"next_update",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"last_update",
":",
"return",
"None",
"interval",
"=",
"timedelta",
"(",
"hours",
"=",
"self",
".",
"update_interval",
")",
"*",
"self",
".",
"update_interval_factor",
"return",
"self",
".",
"last_update",
"+",
"interval"
] |
https://github.com/gpodder/mygpo/blob/7a028ad621d05d4ca0d58fd22fb92656c8835e43/mygpo/podcasts/models.py#L704-L709
|
|||
openstack/tempest
|
fe0ac89a5a1c43fa908a76759cd99eea3b1f9853
|
tempest/lib/services/network/ports_client.py
|
python
|
PortsClient.show_port
|
(self, port_id, **fields)
|
return self.show_resource(uri, **fields)
|
Shows details for a port.
For a full list of available parameters, please refer to the official
API reference:
https://docs.openstack.org/api-ref/network/v2/index.html#show-port-details
|
Shows details for a port.
|
[
"Shows",
"details",
"for",
"a",
"port",
"."
] |
def show_port(self, port_id, **fields):
"""Shows details for a port.
For a full list of available parameters, please refer to the official
API reference:
https://docs.openstack.org/api-ref/network/v2/index.html#show-port-details
"""
uri = '/ports/%s' % port_id
return self.show_resource(uri, **fields)
|
[
"def",
"show_port",
"(",
"self",
",",
"port_id",
",",
"*",
"*",
"fields",
")",
":",
"uri",
"=",
"'/ports/%s'",
"%",
"port_id",
"return",
"self",
".",
"show_resource",
"(",
"uri",
",",
"*",
"*",
"fields",
")"
] |
https://github.com/openstack/tempest/blob/fe0ac89a5a1c43fa908a76759cd99eea3b1f9853/tempest/lib/services/network/ports_client.py#L41-L49
|
|
Gandi/gandi.cli
|
5de0605126247e986f8288b467a52710a78e1794
|
gandi/cli/commands/vm.py
|
python
|
migrate
|
(gandi, resource, force, background, finalize)
|
return oper
|
Migrate a virtual machine to another datacenter.
|
Migrate a virtual machine to another datacenter.
|
[
"Migrate",
"a",
"virtual",
"machine",
"to",
"another",
"datacenter",
"."
] |
def migrate(gandi, resource, force, background, finalize):
""" Migrate a virtual machine to another datacenter. """
if not gandi.iaas.check_can_migrate(resource):
return
if not force:
proceed = click.confirm('Are you sure you want to migrate VM %s ?'
% resource)
if not proceed:
return
if finalize:
gandi.iaas.need_finalize(resource)
output_keys = ['id', 'type', 'step']
oper = gandi.iaas.migrate(resource, background, finalize=finalize)
if background:
output_generic(gandi, oper, output_keys)
return oper
|
[
"def",
"migrate",
"(",
"gandi",
",",
"resource",
",",
"force",
",",
"background",
",",
"finalize",
")",
":",
"if",
"not",
"gandi",
".",
"iaas",
".",
"check_can_migrate",
"(",
"resource",
")",
":",
"return",
"if",
"not",
"force",
":",
"proceed",
"=",
"click",
".",
"confirm",
"(",
"'Are you sure you want to migrate VM %s ?'",
"%",
"resource",
")",
"if",
"not",
"proceed",
":",
"return",
"if",
"finalize",
":",
"gandi",
".",
"iaas",
".",
"need_finalize",
"(",
"resource",
")",
"output_keys",
"=",
"[",
"'id'",
",",
"'type'",
",",
"'step'",
"]",
"oper",
"=",
"gandi",
".",
"iaas",
".",
"migrate",
"(",
"resource",
",",
"background",
",",
"finalize",
"=",
"finalize",
")",
"if",
"background",
":",
"output_generic",
"(",
"gandi",
",",
"oper",
",",
"output_keys",
")",
"return",
"oper"
] |
https://github.com/Gandi/gandi.cli/blob/5de0605126247e986f8288b467a52710a78e1794/gandi/cli/commands/vm.py#L525-L544
|
|
saleor/saleor
|
2221bdf61b037c660ffc2d1efa484d8efe8172f5
|
saleor/graphql/account/mutations/permission_group.py
|
python
|
PermissionGroupUpdate.check_if_removing_user_last_group
|
(
cls, requestor: "User", errors: dict, cleaned_input: dict
)
|
Ensure user doesn't remove user's last group.
|
Ensure user doesn't remove user's last group.
|
[
"Ensure",
"user",
"doesn",
"t",
"remove",
"user",
"s",
"last",
"group",
"."
] |
def check_if_removing_user_last_group(
cls, requestor: "User", errors: dict, cleaned_input: dict
):
"""Ensure user doesn't remove user's last group."""
remove_users = cleaned_input["remove_users"]
if requestor in remove_users and requestor.groups.count() == 1:
# add error
error_msg = "You cannot remove yourself from your last group."
code = PermissionGroupErrorCode.CANNOT_REMOVE_FROM_LAST_GROUP.value
params = {"users": [graphene.Node.to_global_id("User", requestor.pk)]}
cls.update_errors(errors, error_msg, "remove_users", code, params)
|
[
"def",
"check_if_removing_user_last_group",
"(",
"cls",
",",
"requestor",
":",
"\"User\"",
",",
"errors",
":",
"dict",
",",
"cleaned_input",
":",
"dict",
")",
":",
"remove_users",
"=",
"cleaned_input",
"[",
"\"remove_users\"",
"]",
"if",
"requestor",
"in",
"remove_users",
"and",
"requestor",
".",
"groups",
".",
"count",
"(",
")",
"==",
"1",
":",
"# add error",
"error_msg",
"=",
"\"You cannot remove yourself from your last group.\"",
"code",
"=",
"PermissionGroupErrorCode",
".",
"CANNOT_REMOVE_FROM_LAST_GROUP",
".",
"value",
"params",
"=",
"{",
"\"users\"",
":",
"[",
"graphene",
".",
"Node",
".",
"to_global_id",
"(",
"\"User\"",
",",
"requestor",
".",
"pk",
")",
"]",
"}",
"cls",
".",
"update_errors",
"(",
"errors",
",",
"error_msg",
",",
"\"remove_users\"",
",",
"code",
",",
"params",
")"
] |
https://github.com/saleor/saleor/blob/2221bdf61b037c660ffc2d1efa484d8efe8172f5/saleor/graphql/account/mutations/permission_group.py#L340-L350
|
||
nucleic/enaml
|
65c2a2a2d765e88f2e1103046680571894bb41ed
|
enaml/core/parser/parser38.py
|
python
|
Python38EnamlParser.p_return_stmt2
|
(self, p)
|
return_stmt : RETURN testlist_star_expr
|
return_stmt : RETURN testlist_star_expr
|
[
"return_stmt",
":",
"RETURN",
"testlist_star_expr"
] |
def p_return_stmt2(self, p):
''' return_stmt : RETURN testlist_star_expr '''
value = ast_for_testlist(p[2])
ret = ast.Return()
ret.value = value
p[0] = ret
|
[
"def",
"p_return_stmt2",
"(",
"self",
",",
"p",
")",
":",
"value",
"=",
"ast_for_testlist",
"(",
"p",
"[",
"2",
"]",
")",
"ret",
"=",
"ast",
".",
"Return",
"(",
")",
"ret",
".",
"value",
"=",
"value",
"p",
"[",
"0",
"]",
"=",
"ret"
] |
https://github.com/nucleic/enaml/blob/65c2a2a2d765e88f2e1103046680571894bb41ed/enaml/core/parser/parser38.py#L44-L49
|
||
lovelylain/pyctp
|
fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d
|
example/ctp/futures/__init__.py
|
python
|
TraderApi.OnRtnRepealFromFutureToBankByBank
|
(self, pRspRepeal)
|
银行发起冲正期货转银行通知
|
银行发起冲正期货转银行通知
|
[
"银行发起冲正期货转银行通知"
] |
def OnRtnRepealFromFutureToBankByBank(self, pRspRepeal):
"""银行发起冲正期货转银行通知"""
|
[
"def",
"OnRtnRepealFromFutureToBankByBank",
"(",
"self",
",",
"pRspRepeal",
")",
":"
] |
https://github.com/lovelylain/pyctp/blob/fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d/example/ctp/futures/__init__.py#L773-L774
|
||
git-cola/git-cola
|
b48b8028e0c3baf47faf7b074b9773737358163d
|
cola/widgets/editremotes.py
|
python
|
restore_focus
|
(focus)
|
[] |
def restore_focus(focus):
if focus:
focus.setFocus(Qt.OtherFocusReason)
if hasattr(focus, 'selectAll'):
focus.selectAll()
|
[
"def",
"restore_focus",
"(",
"focus",
")",
":",
"if",
"focus",
":",
"focus",
".",
"setFocus",
"(",
"Qt",
".",
"OtherFocusReason",
")",
"if",
"hasattr",
"(",
"focus",
",",
"'selectAll'",
")",
":",
"focus",
".",
"selectAll",
"(",
")"
] |
https://github.com/git-cola/git-cola/blob/b48b8028e0c3baf47faf7b074b9773737358163d/cola/widgets/editremotes.py#L340-L344
|
||||
3DLIRIOUS/MeshLabXML
|
e19fdc911644474f74463aabba1e6860cfad818e
|
meshlabxml/create.py
|
python
|
tube_hires
|
(script, height=1.0, radius=None, radius1=None, radius2=None,
diameter=None, diameter1=None, diameter2=None, cir_segments=32,
rad_segments=1, height_segments=1, center=False,
simple_bottom=False, color=None)
|
return None
|
Create a cylinder with user defined number of segments
|
Create a cylinder with user defined number of segments
|
[
"Create",
"a",
"cylinder",
"with",
"user",
"defined",
"number",
"of",
"segments"
] |
def tube_hires(script, height=1.0, radius=None, radius1=None, radius2=None,
diameter=None, diameter1=None, diameter2=None, cir_segments=32,
rad_segments=1, height_segments=1, center=False,
simple_bottom=False, color=None):
"""Create a cylinder with user defined number of segments
"""
# TODO: add option to round the top of the cylinder, i.e. deform spherically
# TODO: add warnings if values are ignored, e.g. if you specify both radius
# and diameter.
if radius is not None and diameter is None:
if radius1 is None and diameter1 is None:
radius1 = radius
if radius2 is None and diameter2 is None:
radius2 = 0
if diameter is not None:
if radius1 is None and diameter1 is None:
radius1 = diameter / 2
if radius2 is None and diameter2 is None:
radius2 = 0
if diameter1 is not None:
radius1 = diameter1 / 2
if diameter2 is not None:
radius2 = diameter2 / 2
if radius1 is None:
radius1 = 1
if radius2 is None:
radius2 = 0
# Create top
annulus_hires(script,
radius1=radius1,
radius2=radius2,
cir_segments=cir_segments,
rad_segments=rad_segments)
transform.translate(script, [0, 0, height])
# Create bottom
if simple_bottom:
annulus(script,
radius1=radius1,
radius2=radius2,
cir_segments=cir_segments)
else:
layers.duplicate(script)
transform.translate(script, [0, 0, -height])
# Rotate to correct normals
transform.rotate(script, 'x', 180)
# Create outer tube
cylinder_open_hires(script, height, radius1,
cir_segments=cir_segments,
height_segments=height_segments)
# Create inner tube
if radius2 != 0:
cylinder_open_hires(script, height, radius2,
cir_segments=cir_segments,
height_segments=height_segments,
invert_normals=True)
# Join everything together
layers.join(script)
# Need some tolerance on merge_vert due to rounding errors
clean.merge_vert(script, threshold=0.00002)
if center:
transform.translate(script, [0, 0, -height / 2])
if color is not None:
vert_color.function(script, color=color)
return None
|
[
"def",
"tube_hires",
"(",
"script",
",",
"height",
"=",
"1.0",
",",
"radius",
"=",
"None",
",",
"radius1",
"=",
"None",
",",
"radius2",
"=",
"None",
",",
"diameter",
"=",
"None",
",",
"diameter1",
"=",
"None",
",",
"diameter2",
"=",
"None",
",",
"cir_segments",
"=",
"32",
",",
"rad_segments",
"=",
"1",
",",
"height_segments",
"=",
"1",
",",
"center",
"=",
"False",
",",
"simple_bottom",
"=",
"False",
",",
"color",
"=",
"None",
")",
":",
"# TODO: add option to round the top of the cylinder, i.e. deform spherically",
"# TODO: add warnings if values are ignored, e.g. if you specify both radius",
"# and diameter.",
"if",
"radius",
"is",
"not",
"None",
"and",
"diameter",
"is",
"None",
":",
"if",
"radius1",
"is",
"None",
"and",
"diameter1",
"is",
"None",
":",
"radius1",
"=",
"radius",
"if",
"radius2",
"is",
"None",
"and",
"diameter2",
"is",
"None",
":",
"radius2",
"=",
"0",
"if",
"diameter",
"is",
"not",
"None",
":",
"if",
"radius1",
"is",
"None",
"and",
"diameter1",
"is",
"None",
":",
"radius1",
"=",
"diameter",
"/",
"2",
"if",
"radius2",
"is",
"None",
"and",
"diameter2",
"is",
"None",
":",
"radius2",
"=",
"0",
"if",
"diameter1",
"is",
"not",
"None",
":",
"radius1",
"=",
"diameter1",
"/",
"2",
"if",
"diameter2",
"is",
"not",
"None",
":",
"radius2",
"=",
"diameter2",
"/",
"2",
"if",
"radius1",
"is",
"None",
":",
"radius1",
"=",
"1",
"if",
"radius2",
"is",
"None",
":",
"radius2",
"=",
"0",
"# Create top",
"annulus_hires",
"(",
"script",
",",
"radius1",
"=",
"radius1",
",",
"radius2",
"=",
"radius2",
",",
"cir_segments",
"=",
"cir_segments",
",",
"rad_segments",
"=",
"rad_segments",
")",
"transform",
".",
"translate",
"(",
"script",
",",
"[",
"0",
",",
"0",
",",
"height",
"]",
")",
"# Create bottom",
"if",
"simple_bottom",
":",
"annulus",
"(",
"script",
",",
"radius1",
"=",
"radius1",
",",
"radius2",
"=",
"radius2",
",",
"cir_segments",
"=",
"cir_segments",
")",
"else",
":",
"layers",
".",
"duplicate",
"(",
"script",
")",
"transform",
".",
"translate",
"(",
"script",
",",
"[",
"0",
",",
"0",
",",
"-",
"height",
"]",
")",
"# Rotate to correct normals",
"transform",
".",
"rotate",
"(",
"script",
",",
"'x'",
",",
"180",
")",
"# Create outer tube",
"cylinder_open_hires",
"(",
"script",
",",
"height",
",",
"radius1",
",",
"cir_segments",
"=",
"cir_segments",
",",
"height_segments",
"=",
"height_segments",
")",
"# Create inner tube",
"if",
"radius2",
"!=",
"0",
":",
"cylinder_open_hires",
"(",
"script",
",",
"height",
",",
"radius2",
",",
"cir_segments",
"=",
"cir_segments",
",",
"height_segments",
"=",
"height_segments",
",",
"invert_normals",
"=",
"True",
")",
"# Join everything together",
"layers",
".",
"join",
"(",
"script",
")",
"# Need some tolerance on merge_vert due to rounding errors",
"clean",
".",
"merge_vert",
"(",
"script",
",",
"threshold",
"=",
"0.00002",
")",
"if",
"center",
":",
"transform",
".",
"translate",
"(",
"script",
",",
"[",
"0",
",",
"0",
",",
"-",
"height",
"/",
"2",
"]",
")",
"if",
"color",
"is",
"not",
"None",
":",
"vert_color",
".",
"function",
"(",
"script",
",",
"color",
"=",
"color",
")",
"return",
"None"
] |
https://github.com/3DLIRIOUS/MeshLabXML/blob/e19fdc911644474f74463aabba1e6860cfad818e/meshlabxml/create.py#L688-L758
|
|
StanfordHCI/termite
|
f795be291a1598cb2ae1df1a598c989f369e9ce8
|
pipeline/compute_similarity.py
|
python
|
ComputeSimilarity.getSlidingWindowTokens
|
( self, tokens, sliding_window_size )
|
return allWindows
|
[] |
def getSlidingWindowTokens( self, tokens, sliding_window_size ):
allWindows = []
aIndex = 0 - sliding_window_size
bIndex = len(tokens) + sliding_window_size
for index in range( aIndex, bIndex ):
a = max( 0 , index - sliding_window_size )
b = min( len(tokens) , index + sliding_window_size )
allWindows.append( tokens[a:b] )
return allWindows
|
[
"def",
"getSlidingWindowTokens",
"(",
"self",
",",
"tokens",
",",
"sliding_window_size",
")",
":",
"allWindows",
"=",
"[",
"]",
"aIndex",
"=",
"0",
"-",
"sliding_window_size",
"bIndex",
"=",
"len",
"(",
"tokens",
")",
"+",
"sliding_window_size",
"for",
"index",
"in",
"range",
"(",
"aIndex",
",",
"bIndex",
")",
":",
"a",
"=",
"max",
"(",
"0",
",",
"index",
"-",
"sliding_window_size",
")",
"b",
"=",
"min",
"(",
"len",
"(",
"tokens",
")",
",",
"index",
"+",
"sliding_window_size",
")",
"allWindows",
".",
"append",
"(",
"tokens",
"[",
"a",
":",
"b",
"]",
")",
"return",
"allWindows"
] |
https://github.com/StanfordHCI/termite/blob/f795be291a1598cb2ae1df1a598c989f369e9ce8/pipeline/compute_similarity.py#L120-L128
|
|||
google-research/batch-ppo
|
3d09705977bae4e7c3eb20339a3b384d2a5531e4
|
agents/parts/memory.py
|
python
|
EpisodeMemory.replace
|
(self, episodes, length, rows=None)
|
Replace full episodes.
Args:
episodes: Tuple of transition quantities with batch and time dimensions.
length: Batch of sequence lengths.
rows: Episodes to replace, defaults to all.
Returns:
Operation.
|
Replace full episodes.
|
[
"Replace",
"full",
"episodes",
"."
] |
def replace(self, episodes, length, rows=None):
"""Replace full episodes.
Args:
episodes: Tuple of transition quantities with batch and time dimensions.
length: Batch of sequence lengths.
rows: Episodes to replace, defaults to all.
Returns:
Operation.
"""
rows = tf.range(self._capacity) if rows is None else rows
assert rows.shape.ndims == 1
assert_capacity = tf.assert_less(
rows, self._capacity, message='capacity exceeded')
with tf.control_dependencies([assert_capacity]):
assert_max_length = tf.assert_less_equal(
length, self._max_length, message='max length exceeded')
with tf.control_dependencies([assert_max_length]):
replace_ops = tools.nested.map(
lambda var, val: tf.scatter_update(var, rows, val),
self._buffers, episodes, flatten=True)
with tf.control_dependencies(replace_ops):
return tf.scatter_update(self._length, rows, length)
|
[
"def",
"replace",
"(",
"self",
",",
"episodes",
",",
"length",
",",
"rows",
"=",
"None",
")",
":",
"rows",
"=",
"tf",
".",
"range",
"(",
"self",
".",
"_capacity",
")",
"if",
"rows",
"is",
"None",
"else",
"rows",
"assert",
"rows",
".",
"shape",
".",
"ndims",
"==",
"1",
"assert_capacity",
"=",
"tf",
".",
"assert_less",
"(",
"rows",
",",
"self",
".",
"_capacity",
",",
"message",
"=",
"'capacity exceeded'",
")",
"with",
"tf",
".",
"control_dependencies",
"(",
"[",
"assert_capacity",
"]",
")",
":",
"assert_max_length",
"=",
"tf",
".",
"assert_less_equal",
"(",
"length",
",",
"self",
".",
"_max_length",
",",
"message",
"=",
"'max length exceeded'",
")",
"with",
"tf",
".",
"control_dependencies",
"(",
"[",
"assert_max_length",
"]",
")",
":",
"replace_ops",
"=",
"tools",
".",
"nested",
".",
"map",
"(",
"lambda",
"var",
",",
"val",
":",
"tf",
".",
"scatter_update",
"(",
"var",
",",
"rows",
",",
"val",
")",
",",
"self",
".",
"_buffers",
",",
"episodes",
",",
"flatten",
"=",
"True",
")",
"with",
"tf",
".",
"control_dependencies",
"(",
"replace_ops",
")",
":",
"return",
"tf",
".",
"scatter_update",
"(",
"self",
".",
"_length",
",",
"rows",
",",
"length",
")"
] |
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/parts/memory.py#L94-L117
|
||
rembo10/headphones
|
b3199605be1ebc83a7a8feab6b1e99b64014187c
|
lib/mako/template.py
|
python
|
Template._get_def_callable
|
(self, name)
|
return getattr(self.module, "render_%s" % name)
|
[] |
def _get_def_callable(self, name):
return getattr(self.module, "render_%s" % name)
|
[
"def",
"_get_def_callable",
"(",
"self",
",",
"name",
")",
":",
"return",
"getattr",
"(",
"self",
".",
"module",
",",
"\"render_%s\"",
"%",
"name",
")"
] |
https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/mako/template.py#L476-L477
|
|||
oracle/graalpython
|
577e02da9755d916056184ec441c26e00b70145c
|
graalpython/lib-python/3/xml/sax/xmlreader.py
|
python
|
AttributesImpl.getNames
|
(self)
|
return list(self._attrs.keys())
|
[] |
def getNames(self):
return list(self._attrs.keys())
|
[
"def",
"getNames",
"(",
"self",
")",
":",
"return",
"list",
"(",
"self",
".",
"_attrs",
".",
"keys",
"(",
")",
")"
] |
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/xml/sax/xmlreader.py#L308-L309
|
|||
holzschu/Carnets
|
44effb10ddfc6aa5c8b0687582a724ba82c6b547
|
Library/lib/python3.7/site-packages/pandas-0.24.2-py3.7-macosx-10.9-x86_64.egg/pandas/core/window.py
|
python
|
EWM.cov
|
(self, other=None, pairwise=None, bias=False, **kwargs)
|
return _flex_binary_moment(self._selected_obj, other._selected_obj,
_get_cov, pairwise=bool(pairwise))
|
Exponential weighted sample covariance.
|
Exponential weighted sample covariance.
|
[
"Exponential",
"weighted",
"sample",
"covariance",
"."
] |
def cov(self, other=None, pairwise=None, bias=False, **kwargs):
"""
Exponential weighted sample covariance.
"""
if other is None:
other = self._selected_obj
# only default unset
pairwise = True if pairwise is None else pairwise
other = self._shallow_copy(other)
def _get_cov(X, Y):
X = self._shallow_copy(X)
Y = self._shallow_copy(Y)
cov = libwindow.ewmcov(X._prep_values(), Y._prep_values(),
self.com, int(self.adjust),
int(self.ignore_na), int(self.min_periods),
int(bias))
return X._wrap_result(cov)
return _flex_binary_moment(self._selected_obj, other._selected_obj,
_get_cov, pairwise=bool(pairwise))
|
[
"def",
"cov",
"(",
"self",
",",
"other",
"=",
"None",
",",
"pairwise",
"=",
"None",
",",
"bias",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"other",
"is",
"None",
":",
"other",
"=",
"self",
".",
"_selected_obj",
"# only default unset",
"pairwise",
"=",
"True",
"if",
"pairwise",
"is",
"None",
"else",
"pairwise",
"other",
"=",
"self",
".",
"_shallow_copy",
"(",
"other",
")",
"def",
"_get_cov",
"(",
"X",
",",
"Y",
")",
":",
"X",
"=",
"self",
".",
"_shallow_copy",
"(",
"X",
")",
"Y",
"=",
"self",
".",
"_shallow_copy",
"(",
"Y",
")",
"cov",
"=",
"libwindow",
".",
"ewmcov",
"(",
"X",
".",
"_prep_values",
"(",
")",
",",
"Y",
".",
"_prep_values",
"(",
")",
",",
"self",
".",
"com",
",",
"int",
"(",
"self",
".",
"adjust",
")",
",",
"int",
"(",
"self",
".",
"ignore_na",
")",
",",
"int",
"(",
"self",
".",
"min_periods",
")",
",",
"int",
"(",
"bias",
")",
")",
"return",
"X",
".",
"_wrap_result",
"(",
"cov",
")",
"return",
"_flex_binary_moment",
"(",
"self",
".",
"_selected_obj",
",",
"other",
".",
"_selected_obj",
",",
"_get_cov",
",",
"pairwise",
"=",
"bool",
"(",
"pairwise",
")",
")"
] |
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/pandas-0.24.2-py3.7-macosx-10.9-x86_64.egg/pandas/core/window.py#L2358-L2378
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.