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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bitcraze/crazyflie-clients-python
|
65d433a945b097333e5681a937354045dd4b66f4
|
src/cfclient/ui/tabs/GpsTab.py
|
python
|
GpsTab._disconnected
|
(self, link_uri)
|
return
|
Callback for when the Crazyflie has been disconnected
|
Callback for when the Crazyflie has been disconnected
|
[
"Callback",
"for",
"when",
"the",
"Crazyflie",
"has",
"been",
"disconnected"
] |
def _disconnected(self, link_uri):
"""Callback for when the Crazyflie has been disconnected"""
return
|
[
"def",
"_disconnected",
"(",
"self",
",",
"link_uri",
")",
":",
"return"
] |
https://github.com/bitcraze/crazyflie-clients-python/blob/65d433a945b097333e5681a937354045dd4b66f4/src/cfclient/ui/tabs/GpsTab.py#L141-L143
|
|
meetbill/zabbix_manager
|
739e5b51facf19cc6bda2b50f29108f831cf833e
|
ZabbixTool/lib_zabbix/w_lib/mylib/xlwt/antlr.py
|
python
|
TreeParser.matchNot
|
(self,t, ttype)
|
[] |
def matchNot(self,t, ttype) :
if not t or (t == ASTNULL) or (t.getType() == ttype):
raise MismatchedTokenException(self.getTokenNames(), t, ttype, True)
|
[
"def",
"matchNot",
"(",
"self",
",",
"t",
",",
"ttype",
")",
":",
"if",
"not",
"t",
"or",
"(",
"t",
"==",
"ASTNULL",
")",
"or",
"(",
"t",
".",
"getType",
"(",
")",
"==",
"ttype",
")",
":",
"raise",
"MismatchedTokenException",
"(",
"self",
".",
"getTokenNames",
"(",
")",
",",
"t",
",",
"ttype",
",",
"True",
")"
] |
https://github.com/meetbill/zabbix_manager/blob/739e5b51facf19cc6bda2b50f29108f831cf833e/ZabbixTool/lib_zabbix/w_lib/mylib/xlwt/antlr.py#L2140-L2142
|
||||
pypa/pip
|
7f8a6844037fb7255cfd0d34ff8e8cf44f2598d4
|
src/pip/_vendor/urllib3/packages/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/pypa/pip/blob/7f8a6844037fb7255cfd0d34ff8e8cf44f2598d4/src/pip/_vendor/urllib3/packages/six.py#L80-L82
|
||
TencentCloud/tencentcloud-sdk-python
|
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
|
tencentcloud/zj/v20190121/models.py
|
python
|
GetCrowdPackListRequest.__init__
|
(self)
|
r"""
:param License: 商户证书
:type License: str
:param Offset: 偏移量
:type Offset: int
:param Limit: 限制返回数量
:type Limit: int
:param Name: 人群包名称,用于过滤人群包
:type Name: str
:param Status: 人群包状态,默认-1,用于过滤人群包
:type Status: int
|
r"""
:param License: 商户证书
:type License: str
:param Offset: 偏移量
:type Offset: int
:param Limit: 限制返回数量
:type Limit: int
:param Name: 人群包名称,用于过滤人群包
:type Name: str
:param Status: 人群包状态,默认-1,用于过滤人群包
:type Status: int
|
[
"r",
":",
"param",
"License",
":",
"商户证书",
":",
"type",
"License",
":",
"str",
":",
"param",
"Offset",
":",
"偏移量",
":",
"type",
"Offset",
":",
"int",
":",
"param",
"Limit",
":",
"限制返回数量",
":",
"type",
"Limit",
":",
"int",
":",
"param",
"Name",
":",
"人群包名称,用于过滤人群包",
":",
"type",
"Name",
":",
"str",
":",
"param",
"Status",
":",
"人群包状态,默认",
"-",
"1,用于过滤人群包",
":",
"type",
"Status",
":",
"int"
] |
def __init__(self):
r"""
:param License: 商户证书
:type License: str
:param Offset: 偏移量
:type Offset: int
:param Limit: 限制返回数量
:type Limit: int
:param Name: 人群包名称,用于过滤人群包
:type Name: str
:param Status: 人群包状态,默认-1,用于过滤人群包
:type Status: int
"""
self.License = None
self.Offset = None
self.Limit = None
self.Name = None
self.Status = None
|
[
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"License",
"=",
"None",
"self",
".",
"Offset",
"=",
"None",
"self",
".",
"Limit",
"=",
"None",
"self",
".",
"Name",
"=",
"None",
"self",
".",
"Status",
"=",
"None"
] |
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/zj/v20190121/models.py#L1143-L1160
|
||
psychopy/psychopy
|
01b674094f38d0e0bd51c45a6f66f671d7041696
|
psychopy/iohub/client/eyetracker/validation/procedure.py
|
python
|
ValidationTargetRenderer._initTargetData
|
(self, frompos, topos)
|
Internally used to create the data structure used to store position
information and events which occurred during each target position
period.
|
Internally used to create the data structure used to store position
information and events which occurred during each target position
period.
|
[
"Internally",
"used",
"to",
"create",
"the",
"data",
"structure",
"used",
"to",
"store",
"position",
"information",
"and",
"events",
"which",
"occurred",
"during",
"each",
"target",
"position",
"period",
"."
] |
def _initTargetData(self, frompos, topos):
"""
Internally used to create the data structure used to store position
information and events which occurred during each target position
period.
"""
if self.storeevents:
deviceevents = {}
for device in self.storeevents:
deviceevents[device] = []
self.targetdata.append(dict(frompos=frompos, topos=topos, events=deviceevents))
|
[
"def",
"_initTargetData",
"(",
"self",
",",
"frompos",
",",
"topos",
")",
":",
"if",
"self",
".",
"storeevents",
":",
"deviceevents",
"=",
"{",
"}",
"for",
"device",
"in",
"self",
".",
"storeevents",
":",
"deviceevents",
"[",
"device",
"]",
"=",
"[",
"]",
"self",
".",
"targetdata",
".",
"append",
"(",
"dict",
"(",
"frompos",
"=",
"frompos",
",",
"topos",
"=",
"topos",
",",
"events",
"=",
"deviceevents",
")",
")"
] |
https://github.com/psychopy/psychopy/blob/01b674094f38d0e0bd51c45a6f66f671d7041696/psychopy/iohub/client/eyetracker/validation/procedure.py#L994-L1004
|
||
francisck/DanderSpritz_docs
|
86bb7caca5a957147f120b18bb5c31f299914904
|
Python/Core/Lib/lib-tk/ttk.py
|
python
|
Entry.bbox
|
(self, index)
|
return self.tk.call(self._w, 'bbox', index)
|
Return a tuple of (x, y, width, height) which describes the
bounding box of the character given by index.
|
Return a tuple of (x, y, width, height) which describes the
bounding box of the character given by index.
|
[
"Return",
"a",
"tuple",
"of",
"(",
"x",
"y",
"width",
"height",
")",
"which",
"describes",
"the",
"bounding",
"box",
"of",
"the",
"character",
"given",
"by",
"index",
"."
] |
def bbox(self, index):
"""Return a tuple of (x, y, width, height) which describes the
bounding box of the character given by index."""
return self.tk.call(self._w, 'bbox', index)
|
[
"def",
"bbox",
"(",
"self",
",",
"index",
")",
":",
"return",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"'bbox'",
",",
"index",
")"
] |
https://github.com/francisck/DanderSpritz_docs/blob/86bb7caca5a957147f120b18bb5c31f299914904/Python/Core/Lib/lib-tk/ttk.py#L583-L586
|
|
gentoo/portage
|
e5be73709b1a42b40380fd336f9381452b01a723
|
lib/_emerge/CompositeTask.py
|
python
|
CompositeTask._start_task
|
(self, task, exit_handler)
|
Register exit handler for the given task, set it
as self._current_task, and call task.start().
Subclasses can use this as a generic way to start
a task.
|
Register exit handler for the given task, set it
as self._current_task, and call task.start().
|
[
"Register",
"exit",
"handler",
"for",
"the",
"given",
"task",
"set",
"it",
"as",
"self",
".",
"_current_task",
"and",
"call",
"task",
".",
"start",
"()",
"."
] |
def _start_task(self, task, exit_handler):
"""
Register exit handler for the given task, set it
as self._current_task, and call task.start().
Subclasses can use this as a generic way to start
a task.
"""
try:
task.scheduler = self.scheduler
except AttributeError:
pass
task.addExitListener(exit_handler)
self._current_task = task
task.start()
|
[
"def",
"_start_task",
"(",
"self",
",",
"task",
",",
"exit_handler",
")",
":",
"try",
":",
"task",
".",
"scheduler",
"=",
"self",
".",
"scheduler",
"except",
"AttributeError",
":",
"pass",
"task",
".",
"addExitListener",
"(",
"exit_handler",
")",
"self",
".",
"_current_task",
"=",
"task",
"task",
".",
"start",
"(",
")"
] |
https://github.com/gentoo/portage/blob/e5be73709b1a42b40380fd336f9381452b01a723/lib/_emerge/CompositeTask.py#L97-L112
|
||
richardaecn/class-balanced-loss
|
1d7857208a2abc03d84e35a9d5383af8225d4b4d
|
tpu/models/experimental/resnet50_keras/imagenet_input.py
|
python
|
ImageNetInput.input_fn
|
(self)
|
return dataset
|
Input function which provides a single batch for train or eval.
Returns:
A `tf.data.Dataset` object.
|
Input function which provides a single batch for train or eval.
|
[
"Input",
"function",
"which",
"provides",
"a",
"single",
"batch",
"for",
"train",
"or",
"eval",
"."
] |
def input_fn(self):
"""Input function which provides a single batch for train or eval.
Returns:
A `tf.data.Dataset` object.
"""
if self.data_dir is None:
tf.logging.info('Using fake input.')
return self.input_fn_null()
# Shuffle the filenames to ensure better randomization.
file_pattern = os.path.join(
self.data_dir, 'train-*' if self.is_training else 'validation-*')
dataset = tf.data.Dataset.list_files(file_pattern, shuffle=self.is_training)
if self.is_training:
dataset = dataset.repeat()
def fetch_dataset(filename):
buffer_size = 8 * 1024 * 1024 # 8 MiB per file
dataset = tf.data.TFRecordDataset(filename, buffer_size=buffer_size)
return dataset
# Read the data from disk in parallel
dataset = dataset.apply(
tf.contrib.data.parallel_interleave(
fetch_dataset, cycle_length=16, sloppy=self.is_training))
if self.is_training:
dataset = dataset.shuffle(1024)
# Parse, pre-process, and batch the data in parallel
dataset = dataset.apply(
tf.contrib.data.map_and_batch(
self.dataset_parser, batch_size=self.per_core_batch_size,
num_parallel_batches=2,
drop_remainder=True))
# Prefetch overlaps in-feed with training
dataset = dataset.prefetch(tf.contrib.data.AUTOTUNE)
return dataset
|
[
"def",
"input_fn",
"(",
"self",
")",
":",
"if",
"self",
".",
"data_dir",
"is",
"None",
":",
"tf",
".",
"logging",
".",
"info",
"(",
"'Using fake input.'",
")",
"return",
"self",
".",
"input_fn_null",
"(",
")",
"# Shuffle the filenames to ensure better randomization.",
"file_pattern",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"data_dir",
",",
"'train-*'",
"if",
"self",
".",
"is_training",
"else",
"'validation-*'",
")",
"dataset",
"=",
"tf",
".",
"data",
".",
"Dataset",
".",
"list_files",
"(",
"file_pattern",
",",
"shuffle",
"=",
"self",
".",
"is_training",
")",
"if",
"self",
".",
"is_training",
":",
"dataset",
"=",
"dataset",
".",
"repeat",
"(",
")",
"def",
"fetch_dataset",
"(",
"filename",
")",
":",
"buffer_size",
"=",
"8",
"*",
"1024",
"*",
"1024",
"# 8 MiB per file",
"dataset",
"=",
"tf",
".",
"data",
".",
"TFRecordDataset",
"(",
"filename",
",",
"buffer_size",
"=",
"buffer_size",
")",
"return",
"dataset",
"# Read the data from disk in parallel",
"dataset",
"=",
"dataset",
".",
"apply",
"(",
"tf",
".",
"contrib",
".",
"data",
".",
"parallel_interleave",
"(",
"fetch_dataset",
",",
"cycle_length",
"=",
"16",
",",
"sloppy",
"=",
"self",
".",
"is_training",
")",
")",
"if",
"self",
".",
"is_training",
":",
"dataset",
"=",
"dataset",
".",
"shuffle",
"(",
"1024",
")",
"# Parse, pre-process, and batch the data in parallel",
"dataset",
"=",
"dataset",
".",
"apply",
"(",
"tf",
".",
"contrib",
".",
"data",
".",
"map_and_batch",
"(",
"self",
".",
"dataset_parser",
",",
"batch_size",
"=",
"self",
".",
"per_core_batch_size",
",",
"num_parallel_batches",
"=",
"2",
",",
"drop_remainder",
"=",
"True",
")",
")",
"# Prefetch overlaps in-feed with training",
"dataset",
"=",
"dataset",
".",
"prefetch",
"(",
"tf",
".",
"contrib",
".",
"data",
".",
"AUTOTUNE",
")",
"return",
"dataset"
] |
https://github.com/richardaecn/class-balanced-loss/blob/1d7857208a2abc03d84e35a9d5383af8225d4b4d/tpu/models/experimental/resnet50_keras/imagenet_input.py#L122-L161
|
|
psolin/cleanco
|
806bf5f2439b96d8b5b5e21af824d5c870aba168
|
cleanco/clean.py
|
python
|
strip_tail
|
(name)
|
return name
|
get rid of all trailing non-letter symbols except the dot
|
get rid of all trailing non-letter symbols except the dot
|
[
"get",
"rid",
"of",
"all",
"trailing",
"non",
"-",
"letter",
"symbols",
"except",
"the",
"dot"
] |
def strip_tail(name):
"get rid of all trailing non-letter symbols except the dot"
match = re.search(tail_removal_rexp, name)
if match is not None:
name = name[: match.span()[0]]
return name
|
[
"def",
"strip_tail",
"(",
"name",
")",
":",
"match",
"=",
"re",
".",
"search",
"(",
"tail_removal_rexp",
",",
"name",
")",
"if",
"match",
"is",
"not",
"None",
":",
"name",
"=",
"name",
"[",
":",
"match",
".",
"span",
"(",
")",
"[",
"0",
"]",
"]",
"return",
"name"
] |
https://github.com/psolin/cleanco/blob/806bf5f2439b96d8b5b5e21af824d5c870aba168/cleanco/clean.py#L53-L58
|
|
CalebBell/fluids
|
dbbdd1d5ea3c458bd68dd8e21cf6281a0ec3fc80
|
fluids/fittings.py
|
python
|
Kv_to_K
|
(Kv, D)
|
return 1.6E9*D**4*Kv**-2
|
r'''Convert valve flow coefficient from common metric units to regular
loss coefficients.
.. math::
K = 1.6\times 10^9 \frac{D^4}{K_v^2}
Parameters
----------
Kv : float
Metric Kv valve flow coefficient (flow rate of water at a pressure drop
of 1 bar) [m^3/hr]
D : float
Inside diameter of the valve [m]
Returns
-------
K : float
Loss coefficient, [-]
Notes
-----
Crane TP 410 M (2009) gives the coefficient of 0.04 (with diameter in mm).
It also suggests the density of water should be found between 5-40°C.
Older versions specify the density should be found at 60 °F, which is
used here, and the pessure for the appropriate density is back calculated.
.. math::
\Delta P = 1 \text{ bar} = \frac{1}{2}\rho V^2\cdot K
V = \frac{\frac{K_v\cdot \text{ hour}}{3600 \text{ second}}}{\frac{\pi}{4}D^2}
\rho = 999.29744568 \;\; kg/m^3 \text{ at } T=60° F, P = 703572 Pa
The value of density is calculated with IAPWS-95; it is chosen as it makes
the coefficient a very convenient round number. Others constants that have
been used are 1.604E9, and 1.60045E9.
Examples
--------
>>> Kv_to_K(2.312, .015)
15.153374600399898
References
----------
.. [1] ISA-75.01.01-2007 (60534-2-1 Mod) Draft
|
r'''Convert valve flow coefficient from common metric units to regular
loss coefficients.
|
[
"r",
"Convert",
"valve",
"flow",
"coefficient",
"from",
"common",
"metric",
"units",
"to",
"regular",
"loss",
"coefficients",
"."
] |
def Kv_to_K(Kv, D):
r'''Convert valve flow coefficient from common metric units to regular
loss coefficients.
.. math::
K = 1.6\times 10^9 \frac{D^4}{K_v^2}
Parameters
----------
Kv : float
Metric Kv valve flow coefficient (flow rate of water at a pressure drop
of 1 bar) [m^3/hr]
D : float
Inside diameter of the valve [m]
Returns
-------
K : float
Loss coefficient, [-]
Notes
-----
Crane TP 410 M (2009) gives the coefficient of 0.04 (with diameter in mm).
It also suggests the density of water should be found between 5-40°C.
Older versions specify the density should be found at 60 °F, which is
used here, and the pessure for the appropriate density is back calculated.
.. math::
\Delta P = 1 \text{ bar} = \frac{1}{2}\rho V^2\cdot K
V = \frac{\frac{K_v\cdot \text{ hour}}{3600 \text{ second}}}{\frac{\pi}{4}D^2}
\rho = 999.29744568 \;\; kg/m^3 \text{ at } T=60° F, P = 703572 Pa
The value of density is calculated with IAPWS-95; it is chosen as it makes
the coefficient a very convenient round number. Others constants that have
been used are 1.604E9, and 1.60045E9.
Examples
--------
>>> Kv_to_K(2.312, .015)
15.153374600399898
References
----------
.. [1] ISA-75.01.01-2007 (60534-2-1 Mod) Draft
'''
return 1.6E9*D**4*Kv**-2
|
[
"def",
"Kv_to_K",
"(",
"Kv",
",",
"D",
")",
":",
"return",
"1.6E9",
"*",
"D",
"**",
"4",
"*",
"Kv",
"**",
"-",
"2"
] |
https://github.com/CalebBell/fluids/blob/dbbdd1d5ea3c458bd68dd8e21cf6281a0ec3fc80/fluids/fittings.py#L3394-L3442
|
|
pwnieexpress/pwn_plug_sources
|
1a23324f5dc2c3de20f9c810269b6a29b2758cad
|
src/metagoofil/hachoir_parser/image/gif.py
|
python
|
ScreenDescriptor.createDescription
|
(self)
|
return "Screen descriptor: %ux%u pixels %u colors" \
% (self["width"].value, self["height"].value, colors)
|
[] |
def createDescription(self):
colors = 1 << (self["bpp"].value+1)
return "Screen descriptor: %ux%u pixels %u colors" \
% (self["width"].value, self["height"].value, colors)
|
[
"def",
"createDescription",
"(",
"self",
")",
":",
"colors",
"=",
"1",
"<<",
"(",
"self",
"[",
"\"bpp\"",
"]",
".",
"value",
"+",
"1",
")",
"return",
"\"Screen descriptor: %ux%u pixels %u colors\"",
"%",
"(",
"self",
"[",
"\"width\"",
"]",
".",
"value",
",",
"self",
"[",
"\"height\"",
"]",
".",
"value",
",",
"colors",
")"
] |
https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/metagoofil/hachoir_parser/image/gif.py#L159-L162
|
|||
dbt-labs/dbt-core
|
e943b9fc842535e958ef4fd0b8703adc91556bc6
|
core/dbt/adapters/cache.py
|
python
|
RelationsCache._remove_all
|
(self, to_remove: List[_CachedRelation])
|
Remove all the listed relations. Ignore relations that have been
cascaded out.
|
Remove all the listed relations. Ignore relations that have been
cascaded out.
|
[
"Remove",
"all",
"the",
"listed",
"relations",
".",
"Ignore",
"relations",
"that",
"have",
"been",
"cascaded",
"out",
"."
] |
def _remove_all(self, to_remove: List[_CachedRelation]):
"""Remove all the listed relations. Ignore relations that have been
cascaded out.
"""
for relation in to_remove:
# it may have been cascaded out already
drop_key = _make_key(relation)
if drop_key in self.relations:
self.drop(drop_key)
|
[
"def",
"_remove_all",
"(",
"self",
",",
"to_remove",
":",
"List",
"[",
"_CachedRelation",
"]",
")",
":",
"for",
"relation",
"in",
"to_remove",
":",
"# it may have been cascaded out already",
"drop_key",
"=",
"_make_key",
"(",
"relation",
")",
"if",
"drop_key",
"in",
"self",
".",
"relations",
":",
"self",
".",
"drop",
"(",
"drop_key",
")"
] |
https://github.com/dbt-labs/dbt-core/blob/e943b9fc842535e958ef4fd0b8703adc91556bc6/core/dbt/adapters/cache.py#L496-L504
|
||
Tautulli/Tautulli
|
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
|
lib/future/backports/html/parser.py
|
python
|
HTMLParser.set_cdata_mode
|
(self, elem)
|
[] |
def set_cdata_mode(self, elem):
self.cdata_elem = elem.lower()
self.interesting = re.compile(r'</\s*%s\s*>' % self.cdata_elem, re.I)
|
[
"def",
"set_cdata_mode",
"(",
"self",
",",
"elem",
")",
":",
"self",
".",
"cdata_elem",
"=",
"elem",
".",
"lower",
"(",
")",
"self",
".",
"interesting",
"=",
"re",
".",
"compile",
"(",
"r'</\\s*%s\\s*>'",
"%",
"self",
".",
"cdata_elem",
",",
"re",
".",
"I",
")"
] |
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/future/backports/html/parser.py#L165-L167
|
||||
chribsen/simple-machine-learning-examples
|
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
|
venv/lib/python2.7/site-packages/pandas/tseries/tdi.py
|
python
|
TimedeltaIndex.total_seconds
|
(self)
|
return self._maybe_mask_results(1e-9 * self.asi8)
|
Total duration of each element expressed in seconds.
.. versionadded:: 0.17.0
|
Total duration of each element expressed in seconds.
|
[
"Total",
"duration",
"of",
"each",
"element",
"expressed",
"in",
"seconds",
"."
] |
def total_seconds(self):
"""
Total duration of each element expressed in seconds.
.. versionadded:: 0.17.0
"""
return self._maybe_mask_results(1e-9 * self.asi8)
|
[
"def",
"total_seconds",
"(",
"self",
")",
":",
"return",
"self",
".",
"_maybe_mask_results",
"(",
"1e-9",
"*",
"self",
".",
"asi8",
")"
] |
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/pandas/tseries/tdi.py#L440-L446
|
|
GNS3/gns3-server
|
aff06572d4173df945ad29ea8feb274f7885d9e4
|
gns3server/compute/dynamips/nodes/router.py
|
python
|
Router.stop_capture
|
(self, slot_number, port_number)
|
Stops a packet capture.
:param slot_number: slot number
:param port_number: port number
|
Stops a packet capture.
|
[
"Stops",
"a",
"packet",
"capture",
"."
] |
async def stop_capture(self, slot_number, port_number):
"""
Stops a packet capture.
:param slot_number: slot number
:param port_number: port number
"""
try:
adapter = self._slots[slot_number]
except IndexError:
raise DynamipsError('Slot {slot_number} does not exist on router "{name}"'.format(name=self._name,
slot_number=slot_number))
if not adapter.port_exists(port_number):
raise DynamipsError("Port {port_number} does not exist on adapter {adapter}".format(adapter=adapter,
port_number=port_number))
nio = adapter.get_nio(port_number)
if not nio:
raise DynamipsError("Port {slot_number}/{port_number} is not connected".format(slot_number=slot_number,
port_number=port_number))
if not nio.capturing:
return
await nio.stop_packet_capture()
log.info('Router "{name}" [{id}]: stopping packet capture on port {slot_number}/{port_number}'.format(name=self._name,
id=self._id,
nio_name=nio.name,
slot_number=slot_number,
port_number=port_number))
|
[
"async",
"def",
"stop_capture",
"(",
"self",
",",
"slot_number",
",",
"port_number",
")",
":",
"try",
":",
"adapter",
"=",
"self",
".",
"_slots",
"[",
"slot_number",
"]",
"except",
"IndexError",
":",
"raise",
"DynamipsError",
"(",
"'Slot {slot_number} does not exist on router \"{name}\"'",
".",
"format",
"(",
"name",
"=",
"self",
".",
"_name",
",",
"slot_number",
"=",
"slot_number",
")",
")",
"if",
"not",
"adapter",
".",
"port_exists",
"(",
"port_number",
")",
":",
"raise",
"DynamipsError",
"(",
"\"Port {port_number} does not exist on adapter {adapter}\"",
".",
"format",
"(",
"adapter",
"=",
"adapter",
",",
"port_number",
"=",
"port_number",
")",
")",
"nio",
"=",
"adapter",
".",
"get_nio",
"(",
"port_number",
")",
"if",
"not",
"nio",
":",
"raise",
"DynamipsError",
"(",
"\"Port {slot_number}/{port_number} is not connected\"",
".",
"format",
"(",
"slot_number",
"=",
"slot_number",
",",
"port_number",
"=",
"port_number",
")",
")",
"if",
"not",
"nio",
".",
"capturing",
":",
"return",
"await",
"nio",
".",
"stop_packet_capture",
"(",
")",
"log",
".",
"info",
"(",
"'Router \"{name}\" [{id}]: stopping packet capture on port {slot_number}/{port_number}'",
".",
"format",
"(",
"name",
"=",
"self",
".",
"_name",
",",
"id",
"=",
"self",
".",
"_id",
",",
"nio_name",
"=",
"nio",
".",
"name",
",",
"slot_number",
"=",
"slot_number",
",",
"port_number",
"=",
"port_number",
")",
")"
] |
https://github.com/GNS3/gns3-server/blob/aff06572d4173df945ad29ea8feb274f7885d9e4/gns3server/compute/dynamips/nodes/router.py#L1462-L1493
|
||
miso-belica/sumy
|
87fc584b3b984732ba63d902e0701dd883749899
|
sumy/models/tf.py
|
python
|
TfDocumentModel.term_frequency
|
(self, term)
|
return self._terms.get(term, 0)
|
Returns frequency of term in document.
:returns int:
Returns count of words in document.
|
Returns frequency of term in document.
|
[
"Returns",
"frequency",
"of",
"term",
"in",
"document",
"."
] |
def term_frequency(self, term):
"""
Returns frequency of term in document.
:returns int:
Returns count of words in document.
"""
return self._terms.get(term, 0)
|
[
"def",
"term_frequency",
"(",
"self",
",",
"term",
")",
":",
"return",
"self",
".",
"_terms",
".",
"get",
"(",
"term",
",",
"0",
")"
] |
https://github.com/miso-belica/sumy/blob/87fc584b3b984732ba63d902e0701dd883749899/sumy/models/tf.py#L60-L67
|
|
KhronosGroup/NNEF-Tools
|
c913758ca687dab8cb7b49e8f1556819a2d0ca25
|
nnef_tools/io/tf/lite/flatbuffers/Operator.py
|
python
|
Operator.MutatingVariableInputsLength
|
(self)
|
return 0
|
[] |
def MutatingVariableInputsLength(self):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18))
if o != 0:
return self._tab.VectorLen(o)
return 0
|
[
"def",
"MutatingVariableInputsLength",
"(",
"self",
")",
":",
"o",
"=",
"flatbuffers",
".",
"number_types",
".",
"UOffsetTFlags",
".",
"py_type",
"(",
"self",
".",
"_tab",
".",
"Offset",
"(",
"18",
")",
")",
"if",
"o",
"!=",
"0",
":",
"return",
"self",
".",
"_tab",
".",
"VectorLen",
"(",
"o",
")",
"return",
"0"
] |
https://github.com/KhronosGroup/NNEF-Tools/blob/c913758ca687dab8cb7b49e8f1556819a2d0ca25/nnef_tools/io/tf/lite/flatbuffers/Operator.py#L155-L159
|
|||
ryu577/pyray
|
860b71463e2729a85b1319b5c3571c0b8f3ba50c
|
pyray/rotation.py
|
python
|
axis_rotation
|
(pt1, pt2, theta)
|
return np.dot(np.dot(tr_inv,rot),tr)
|
Applies to 3-d space.
Performs a rotation about an axis given by two points
not necessarily centered at the origin. Unfortunately,
we need to return a 4x4 matrix here since translations
can't be expressed as a 3x3 matrix. So, it is the users
responsibility to add a 1 to any vector they are applying
this matrix to so that is is 4 dimensional. Also, unlike
general_rotation, this will only work for vectors post-multiplied
to the matrix.
Refer to:
http://paulbourke.net/geometry/rotate/
https://en.wikipedia.org/wiki/Translation_(geometry).
args:
pt1: The first point of the axis of rotation.
pt2: The second point of the axis of rotation.
theta: The angle by which the rotation will occur.
|
Applies to 3-d space.
Performs a rotation about an axis given by two points
not necessarily centered at the origin. Unfortunately,
we need to return a 4x4 matrix here since translations
can't be expressed as a 3x3 matrix. So, it is the users
responsibility to add a 1 to any vector they are applying
this matrix to so that is is 4 dimensional. Also, unlike
general_rotation, this will only work for vectors post-multiplied
to the matrix.
Refer to:
http://paulbourke.net/geometry/rotate/
https://en.wikipedia.org/wiki/Translation_(geometry).
args:
pt1: The first point of the axis of rotation.
pt2: The second point of the axis of rotation.
theta: The angle by which the rotation will occur.
|
[
"Applies",
"to",
"3",
"-",
"d",
"space",
".",
"Performs",
"a",
"rotation",
"about",
"an",
"axis",
"given",
"by",
"two",
"points",
"not",
"necessarily",
"centered",
"at",
"the",
"origin",
".",
"Unfortunately",
"we",
"need",
"to",
"return",
"a",
"4x4",
"matrix",
"here",
"since",
"translations",
"can",
"t",
"be",
"expressed",
"as",
"a",
"3x3",
"matrix",
".",
"So",
"it",
"is",
"the",
"users",
"responsibility",
"to",
"add",
"a",
"1",
"to",
"any",
"vector",
"they",
"are",
"applying",
"this",
"matrix",
"to",
"so",
"that",
"is",
"is",
"4",
"dimensional",
".",
"Also",
"unlike",
"general_rotation",
"this",
"will",
"only",
"work",
"for",
"vectors",
"post",
"-",
"multiplied",
"to",
"the",
"matrix",
".",
"Refer",
"to",
":",
"http",
":",
"//",
"paulbourke",
".",
"net",
"/",
"geometry",
"/",
"rotate",
"/",
"https",
":",
"//",
"en",
".",
"wikipedia",
".",
"org",
"/",
"wiki",
"/",
"Translation_",
"(",
"geometry",
")",
".",
"args",
":",
"pt1",
":",
"The",
"first",
"point",
"of",
"the",
"axis",
"of",
"rotation",
".",
"pt2",
":",
"The",
"second",
"point",
"of",
"the",
"axis",
"of",
"rotation",
".",
"theta",
":",
"The",
"angle",
"by",
"which",
"the",
"rotation",
"will",
"occur",
"."
] |
def axis_rotation(pt1, pt2, theta):
"""
Applies to 3-d space.
Performs a rotation about an axis given by two points
not necessarily centered at the origin. Unfortunately,
we need to return a 4x4 matrix here since translations
can't be expressed as a 3x3 matrix. So, it is the users
responsibility to add a 1 to any vector they are applying
this matrix to so that is is 4 dimensional. Also, unlike
general_rotation, this will only work for vectors post-multiplied
to the matrix.
Refer to:
http://paulbourke.net/geometry/rotate/
https://en.wikipedia.org/wiki/Translation_(geometry).
args:
pt1: The first point of the axis of rotation.
pt2: The second point of the axis of rotation.
theta: The angle by which the rotation will occur.
"""
tr = np.eye(4)
tr_inv = np.eye(4)
tr[0,3] = -pt1[0]
tr[1,3] = -pt1[1]
tr[2,3] = -pt1[2]
tr_inv[0,3] = pt1[0]
tr_inv[1,3] = pt1[1]
tr_inv[2,3] = pt1[2]
rot = np.eye(4)
rot[:3,:3] = general_rotation(pt2-pt1,theta)
return np.dot(np.dot(tr_inv,rot),tr)
|
[
"def",
"axis_rotation",
"(",
"pt1",
",",
"pt2",
",",
"theta",
")",
":",
"tr",
"=",
"np",
".",
"eye",
"(",
"4",
")",
"tr_inv",
"=",
"np",
".",
"eye",
"(",
"4",
")",
"tr",
"[",
"0",
",",
"3",
"]",
"=",
"-",
"pt1",
"[",
"0",
"]",
"tr",
"[",
"1",
",",
"3",
"]",
"=",
"-",
"pt1",
"[",
"1",
"]",
"tr",
"[",
"2",
",",
"3",
"]",
"=",
"-",
"pt1",
"[",
"2",
"]",
"tr_inv",
"[",
"0",
",",
"3",
"]",
"=",
"pt1",
"[",
"0",
"]",
"tr_inv",
"[",
"1",
",",
"3",
"]",
"=",
"pt1",
"[",
"1",
"]",
"tr_inv",
"[",
"2",
",",
"3",
"]",
"=",
"pt1",
"[",
"2",
"]",
"rot",
"=",
"np",
".",
"eye",
"(",
"4",
")",
"rot",
"[",
":",
"3",
",",
":",
"3",
"]",
"=",
"general_rotation",
"(",
"pt2",
"-",
"pt1",
",",
"theta",
")",
"return",
"np",
".",
"dot",
"(",
"np",
".",
"dot",
"(",
"tr_inv",
",",
"rot",
")",
",",
"tr",
")"
] |
https://github.com/ryu577/pyray/blob/860b71463e2729a85b1319b5c3571c0b8f3ba50c/pyray/rotation.py#L82-L111
|
|
openstack/sahara
|
c4f4d29847d5bcca83d49ef7e9a3378458462a79
|
sahara/plugins/images.py
|
python
|
SaharaArgumentCaseValidator.validate
|
(self, remote, test_only=False,
image_arguments=None, **kwargs)
|
Attempts to validate depending on argument value.
:param remote: A remote socket to the instance.
:param test_only: If true, all validators will only verify that a
desired state is present, and fail if it is not. If false, all
validators will attempt to enforce the desired state if possible,
and succeed if this enforcement succeeds.
:param image_arguments: A dictionary of image argument values keyed by
argument name.
:raises ImageValidationError: If validation fails.
|
Attempts to validate depending on argument value.
|
[
"Attempts",
"to",
"validate",
"depending",
"on",
"argument",
"value",
"."
] |
def validate(self, remote, test_only=False,
image_arguments=None, **kwargs):
"""Attempts to validate depending on argument value.
:param remote: A remote socket to the instance.
:param test_only: If true, all validators will only verify that a
desired state is present, and fail if it is not. If false, all
validators will attempt to enforce the desired state if possible,
and succeed if this enforcement succeeds.
:param image_arguments: A dictionary of image argument values keyed by
argument name.
:raises ImageValidationError: If validation fails.
"""
arg = self.argument_name
if arg not in image_arguments:
raise p_ex.ImageValidationError(
_("Argument {name} not found.").format(name=arg))
value = image_arguments[arg]
if value in self.cases:
self.cases[value].validate(
remote, test_only=test_only,
image_arguments=image_arguments)
|
[
"def",
"validate",
"(",
"self",
",",
"remote",
",",
"test_only",
"=",
"False",
",",
"image_arguments",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"arg",
"=",
"self",
".",
"argument_name",
"if",
"arg",
"not",
"in",
"image_arguments",
":",
"raise",
"p_ex",
".",
"ImageValidationError",
"(",
"_",
"(",
"\"Argument {name} not found.\"",
")",
".",
"format",
"(",
"name",
"=",
"arg",
")",
")",
"value",
"=",
"image_arguments",
"[",
"arg",
"]",
"if",
"value",
"in",
"self",
".",
"cases",
":",
"self",
".",
"cases",
"[",
"value",
"]",
".",
"validate",
"(",
"remote",
",",
"test_only",
"=",
"test_only",
",",
"image_arguments",
"=",
"image_arguments",
")"
] |
https://github.com/openstack/sahara/blob/c4f4d29847d5bcca83d49ef7e9a3378458462a79/sahara/plugins/images.py#L1027-L1048
|
||
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
|
cb692f527e4e819b6c228187c5702d990a180043
|
external/Scripting Engine/Xenotix Python Scripting Engine/Lib/lib2to3/fixes/fix_metaclass.py
|
python
|
fixup_simple_stmt
|
(parent, i, stmt_node)
|
if there is a semi-colon all the parts count as part of the same
simple_stmt. We just want the __metaclass__ part so we move
everything efter the semi-colon into its own simple_stmt node
|
if there is a semi-colon all the parts count as part of the same
simple_stmt. We just want the __metaclass__ part so we move
everything efter the semi-colon into its own simple_stmt node
|
[
"if",
"there",
"is",
"a",
"semi",
"-",
"colon",
"all",
"the",
"parts",
"count",
"as",
"part",
"of",
"the",
"same",
"simple_stmt",
".",
"We",
"just",
"want",
"the",
"__metaclass__",
"part",
"so",
"we",
"move",
"everything",
"efter",
"the",
"semi",
"-",
"colon",
"into",
"its",
"own",
"simple_stmt",
"node"
] |
def fixup_simple_stmt(parent, i, stmt_node):
""" if there is a semi-colon all the parts count as part of the same
simple_stmt. We just want the __metaclass__ part so we move
everything efter the semi-colon into its own simple_stmt node
"""
for semi_ind, node in enumerate(stmt_node.children):
if node.type == token.SEMI: # *sigh*
break
else:
return
node.remove() # kill the semicolon
new_expr = Node(syms.expr_stmt, [])
new_stmt = Node(syms.simple_stmt, [new_expr])
while stmt_node.children[semi_ind:]:
move_node = stmt_node.children[semi_ind]
new_expr.append_child(move_node.clone())
move_node.remove()
parent.insert_child(i, new_stmt)
new_leaf1 = new_stmt.children[0].children[0]
old_leaf1 = stmt_node.children[0].children[0]
new_leaf1.prefix = old_leaf1.prefix
|
[
"def",
"fixup_simple_stmt",
"(",
"parent",
",",
"i",
",",
"stmt_node",
")",
":",
"for",
"semi_ind",
",",
"node",
"in",
"enumerate",
"(",
"stmt_node",
".",
"children",
")",
":",
"if",
"node",
".",
"type",
"==",
"token",
".",
"SEMI",
":",
"# *sigh*",
"break",
"else",
":",
"return",
"node",
".",
"remove",
"(",
")",
"# kill the semicolon",
"new_expr",
"=",
"Node",
"(",
"syms",
".",
"expr_stmt",
",",
"[",
"]",
")",
"new_stmt",
"=",
"Node",
"(",
"syms",
".",
"simple_stmt",
",",
"[",
"new_expr",
"]",
")",
"while",
"stmt_node",
".",
"children",
"[",
"semi_ind",
":",
"]",
":",
"move_node",
"=",
"stmt_node",
".",
"children",
"[",
"semi_ind",
"]",
"new_expr",
".",
"append_child",
"(",
"move_node",
".",
"clone",
"(",
")",
")",
"move_node",
".",
"remove",
"(",
")",
"parent",
".",
"insert_child",
"(",
"i",
",",
"new_stmt",
")",
"new_leaf1",
"=",
"new_stmt",
".",
"children",
"[",
"0",
"]",
".",
"children",
"[",
"0",
"]",
"old_leaf1",
"=",
"stmt_node",
".",
"children",
"[",
"0",
"]",
".",
"children",
"[",
"0",
"]",
"new_leaf1",
".",
"prefix",
"=",
"old_leaf1",
".",
"prefix"
] |
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/Lib/lib2to3/fixes/fix_metaclass.py#L71-L92
|
||
sagemath/sage
|
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
|
src/sage/rings/asymptotic/growth_group.py
|
python
|
AbstractGrowthGroupFunctor.__init__
|
(self, var, domain)
|
r"""
See :class:`AbstractGrowthGroupFunctor` for details.
TESTS::
sage: from sage.rings.asymptotic.growth_group import AbstractGrowthGroupFunctor
sage: AbstractGrowthGroupFunctor('x', Groups())
AbstractGrowthGroup[x]
|
r"""
See :class:`AbstractGrowthGroupFunctor` for details.
|
[
"r",
"See",
":",
"class",
":",
"AbstractGrowthGroupFunctor",
"for",
"details",
"."
] |
def __init__(self, var, domain):
r"""
See :class:`AbstractGrowthGroupFunctor` for details.
TESTS::
sage: from sage.rings.asymptotic.growth_group import AbstractGrowthGroupFunctor
sage: AbstractGrowthGroupFunctor('x', Groups())
AbstractGrowthGroup[x]
"""
from sage.categories.monoids import Monoids
from sage.categories.posets import Posets
if var is None:
var = Variable('')
elif not isinstance(var, Variable):
var = Variable(var)
self.var = var
super(ConstructionFunctor, self).__init__(
domain, Monoids() & Posets())
|
[
"def",
"__init__",
"(",
"self",
",",
"var",
",",
"domain",
")",
":",
"from",
"sage",
".",
"categories",
".",
"monoids",
"import",
"Monoids",
"from",
"sage",
".",
"categories",
".",
"posets",
"import",
"Posets",
"if",
"var",
"is",
"None",
":",
"var",
"=",
"Variable",
"(",
"''",
")",
"elif",
"not",
"isinstance",
"(",
"var",
",",
"Variable",
")",
":",
"var",
"=",
"Variable",
"(",
"var",
")",
"self",
".",
"var",
"=",
"var",
"super",
"(",
"ConstructionFunctor",
",",
"self",
")",
".",
"__init__",
"(",
"domain",
",",
"Monoids",
"(",
")",
"&",
"Posets",
"(",
")",
")"
] |
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/rings/asymptotic/growth_group.py#L2699-L2718
|
||
and3rson/clay
|
c271cecf6b6ea6465abcdd2444171b1a565a60a3
|
clay/vlc.py
|
python
|
MediaPlayer.audio_set_delay
|
(self, i_delay)
|
return libvlc_audio_set_delay(self, i_delay)
|
Set current audio delay. The audio delay will be reset to zero each time the media changes.
@param i_delay: the audio delay (microseconds).
@return: 0 on success, -1 on error.
@version: LibVLC 1.1.1 or later.
|
Set current audio delay. The audio delay will be reset to zero each time the media changes.
|
[
"Set",
"current",
"audio",
"delay",
".",
"The",
"audio",
"delay",
"will",
"be",
"reset",
"to",
"zero",
"each",
"time",
"the",
"media",
"changes",
"."
] |
def audio_set_delay(self, i_delay):
'''Set current audio delay. The audio delay will be reset to zero each time the media changes.
@param i_delay: the audio delay (microseconds).
@return: 0 on success, -1 on error.
@version: LibVLC 1.1.1 or later.
'''
return libvlc_audio_set_delay(self, i_delay)
|
[
"def",
"audio_set_delay",
"(",
"self",
",",
"i_delay",
")",
":",
"return",
"libvlc_audio_set_delay",
"(",
"self",
",",
"i_delay",
")"
] |
https://github.com/and3rson/clay/blob/c271cecf6b6ea6465abcdd2444171b1a565a60a3/clay/vlc.py#L3706-L3712
|
|
GNS3/gns3-gui
|
da8adbaa18ab60e053af2a619efd468f4c8950f3
|
gns3/modules/dynamips/pages/ios_router_preferences_page.py
|
python
|
IOSRouterPreferencesPage._iosRouterCopySlot
|
(self)
|
Copies an IOS router.
|
Copies an IOS router.
|
[
"Copies",
"an",
"IOS",
"router",
"."
] |
def _iosRouterCopySlot(self):
"""
Copies an IOS router.
"""
item = self.uiIOSRoutersTreeWidget.currentItem()
if item:
key = item.data(0, QtCore.Qt.UserRole)
copied_ios_router_settings = copy.deepcopy(self._ios_routers[key])
new_name, ok = QtWidgets.QInputDialog.getText(self, "Copy IOS router template", "Template name:", QtWidgets.QLineEdit.Normal, "Copy of {}".format(copied_ios_router_settings["name"]))
if ok:
key = "{server}:{name}".format(server=copied_ios_router_settings["compute_id"], name=new_name)
if key in self._ios_routers:
QtWidgets.QMessageBox.critical(self, "IOS router template", "IOS router template name {} already exists".format(new_name))
return
self._ios_routers[key] = IOS_ROUTER_SETTINGS.copy()
self._ios_routers[key].update(copied_ios_router_settings)
self._ios_routers[key]["name"] = new_name
self._ios_routers[key].pop("template_id", None)
item = QtWidgets.QTreeWidgetItem(self.uiIOSRoutersTreeWidget)
item.setText(0, self._ios_routers[key]["name"])
Controller.instance().getSymbolIcon(self._ios_routers[key]["symbol"], qpartial(self._setItemIcon, item))
item.setData(0, QtCore.Qt.UserRole, key)
self._items.append(item)
self.uiIOSRoutersTreeWidget.setCurrentItem(item)
|
[
"def",
"_iosRouterCopySlot",
"(",
"self",
")",
":",
"item",
"=",
"self",
".",
"uiIOSRoutersTreeWidget",
".",
"currentItem",
"(",
")",
"if",
"item",
":",
"key",
"=",
"item",
".",
"data",
"(",
"0",
",",
"QtCore",
".",
"Qt",
".",
"UserRole",
")",
"copied_ios_router_settings",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"_ios_routers",
"[",
"key",
"]",
")",
"new_name",
",",
"ok",
"=",
"QtWidgets",
".",
"QInputDialog",
".",
"getText",
"(",
"self",
",",
"\"Copy IOS router template\"",
",",
"\"Template name:\"",
",",
"QtWidgets",
".",
"QLineEdit",
".",
"Normal",
",",
"\"Copy of {}\"",
".",
"format",
"(",
"copied_ios_router_settings",
"[",
"\"name\"",
"]",
")",
")",
"if",
"ok",
":",
"key",
"=",
"\"{server}:{name}\"",
".",
"format",
"(",
"server",
"=",
"copied_ios_router_settings",
"[",
"\"compute_id\"",
"]",
",",
"name",
"=",
"new_name",
")",
"if",
"key",
"in",
"self",
".",
"_ios_routers",
":",
"QtWidgets",
".",
"QMessageBox",
".",
"critical",
"(",
"self",
",",
"\"IOS router template\"",
",",
"\"IOS router template name {} already exists\"",
".",
"format",
"(",
"new_name",
")",
")",
"return",
"self",
".",
"_ios_routers",
"[",
"key",
"]",
"=",
"IOS_ROUTER_SETTINGS",
".",
"copy",
"(",
")",
"self",
".",
"_ios_routers",
"[",
"key",
"]",
".",
"update",
"(",
"copied_ios_router_settings",
")",
"self",
".",
"_ios_routers",
"[",
"key",
"]",
"[",
"\"name\"",
"]",
"=",
"new_name",
"self",
".",
"_ios_routers",
"[",
"key",
"]",
".",
"pop",
"(",
"\"template_id\"",
",",
"None",
")",
"item",
"=",
"QtWidgets",
".",
"QTreeWidgetItem",
"(",
"self",
".",
"uiIOSRoutersTreeWidget",
")",
"item",
".",
"setText",
"(",
"0",
",",
"self",
".",
"_ios_routers",
"[",
"key",
"]",
"[",
"\"name\"",
"]",
")",
"Controller",
".",
"instance",
"(",
")",
".",
"getSymbolIcon",
"(",
"self",
".",
"_ios_routers",
"[",
"key",
"]",
"[",
"\"symbol\"",
"]",
",",
"qpartial",
"(",
"self",
".",
"_setItemIcon",
",",
"item",
")",
")",
"item",
".",
"setData",
"(",
"0",
",",
"QtCore",
".",
"Qt",
".",
"UserRole",
",",
"key",
")",
"self",
".",
"_items",
".",
"append",
"(",
"item",
")",
"self",
".",
"uiIOSRoutersTreeWidget",
".",
"setCurrentItem",
"(",
"item",
")"
] |
https://github.com/GNS3/gns3-gui/blob/da8adbaa18ab60e053af2a619efd468f4c8950f3/gns3/modules/dynamips/pages/ios_router_preferences_page.py#L134-L159
|
||
pabigot/pyxb
|
14737c23a125fd12c954823ad64fc4497816fae3
|
pyxb/binding/basis.py
|
python
|
simpleTypeDefinition._FacetMap
|
(cls)
|
return getattr(cls, cls.__FacetMapAttributeName())
|
Return a reference to the facet map for this datatype.
The facet map is a map from leaf facet classes to instances of those
classes that constrain or otherwise apply to the lexical or value
space of the datatype. Classes may inherit their facet map from their
superclass, or may create a new class instance if the class adds a new
constraint type.
@raise AttributeError: if the facet map has not been defined
|
Return a reference to the facet map for this datatype.
|
[
"Return",
"a",
"reference",
"to",
"the",
"facet",
"map",
"for",
"this",
"datatype",
"."
] |
def _FacetMap (cls):
"""Return a reference to the facet map for this datatype.
The facet map is a map from leaf facet classes to instances of those
classes that constrain or otherwise apply to the lexical or value
space of the datatype. Classes may inherit their facet map from their
superclass, or may create a new class instance if the class adds a new
constraint type.
@raise AttributeError: if the facet map has not been defined"""
return getattr(cls, cls.__FacetMapAttributeName())
|
[
"def",
"_FacetMap",
"(",
"cls",
")",
":",
"return",
"getattr",
"(",
"cls",
",",
"cls",
".",
"__FacetMapAttributeName",
"(",
")",
")"
] |
https://github.com/pabigot/pyxb/blob/14737c23a125fd12c954823ad64fc4497816fae3/pyxb/binding/basis.py#L787-L797
|
|
jazzband/django-oauth-toolkit
|
ac201526843ff63ad3861bb37e4099521cff091a
|
oauth2_provider/oauth2_backends.py
|
python
|
OAuthLibCore.authenticate_client
|
(self, request)
|
return self.server.request_validator.authenticate_client(oauth_request)
|
Wrapper to call `authenticate_client` on `server_class` instance.
:param request: The current django.http.HttpRequest object
|
Wrapper to call `authenticate_client` on `server_class` instance.
|
[
"Wrapper",
"to",
"call",
"authenticate_client",
"on",
"server_class",
"instance",
"."
] |
def authenticate_client(self, request):
"""Wrapper to call `authenticate_client` on `server_class` instance.
:param request: The current django.http.HttpRequest object
"""
uri, http_method, body, headers = self._extract_params(request)
oauth_request = OauthlibRequest(uri, http_method, body, headers)
return self.server.request_validator.authenticate_client(oauth_request)
|
[
"def",
"authenticate_client",
"(",
"self",
",",
"request",
")",
":",
"uri",
",",
"http_method",
",",
"body",
",",
"headers",
"=",
"self",
".",
"_extract_params",
"(",
"request",
")",
"oauth_request",
"=",
"OauthlibRequest",
"(",
"uri",
",",
"http_method",
",",
"body",
",",
"headers",
")",
"return",
"self",
".",
"server",
".",
"request_validator",
".",
"authenticate_client",
"(",
"oauth_request",
")"
] |
https://github.com/jazzband/django-oauth-toolkit/blob/ac201526843ff63ad3861bb37e4099521cff091a/oauth2_provider/oauth2_backends.py#L203-L210
|
|
TencentCloud/tencentcloud-sdk-python
|
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
|
tencentcloud/cfs/v20190719/models.py
|
python
|
CreateCfsPGroupResponse.__init__
|
(self)
|
r"""
:param PGroupId: 权限组 ID
:type PGroupId: str
:param Name: 权限组名字
:type Name: str
:param DescInfo: 权限组描述信息
:type DescInfo: str
:param BindCfsNum: 已经与该权限组绑定的文件系统个数
:type BindCfsNum: int
:param CDate: 权限组创建时间
:type CDate: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
|
r"""
:param PGroupId: 权限组 ID
:type PGroupId: str
:param Name: 权限组名字
:type Name: str
:param DescInfo: 权限组描述信息
:type DescInfo: str
:param BindCfsNum: 已经与该权限组绑定的文件系统个数
:type BindCfsNum: int
:param CDate: 权限组创建时间
:type CDate: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
|
[
"r",
":",
"param",
"PGroupId",
":",
"权限组",
"ID",
":",
"type",
"PGroupId",
":",
"str",
":",
"param",
"Name",
":",
"权限组名字",
":",
"type",
"Name",
":",
"str",
":",
"param",
"DescInfo",
":",
"权限组描述信息",
":",
"type",
"DescInfo",
":",
"str",
":",
"param",
"BindCfsNum",
":",
"已经与该权限组绑定的文件系统个数",
":",
"type",
"BindCfsNum",
":",
"int",
":",
"param",
"CDate",
":",
"权限组创建时间",
":",
"type",
"CDate",
":",
"str",
":",
"param",
"RequestId",
":",
"唯一请求",
"ID,每次请求都会返回。定位问题时需要提供该次请求的",
"RequestId。",
":",
"type",
"RequestId",
":",
"str"
] |
def __init__(self):
r"""
:param PGroupId: 权限组 ID
:type PGroupId: str
:param Name: 权限组名字
:type Name: str
:param DescInfo: 权限组描述信息
:type DescInfo: str
:param BindCfsNum: 已经与该权限组绑定的文件系统个数
:type BindCfsNum: int
:param CDate: 权限组创建时间
:type CDate: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.PGroupId = None
self.Name = None
self.DescInfo = None
self.BindCfsNum = None
self.CDate = None
self.RequestId = None
|
[
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"PGroupId",
"=",
"None",
"self",
".",
"Name",
"=",
"None",
"self",
".",
"DescInfo",
"=",
"None",
"self",
".",
"BindCfsNum",
"=",
"None",
"self",
".",
"CDate",
"=",
"None",
"self",
".",
"RequestId",
"=",
"None"
] |
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/cfs/v20190719/models.py#L339-L359
|
||
linxid/Machine_Learning_Study_Path
|
558e82d13237114bbb8152483977806fc0c222af
|
Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/_vendor/ipaddress.py
|
python
|
_compat_to_bytes
|
(intval, length, endianess)
|
[] |
def _compat_to_bytes(intval, length, endianess):
assert isinstance(intval, _compat_int_types)
assert endianess == 'big'
if length == 4:
if intval < 0 or intval >= 2 ** 32:
raise struct.error("integer out of range for 'I' format code")
return struct.pack(b'!I', intval)
elif length == 16:
if intval < 0 or intval >= 2 ** 128:
raise struct.error("integer out of range for 'QQ' format code")
return struct.pack(b'!QQ', intval >> 64, intval & 0xffffffffffffffff)
else:
raise NotImplementedError()
|
[
"def",
"_compat_to_bytes",
"(",
"intval",
",",
"length",
",",
"endianess",
")",
":",
"assert",
"isinstance",
"(",
"intval",
",",
"_compat_int_types",
")",
"assert",
"endianess",
"==",
"'big'",
"if",
"length",
"==",
"4",
":",
"if",
"intval",
"<",
"0",
"or",
"intval",
">=",
"2",
"**",
"32",
":",
"raise",
"struct",
".",
"error",
"(",
"\"integer out of range for 'I' format code\"",
")",
"return",
"struct",
".",
"pack",
"(",
"b'!I'",
",",
"intval",
")",
"elif",
"length",
"==",
"16",
":",
"if",
"intval",
"<",
"0",
"or",
"intval",
">=",
"2",
"**",
"128",
":",
"raise",
"struct",
".",
"error",
"(",
"\"integer out of range for 'QQ' format code\"",
")",
"return",
"struct",
".",
"pack",
"(",
"b'!QQ'",
",",
"intval",
">>",
"64",
",",
"intval",
"&",
"0xffffffffffffffff",
")",
"else",
":",
"raise",
"NotImplementedError",
"(",
")"
] |
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/_vendor/ipaddress.py#L48-L60
|
||||
bjmayor/hacker
|
e3ce2ad74839c2733b27dac6c0f495e0743e1866
|
venv/lib/python3.5/site-packages/pip/_vendor/cachecontrol/adapter.py
|
python
|
CacheControlAdapter.build_response
|
(self, request, response, from_cache=False)
|
return resp
|
Build a response by making a request or using the cache.
This will end up calling send and returning a potentially
cached response
|
Build a response by making a request or using the cache.
|
[
"Build",
"a",
"response",
"by",
"making",
"a",
"request",
"or",
"using",
"the",
"cache",
"."
] |
def build_response(self, request, response, from_cache=False):
"""
Build a response by making a request or using the cache.
This will end up calling send and returning a potentially
cached response
"""
if not from_cache and request.method == 'GET':
# Check for any heuristics that might update headers
# before trying to cache.
if self.heuristic:
response = self.heuristic.apply(response)
# apply any expiration heuristics
if response.status == 304:
# We must have sent an ETag request. This could mean
# that we've been expired already or that we simply
# have an etag. In either case, we want to try and
# update the cache if that is the case.
cached_response = self.controller.update_cached_response(
request, response
)
if cached_response is not response:
from_cache = True
# We are done with the server response, read a
# possible response body (compliant servers will
# not return one, but we cannot be 100% sure) and
# release the connection back to the pool.
response.read(decode_content=False)
response.release_conn()
response = cached_response
# We always cache the 301 responses
elif response.status == 301:
self.controller.cache_response(request, response)
else:
# Wrap the response file with a wrapper that will cache the
# response when the stream has been consumed.
response._fp = CallbackFileWrapper(
response._fp,
functools.partial(
self.controller.cache_response,
request,
response,
)
)
if response.chunked:
super_update_chunk_length = response._update_chunk_length
def _update_chunk_length(self):
super_update_chunk_length()
if self.chunk_left == 0:
self._fp._close()
response._update_chunk_length = types.MethodType(_update_chunk_length, response)
resp = super(CacheControlAdapter, self).build_response(
request, response
)
# See if we should invalidate the cache.
if request.method in self.invalidating_methods and resp.ok:
cache_url = self.controller.cache_url(request.url)
self.cache.delete(cache_url)
# Give the request a from_cache attr to let people use it
resp.from_cache = from_cache
return resp
|
[
"def",
"build_response",
"(",
"self",
",",
"request",
",",
"response",
",",
"from_cache",
"=",
"False",
")",
":",
"if",
"not",
"from_cache",
"and",
"request",
".",
"method",
"==",
"'GET'",
":",
"# Check for any heuristics that might update headers",
"# before trying to cache.",
"if",
"self",
".",
"heuristic",
":",
"response",
"=",
"self",
".",
"heuristic",
".",
"apply",
"(",
"response",
")",
"# apply any expiration heuristics",
"if",
"response",
".",
"status",
"==",
"304",
":",
"# We must have sent an ETag request. This could mean",
"# that we've been expired already or that we simply",
"# have an etag. In either case, we want to try and",
"# update the cache if that is the case.",
"cached_response",
"=",
"self",
".",
"controller",
".",
"update_cached_response",
"(",
"request",
",",
"response",
")",
"if",
"cached_response",
"is",
"not",
"response",
":",
"from_cache",
"=",
"True",
"# We are done with the server response, read a",
"# possible response body (compliant servers will",
"# not return one, but we cannot be 100% sure) and",
"# release the connection back to the pool.",
"response",
".",
"read",
"(",
"decode_content",
"=",
"False",
")",
"response",
".",
"release_conn",
"(",
")",
"response",
"=",
"cached_response",
"# We always cache the 301 responses",
"elif",
"response",
".",
"status",
"==",
"301",
":",
"self",
".",
"controller",
".",
"cache_response",
"(",
"request",
",",
"response",
")",
"else",
":",
"# Wrap the response file with a wrapper that will cache the",
"# response when the stream has been consumed.",
"response",
".",
"_fp",
"=",
"CallbackFileWrapper",
"(",
"response",
".",
"_fp",
",",
"functools",
".",
"partial",
"(",
"self",
".",
"controller",
".",
"cache_response",
",",
"request",
",",
"response",
",",
")",
")",
"if",
"response",
".",
"chunked",
":",
"super_update_chunk_length",
"=",
"response",
".",
"_update_chunk_length",
"def",
"_update_chunk_length",
"(",
"self",
")",
":",
"super_update_chunk_length",
"(",
")",
"if",
"self",
".",
"chunk_left",
"==",
"0",
":",
"self",
".",
"_fp",
".",
"_close",
"(",
")",
"response",
".",
"_update_chunk_length",
"=",
"types",
".",
"MethodType",
"(",
"_update_chunk_length",
",",
"response",
")",
"resp",
"=",
"super",
"(",
"CacheControlAdapter",
",",
"self",
")",
".",
"build_response",
"(",
"request",
",",
"response",
")",
"# See if we should invalidate the cache.",
"if",
"request",
".",
"method",
"in",
"self",
".",
"invalidating_methods",
"and",
"resp",
".",
"ok",
":",
"cache_url",
"=",
"self",
".",
"controller",
".",
"cache_url",
"(",
"request",
".",
"url",
")",
"self",
".",
"cache",
".",
"delete",
"(",
"cache_url",
")",
"# Give the request a from_cache attr to let people use it",
"resp",
".",
"from_cache",
"=",
"from_cache",
"return",
"resp"
] |
https://github.com/bjmayor/hacker/blob/e3ce2ad74839c2733b27dac6c0f495e0743e1866/venv/lib/python3.5/site-packages/pip/_vendor/cachecontrol/adapter.py#L51-L121
|
|
PixarAnimationStudios/OpenTimelineIO
|
990a54ccbe6488180a93753370fc87902b982962
|
src/opentimelineview/track_widgets.py
|
python
|
NestedItem.__init__
|
(self, *args, **kwargs)
|
[] |
def __init__(self, *args, **kwargs):
super(NestedItem, self).__init__(*args, **kwargs)
self.setBrush(
QtGui.QBrush(QtGui.QColor(255, 113, 91, 255))
)
self.source_name_label.setText(self.item.name)
|
[
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"NestedItem",
",",
"self",
")",
".",
"__init__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"setBrush",
"(",
"QtGui",
".",
"QBrush",
"(",
"QtGui",
".",
"QColor",
"(",
"255",
",",
"113",
",",
"91",
",",
"255",
")",
")",
")",
"self",
".",
"source_name_label",
".",
"setText",
"(",
"self",
".",
"item",
".",
"name",
")"
] |
https://github.com/PixarAnimationStudios/OpenTimelineIO/blob/990a54ccbe6488180a93753370fc87902b982962/src/opentimelineview/track_widgets.py#L421-L427
|
||||
sagemath/sage
|
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
|
src/sage/algebras/orlik_terao.py
|
python
|
OrlikTeraoAlgebra.__classcall_private__
|
(cls, R, M, ordering=None)
|
return super(OrlikTeraoAlgebra, cls).__classcall__(cls, R, M, tuple(ordering))
|
Normalize input to ensure a unique representation.
EXAMPLES::
sage: M = matroids.Wheel(3)
sage: from sage.algebras.orlik_terao import OrlikTeraoAlgebra
sage: OT1 = algebras.OrlikTerao(QQ, M)
sage: OT2 = OrlikTeraoAlgebra(QQ, M, ordering=(0,1,2,3,4,5))
sage: OT3 = OrlikTeraoAlgebra(QQ, M, ordering=[0,1,2,3,4,5])
sage: OT1 is OT2 and OT2 is OT3
True
|
Normalize input to ensure a unique representation.
|
[
"Normalize",
"input",
"to",
"ensure",
"a",
"unique",
"representation",
"."
] |
def __classcall_private__(cls, R, M, ordering=None):
"""
Normalize input to ensure a unique representation.
EXAMPLES::
sage: M = matroids.Wheel(3)
sage: from sage.algebras.orlik_terao import OrlikTeraoAlgebra
sage: OT1 = algebras.OrlikTerao(QQ, M)
sage: OT2 = OrlikTeraoAlgebra(QQ, M, ordering=(0,1,2,3,4,5))
sage: OT3 = OrlikTeraoAlgebra(QQ, M, ordering=[0,1,2,3,4,5])
sage: OT1 is OT2 and OT2 is OT3
True
"""
if ordering is None:
ordering = sorted(M.groundset())
return super(OrlikTeraoAlgebra, cls).__classcall__(cls, R, M, tuple(ordering))
|
[
"def",
"__classcall_private__",
"(",
"cls",
",",
"R",
",",
"M",
",",
"ordering",
"=",
"None",
")",
":",
"if",
"ordering",
"is",
"None",
":",
"ordering",
"=",
"sorted",
"(",
"M",
".",
"groundset",
"(",
")",
")",
"return",
"super",
"(",
"OrlikTeraoAlgebra",
",",
"cls",
")",
".",
"__classcall__",
"(",
"cls",
",",
"R",
",",
"M",
",",
"tuple",
"(",
"ordering",
")",
")"
] |
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/algebras/orlik_terao.py#L105-L121
|
|
mdiazcl/fuzzbunch-debian
|
2b76c2249ade83a389ae3badb12a1bd09901fd2c
|
windows/Resources/Python/Core/Lib/collections.py
|
python
|
Counter.__init__
|
(self, iterable=None, **kwds)
|
Create a new, empty Counter object. And if given, count elements
from an input iterable. Or, initialize the count from another mapping
of elements to their counts.
>>> c = Counter() # a new, empty counter
>>> c = Counter('gallahad') # a new counter from an iterable
>>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping
>>> c = Counter(a=4, b=2) # a new counter from keyword args
|
Create a new, empty Counter object. And if given, count elements
from an input iterable. Or, initialize the count from another mapping
of elements to their counts.
>>> c = Counter() # a new, empty counter
>>> c = Counter('gallahad') # a new counter from an iterable
>>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping
>>> c = Counter(a=4, b=2) # a new counter from keyword args
|
[
"Create",
"a",
"new",
"empty",
"Counter",
"object",
".",
"And",
"if",
"given",
"count",
"elements",
"from",
"an",
"input",
"iterable",
".",
"Or",
"initialize",
"the",
"count",
"from",
"another",
"mapping",
"of",
"elements",
"to",
"their",
"counts",
".",
">>>",
"c",
"=",
"Counter",
"()",
"#",
"a",
"new",
"empty",
"counter",
">>>",
"c",
"=",
"Counter",
"(",
"gallahad",
")",
"#",
"a",
"new",
"counter",
"from",
"an",
"iterable",
">>>",
"c",
"=",
"Counter",
"(",
"{",
"a",
":",
"4",
"b",
":",
"2",
"}",
")",
"#",
"a",
"new",
"counter",
"from",
"a",
"mapping",
">>>",
"c",
"=",
"Counter",
"(",
"a",
"=",
"4",
"b",
"=",
"2",
")",
"#",
"a",
"new",
"counter",
"from",
"keyword",
"args"
] |
def __init__(self, iterable=None, **kwds):
"""Create a new, empty Counter object. And if given, count elements
from an input iterable. Or, initialize the count from another mapping
of elements to their counts.
>>> c = Counter() # a new, empty counter
>>> c = Counter('gallahad') # a new counter from an iterable
>>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping
>>> c = Counter(a=4, b=2) # a new counter from keyword args
"""
super(Counter, self).__init__()
self.update(iterable, **kwds)
|
[
"def",
"__init__",
"(",
"self",
",",
"iterable",
"=",
"None",
",",
"*",
"*",
"kwds",
")",
":",
"super",
"(",
"Counter",
",",
"self",
")",
".",
"__init__",
"(",
")",
"self",
".",
"update",
"(",
"iterable",
",",
"*",
"*",
"kwds",
")"
] |
https://github.com/mdiazcl/fuzzbunch-debian/blob/2b76c2249ade83a389ae3badb12a1bd09901fd2c/windows/Resources/Python/Core/Lib/collections.py#L339-L351
|
||
mkusner/grammarVAE
|
ffffe272a8cf1772578dfc92254c55c224cddc02
|
Theano-master/theano/tensor/inplace.py
|
python
|
maximum_inplace
|
(a, b)
|
elementwise addition (inplace on `a`)
|
elementwise addition (inplace on `a`)
|
[
"elementwise",
"addition",
"(",
"inplace",
"on",
"a",
")"
] |
def maximum_inplace(a, b):
"""elementwise addition (inplace on `a`)"""
|
[
"def",
"maximum_inplace",
"(",
"a",
",",
"b",
")",
":"
] |
https://github.com/mkusner/grammarVAE/blob/ffffe272a8cf1772578dfc92254c55c224cddc02/Theano-master/theano/tensor/inplace.py#L307-L308
|
||
dimagi/commcare-hq
|
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
|
corehq/apps/enterprise/views.py
|
python
|
enterprise_settings
|
(request, domain)
|
return render(request, "enterprise/enterprise_settings.html", context)
|
[] |
def enterprise_settings(request, domain):
export_settings = get_default_export_settings_if_available(domain)
if request.method == 'POST':
form = EnterpriseSettingsForm(request.POST, domain=domain, account=request.account,
username=request.user.username, export_settings=export_settings)
else:
form = EnterpriseSettingsForm(domain=domain, account=request.account, username=request.user.username,
export_settings=export_settings)
context = {
'account': request.account,
'accounts_email': settings.ACCOUNTS_EMAIL,
'domain': domain,
'restrict_signup': request.POST.get('restrict_signup', request.account.restrict_signup),
'current_page': {
'title': _('Enterprise Settings'),
'page_name': _('Enterprise Settings'),
},
'settings_form': form,
}
return render(request, "enterprise/enterprise_settings.html", context)
|
[
"def",
"enterprise_settings",
"(",
"request",
",",
"domain",
")",
":",
"export_settings",
"=",
"get_default_export_settings_if_available",
"(",
"domain",
")",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"form",
"=",
"EnterpriseSettingsForm",
"(",
"request",
".",
"POST",
",",
"domain",
"=",
"domain",
",",
"account",
"=",
"request",
".",
"account",
",",
"username",
"=",
"request",
".",
"user",
".",
"username",
",",
"export_settings",
"=",
"export_settings",
")",
"else",
":",
"form",
"=",
"EnterpriseSettingsForm",
"(",
"domain",
"=",
"domain",
",",
"account",
"=",
"request",
".",
"account",
",",
"username",
"=",
"request",
".",
"user",
".",
"username",
",",
"export_settings",
"=",
"export_settings",
")",
"context",
"=",
"{",
"'account'",
":",
"request",
".",
"account",
",",
"'accounts_email'",
":",
"settings",
".",
"ACCOUNTS_EMAIL",
",",
"'domain'",
":",
"domain",
",",
"'restrict_signup'",
":",
"request",
".",
"POST",
".",
"get",
"(",
"'restrict_signup'",
",",
"request",
".",
"account",
".",
"restrict_signup",
")",
",",
"'current_page'",
":",
"{",
"'title'",
":",
"_",
"(",
"'Enterprise Settings'",
")",
",",
"'page_name'",
":",
"_",
"(",
"'Enterprise Settings'",
")",
",",
"}",
",",
"'settings_form'",
":",
"form",
",",
"}",
"return",
"render",
"(",
"request",
",",
"\"enterprise/enterprise_settings.html\"",
",",
"context",
")"
] |
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/enterprise/views.py#L123-L144
|
|||
cowrie/cowrie
|
86488fa4eed1559574653eee4c76b4a33d1b42db
|
src/cowrie/shell/protocol.py
|
python
|
HoneyPotBaseProtocol.logDispatch
|
(self, **args)
|
Send log directly to factory, avoiding normal log dispatch
|
Send log directly to factory, avoiding normal log dispatch
|
[
"Send",
"log",
"directly",
"to",
"factory",
"avoiding",
"normal",
"log",
"dispatch"
] |
def logDispatch(self, **args):
"""
Send log directly to factory, avoiding normal log dispatch
"""
args["sessionno"] = self.sessionno
self.factory.logDispatch(**args)
|
[
"def",
"logDispatch",
"(",
"self",
",",
"*",
"*",
"args",
")",
":",
"args",
"[",
"\"sessionno\"",
"]",
"=",
"self",
".",
"sessionno",
"self",
".",
"factory",
".",
"logDispatch",
"(",
"*",
"*",
"args",
")"
] |
https://github.com/cowrie/cowrie/blob/86488fa4eed1559574653eee4c76b4a33d1b42db/src/cowrie/shell/protocol.py#L78-L83
|
||
openstack/taskflow
|
38b9011094dbcfdd00e6446393816201e8256d38
|
taskflow/types/failure.py
|
python
|
Failure.reraise
|
(self)
|
Re-raise captured exception.
|
Re-raise captured exception.
|
[
"Re",
"-",
"raise",
"captured",
"exception",
"."
] |
def reraise(self):
"""Re-raise captured exception."""
if self._exc_info:
six.reraise(*self._exc_info)
else:
raise exc.WrappedFailure([self])
|
[
"def",
"reraise",
"(",
"self",
")",
":",
"if",
"self",
".",
"_exc_info",
":",
"six",
".",
"reraise",
"(",
"*",
"self",
".",
"_exc_info",
")",
"else",
":",
"raise",
"exc",
".",
"WrappedFailure",
"(",
"[",
"self",
"]",
")"
] |
https://github.com/openstack/taskflow/blob/38b9011094dbcfdd00e6446393816201e8256d38/taskflow/types/failure.py#L343-L348
|
||
quodlibet/mutagen
|
399513b167ed00c4b7a9ef98dfe591a276efb701
|
mutagen/_iff.py
|
python
|
IffFile.__contains__
|
(self, id_)
|
return id_ in self.root
|
Check if the IFF file contains a specific chunk
|
Check if the IFF file contains a specific chunk
|
[
"Check",
"if",
"the",
"IFF",
"file",
"contains",
"a",
"specific",
"chunk"
] |
def __contains__(self, id_):
"""Check if the IFF file contains a specific chunk"""
return id_ in self.root
|
[
"def",
"__contains__",
"(",
"self",
",",
"id_",
")",
":",
"return",
"id_",
"in",
"self",
".",
"root"
] |
https://github.com/quodlibet/mutagen/blob/399513b167ed00c4b7a9ef98dfe591a276efb701/mutagen/_iff.py#L319-L321
|
|
sarumont/py-trello
|
c711809a076aee3fc04784e26e6b0b9688229ebd
|
trello/card.py
|
python
|
Card.listCardMove_date
|
(self)
|
return self._list_movements(movement_function=Card._movement_as_triplet)
|
Will return the history of transitions of a card from one list to
another. The lower the index the more recent the historical item.
It returns a list of lists. The sublists are triplets of
starting list, ending list and when the transition occurred.
|
Will return the history of transitions of a card from one list to
another. The lower the index the more recent the historical item.
|
[
"Will",
"return",
"the",
"history",
"of",
"transitions",
"of",
"a",
"card",
"from",
"one",
"list",
"to",
"another",
".",
"The",
"lower",
"the",
"index",
"the",
"more",
"recent",
"the",
"historical",
"item",
"."
] |
def listCardMove_date(self):
"""Will return the history of transitions of a card from one list to
another. The lower the index the more recent the historical item.
It returns a list of lists. The sublists are triplets of
starting list, ending list and when the transition occurred.
"""
return self._list_movements(movement_function=Card._movement_as_triplet)
|
[
"def",
"listCardMove_date",
"(",
"self",
")",
":",
"return",
"self",
".",
"_list_movements",
"(",
"movement_function",
"=",
"Card",
".",
"_movement_as_triplet",
")"
] |
https://github.com/sarumont/py-trello/blob/c711809a076aee3fc04784e26e6b0b9688229ebd/trello/card.py#L347-L354
|
|
larryhastings/gilectomy
|
4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a
|
Lib/logging/config.py
|
python
|
DictConfigurator.configure_filter
|
(self, config)
|
return result
|
Configure a filter from a dictionary.
|
Configure a filter from a dictionary.
|
[
"Configure",
"a",
"filter",
"from",
"a",
"dictionary",
"."
] |
def configure_filter(self, config):
"""Configure a filter from a dictionary."""
if '()' in config:
result = self.configure_custom(config)
else:
name = config.get('name', '')
result = logging.Filter(name)
return result
|
[
"def",
"configure_filter",
"(",
"self",
",",
"config",
")",
":",
"if",
"'()'",
"in",
"config",
":",
"result",
"=",
"self",
".",
"configure_custom",
"(",
"config",
")",
"else",
":",
"name",
"=",
"config",
".",
"get",
"(",
"'name'",
",",
"''",
")",
"result",
"=",
"logging",
".",
"Filter",
"(",
"name",
")",
"return",
"result"
] |
https://github.com/larryhastings/gilectomy/blob/4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a/Lib/logging/config.py#L672-L679
|
|
buke/GreenOdoo
|
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
|
runtime/common/lib/python2.7/site-packages/libxml2.py
|
python
|
xmlDoc.validateOneAttribute
|
(self, ctxt, elem, attr, value)
|
return ret
|
Try to validate a single attribute for an element basically
it does the following checks as described by the XML-1.0
recommendation: - [ VC: Attribute Value Type ] - [ VC:
Fixed Attribute Default ] - [ VC: Entity Name ] - [ VC:
Name Token ] - [ VC: ID ] - [ VC: IDREF ] - [ VC: Entity
Name ] - [ VC: Notation Attributes ] The ID/IDREF
uniqueness and matching are done separately
|
Try to validate a single attribute for an element basically
it does the following checks as described by the XML-1.0
recommendation: - [ VC: Attribute Value Type ] - [ VC:
Fixed Attribute Default ] - [ VC: Entity Name ] - [ VC:
Name Token ] - [ VC: ID ] - [ VC: IDREF ] - [ VC: Entity
Name ] - [ VC: Notation Attributes ] The ID/IDREF
uniqueness and matching are done separately
|
[
"Try",
"to",
"validate",
"a",
"single",
"attribute",
"for",
"an",
"element",
"basically",
"it",
"does",
"the",
"following",
"checks",
"as",
"described",
"by",
"the",
"XML",
"-",
"1",
".",
"0",
"recommendation",
":",
"-",
"[",
"VC",
":",
"Attribute",
"Value",
"Type",
"]",
"-",
"[",
"VC",
":",
"Fixed",
"Attribute",
"Default",
"]",
"-",
"[",
"VC",
":",
"Entity",
"Name",
"]",
"-",
"[",
"VC",
":",
"Name",
"Token",
"]",
"-",
"[",
"VC",
":",
"ID",
"]",
"-",
"[",
"VC",
":",
"IDREF",
"]",
"-",
"[",
"VC",
":",
"Entity",
"Name",
"]",
"-",
"[",
"VC",
":",
"Notation",
"Attributes",
"]",
"The",
"ID",
"/",
"IDREF",
"uniqueness",
"and",
"matching",
"are",
"done",
"separately"
] |
def validateOneAttribute(self, ctxt, elem, attr, value):
"""Try to validate a single attribute for an element basically
it does the following checks as described by the XML-1.0
recommendation: - [ VC: Attribute Value Type ] - [ VC:
Fixed Attribute Default ] - [ VC: Entity Name ] - [ VC:
Name Token ] - [ VC: ID ] - [ VC: IDREF ] - [ VC: Entity
Name ] - [ VC: Notation Attributes ] The ID/IDREF
uniqueness and matching are done separately """
if ctxt is None: ctxt__o = None
else: ctxt__o = ctxt._o
if elem is None: elem__o = None
else: elem__o = elem._o
if attr is None: attr__o = None
else: attr__o = attr._o
ret = libxml2mod.xmlValidateOneAttribute(ctxt__o, self._o, elem__o, attr__o, value)
return ret
|
[
"def",
"validateOneAttribute",
"(",
"self",
",",
"ctxt",
",",
"elem",
",",
"attr",
",",
"value",
")",
":",
"if",
"ctxt",
"is",
"None",
":",
"ctxt__o",
"=",
"None",
"else",
":",
"ctxt__o",
"=",
"ctxt",
".",
"_o",
"if",
"elem",
"is",
"None",
":",
"elem__o",
"=",
"None",
"else",
":",
"elem__o",
"=",
"elem",
".",
"_o",
"if",
"attr",
"is",
"None",
":",
"attr__o",
"=",
"None",
"else",
":",
"attr__o",
"=",
"attr",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlValidateOneAttribute",
"(",
"ctxt__o",
",",
"self",
".",
"_o",
",",
"elem__o",
",",
"attr__o",
",",
"value",
")",
"return",
"ret"
] |
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/common/lib/python2.7/site-packages/libxml2.py#L4670-L4685
|
|
textX/Arpeggio
|
9ec6c7ee402054616b2f81e76557d39d3d376fcd
|
arpeggio/cleanpeg.py
|
python
|
str_match
|
()
|
return _(r'''(?s)('[^'\\]*(?:\\.[^'\\]*)*')|'''
r'''("[^"\\]*(?:\\.[^"\\]*)*")''')
|
[] |
def str_match(): return _(r'''(?s)('[^'\\]*(?:\\.[^'\\]*)*')|'''
r'''("[^"\\]*(?:\\.[^"\\]*)*")''')
|
[
"def",
"str_match",
"(",
")",
":",
"return",
"_",
"(",
"r'''(?s)('[^'\\\\]*(?:\\\\.[^'\\\\]*)*')|'''",
"r'''(\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\")'''",
")"
] |
https://github.com/textX/Arpeggio/blob/9ec6c7ee402054616b2f81e76557d39d3d376fcd/arpeggio/cleanpeg.py#L53-L54
|
|||
n1nj4sec/pupy
|
a5d766ea81fdfe3bc2c38c9bdaf10e9b75af3b39
|
pupy/network/lib/picocmd/picocmd.py
|
python
|
OnlineStatusRequest.unpack
|
(data)
|
return OnlineStatusRequest(), 0
|
[] |
def unpack(data):
return OnlineStatusRequest(), 0
|
[
"def",
"unpack",
"(",
"data",
")",
":",
"return",
"OnlineStatusRequest",
"(",
")",
",",
"0"
] |
https://github.com/n1nj4sec/pupy/blob/a5d766ea81fdfe3bc2c38c9bdaf10e9b75af3b39/pupy/network/lib/picocmd/picocmd.py#L1045-L1046
|
|||
apple/ccs-calendarserver
|
13c706b985fb728b9aab42dc0fef85aae21921c3
|
calendarserver/tap/caldav.py
|
python
|
conflictBetweenIPv4AndIPv6
|
()
|
Is there a conflict between binding an IPv6 and an IPv4 port? Return True
if there is, False if there isn't.
This is a temporary workaround until maybe Twisted starts setting
C{IPPROTO_IPV6 / IPV6_V6ONLY} on IPv6 sockets.
@return: C{True} if listening on IPv4 conflicts with listening on IPv6.
|
Is there a conflict between binding an IPv6 and an IPv4 port? Return True
if there is, False if there isn't.
|
[
"Is",
"there",
"a",
"conflict",
"between",
"binding",
"an",
"IPv6",
"and",
"an",
"IPv4",
"port?",
"Return",
"True",
"if",
"there",
"is",
"False",
"if",
"there",
"isn",
"t",
"."
] |
def conflictBetweenIPv4AndIPv6():
"""
Is there a conflict between binding an IPv6 and an IPv4 port? Return True
if there is, False if there isn't.
This is a temporary workaround until maybe Twisted starts setting
C{IPPROTO_IPV6 / IPV6_V6ONLY} on IPv6 sockets.
@return: C{True} if listening on IPv4 conflicts with listening on IPv6.
"""
s4 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s6 = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
try:
s4.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s6.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s4.bind(("", 0))
s4.listen(1)
usedport = s4.getsockname()[1]
try:
s6.bind(("::", usedport))
except socket.error:
return True
else:
return False
finally:
s4.close()
s6.close()
|
[
"def",
"conflictBetweenIPv4AndIPv6",
"(",
")",
":",
"s4",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"s6",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET6",
",",
"socket",
".",
"SOCK_STREAM",
")",
"try",
":",
"s4",
".",
"setsockopt",
"(",
"socket",
".",
"SOL_SOCKET",
",",
"socket",
".",
"SO_REUSEADDR",
",",
"1",
")",
"s6",
".",
"setsockopt",
"(",
"socket",
".",
"SOL_SOCKET",
",",
"socket",
".",
"SO_REUSEADDR",
",",
"1",
")",
"s4",
".",
"bind",
"(",
"(",
"\"\"",
",",
"0",
")",
")",
"s4",
".",
"listen",
"(",
"1",
")",
"usedport",
"=",
"s4",
".",
"getsockname",
"(",
")",
"[",
"1",
"]",
"try",
":",
"s6",
".",
"bind",
"(",
"(",
"\"::\"",
",",
"usedport",
")",
")",
"except",
"socket",
".",
"error",
":",
"return",
"True",
"else",
":",
"return",
"False",
"finally",
":",
"s4",
".",
"close",
"(",
")",
"s6",
".",
"close",
"(",
")"
] |
https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/calendarserver/tap/caldav.py#L158-L184
|
||
spyder-ide/spyder
|
55da47c032dfcf519600f67f8b30eab467f965e7
|
spyder/plugins/editor/widgets/editorstack_helpers.py
|
python
|
FileInfo.run_todo_finder
|
(self)
|
Run TODO finder.
|
Run TODO finder.
|
[
"Run",
"TODO",
"finder",
"."
] |
def run_todo_finder(self):
"""Run TODO finder."""
if self.editor.is_python_or_ipython():
self.threadmanager.add_thread(find_tasks,
self.todo_finished,
self.get_source_code(), self)
|
[
"def",
"run_todo_finder",
"(",
"self",
")",
":",
"if",
"self",
".",
"editor",
".",
"is_python_or_ipython",
"(",
")",
":",
"self",
".",
"threadmanager",
".",
"add_thread",
"(",
"find_tasks",
",",
"self",
".",
"todo_finished",
",",
"self",
".",
"get_source_code",
"(",
")",
",",
"self",
")"
] |
https://github.com/spyder-ide/spyder/blob/55da47c032dfcf519600f67f8b30eab467f965e7/spyder/plugins/editor/widgets/editorstack_helpers.py#L171-L176
|
||
rowanz/r2c
|
77813d9e335711759c25df79c348a7c2a8275d72
|
dataloaders/vcr.py
|
python
|
VCR.__init__
|
(self, split, mode, only_use_relevant_dets=True, add_image_as_a_box=True, embs_to_load='bert_da',
conditioned_answer_choice=0)
|
:param split: train, val, or test
:param mode: answer or rationale
:param only_use_relevant_dets: True, if we will only use the detections mentioned in the question and answer.
False, if we should use all detections.
:param add_image_as_a_box: True to add the image in as an additional 'detection'. It'll go first in the list
of objects.
:param embs_to_load: Which precomputed embeddings to load.
:param conditioned_answer_choice: If you're in test mode, the answer labels aren't provided, which could be
a problem for the QA->R task. Pass in 'conditioned_answer_choice=i'
to always condition on the i-th answer.
|
[] |
def __init__(self, split, mode, only_use_relevant_dets=True, add_image_as_a_box=True, embs_to_load='bert_da',
conditioned_answer_choice=0):
"""
:param split: train, val, or test
:param mode: answer or rationale
:param only_use_relevant_dets: True, if we will only use the detections mentioned in the question and answer.
False, if we should use all detections.
:param add_image_as_a_box: True to add the image in as an additional 'detection'. It'll go first in the list
of objects.
:param embs_to_load: Which precomputed embeddings to load.
:param conditioned_answer_choice: If you're in test mode, the answer labels aren't provided, which could be
a problem for the QA->R task. Pass in 'conditioned_answer_choice=i'
to always condition on the i-th answer.
"""
self.split = split
self.mode = mode
self.only_use_relevant_dets = only_use_relevant_dets
print("Only relevant dets" if only_use_relevant_dets else "Using all detections", flush=True)
self.add_image_as_a_box = add_image_as_a_box
self.conditioned_answer_choice = conditioned_answer_choice
with open(os.path.join(VCR_ANNOTS_DIR, '{}.jsonl'.format(split)), 'r') as f:
self.items = [json.loads(s) for s in f]
if split not in ('test', 'train', 'val'):
raise ValueError("Mode must be in test, train, or val. Supplied {}".format(mode))
if mode not in ('answer', 'rationale'):
raise ValueError("split must be answer or rationale")
self.token_indexers = {'elmo': ELMoTokenCharactersIndexer()}
self.vocab = Vocabulary()
with open(os.path.join(os.path.dirname(VCR_ANNOTS_DIR), 'dataloaders', 'cocoontology.json'), 'r') as f:
coco = json.load(f)
self.coco_objects = ['__background__'] + [x['name'] for k, x in sorted(coco.items(), key=lambda x: int(x[0]))]
self.coco_obj_to_ind = {o: i for i, o in enumerate(self.coco_objects)}
self.embs_to_load = embs_to_load
self.h5fn = os.path.join(VCR_ANNOTS_DIR, f'{self.embs_to_load}_{self.mode}_{self.split}.h5')
print("Loading embeddings from {}".format(self.h5fn), flush=True)
|
[
"def",
"__init__",
"(",
"self",
",",
"split",
",",
"mode",
",",
"only_use_relevant_dets",
"=",
"True",
",",
"add_image_as_a_box",
"=",
"True",
",",
"embs_to_load",
"=",
"'bert_da'",
",",
"conditioned_answer_choice",
"=",
"0",
")",
":",
"self",
".",
"split",
"=",
"split",
"self",
".",
"mode",
"=",
"mode",
"self",
".",
"only_use_relevant_dets",
"=",
"only_use_relevant_dets",
"print",
"(",
"\"Only relevant dets\"",
"if",
"only_use_relevant_dets",
"else",
"\"Using all detections\"",
",",
"flush",
"=",
"True",
")",
"self",
".",
"add_image_as_a_box",
"=",
"add_image_as_a_box",
"self",
".",
"conditioned_answer_choice",
"=",
"conditioned_answer_choice",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"VCR_ANNOTS_DIR",
",",
"'{}.jsonl'",
".",
"format",
"(",
"split",
")",
")",
",",
"'r'",
")",
"as",
"f",
":",
"self",
".",
"items",
"=",
"[",
"json",
".",
"loads",
"(",
"s",
")",
"for",
"s",
"in",
"f",
"]",
"if",
"split",
"not",
"in",
"(",
"'test'",
",",
"'train'",
",",
"'val'",
")",
":",
"raise",
"ValueError",
"(",
"\"Mode must be in test, train, or val. Supplied {}\"",
".",
"format",
"(",
"mode",
")",
")",
"if",
"mode",
"not",
"in",
"(",
"'answer'",
",",
"'rationale'",
")",
":",
"raise",
"ValueError",
"(",
"\"split must be answer or rationale\"",
")",
"self",
".",
"token_indexers",
"=",
"{",
"'elmo'",
":",
"ELMoTokenCharactersIndexer",
"(",
")",
"}",
"self",
".",
"vocab",
"=",
"Vocabulary",
"(",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"VCR_ANNOTS_DIR",
")",
",",
"'dataloaders'",
",",
"'cocoontology.json'",
")",
",",
"'r'",
")",
"as",
"f",
":",
"coco",
"=",
"json",
".",
"load",
"(",
"f",
")",
"self",
".",
"coco_objects",
"=",
"[",
"'__background__'",
"]",
"+",
"[",
"x",
"[",
"'name'",
"]",
"for",
"k",
",",
"x",
"in",
"sorted",
"(",
"coco",
".",
"items",
"(",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"int",
"(",
"x",
"[",
"0",
"]",
")",
")",
"]",
"self",
".",
"coco_obj_to_ind",
"=",
"{",
"o",
":",
"i",
"for",
"i",
",",
"o",
"in",
"enumerate",
"(",
"self",
".",
"coco_objects",
")",
"}",
"self",
".",
"embs_to_load",
"=",
"embs_to_load",
"self",
".",
"h5fn",
"=",
"os",
".",
"path",
".",
"join",
"(",
"VCR_ANNOTS_DIR",
",",
"f'{self.embs_to_load}_{self.mode}_{self.split}.h5'",
")",
"print",
"(",
"\"Loading embeddings from {}\"",
".",
"format",
"(",
"self",
".",
"h5fn",
")",
",",
"flush",
"=",
"True",
")"
] |
https://github.com/rowanz/r2c/blob/77813d9e335711759c25df79c348a7c2a8275d72/dataloaders/vcr.py#L99-L141
|
|||
leancloud/satori
|
701caccbd4fe45765001ca60435c0cb499477c03
|
satori-rules/plugin/libs/urllib3/packages/six.py
|
python
|
_LazyDescr.__get__
|
(self, obj, tp)
|
return result
|
[] |
def __get__(self, obj, tp):
result = self._resolve()
setattr(obj, self.name, result) # Invokes __set__.
try:
# This is a bit ugly, but it avoids running this again by
# removing this descriptor.
delattr(obj.__class__, self.name)
except AttributeError:
pass
return result
|
[
"def",
"__get__",
"(",
"self",
",",
"obj",
",",
"tp",
")",
":",
"result",
"=",
"self",
".",
"_resolve",
"(",
")",
"setattr",
"(",
"obj",
",",
"self",
".",
"name",
",",
"result",
")",
"# Invokes __set__.",
"try",
":",
"# This is a bit ugly, but it avoids running this again by",
"# removing this descriptor.",
"delattr",
"(",
"obj",
".",
"__class__",
",",
"self",
".",
"name",
")",
"except",
"AttributeError",
":",
"pass",
"return",
"result"
] |
https://github.com/leancloud/satori/blob/701caccbd4fe45765001ca60435c0cb499477c03/satori-rules/plugin/libs/urllib3/packages/six.py#L91-L100
|
|||
zhl2008/awd-platform
|
0416b31abea29743387b10b3914581fbe8e7da5e
|
web_flaskbb/Python-2.7.9/Lib/plat-irix6/WAIT.py
|
python
|
WEXITSTATUS
|
(stat)
|
return ((_W_INT(stat)>>8)&0377)
|
[] |
def WEXITSTATUS(stat): return ((_W_INT(stat)>>8)&0377)
|
[
"def",
"WEXITSTATUS",
"(",
"stat",
")",
":",
"return",
"(",
"(",
"_W_INT",
"(",
"stat",
")",
">>",
"8",
")",
"&",
"0377",
")"
] |
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/plat-irix6/WAIT.py#L14-L14
|
|||
tomplus/kubernetes_asyncio
|
f028cc793e3a2c519be6a52a49fb77ff0b014c9b
|
kubernetes_asyncio/client/models/v1_client_ip_config.py
|
python
|
V1ClientIPConfig.__eq__
|
(self, other)
|
return self.to_dict() == other.to_dict()
|
Returns true if both objects are equal
|
Returns true if both objects are equal
|
[
"Returns",
"true",
"if",
"both",
"objects",
"are",
"equal"
] |
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1ClientIPConfig):
return False
return self.to_dict() == other.to_dict()
|
[
"def",
"__eq__",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"V1ClientIPConfig",
")",
":",
"return",
"False",
"return",
"self",
".",
"to_dict",
"(",
")",
"==",
"other",
".",
"to_dict",
"(",
")"
] |
https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/models/v1_client_ip_config.py#L110-L115
|
|
AmesCornish/buttersink
|
5cc37e30d9f8071fcf3497dca8b8a91b910321ea
|
buttersink/btrfslist.py
|
python
|
main
|
()
|
return 0
|
Main program.
|
Main program.
|
[
"Main",
"program",
"."
] |
def main():
""" Main program. """
args = command.parse_args()
with btrfs.FileSystem(args.dir) as mount:
# mount.rescanSizes()
fInfo = mount.FS_INFO()
pprint.pprint(fInfo)
vols = mount.subvolumes
# for dev in mount.devices:
# pprint.pprint(dev)
for vol in vols:
print(vol)
return 0
|
[
"def",
"main",
"(",
")",
":",
"args",
"=",
"command",
".",
"parse_args",
"(",
")",
"with",
"btrfs",
".",
"FileSystem",
"(",
"args",
".",
"dir",
")",
"as",
"mount",
":",
"# mount.rescanSizes()",
"fInfo",
"=",
"mount",
".",
"FS_INFO",
"(",
")",
"pprint",
".",
"pprint",
"(",
"fInfo",
")",
"vols",
"=",
"mount",
".",
"subvolumes",
"# for dev in mount.devices:",
"# pprint.pprint(dev)",
"for",
"vol",
"in",
"vols",
":",
"print",
"(",
"vol",
")",
"return",
"0"
] |
https://github.com/AmesCornish/buttersink/blob/5cc37e30d9f8071fcf3497dca8b8a91b910321ea/buttersink/btrfslist.py#L44-L62
|
|
Nuitka/Nuitka
|
39262276993757fa4e299f497654065600453fc9
|
nuitka/build/inline_copy/jinja2_35/jinja2/runtime.py
|
python
|
Context.super
|
(self, name, current)
|
return BlockReference(name, self, blocks, index)
|
Render a parent block.
|
Render a parent block.
|
[
"Render",
"a",
"parent",
"block",
"."
] |
def super(self, name, current):
"""Render a parent block."""
try:
blocks = self.blocks[name]
index = blocks.index(current) + 1
blocks[index]
except LookupError:
return self.environment.undefined('there is no parent block '
'called %r.' % name,
name='super')
return BlockReference(name, self, blocks, index)
|
[
"def",
"super",
"(",
"self",
",",
"name",
",",
"current",
")",
":",
"try",
":",
"blocks",
"=",
"self",
".",
"blocks",
"[",
"name",
"]",
"index",
"=",
"blocks",
".",
"index",
"(",
"current",
")",
"+",
"1",
"blocks",
"[",
"index",
"]",
"except",
"LookupError",
":",
"return",
"self",
".",
"environment",
".",
"undefined",
"(",
"'there is no parent block '",
"'called %r.'",
"%",
"name",
",",
"name",
"=",
"'super'",
")",
"return",
"BlockReference",
"(",
"name",
",",
"self",
",",
"blocks",
",",
"index",
")"
] |
https://github.com/Nuitka/Nuitka/blob/39262276993757fa4e299f497654065600453fc9/nuitka/build/inline_copy/jinja2_35/jinja2/runtime.py#L175-L185
|
|
devassistant/devassistant
|
2dbfeaa666a64127263664d18969c55d19ecc83e
|
devassistant/yaml_assistant_loader.py
|
python
|
YamlAssistantLoader.assistant_from_yaml
|
(cls, source, y, superassistant, fully_loaded=True,
role=settings.DEFAULT_ASSISTANT_ROLE)
|
return assistant
|
Constructs instance of YamlAssistant loaded from given structure y, loaded
from source file source.
Args:
source: path to assistant source file
y: loaded yaml structure
superassistant: superassistant of this assistant
Returns:
YamlAssistant instance constructed from y with source file source
Raises:
YamlError: if the assistant is malformed
|
Constructs instance of YamlAssistant loaded from given structure y, loaded
from source file source.
|
[
"Constructs",
"instance",
"of",
"YamlAssistant",
"loaded",
"from",
"given",
"structure",
"y",
"loaded",
"from",
"source",
"file",
"source",
"."
] |
def assistant_from_yaml(cls, source, y, superassistant, fully_loaded=True,
role=settings.DEFAULT_ASSISTANT_ROLE):
"""Constructs instance of YamlAssistant loaded from given structure y, loaded
from source file source.
Args:
source: path to assistant source file
y: loaded yaml structure
superassistant: superassistant of this assistant
Returns:
YamlAssistant instance constructed from y with source file source
Raises:
YamlError: if the assistant is malformed
"""
# In pre-0.9.0, we required assistant to be a mapping of {name: assistant_attributes}
# now we allow that, but we also allow omitting the assistant name and putting
# the attributes to top_level, too.
name = os.path.splitext(os.path.basename(source))[0]
yaml_checker.check(source, y)
assistant = yaml_assistant.YamlAssistant(name, y, source, superassistant,
fully_loaded=fully_loaded, role=role)
return assistant
|
[
"def",
"assistant_from_yaml",
"(",
"cls",
",",
"source",
",",
"y",
",",
"superassistant",
",",
"fully_loaded",
"=",
"True",
",",
"role",
"=",
"settings",
".",
"DEFAULT_ASSISTANT_ROLE",
")",
":",
"# In pre-0.9.0, we required assistant to be a mapping of {name: assistant_attributes}",
"# now we allow that, but we also allow omitting the assistant name and putting",
"# the attributes to top_level, too.",
"name",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"source",
")",
")",
"[",
"0",
"]",
"yaml_checker",
".",
"check",
"(",
"source",
",",
"y",
")",
"assistant",
"=",
"yaml_assistant",
".",
"YamlAssistant",
"(",
"name",
",",
"y",
",",
"source",
",",
"superassistant",
",",
"fully_loaded",
"=",
"fully_loaded",
",",
"role",
"=",
"role",
")",
"return",
"assistant"
] |
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/yaml_assistant_loader.py#L173-L195
|
|
ansible-community/ansible-lint
|
be43b50f17f829e40845a53d0be4d4ccb2cc1728
|
src/ansiblelint/rules/__init__.py
|
python
|
AnsibleLintRule.get_config
|
(self, key: str)
|
return self.rule_config.get(key, None)
|
Return a configured value for given key string.
|
Return a configured value for given key string.
|
[
"Return",
"a",
"configured",
"value",
"for",
"given",
"key",
"string",
"."
] |
def get_config(self, key: str) -> Any:
"""Return a configured value for given key string."""
return self.rule_config.get(key, None)
|
[
"def",
"get_config",
"(",
"self",
",",
"key",
":",
"str",
")",
"->",
"Any",
":",
"return",
"self",
".",
"rule_config",
".",
"get",
"(",
"key",
",",
"None",
")"
] |
https://github.com/ansible-community/ansible-lint/blob/be43b50f17f829e40845a53d0be4d4ccb2cc1728/src/ansiblelint/rules/__init__.py#L35-L37
|
|
indico/indico
|
1579ea16235bbe5f22a308b79c5902c85374721f
|
indico/modules/vc/util.py
|
python
|
get_managed_vc_plugins
|
(user)
|
return [p for p in get_vc_plugins().values() if p.can_manage_vc(user)]
|
Return the plugins the user can manage.
|
Return the plugins the user can manage.
|
[
"Return",
"the",
"plugins",
"the",
"user",
"can",
"manage",
"."
] |
def get_managed_vc_plugins(user):
"""Return the plugins the user can manage."""
return [p for p in get_vc_plugins().values() if p.can_manage_vc(user)]
|
[
"def",
"get_managed_vc_plugins",
"(",
"user",
")",
":",
"return",
"[",
"p",
"for",
"p",
"in",
"get_vc_plugins",
"(",
")",
".",
"values",
"(",
")",
"if",
"p",
".",
"can_manage_vc",
"(",
"user",
")",
"]"
] |
https://github.com/indico/indico/blob/1579ea16235bbe5f22a308b79c5902c85374721f/indico/modules/vc/util.py#L34-L36
|
|
ray-project/ray
|
703c1610348615dcb8c2d141a0c46675084660f5
|
python/ray/_private/utils.py
|
python
|
get_wheel_filename
|
(
sys_platform: str = sys.platform,
ray_version: str = ray.__version__,
py_version: str = f"{sys.version_info.major}{sys.version_info.minor}"
)
|
return wheel_filename
|
Returns the filename used for the nightly Ray wheel.
Args:
sys_platform (str): The platform as returned by sys.platform. Examples:
"darwin", "linux", "win32"
ray_version (str): The Ray version as returned by ray.__version__ or
`ray --version`. Examples: "2.0.0.dev0"
py_version (str):
The major and minor Python versions concatenated. Examples: "36",
"37", "38", "39"
Returns:
The wheel file name. Examples:
ray-2.0.0.dev0-cp38-cp38-manylinux2014_x86_64.whl
|
Returns the filename used for the nightly Ray wheel.
|
[
"Returns",
"the",
"filename",
"used",
"for",
"the",
"nightly",
"Ray",
"wheel",
"."
] |
def get_wheel_filename(
sys_platform: str = sys.platform,
ray_version: str = ray.__version__,
py_version: str = f"{sys.version_info.major}{sys.version_info.minor}"
) -> str:
"""Returns the filename used for the nightly Ray wheel.
Args:
sys_platform (str): The platform as returned by sys.platform. Examples:
"darwin", "linux", "win32"
ray_version (str): The Ray version as returned by ray.__version__ or
`ray --version`. Examples: "2.0.0.dev0"
py_version (str):
The major and minor Python versions concatenated. Examples: "36",
"37", "38", "39"
Returns:
The wheel file name. Examples:
ray-2.0.0.dev0-cp38-cp38-manylinux2014_x86_64.whl
"""
assert py_version in ["36", "37", "38", "39"], py_version
os_strings = {
"darwin": "macosx_10_15_x86_64"
if py_version in ["38", "39"] else "macosx_10_15_intel",
"linux": "manylinux2014_x86_64",
"win32": "win_amd64"
}
assert sys_platform in os_strings, sys_platform
wheel_filename = (
f"ray-{ray_version}-cp{py_version}-"
f"cp{py_version}{'m' if py_version in ['36', '37'] else ''}"
f"-{os_strings[sys_platform]}.whl")
return wheel_filename
|
[
"def",
"get_wheel_filename",
"(",
"sys_platform",
":",
"str",
"=",
"sys",
".",
"platform",
",",
"ray_version",
":",
"str",
"=",
"ray",
".",
"__version__",
",",
"py_version",
":",
"str",
"=",
"f\"{sys.version_info.major}{sys.version_info.minor}\"",
")",
"->",
"str",
":",
"assert",
"py_version",
"in",
"[",
"\"36\"",
",",
"\"37\"",
",",
"\"38\"",
",",
"\"39\"",
"]",
",",
"py_version",
"os_strings",
"=",
"{",
"\"darwin\"",
":",
"\"macosx_10_15_x86_64\"",
"if",
"py_version",
"in",
"[",
"\"38\"",
",",
"\"39\"",
"]",
"else",
"\"macosx_10_15_intel\"",
",",
"\"linux\"",
":",
"\"manylinux2014_x86_64\"",
",",
"\"win32\"",
":",
"\"win_amd64\"",
"}",
"assert",
"sys_platform",
"in",
"os_strings",
",",
"sys_platform",
"wheel_filename",
"=",
"(",
"f\"ray-{ray_version}-cp{py_version}-\"",
"f\"cp{py_version}{'m' if py_version in ['36', '37'] else ''}\"",
"f\"-{os_strings[sys_platform]}.whl\"",
")",
"return",
"wheel_filename"
] |
https://github.com/ray-project/ray/blob/703c1610348615dcb8c2d141a0c46675084660f5/python/ray/_private/utils.py#L1047-L1082
|
|
OpenMDAO/OpenMDAO-Framework
|
f2e37b7de3edeaaeb2d251b375917adec059db9b
|
openmdao.lib/src/openmdao/lib/casehandlers/csvcase.py
|
python
|
CSVCaseRecorder.get_iterator
|
(self)
|
return CSVCaseIterator(self.filename)
|
Return CSVCaseIterator that points to our current file.
|
Return CSVCaseIterator that points to our current file.
|
[
"Return",
"CSVCaseIterator",
"that",
"points",
"to",
"our",
"current",
"file",
"."
] |
def get_iterator(self):
'''Return CSVCaseIterator that points to our current file.'''
# I think we can safely close the oufile if someone is
# requesting the iterator
self.close()
return CSVCaseIterator(self.filename)
|
[
"def",
"get_iterator",
"(",
"self",
")",
":",
"# I think we can safely close the oufile if someone is",
"# requesting the iterator",
"self",
".",
"close",
"(",
")",
"return",
"CSVCaseIterator",
"(",
"self",
".",
"filename",
")"
] |
https://github.com/OpenMDAO/OpenMDAO-Framework/blob/f2e37b7de3edeaaeb2d251b375917adec059db9b/openmdao.lib/src/openmdao/lib/casehandlers/csvcase.py#L354-L361
|
|
securesystemslab/zippy
|
ff0e84ac99442c2c55fe1d285332cfd4e185e089
|
zippy/benchmarks/src/benchmarks/sympy/sympy/polys/polyclasses.py
|
python
|
DMP.degree_list
|
(f)
|
return dmp_degree_list(f.rep, f.lev)
|
Returns a list of degrees of ``f``.
|
Returns a list of degrees of ``f``.
|
[
"Returns",
"a",
"list",
"of",
"degrees",
"of",
"f",
"."
] |
def degree_list(f):
"""Returns a list of degrees of ``f``. """
return dmp_degree_list(f.rep, f.lev)
|
[
"def",
"degree_list",
"(",
"f",
")",
":",
"return",
"dmp_degree_list",
"(",
"f",
".",
"rep",
",",
"f",
".",
"lev",
")"
] |
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/polys/polyclasses.py#L503-L505
|
|
django-mptt/django-mptt
|
7a6a54c6d2572a45ea63bd639c25507108fff3e6
|
mptt/managers.py
|
python
|
TreeManager._mptt_filter
|
(self, qs=None, **filters)
|
return qs.filter(**self._translate_lookups(**filters))
|
Like ``self.filter()``, but translates name-agnostic filters for MPTT
fields.
|
Like ``self.filter()``, but translates name-agnostic filters for MPTT
fields.
|
[
"Like",
"self",
".",
"filter",
"()",
"but",
"translates",
"name",
"-",
"agnostic",
"filters",
"for",
"MPTT",
"fields",
"."
] |
def _mptt_filter(self, qs=None, **filters):
"""
Like ``self.filter()``, but translates name-agnostic filters for MPTT
fields.
"""
if qs is None:
qs = self
return qs.filter(**self._translate_lookups(**filters))
|
[
"def",
"_mptt_filter",
"(",
"self",
",",
"qs",
"=",
"None",
",",
"*",
"*",
"filters",
")",
":",
"if",
"qs",
"is",
"None",
":",
"qs",
"=",
"self",
"return",
"qs",
".",
"filter",
"(",
"*",
"*",
"self",
".",
"_translate_lookups",
"(",
"*",
"*",
"filters",
")",
")"
] |
https://github.com/django-mptt/django-mptt/blob/7a6a54c6d2572a45ea63bd639c25507108fff3e6/mptt/managers.py#L381-L388
|
|
blurstudio/cross3d
|
277968d1227de740fc87ef61005c75034420eadf
|
cross3d/abstract/abstractscene.py
|
python
|
AbstractScene.currentFrame
|
(self)
|
return 0
|
\remarks returns the current frame
\return <int> frame
|
\remarks returns the current frame
\return <int> frame
|
[
"\\",
"remarks",
"returns",
"the",
"current",
"frame",
"\\",
"return",
"<int",
">",
"frame"
] |
def currentFrame(self):
"""
\remarks returns the current frame
\return <int> frame
"""
return 0
|
[
"def",
"currentFrame",
"(",
"self",
")",
":",
"return",
"0"
] |
https://github.com/blurstudio/cross3d/blob/277968d1227de740fc87ef61005c75034420eadf/cross3d/abstract/abstractscene.py#L956-L961
|
|
ARM-DOE/pyart
|
72affe5b669f1996cd3cc39ec7d8dd29b838bd48
|
pyart/graph/radardisplay.py
|
python
|
RadarDisplay.label_yaxis_y
|
(self, ax=None)
|
Label the yaxis with the default label for y units.
|
Label the yaxis with the default label for y units.
|
[
"Label",
"the",
"yaxis",
"with",
"the",
"default",
"label",
"for",
"y",
"units",
"."
] |
def label_yaxis_y(self, ax=None):
""" Label the yaxis with the default label for y units. """
ax = common.parse_ax(ax)
ax.set_ylabel('North South distance from ' + self.origin + ' (km)')
|
[
"def",
"label_yaxis_y",
"(",
"self",
",",
"ax",
"=",
"None",
")",
":",
"ax",
"=",
"common",
".",
"parse_ax",
"(",
"ax",
")",
"ax",
".",
"set_ylabel",
"(",
"'North South distance from '",
"+",
"self",
".",
"origin",
"+",
"' (km)'",
")"
] |
https://github.com/ARM-DOE/pyart/blob/72affe5b669f1996cd3cc39ec7d8dd29b838bd48/pyart/graph/radardisplay.py#L1190-L1193
|
||
zzzeek/sqlalchemy
|
fc5c54fcd4d868c2a4c7ac19668d72f506fe821e
|
lib/sqlalchemy/sql/ddl.py
|
python
|
DropSchema.__init__
|
(self, name, quote=None, cascade=False, **kw)
|
Create a new :class:`.DropSchema` construct.
|
Create a new :class:`.DropSchema` construct.
|
[
"Create",
"a",
"new",
":",
"class",
":",
".",
"DropSchema",
"construct",
"."
] |
def __init__(self, name, quote=None, cascade=False, **kw):
"""Create a new :class:`.DropSchema` construct."""
self.quote = quote
self.cascade = cascade
super(DropSchema, self).__init__(name, **kw)
|
[
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"quote",
"=",
"None",
",",
"cascade",
"=",
"False",
",",
"*",
"*",
"kw",
")",
":",
"self",
".",
"quote",
"=",
"quote",
"self",
".",
"cascade",
"=",
"cascade",
"super",
"(",
"DropSchema",
",",
"self",
")",
".",
"__init__",
"(",
"name",
",",
"*",
"*",
"kw",
")"
] |
https://github.com/zzzeek/sqlalchemy/blob/fc5c54fcd4d868c2a4c7ac19668d72f506fe821e/lib/sqlalchemy/sql/ddl.py#L436-L441
|
||
freqtrade/freqtrade
|
13651fd3be8d5ce8dcd7c94b920bda4e00b75aca
|
freqtrade/optimize/optimize_reports.py
|
python
|
generate_backtest_stats
|
(btdata: Dict[str, DataFrame],
all_results: Dict[str, Dict[str, Union[DataFrame, Dict]]],
min_date: datetime, max_date: datetime
)
|
return result
|
:param btdata: Backtest data
:param all_results: backtest result - dictionary in the form:
{ Strategy: {'results: results, 'config: config}}.
:param min_date: Backtest start date
:param max_date: Backtest end date
:return: Dictionary containing results per strategy and a strategy summary.
|
:param btdata: Backtest data
:param all_results: backtest result - dictionary in the form:
{ Strategy: {'results: results, 'config: config}}.
:param min_date: Backtest start date
:param max_date: Backtest end date
:return: Dictionary containing results per strategy and a strategy summary.
|
[
":",
"param",
"btdata",
":",
"Backtest",
"data",
":",
"param",
"all_results",
":",
"backtest",
"result",
"-",
"dictionary",
"in",
"the",
"form",
":",
"{",
"Strategy",
":",
"{",
"results",
":",
"results",
"config",
":",
"config",
"}}",
".",
":",
"param",
"min_date",
":",
"Backtest",
"start",
"date",
":",
"param",
"max_date",
":",
"Backtest",
"end",
"date",
":",
"return",
":",
"Dictionary",
"containing",
"results",
"per",
"strategy",
"and",
"a",
"strategy",
"summary",
"."
] |
def generate_backtest_stats(btdata: Dict[str, DataFrame],
all_results: Dict[str, Dict[str, Union[DataFrame, Dict]]],
min_date: datetime, max_date: datetime
) -> Dict[str, Any]:
"""
:param btdata: Backtest data
:param all_results: backtest result - dictionary in the form:
{ Strategy: {'results: results, 'config: config}}.
:param min_date: Backtest start date
:param max_date: Backtest end date
:return: Dictionary containing results per strategy and a strategy summary.
"""
result: Dict[str, Any] = {'strategy': {}}
market_change = calculate_market_change(btdata, 'close')
pairlist = list(btdata.keys())
for strategy, content in all_results.items():
strat_stats = generate_strategy_stats(pairlist, strategy, content,
min_date, max_date, market_change=market_change)
result['strategy'][strategy] = strat_stats
strategy_results = generate_strategy_comparison(bt_stats=result['strategy'])
result['strategy_comparison'] = strategy_results
return result
|
[
"def",
"generate_backtest_stats",
"(",
"btdata",
":",
"Dict",
"[",
"str",
",",
"DataFrame",
"]",
",",
"all_results",
":",
"Dict",
"[",
"str",
",",
"Dict",
"[",
"str",
",",
"Union",
"[",
"DataFrame",
",",
"Dict",
"]",
"]",
"]",
",",
"min_date",
":",
"datetime",
",",
"max_date",
":",
"datetime",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"result",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"{",
"'strategy'",
":",
"{",
"}",
"}",
"market_change",
"=",
"calculate_market_change",
"(",
"btdata",
",",
"'close'",
")",
"pairlist",
"=",
"list",
"(",
"btdata",
".",
"keys",
"(",
")",
")",
"for",
"strategy",
",",
"content",
"in",
"all_results",
".",
"items",
"(",
")",
":",
"strat_stats",
"=",
"generate_strategy_stats",
"(",
"pairlist",
",",
"strategy",
",",
"content",
",",
"min_date",
",",
"max_date",
",",
"market_change",
"=",
"market_change",
")",
"result",
"[",
"'strategy'",
"]",
"[",
"strategy",
"]",
"=",
"strat_stats",
"strategy_results",
"=",
"generate_strategy_comparison",
"(",
"bt_stats",
"=",
"result",
"[",
"'strategy'",
"]",
")",
"result",
"[",
"'strategy_comparison'",
"]",
"=",
"strategy_results",
"return",
"result"
] |
https://github.com/freqtrade/freqtrade/blob/13651fd3be8d5ce8dcd7c94b920bda4e00b75aca/freqtrade/optimize/optimize_reports.py#L500-L524
|
|
Komodo/KomodoEdit
|
61edab75dce2bdb03943b387b0608ea36f548e8e
|
contrib/paramiko/paramiko/transport.py
|
python
|
Transport.set_subsystem_handler
|
(self, name, handler, *larg, **kwarg)
|
Set the handler class for a subsystem in server mode. If a request
for this subsystem is made on an open ssh channel later, this handler
will be constructed and called -- see `.SubsystemHandler` for more
detailed documentation.
Any extra parameters (including keyword arguments) are saved and
passed to the `.SubsystemHandler` constructor later.
:param str name: name of the subsystem.
:param class handler:
subclass of `.SubsystemHandler` that handles this subsystem.
|
Set the handler class for a subsystem in server mode. If a request
for this subsystem is made on an open ssh channel later, this handler
will be constructed and called -- see `.SubsystemHandler` for more
detailed documentation.
|
[
"Set",
"the",
"handler",
"class",
"for",
"a",
"subsystem",
"in",
"server",
"mode",
".",
"If",
"a",
"request",
"for",
"this",
"subsystem",
"is",
"made",
"on",
"an",
"open",
"ssh",
"channel",
"later",
"this",
"handler",
"will",
"be",
"constructed",
"and",
"called",
"--",
"see",
".",
"SubsystemHandler",
"for",
"more",
"detailed",
"documentation",
"."
] |
def set_subsystem_handler(self, name, handler, *larg, **kwarg):
"""
Set the handler class for a subsystem in server mode. If a request
for this subsystem is made on an open ssh channel later, this handler
will be constructed and called -- see `.SubsystemHandler` for more
detailed documentation.
Any extra parameters (including keyword arguments) are saved and
passed to the `.SubsystemHandler` constructor later.
:param str name: name of the subsystem.
:param class handler:
subclass of `.SubsystemHandler` that handles this subsystem.
"""
try:
self.lock.acquire()
self.subsystem_table[name] = (handler, larg, kwarg)
finally:
self.lock.release()
|
[
"def",
"set_subsystem_handler",
"(",
"self",
",",
"name",
",",
"handler",
",",
"*",
"larg",
",",
"*",
"*",
"kwarg",
")",
":",
"try",
":",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"self",
".",
"subsystem_table",
"[",
"name",
"]",
"=",
"(",
"handler",
",",
"larg",
",",
"kwarg",
")",
"finally",
":",
"self",
".",
"lock",
".",
"release",
"(",
")"
] |
https://github.com/Komodo/KomodoEdit/blob/61edab75dce2bdb03943b387b0608ea36f548e8e/contrib/paramiko/paramiko/transport.py#L1124-L1142
|
||
tahoe-lafs/tahoe-lafs
|
766a53b5208c03c45ca0a98e97eee76870276aa1
|
integration/util.py
|
python
|
web_post
|
(tahoe, uri_fragment, **kwargs)
|
return resp.content
|
Make a POST request to the webport of `node` (a `TahoeProcess,
usually from a fixture e.g. `alice`). This will look like:
`http://localhost:<webport>/<uri_fragment>`. All `kwargs` are
passed on to `requests.post`
|
Make a POST request to the webport of `node` (a `TahoeProcess,
usually from a fixture e.g. `alice`). This will look like:
`http://localhost:<webport>/<uri_fragment>`. All `kwargs` are
passed on to `requests.post`
|
[
"Make",
"a",
"POST",
"request",
"to",
"the",
"webport",
"of",
"node",
"(",
"a",
"TahoeProcess",
"usually",
"from",
"a",
"fixture",
"e",
".",
"g",
".",
"alice",
")",
".",
"This",
"will",
"look",
"like",
":",
"http",
":",
"//",
"localhost",
":",
"<webport",
">",
"/",
"<uri_fragment",
">",
".",
"All",
"kwargs",
"are",
"passed",
"on",
"to",
"requests",
".",
"post"
] |
def web_post(tahoe, uri_fragment, **kwargs):
"""
Make a POST request to the webport of `node` (a `TahoeProcess,
usually from a fixture e.g. `alice`). This will look like:
`http://localhost:<webport>/<uri_fragment>`. All `kwargs` are
passed on to `requests.post`
"""
url = node_url(tahoe.node_dir, uri_fragment)
resp = requests.post(url, **kwargs)
_check_status(resp)
return resp.content
|
[
"def",
"web_post",
"(",
"tahoe",
",",
"uri_fragment",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"node_url",
"(",
"tahoe",
".",
"node_dir",
",",
"uri_fragment",
")",
"resp",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"*",
"*",
"kwargs",
")",
"_check_status",
"(",
"resp",
")",
"return",
"resp",
".",
"content"
] |
https://github.com/tahoe-lafs/tahoe-lafs/blob/766a53b5208c03c45ca0a98e97eee76870276aa1/integration/util.py#L472-L482
|
|
cloudera/hue
|
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
|
desktop/core/ext-py/django-nose-1.4.5/django_nose/plugin.py
|
python
|
DjangoSetUpPlugin.prepareTest
|
(self, test)
|
Create the Django DB and model tables, and do other setup.
This isn't done in begin() because that's too early--the DB has to be
set up *after* the tests are imported so the model registry contains
models defined in tests.py modules. Models are registered at
declaration time by their metaclass.
prepareTestRunner() might also have been a sane choice, except that, if
some plugin returns something from it, none of the other ones get
called. I'd rather not dink with scores if I don't have to.
|
Create the Django DB and model tables, and do other setup.
|
[
"Create",
"the",
"Django",
"DB",
"and",
"model",
"tables",
"and",
"do",
"other",
"setup",
"."
] |
def prepareTest(self, test):
"""Create the Django DB and model tables, and do other setup.
This isn't done in begin() because that's too early--the DB has to be
set up *after* the tests are imported so the model registry contains
models defined in tests.py modules. Models are registered at
declaration time by their metaclass.
prepareTestRunner() might also have been a sane choice, except that, if
some plugin returns something from it, none of the other ones get
called. I'd rather not dink with scores if I don't have to.
"""
# What is this stdout switcheroo for?
sys_stdout = sys.stdout
sys.stdout = self.sys_stdout
self.runner.setup_test_environment()
self.old_names = self.runner.setup_databases()
sys.stdout = sys_stdout
|
[
"def",
"prepareTest",
"(",
"self",
",",
"test",
")",
":",
"# What is this stdout switcheroo for?",
"sys_stdout",
"=",
"sys",
".",
"stdout",
"sys",
".",
"stdout",
"=",
"self",
".",
"sys_stdout",
"self",
".",
"runner",
".",
"setup_test_environment",
"(",
")",
"self",
".",
"old_names",
"=",
"self",
".",
"runner",
".",
"setup_databases",
"(",
")",
"sys",
".",
"stdout",
"=",
"sys_stdout"
] |
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/django-nose-1.4.5/django_nose/plugin.py#L64-L84
|
||
lvpengyuan/masktextspotter.caffe2
|
da99ef31f5ccb4de5248bb881d5b4a291910c8ae
|
lib/modeling/FPN.py
|
python
|
get_min_max_levels
|
()
|
return min_level, max_level
|
The min and max FPN levels required for supporting RPN and/or RoI
transform operations on multiple FPN levels.
|
The min and max FPN levels required for supporting RPN and/or RoI
transform operations on multiple FPN levels.
|
[
"The",
"min",
"and",
"max",
"FPN",
"levels",
"required",
"for",
"supporting",
"RPN",
"and",
"/",
"or",
"RoI",
"transform",
"operations",
"on",
"multiple",
"FPN",
"levels",
"."
] |
def get_min_max_levels():
"""The min and max FPN levels required for supporting RPN and/or RoI
transform operations on multiple FPN levels.
"""
min_level = LOWEST_BACKBONE_LVL
max_level = HIGHEST_BACKBONE_LVL
if cfg.FPN.MULTILEVEL_RPN and not cfg.FPN.MULTILEVEL_ROIS:
max_level = cfg.FPN.RPN_MAX_LEVEL
min_level = cfg.FPN.RPN_MIN_LEVEL
if not cfg.FPN.MULTILEVEL_RPN and cfg.FPN.MULTILEVEL_ROIS:
max_level = cfg.FPN.ROI_MAX_LEVEL
min_level = cfg.FPN.ROI_MIN_LEVEL
if cfg.FPN.MULTILEVEL_RPN and cfg.FPN.MULTILEVEL_ROIS:
max_level = max(cfg.FPN.RPN_MAX_LEVEL, cfg.FPN.ROI_MAX_LEVEL)
min_level = min(cfg.FPN.RPN_MIN_LEVEL, cfg.FPN.ROI_MIN_LEVEL)
return min_level, max_level
|
[
"def",
"get_min_max_levels",
"(",
")",
":",
"min_level",
"=",
"LOWEST_BACKBONE_LVL",
"max_level",
"=",
"HIGHEST_BACKBONE_LVL",
"if",
"cfg",
".",
"FPN",
".",
"MULTILEVEL_RPN",
"and",
"not",
"cfg",
".",
"FPN",
".",
"MULTILEVEL_ROIS",
":",
"max_level",
"=",
"cfg",
".",
"FPN",
".",
"RPN_MAX_LEVEL",
"min_level",
"=",
"cfg",
".",
"FPN",
".",
"RPN_MIN_LEVEL",
"if",
"not",
"cfg",
".",
"FPN",
".",
"MULTILEVEL_RPN",
"and",
"cfg",
".",
"FPN",
".",
"MULTILEVEL_ROIS",
":",
"max_level",
"=",
"cfg",
".",
"FPN",
".",
"ROI_MAX_LEVEL",
"min_level",
"=",
"cfg",
".",
"FPN",
".",
"ROI_MIN_LEVEL",
"if",
"cfg",
".",
"FPN",
".",
"MULTILEVEL_RPN",
"and",
"cfg",
".",
"FPN",
".",
"MULTILEVEL_ROIS",
":",
"max_level",
"=",
"max",
"(",
"cfg",
".",
"FPN",
".",
"RPN_MAX_LEVEL",
",",
"cfg",
".",
"FPN",
".",
"ROI_MAX_LEVEL",
")",
"min_level",
"=",
"min",
"(",
"cfg",
".",
"FPN",
".",
"RPN_MIN_LEVEL",
",",
"cfg",
".",
"FPN",
".",
"ROI_MIN_LEVEL",
")",
"return",
"min_level",
",",
"max_level"
] |
https://github.com/lvpengyuan/masktextspotter.caffe2/blob/da99ef31f5ccb4de5248bb881d5b4a291910c8ae/lib/modeling/FPN.py#L252-L267
|
|
igraph/python-igraph
|
e9f83e8af08f24ea025596e745917197d8b44d94
|
src/igraph/__init__.py
|
python
|
Graph.get_adjacency
|
(
self, type=GET_ADJACENCY_BOTH, attribute=None, default=0, eids=False
)
|
return Matrix(data)
|
Returns the adjacency matrix of a graph.
@param type: either C{GET_ADJACENCY_LOWER} (uses the lower
triangle of the matrix) or C{GET_ADJACENCY_UPPER}
(uses the upper triangle) or C{GET_ADJACENCY_BOTH}
(uses both parts). Ignored for directed graphs.
@param attribute: if C{None}, returns the ordinary adjacency
matrix. When the name of a valid edge attribute is given
here, the matrix returned will contain the default value
at the places where there is no edge or the value of the
given attribute where there is an edge. Multiple edges are
not supported, the value written in the matrix in this case
will be unpredictable. This parameter is ignored if
I{eids} is C{True}
@param default: the default value written to the cells in the
case of adjacency matrices with attributes.
@param eids: specifies whether the edge IDs should be returned
in the adjacency matrix. Since zero is a valid edge ID, the
cells in the matrix that correspond to unconnected vertex
pairs will contain -1 instead of 0 if I{eids} is C{True}.
If I{eids} is C{False}, the number of edges will be returned
in the matrix for each vertex pair.
@return: the adjacency matrix as a L{Matrix}.
|
Returns the adjacency matrix of a graph.
|
[
"Returns",
"the",
"adjacency",
"matrix",
"of",
"a",
"graph",
"."
] |
def get_adjacency(
self, type=GET_ADJACENCY_BOTH, attribute=None, default=0, eids=False
):
"""Returns the adjacency matrix of a graph.
@param type: either C{GET_ADJACENCY_LOWER} (uses the lower
triangle of the matrix) or C{GET_ADJACENCY_UPPER}
(uses the upper triangle) or C{GET_ADJACENCY_BOTH}
(uses both parts). Ignored for directed graphs.
@param attribute: if C{None}, returns the ordinary adjacency
matrix. When the name of a valid edge attribute is given
here, the matrix returned will contain the default value
at the places where there is no edge or the value of the
given attribute where there is an edge. Multiple edges are
not supported, the value written in the matrix in this case
will be unpredictable. This parameter is ignored if
I{eids} is C{True}
@param default: the default value written to the cells in the
case of adjacency matrices with attributes.
@param eids: specifies whether the edge IDs should be returned
in the adjacency matrix. Since zero is a valid edge ID, the
cells in the matrix that correspond to unconnected vertex
pairs will contain -1 instead of 0 if I{eids} is C{True}.
If I{eids} is C{False}, the number of edges will be returned
in the matrix for each vertex pair.
@return: the adjacency matrix as a L{Matrix}.
"""
if (
type != GET_ADJACENCY_LOWER
and type != GET_ADJACENCY_UPPER
and type != GET_ADJACENCY_BOTH
):
# Maybe it was called with the first argument as the attribute name
type, attribute = attribute, type
if type is None:
type = GET_ADJACENCY_BOTH
if eids:
result = Matrix(GraphBase.get_adjacency(self, type, eids))
result -= 1
return result
if attribute is None:
return Matrix(GraphBase.get_adjacency(self, type))
if attribute not in self.es.attribute_names():
raise ValueError("Attribute does not exist")
data = [[default] * self.vcount() for _ in range(self.vcount())]
if self.is_directed():
for edge in self.es:
data[edge.source][edge.target] = edge[attribute]
return Matrix(data)
if type == GET_ADJACENCY_BOTH:
for edge in self.es:
source, target = edge.tuple
data[source][target] = edge[attribute]
data[target][source] = edge[attribute]
elif type == GET_ADJACENCY_UPPER:
for edge in self.es:
data[min(edge.tuple)][max(edge.tuple)] = edge[attribute]
else:
for edge in self.es:
data[max(edge.tuple)][min(edge.tuple)] = edge[attribute]
return Matrix(data)
|
[
"def",
"get_adjacency",
"(",
"self",
",",
"type",
"=",
"GET_ADJACENCY_BOTH",
",",
"attribute",
"=",
"None",
",",
"default",
"=",
"0",
",",
"eids",
"=",
"False",
")",
":",
"if",
"(",
"type",
"!=",
"GET_ADJACENCY_LOWER",
"and",
"type",
"!=",
"GET_ADJACENCY_UPPER",
"and",
"type",
"!=",
"GET_ADJACENCY_BOTH",
")",
":",
"# Maybe it was called with the first argument as the attribute name",
"type",
",",
"attribute",
"=",
"attribute",
",",
"type",
"if",
"type",
"is",
"None",
":",
"type",
"=",
"GET_ADJACENCY_BOTH",
"if",
"eids",
":",
"result",
"=",
"Matrix",
"(",
"GraphBase",
".",
"get_adjacency",
"(",
"self",
",",
"type",
",",
"eids",
")",
")",
"result",
"-=",
"1",
"return",
"result",
"if",
"attribute",
"is",
"None",
":",
"return",
"Matrix",
"(",
"GraphBase",
".",
"get_adjacency",
"(",
"self",
",",
"type",
")",
")",
"if",
"attribute",
"not",
"in",
"self",
".",
"es",
".",
"attribute_names",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attribute does not exist\"",
")",
"data",
"=",
"[",
"[",
"default",
"]",
"*",
"self",
".",
"vcount",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"self",
".",
"vcount",
"(",
")",
")",
"]",
"if",
"self",
".",
"is_directed",
"(",
")",
":",
"for",
"edge",
"in",
"self",
".",
"es",
":",
"data",
"[",
"edge",
".",
"source",
"]",
"[",
"edge",
".",
"target",
"]",
"=",
"edge",
"[",
"attribute",
"]",
"return",
"Matrix",
"(",
"data",
")",
"if",
"type",
"==",
"GET_ADJACENCY_BOTH",
":",
"for",
"edge",
"in",
"self",
".",
"es",
":",
"source",
",",
"target",
"=",
"edge",
".",
"tuple",
"data",
"[",
"source",
"]",
"[",
"target",
"]",
"=",
"edge",
"[",
"attribute",
"]",
"data",
"[",
"target",
"]",
"[",
"source",
"]",
"=",
"edge",
"[",
"attribute",
"]",
"elif",
"type",
"==",
"GET_ADJACENCY_UPPER",
":",
"for",
"edge",
"in",
"self",
".",
"es",
":",
"data",
"[",
"min",
"(",
"edge",
".",
"tuple",
")",
"]",
"[",
"max",
"(",
"edge",
".",
"tuple",
")",
"]",
"=",
"edge",
"[",
"attribute",
"]",
"else",
":",
"for",
"edge",
"in",
"self",
".",
"es",
":",
"data",
"[",
"max",
"(",
"edge",
".",
"tuple",
")",
"]",
"[",
"min",
"(",
"edge",
".",
"tuple",
")",
"]",
"=",
"edge",
"[",
"attribute",
"]",
"return",
"Matrix",
"(",
"data",
")"
] |
https://github.com/igraph/python-igraph/blob/e9f83e8af08f24ea025596e745917197d8b44d94/src/igraph/__init__.py#L653-L720
|
|
saltstack/salt
|
fae5bc757ad0f1716483ce7ae180b451545c2058
|
salt/modules/zfs.py
|
python
|
exists
|
(name, **kwargs)
|
return res["retcode"] == 0
|
Check if a ZFS filesystem or volume or snapshot exists.
name : string
name of dataset
type : string
also check if dataset is of a certain type, valid choices are:
filesystem, snapshot, volume, bookmark, or all.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' zfs.exists myzpool/mydataset
salt '*' zfs.exists myzpool/myvolume type=volume
|
Check if a ZFS filesystem or volume or snapshot exists.
|
[
"Check",
"if",
"a",
"ZFS",
"filesystem",
"or",
"volume",
"or",
"snapshot",
"exists",
"."
] |
def exists(name, **kwargs):
"""
Check if a ZFS filesystem or volume or snapshot exists.
name : string
name of dataset
type : string
also check if dataset is of a certain type, valid choices are:
filesystem, snapshot, volume, bookmark, or all.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' zfs.exists myzpool/mydataset
salt '*' zfs.exists myzpool/myvolume type=volume
"""
## Configure command
# NOTE: initialize the defaults
opts = {}
# NOTE: set extra config from kwargs
if kwargs.get("type", False):
opts["-t"] = kwargs.get("type")
## Check if 'name' of 'type' exists
res = __salt__["cmd.run_all"](
__utils__["zfs.zfs_command"](
command="list",
opts=opts,
target=name,
),
python_shell=False,
ignore_retcode=True,
)
return res["retcode"] == 0
|
[
"def",
"exists",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"## Configure command",
"# NOTE: initialize the defaults",
"opts",
"=",
"{",
"}",
"# NOTE: set extra config from kwargs",
"if",
"kwargs",
".",
"get",
"(",
"\"type\"",
",",
"False",
")",
":",
"opts",
"[",
"\"-t\"",
"]",
"=",
"kwargs",
".",
"get",
"(",
"\"type\"",
")",
"## Check if 'name' of 'type' exists",
"res",
"=",
"__salt__",
"[",
"\"cmd.run_all\"",
"]",
"(",
"__utils__",
"[",
"\"zfs.zfs_command\"",
"]",
"(",
"command",
"=",
"\"list\"",
",",
"opts",
"=",
"opts",
",",
"target",
"=",
"name",
",",
")",
",",
"python_shell",
"=",
"False",
",",
"ignore_retcode",
"=",
"True",
",",
")",
"return",
"res",
"[",
"\"retcode\"",
"]",
"==",
"0"
] |
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/modules/zfs.py#L44-L83
|
|
JacquesLucke/animation_nodes
|
b1e3ace8dcb0a771fd882fc3ac4e490b009fa0d1
|
animation_nodes/utils/attributes.py
|
python
|
pathBelongsToArray
|
(object, dataPath)
|
return pathArrayCache.get(inputHash, None)
|
[] |
def pathBelongsToArray(object, dataPath):
inputHash = hash((object, dataPath))
if inputHash not in pathArrayCache:
result = _pathBelongsToArray(object, dataPath)
if result is not None:
pathArrayCache[inputHash] = result
return pathArrayCache.get(inputHash, None)
|
[
"def",
"pathBelongsToArray",
"(",
"object",
",",
"dataPath",
")",
":",
"inputHash",
"=",
"hash",
"(",
"(",
"object",
",",
"dataPath",
")",
")",
"if",
"inputHash",
"not",
"in",
"pathArrayCache",
":",
"result",
"=",
"_pathBelongsToArray",
"(",
"object",
",",
"dataPath",
")",
"if",
"result",
"is",
"not",
"None",
":",
"pathArrayCache",
"[",
"inputHash",
"]",
"=",
"result",
"return",
"pathArrayCache",
".",
"get",
"(",
"inputHash",
",",
"None",
")"
] |
https://github.com/JacquesLucke/animation_nodes/blob/b1e3ace8dcb0a771fd882fc3ac4e490b009fa0d1/animation_nodes/utils/attributes.py#L53-L59
|
|||
ClusterHQ/flocker
|
eaa586248986d7cd681c99c948546c2b507e44de
|
flocker/ca/_ca.py
|
python
|
FlockerCredential.write_credential_files
|
(self, key_filename, certificate_filename)
|
Write PEM encoded certificate and private key files for this credential
instance.
:param bytes key_filename: The name of the private key file to write,
e.g. "cluster.key"
:param bytes certificate_filename: The name of the certificate file to
write, e.g. "cluster.crt"
|
Write PEM encoded certificate and private key files for this credential
instance.
|
[
"Write",
"PEM",
"encoded",
"certificate",
"and",
"private",
"key",
"files",
"for",
"this",
"credential",
"instance",
"."
] |
def write_credential_files(self, key_filename, certificate_filename):
"""
Write PEM encoded certificate and private key files for this credential
instance.
:param bytes key_filename: The name of the private key file to write,
e.g. "cluster.key"
:param bytes certificate_filename: The name of the certificate file to
write, e.g. "cluster.crt"
"""
key_path = self.path.child(key_filename)
cert_path = self.path.child(certificate_filename)
original_umask = os.umask(0)
mode = 0o600
try:
with os.fdopen(os.open(
cert_path.path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, mode
), b'w') as cert_file:
cert_file.write(self.certificate.dumpPEM())
try:
with os.fdopen(os.open(
key_path.path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, mode
), b'w') as key_file:
key_file.write(
self.keypair.keypair.dump(crypto.FILETYPE_PEM))
except (IOError, OSError) as e:
code, failure = e
raise PathError(
b"Unable to write private key file.",
e.filename, code, failure
)
except (IOError, OSError) as e:
code, failure = e
raise PathError(
b"Unable to write certificate file.",
e.filename, code, failure
)
finally:
os.umask(original_umask)
|
[
"def",
"write_credential_files",
"(",
"self",
",",
"key_filename",
",",
"certificate_filename",
")",
":",
"key_path",
"=",
"self",
".",
"path",
".",
"child",
"(",
"key_filename",
")",
"cert_path",
"=",
"self",
".",
"path",
".",
"child",
"(",
"certificate_filename",
")",
"original_umask",
"=",
"os",
".",
"umask",
"(",
"0",
")",
"mode",
"=",
"0o600",
"try",
":",
"with",
"os",
".",
"fdopen",
"(",
"os",
".",
"open",
"(",
"cert_path",
".",
"path",
",",
"os",
".",
"O_WRONLY",
"|",
"os",
".",
"O_CREAT",
"|",
"os",
".",
"O_EXCL",
",",
"mode",
")",
",",
"b'w'",
")",
"as",
"cert_file",
":",
"cert_file",
".",
"write",
"(",
"self",
".",
"certificate",
".",
"dumpPEM",
"(",
")",
")",
"try",
":",
"with",
"os",
".",
"fdopen",
"(",
"os",
".",
"open",
"(",
"key_path",
".",
"path",
",",
"os",
".",
"O_WRONLY",
"|",
"os",
".",
"O_CREAT",
"|",
"os",
".",
"O_EXCL",
",",
"mode",
")",
",",
"b'w'",
")",
"as",
"key_file",
":",
"key_file",
".",
"write",
"(",
"self",
".",
"keypair",
".",
"keypair",
".",
"dump",
"(",
"crypto",
".",
"FILETYPE_PEM",
")",
")",
"except",
"(",
"IOError",
",",
"OSError",
")",
"as",
"e",
":",
"code",
",",
"failure",
"=",
"e",
"raise",
"PathError",
"(",
"b\"Unable to write private key file.\"",
",",
"e",
".",
"filename",
",",
"code",
",",
"failure",
")",
"except",
"(",
"IOError",
",",
"OSError",
")",
"as",
"e",
":",
"code",
",",
"failure",
"=",
"e",
"raise",
"PathError",
"(",
"b\"Unable to write certificate file.\"",
",",
"e",
".",
"filename",
",",
"code",
",",
"failure",
")",
"finally",
":",
"os",
".",
"umask",
"(",
"original_umask",
")"
] |
https://github.com/ClusterHQ/flocker/blob/eaa586248986d7cd681c99c948546c2b507e44de/flocker/ca/_ca.py#L295-L333
|
||
openstack/rally
|
58b12c2e0bfa541bdb038be6e1679c5117b98484
|
rally/task/types.py
|
python
|
_name_from_id
|
(resource_config, resources, typename)
|
return obj_from_id(resource_config, resources, typename).name
|
Return the name of the resource which has the id.
resource_config has to contain `id`, as it is used to lookup a name.
:param resource_config: resource to be transformed
:param resources: iterable containing all resources
:param typename: name which describes the type of resource
:returns: resource name mapped to `id`
|
Return the name of the resource which has the id.
|
[
"Return",
"the",
"name",
"of",
"the",
"resource",
"which",
"has",
"the",
"id",
"."
] |
def _name_from_id(resource_config, resources, typename):
"""Return the name of the resource which has the id.
resource_config has to contain `id`, as it is used to lookup a name.
:param resource_config: resource to be transformed
:param resources: iterable containing all resources
:param typename: name which describes the type of resource
:returns: resource name mapped to `id`
"""
return obj_from_id(resource_config, resources, typename).name
|
[
"def",
"_name_from_id",
"(",
"resource_config",
",",
"resources",
",",
"typename",
")",
":",
"return",
"obj_from_id",
"(",
"resource_config",
",",
"resources",
",",
"typename",
")",
".",
"name"
] |
https://github.com/openstack/rally/blob/58b12c2e0bfa541bdb038be6e1679c5117b98484/rally/task/types.py#L218-L229
|
|
securityclippy/elasticintel
|
aa08d3e9f5ab1c000128e95161139ce97ff0e334
|
intelbot/requests/models.py
|
python
|
Response.links
|
(self)
|
return l
|
Returns the parsed header links of the response, if any.
|
Returns the parsed header links of the response, if any.
|
[
"Returns",
"the",
"parsed",
"header",
"links",
"of",
"the",
"response",
"if",
"any",
"."
] |
def links(self):
"""Returns the parsed header links of the response, if any."""
header = self.headers.get('link')
# l = MultiDict()
l = {}
if header:
links = parse_header_links(header)
for link in links:
key = link.get('rel') or link.get('url')
l[key] = link
return l
|
[
"def",
"links",
"(",
"self",
")",
":",
"header",
"=",
"self",
".",
"headers",
".",
"get",
"(",
"'link'",
")",
"# l = MultiDict()",
"l",
"=",
"{",
"}",
"if",
"header",
":",
"links",
"=",
"parse_header_links",
"(",
"header",
")",
"for",
"link",
"in",
"links",
":",
"key",
"=",
"link",
".",
"get",
"(",
"'rel'",
")",
"or",
"link",
".",
"get",
"(",
"'url'",
")",
"l",
"[",
"key",
"]",
"=",
"link",
"return",
"l"
] |
https://github.com/securityclippy/elasticintel/blob/aa08d3e9f5ab1c000128e95161139ce97ff0e334/intelbot/requests/models.py#L809-L824
|
|
brightmart/ai_law
|
33fdcfa20d2b98937f28722b25a263da8a218301
|
predictor/model_single_task_1.py
|
python
|
HierarchicalAttention.dpcnn_two_layers_conv
|
(self, inputs,double_num_filters=False)
|
return conv2
|
two layers of conv
inputs:[batch_size,total_sequence_length,embed_size,dimension]. e.g.(128, 400, 64,1)-->[128,200,32,250]
:return:[batch_size,total_sequence_length,embed_size,num_filters]
|
two layers of conv
inputs:[batch_size,total_sequence_length,embed_size,dimension]. e.g.(128, 400, 64,1)-->[128,200,32,250]
:return:[batch_size,total_sequence_length,embed_size,num_filters]
|
[
"two",
"layers",
"of",
"conv",
"inputs",
":",
"[",
"batch_size",
"total_sequence_length",
"embed_size",
"dimension",
"]",
".",
"e",
".",
"g",
".",
"(",
"128",
"400",
"64",
"1",
")",
"--",
">",
"[",
"128",
"200",
"32",
"250",
"]",
":",
"return",
":",
"[",
"batch_size",
"total_sequence_length",
"embed_size",
"num_filters",
"]"
] |
def dpcnn_two_layers_conv(self, inputs,double_num_filters=False):
"""
two layers of conv
inputs:[batch_size,total_sequence_length,embed_size,dimension]. e.g.(128, 400, 64,1)-->[128,200,32,250]
:return:[batch_size,total_sequence_length,embed_size,num_filters]
"""
# conv1:
# filter1's first three dimension apply to [total_sequence_length, embed_size, 1] of embedding_documents
print("dpcnn_two_layers_conv.inputs:", inputs) # (128, 400, 64, 250)
channel = inputs.get_shape().as_list()[-1]
if double_num_filters:
hpcnn_number_filters =channel * 2
else:
hpcnn_number_filters=self.hpcnn_number_filters
filter1 = tf.get_variable("filter1-%s" % self.hpcnn_filter_size,[self.hpcnn_filter_size, 1, channel, hpcnn_number_filters],initializer=self.initializer)
conv1 = tf.nn.conv2d(inputs, filter1, strides=[1, self.stride_length, 1, 1], padding="SAME",name="conv") # shape:[batch_size,total_sequence_length,embed_size,hpcnn_number_filters]
conv1 = tf.contrib.layers.batch_norm(conv1, is_training=self.is_training_flag, scope='cnn1')
print("dpcnn_two_layers_conv.conv1:", conv1) # (128, 400, 64, 250)
b1 = tf.get_variable("b-cnn-%s" % hpcnn_number_filters, [hpcnn_number_filters])
conv1 = tf.nn.relu(tf.nn.bias_add(conv1, b1),"relu1") # shape:[batch_size,total_sequence_length,embed_size,hpcnn_number_filters]
# conv2
# filter2's first three dimension apply to:[total_sequence_length,embed_size,hpcnn_number_filters] of conv1
filter2 = tf.get_variable("filter2-%s" % self.hpcnn_filter_size,[self.hpcnn_filter_size, 1, hpcnn_number_filters, hpcnn_number_filters],initializer=self.initializer)
conv2 = tf.nn.conv2d(conv1, filter2, strides=[1, self.stride_length, 1, 1], padding="SAME",name="conv2") # shape:[batch_size,stotal_sequence_length,embed_size,hpcnn_number_filters]
conv2 = tf.contrib.layers.batch_norm(conv2, is_training=self.is_training_flag, scope='cnn2')
print("dpcnn_two_layers_conv.conv2:", conv2) # (128, 400, 64, 250)
return conv2
|
[
"def",
"dpcnn_two_layers_conv",
"(",
"self",
",",
"inputs",
",",
"double_num_filters",
"=",
"False",
")",
":",
"# conv1:",
"# filter1's first three dimension apply to [total_sequence_length, embed_size, 1] of embedding_documents",
"print",
"(",
"\"dpcnn_two_layers_conv.inputs:\"",
",",
"inputs",
")",
"# (128, 400, 64, 250)",
"channel",
"=",
"inputs",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"[",
"-",
"1",
"]",
"if",
"double_num_filters",
":",
"hpcnn_number_filters",
"=",
"channel",
"*",
"2",
"else",
":",
"hpcnn_number_filters",
"=",
"self",
".",
"hpcnn_number_filters",
"filter1",
"=",
"tf",
".",
"get_variable",
"(",
"\"filter1-%s\"",
"%",
"self",
".",
"hpcnn_filter_size",
",",
"[",
"self",
".",
"hpcnn_filter_size",
",",
"1",
",",
"channel",
",",
"hpcnn_number_filters",
"]",
",",
"initializer",
"=",
"self",
".",
"initializer",
")",
"conv1",
"=",
"tf",
".",
"nn",
".",
"conv2d",
"(",
"inputs",
",",
"filter1",
",",
"strides",
"=",
"[",
"1",
",",
"self",
".",
"stride_length",
",",
"1",
",",
"1",
"]",
",",
"padding",
"=",
"\"SAME\"",
",",
"name",
"=",
"\"conv\"",
")",
"# shape:[batch_size,total_sequence_length,embed_size,hpcnn_number_filters]",
"conv1",
"=",
"tf",
".",
"contrib",
".",
"layers",
".",
"batch_norm",
"(",
"conv1",
",",
"is_training",
"=",
"self",
".",
"is_training_flag",
",",
"scope",
"=",
"'cnn1'",
")",
"print",
"(",
"\"dpcnn_two_layers_conv.conv1:\"",
",",
"conv1",
")",
"# (128, 400, 64, 250)",
"b1",
"=",
"tf",
".",
"get_variable",
"(",
"\"b-cnn-%s\"",
"%",
"hpcnn_number_filters",
",",
"[",
"hpcnn_number_filters",
"]",
")",
"conv1",
"=",
"tf",
".",
"nn",
".",
"relu",
"(",
"tf",
".",
"nn",
".",
"bias_add",
"(",
"conv1",
",",
"b1",
")",
",",
"\"relu1\"",
")",
"# shape:[batch_size,total_sequence_length,embed_size,hpcnn_number_filters]",
"# conv2",
"# filter2's first three dimension apply to:[total_sequence_length,embed_size,hpcnn_number_filters] of conv1",
"filter2",
"=",
"tf",
".",
"get_variable",
"(",
"\"filter2-%s\"",
"%",
"self",
".",
"hpcnn_filter_size",
",",
"[",
"self",
".",
"hpcnn_filter_size",
",",
"1",
",",
"hpcnn_number_filters",
",",
"hpcnn_number_filters",
"]",
",",
"initializer",
"=",
"self",
".",
"initializer",
")",
"conv2",
"=",
"tf",
".",
"nn",
".",
"conv2d",
"(",
"conv1",
",",
"filter2",
",",
"strides",
"=",
"[",
"1",
",",
"self",
".",
"stride_length",
",",
"1",
",",
"1",
"]",
",",
"padding",
"=",
"\"SAME\"",
",",
"name",
"=",
"\"conv2\"",
")",
"# shape:[batch_size,stotal_sequence_length,embed_size,hpcnn_number_filters]",
"conv2",
"=",
"tf",
".",
"contrib",
".",
"layers",
".",
"batch_norm",
"(",
"conv2",
",",
"is_training",
"=",
"self",
".",
"is_training_flag",
",",
"scope",
"=",
"'cnn2'",
")",
"print",
"(",
"\"dpcnn_two_layers_conv.conv2:\"",
",",
"conv2",
")",
"# (128, 400, 64, 250)",
"return",
"conv2"
] |
https://github.com/brightmart/ai_law/blob/33fdcfa20d2b98937f28722b25a263da8a218301/predictor/model_single_task_1.py#L318-L347
|
|
omz/PythonistaAppTemplate
|
f560f93f8876d82a21d108977f90583df08d55af
|
PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/matplotlib/projections/geo.py
|
python
|
GeoAxes.set_longitude_grid_ends
|
(self, degrees)
|
Set the latitude(s) at which to stop drawing the longitude grids.
|
Set the latitude(s) at which to stop drawing the longitude grids.
|
[
"Set",
"the",
"latitude",
"(",
"s",
")",
"at",
"which",
"to",
"stop",
"drawing",
"the",
"longitude",
"grids",
"."
] |
def set_longitude_grid_ends(self, degrees):
"""
Set the latitude(s) at which to stop drawing the longitude grids.
"""
self._longitude_cap = degrees * (np.pi / 180.0)
self._xaxis_pretransform \
.clear() \
.scale(1.0, self._longitude_cap * 2.0) \
.translate(0.0, -self._longitude_cap)
|
[
"def",
"set_longitude_grid_ends",
"(",
"self",
",",
"degrees",
")",
":",
"self",
".",
"_longitude_cap",
"=",
"degrees",
"*",
"(",
"np",
".",
"pi",
"/",
"180.0",
")",
"self",
".",
"_xaxis_pretransform",
".",
"clear",
"(",
")",
".",
"scale",
"(",
"1.0",
",",
"self",
".",
"_longitude_cap",
"*",
"2.0",
")",
".",
"translate",
"(",
"0.0",
",",
"-",
"self",
".",
"_longitude_cap",
")"
] |
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/matplotlib/projections/geo.py#L203-L211
|
||
yuhaozhang/tacred-relation
|
18221efc28be400ad3ec3939f1bbd32ab74b64f5
|
data/loader.py
|
python
|
DataLoader.__getitem__
|
(self, key)
|
return (words, masks, pos, ner, deprel, subj_positions, obj_positions, rels, orig_idx)
|
Get a batch with index.
|
Get a batch with index.
|
[
"Get",
"a",
"batch",
"with",
"index",
"."
] |
def __getitem__(self, key):
""" Get a batch with index. """
if not isinstance(key, int):
raise TypeError
if key < 0 or key >= len(self.data):
raise IndexError
batch = self.data[key]
batch_size = len(batch)
batch = list(zip(*batch))
assert len(batch) == 7
# sort all fields by lens for easy RNN operations
lens = [len(x) for x in batch[0]]
batch, orig_idx = sort_all(batch, lens)
# word dropout
if not self.eval:
words = [word_dropout(sent, self.opt['word_dropout']) for sent in batch[0]]
else:
words = batch[0]
# convert to tensors
words = get_long_tensor(words, batch_size)
masks = torch.eq(words, 0)
pos = get_long_tensor(batch[1], batch_size)
ner = get_long_tensor(batch[2], batch_size)
deprel = get_long_tensor(batch[3], batch_size)
subj_positions = get_long_tensor(batch[4], batch_size)
obj_positions = get_long_tensor(batch[5], batch_size)
rels = torch.LongTensor(batch[6])
return (words, masks, pos, ner, deprel, subj_positions, obj_positions, rels, orig_idx)
|
[
"def",
"__getitem__",
"(",
"self",
",",
"key",
")",
":",
"if",
"not",
"isinstance",
"(",
"key",
",",
"int",
")",
":",
"raise",
"TypeError",
"if",
"key",
"<",
"0",
"or",
"key",
">=",
"len",
"(",
"self",
".",
"data",
")",
":",
"raise",
"IndexError",
"batch",
"=",
"self",
".",
"data",
"[",
"key",
"]",
"batch_size",
"=",
"len",
"(",
"batch",
")",
"batch",
"=",
"list",
"(",
"zip",
"(",
"*",
"batch",
")",
")",
"assert",
"len",
"(",
"batch",
")",
"==",
"7",
"# sort all fields by lens for easy RNN operations",
"lens",
"=",
"[",
"len",
"(",
"x",
")",
"for",
"x",
"in",
"batch",
"[",
"0",
"]",
"]",
"batch",
",",
"orig_idx",
"=",
"sort_all",
"(",
"batch",
",",
"lens",
")",
"# word dropout",
"if",
"not",
"self",
".",
"eval",
":",
"words",
"=",
"[",
"word_dropout",
"(",
"sent",
",",
"self",
".",
"opt",
"[",
"'word_dropout'",
"]",
")",
"for",
"sent",
"in",
"batch",
"[",
"0",
"]",
"]",
"else",
":",
"words",
"=",
"batch",
"[",
"0",
"]",
"# convert to tensors",
"words",
"=",
"get_long_tensor",
"(",
"words",
",",
"batch_size",
")",
"masks",
"=",
"torch",
".",
"eq",
"(",
"words",
",",
"0",
")",
"pos",
"=",
"get_long_tensor",
"(",
"batch",
"[",
"1",
"]",
",",
"batch_size",
")",
"ner",
"=",
"get_long_tensor",
"(",
"batch",
"[",
"2",
"]",
",",
"batch_size",
")",
"deprel",
"=",
"get_long_tensor",
"(",
"batch",
"[",
"3",
"]",
",",
"batch_size",
")",
"subj_positions",
"=",
"get_long_tensor",
"(",
"batch",
"[",
"4",
"]",
",",
"batch_size",
")",
"obj_positions",
"=",
"get_long_tensor",
"(",
"batch",
"[",
"5",
"]",
",",
"batch_size",
")",
"rels",
"=",
"torch",
".",
"LongTensor",
"(",
"batch",
"[",
"6",
"]",
")",
"return",
"(",
"words",
",",
"masks",
",",
"pos",
",",
"ner",
",",
"deprel",
",",
"subj_positions",
",",
"obj_positions",
",",
"rels",
",",
"orig_idx",
")"
] |
https://github.com/yuhaozhang/tacred-relation/blob/18221efc28be400ad3ec3939f1bbd32ab74b64f5/data/loader.py#L70-L102
|
|
facebookresearch/Detectron
|
1809dd41c1ffc881c0d6b1c16ea38d08894f8b6d
|
detectron/utils/segms.py
|
python
|
rle_mask_nms
|
(masks, dets, thresh, mode='IOU')
|
return keep
|
Performs greedy non-maximum suppression based on an overlap measurement
between masks. The type of measurement is determined by `mode` and can be
either 'IOU' (standard intersection over union) or 'IOMA' (intersection over
mininum area).
|
Performs greedy non-maximum suppression based on an overlap measurement
between masks. The type of measurement is determined by `mode` and can be
either 'IOU' (standard intersection over union) or 'IOMA' (intersection over
mininum area).
|
[
"Performs",
"greedy",
"non",
"-",
"maximum",
"suppression",
"based",
"on",
"an",
"overlap",
"measurement",
"between",
"masks",
".",
"The",
"type",
"of",
"measurement",
"is",
"determined",
"by",
"mode",
"and",
"can",
"be",
"either",
"IOU",
"(",
"standard",
"intersection",
"over",
"union",
")",
"or",
"IOMA",
"(",
"intersection",
"over",
"mininum",
"area",
")",
"."
] |
def rle_mask_nms(masks, dets, thresh, mode='IOU'):
"""Performs greedy non-maximum suppression based on an overlap measurement
between masks. The type of measurement is determined by `mode` and can be
either 'IOU' (standard intersection over union) or 'IOMA' (intersection over
mininum area).
"""
if len(masks) == 0:
return []
if len(masks) == 1:
return [0]
if mode == 'IOU':
# Computes ious[m1, m2] = area(intersect(m1, m2)) / area(union(m1, m2))
all_not_crowds = [False] * len(masks)
ious = mask_util.iou(masks, masks, all_not_crowds)
elif mode == 'IOMA':
# Computes ious[m1, m2] = area(intersect(m1, m2)) / min(area(m1), area(m2))
all_crowds = [True] * len(masks)
# ious[m1, m2] = area(intersect(m1, m2)) / area(m2)
ious = mask_util.iou(masks, masks, all_crowds)
# ... = max(area(intersect(m1, m2)) / area(m2),
# area(intersect(m2, m1)) / area(m1))
ious = np.maximum(ious, ious.transpose())
elif mode == 'CONTAINMENT':
# Computes ious[m1, m2] = area(intersect(m1, m2)) / area(m2)
# Which measures how much m2 is contained inside m1
all_crowds = [True] * len(masks)
ious = mask_util.iou(masks, masks, all_crowds)
else:
raise NotImplementedError('Mode {} is unknown'.format(mode))
scores = dets[:, 4]
order = np.argsort(-scores)
keep = []
while order.size > 0:
i = order[0]
keep.append(i)
ovr = ious[i, order[1:]]
inds_to_keep = np.where(ovr <= thresh)[0]
order = order[inds_to_keep + 1]
return keep
|
[
"def",
"rle_mask_nms",
"(",
"masks",
",",
"dets",
",",
"thresh",
",",
"mode",
"=",
"'IOU'",
")",
":",
"if",
"len",
"(",
"masks",
")",
"==",
"0",
":",
"return",
"[",
"]",
"if",
"len",
"(",
"masks",
")",
"==",
"1",
":",
"return",
"[",
"0",
"]",
"if",
"mode",
"==",
"'IOU'",
":",
"# Computes ious[m1, m2] = area(intersect(m1, m2)) / area(union(m1, m2))",
"all_not_crowds",
"=",
"[",
"False",
"]",
"*",
"len",
"(",
"masks",
")",
"ious",
"=",
"mask_util",
".",
"iou",
"(",
"masks",
",",
"masks",
",",
"all_not_crowds",
")",
"elif",
"mode",
"==",
"'IOMA'",
":",
"# Computes ious[m1, m2] = area(intersect(m1, m2)) / min(area(m1), area(m2))",
"all_crowds",
"=",
"[",
"True",
"]",
"*",
"len",
"(",
"masks",
")",
"# ious[m1, m2] = area(intersect(m1, m2)) / area(m2)",
"ious",
"=",
"mask_util",
".",
"iou",
"(",
"masks",
",",
"masks",
",",
"all_crowds",
")",
"# ... = max(area(intersect(m1, m2)) / area(m2),",
"# area(intersect(m2, m1)) / area(m1))",
"ious",
"=",
"np",
".",
"maximum",
"(",
"ious",
",",
"ious",
".",
"transpose",
"(",
")",
")",
"elif",
"mode",
"==",
"'CONTAINMENT'",
":",
"# Computes ious[m1, m2] = area(intersect(m1, m2)) / area(m2)",
"# Which measures how much m2 is contained inside m1",
"all_crowds",
"=",
"[",
"True",
"]",
"*",
"len",
"(",
"masks",
")",
"ious",
"=",
"mask_util",
".",
"iou",
"(",
"masks",
",",
"masks",
",",
"all_crowds",
")",
"else",
":",
"raise",
"NotImplementedError",
"(",
"'Mode {} is unknown'",
".",
"format",
"(",
"mode",
")",
")",
"scores",
"=",
"dets",
"[",
":",
",",
"4",
"]",
"order",
"=",
"np",
".",
"argsort",
"(",
"-",
"scores",
")",
"keep",
"=",
"[",
"]",
"while",
"order",
".",
"size",
">",
"0",
":",
"i",
"=",
"order",
"[",
"0",
"]",
"keep",
".",
"append",
"(",
"i",
")",
"ovr",
"=",
"ious",
"[",
"i",
",",
"order",
"[",
"1",
":",
"]",
"]",
"inds_to_keep",
"=",
"np",
".",
"where",
"(",
"ovr",
"<=",
"thresh",
")",
"[",
"0",
"]",
"order",
"=",
"order",
"[",
"inds_to_keep",
"+",
"1",
"]",
"return",
"keep"
] |
https://github.com/facebookresearch/Detectron/blob/1809dd41c1ffc881c0d6b1c16ea38d08894f8b6d/detectron/utils/segms.py#L209-L251
|
|
haiwen/seafile-docker
|
2d2461d4c8cab3458ec9832611c419d47506c300
|
cluster/image/pro_seafile_7.1/scripts_7.1/setup-seafile-mysql.py
|
python
|
AbstractDBConfigurator.check_mysql_user
|
(self, user, password, host=None, unix_socket=None)
|
return conn
|
[] |
def check_mysql_user(self, user, password, host=None, unix_socket=None):
print('\nverifying password of user %s ... ' % user, end=' ')
kwargs = dict(port=self.mysql_port,
user=user,
passwd=password)
if unix_socket:
kwargs['unix_socket'] = unix_socket
else:
kwargs['host'] = host or self.mysql_host
try:
conn = pymysql.connect(**kwargs)
except Exception as e:
if isinstance(e, pymysql.err.OperationalError):
raise InvalidAnswer('Failed to connect to mysql server using user "%s" and password "***": %s' \
% (user, e.args[1]))
else:
raise InvalidAnswer('Failed to connect to mysql server using user "%s" and password "***": %s' \
% (user, e))
print('done')
return conn
|
[
"def",
"check_mysql_user",
"(",
"self",
",",
"user",
",",
"password",
",",
"host",
"=",
"None",
",",
"unix_socket",
"=",
"None",
")",
":",
"print",
"(",
"'\\nverifying password of user %s ... '",
"%",
"user",
",",
"end",
"=",
"' '",
")",
"kwargs",
"=",
"dict",
"(",
"port",
"=",
"self",
".",
"mysql_port",
",",
"user",
"=",
"user",
",",
"passwd",
"=",
"password",
")",
"if",
"unix_socket",
":",
"kwargs",
"[",
"'unix_socket'",
"]",
"=",
"unix_socket",
"else",
":",
"kwargs",
"[",
"'host'",
"]",
"=",
"host",
"or",
"self",
".",
"mysql_host",
"try",
":",
"conn",
"=",
"pymysql",
".",
"connect",
"(",
"*",
"*",
"kwargs",
")",
"except",
"Exception",
"as",
"e",
":",
"if",
"isinstance",
"(",
"e",
",",
"pymysql",
".",
"err",
".",
"OperationalError",
")",
":",
"raise",
"InvalidAnswer",
"(",
"'Failed to connect to mysql server using user \"%s\" and password \"***\": %s'",
"%",
"(",
"user",
",",
"e",
".",
"args",
"[",
"1",
"]",
")",
")",
"else",
":",
"raise",
"InvalidAnswer",
"(",
"'Failed to connect to mysql server using user \"%s\" and password \"***\": %s'",
"%",
"(",
"user",
",",
"e",
")",
")",
"print",
"(",
"'done'",
")",
"return",
"conn"
] |
https://github.com/haiwen/seafile-docker/blob/2d2461d4c8cab3458ec9832611c419d47506c300/cluster/image/pro_seafile_7.1/scripts_7.1/setup-seafile-mysql.py#L485-L506
|
|||
inspurer/WorkAttendanceSystem
|
1221e2d67bdf5bb15fe99517cc3ded58ccb066df
|
V1.0/venv/Lib/site-packages/pip-9.0.1-py3.5.egg/pip/_vendor/distlib/index.py
|
python
|
PackageIndex.check_credentials
|
(self)
|
Check that ``username`` and ``password`` have been set, and raise an
exception if not.
|
Check that ``username`` and ``password`` have been set, and raise an
exception if not.
|
[
"Check",
"that",
"username",
"and",
"password",
"have",
"been",
"set",
"and",
"raise",
"an",
"exception",
"if",
"not",
"."
] |
def check_credentials(self):
"""
Check that ``username`` and ``password`` have been set, and raise an
exception if not.
"""
if self.username is None or self.password is None:
raise DistlibException('username and password must be set')
pm = HTTPPasswordMgr()
_, netloc, _, _, _, _ = urlparse(self.url)
pm.add_password(self.realm, netloc, self.username, self.password)
self.password_handler = HTTPBasicAuthHandler(pm)
|
[
"def",
"check_credentials",
"(",
"self",
")",
":",
"if",
"self",
".",
"username",
"is",
"None",
"or",
"self",
".",
"password",
"is",
"None",
":",
"raise",
"DistlibException",
"(",
"'username and password must be set'",
")",
"pm",
"=",
"HTTPPasswordMgr",
"(",
")",
"_",
",",
"netloc",
",",
"_",
",",
"_",
",",
"_",
",",
"_",
"=",
"urlparse",
"(",
"self",
".",
"url",
")",
"pm",
".",
"add_password",
"(",
"self",
".",
"realm",
",",
"netloc",
",",
"self",
".",
"username",
",",
"self",
".",
"password",
")",
"self",
".",
"password_handler",
"=",
"HTTPBasicAuthHandler",
"(",
"pm",
")"
] |
https://github.com/inspurer/WorkAttendanceSystem/blob/1221e2d67bdf5bb15fe99517cc3ded58ccb066df/V1.0/venv/Lib/site-packages/pip-9.0.1-py3.5.egg/pip/_vendor/distlib/index.py#L103-L113
|
||
hyperopt/hyperopt-sklearn
|
c66f8df76003b5e72cb242399eeb139f951a1883
|
hpsklearn/components.py
|
python
|
sklearn_ElasticNet
|
(*args, **kwargs)
|
return sklearn.linear_model.ElasticNet(*args, **kwargs)
|
[] |
def sklearn_ElasticNet(*args, **kwargs):
return sklearn.linear_model.ElasticNet(*args, **kwargs)
|
[
"def",
"sklearn_ElasticNet",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"sklearn",
".",
"linear_model",
".",
"ElasticNet",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/hyperopt/hyperopt-sklearn/blob/c66f8df76003b5e72cb242399eeb139f951a1883/hpsklearn/components.py#L97-L98
|
|||
SteveDoyle2/pyNastran
|
eda651ac2d4883d95a34951f8a002ff94f642a1a
|
pyNastran/bdf/cards/elements/rigid.py
|
python
|
RSPLINE.safe_cross_reference
|
(self, model: BDF, xref_errors)
|
Cross links the card so referenced cards can be extracted directly
Parameters
----------
model : BDF()
the BDF object
|
Cross links the card so referenced cards can be extracted directly
|
[
"Cross",
"links",
"the",
"card",
"so",
"referenced",
"cards",
"can",
"be",
"extracted",
"directly"
] |
def safe_cross_reference(self, model: BDF, xref_errors):
"""
Cross links the card so referenced cards can be extracted directly
Parameters
----------
model : BDF()
the BDF object
"""
self.cross_reference(model)
|
[
"def",
"safe_cross_reference",
"(",
"self",
",",
"model",
":",
"BDF",
",",
"xref_errors",
")",
":",
"self",
".",
"cross_reference",
"(",
"model",
")"
] |
https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/bdf/cards/elements/rigid.py#L1730-L1740
|
||
zhl2008/awd-platform
|
0416b31abea29743387b10b3914581fbe8e7da5e
|
web_flaskbb/lib/python2.7/site-packages/kombu/transport/redis.py
|
python
|
Channel._size
|
(self, queue)
|
[] |
def _size(self, queue):
with self.conn_or_acquire() as client:
with client.pipeline() as pipe:
for pri in self.priority_steps:
pipe = pipe.llen(self._q_for_pri(queue, pri))
sizes = pipe.execute()
return sum(size for size in sizes
if isinstance(size, numbers.Integral))
|
[
"def",
"_size",
"(",
"self",
",",
"queue",
")",
":",
"with",
"self",
".",
"conn_or_acquire",
"(",
")",
"as",
"client",
":",
"with",
"client",
".",
"pipeline",
"(",
")",
"as",
"pipe",
":",
"for",
"pri",
"in",
"self",
".",
"priority_steps",
":",
"pipe",
"=",
"pipe",
".",
"llen",
"(",
"self",
".",
"_q_for_pri",
"(",
"queue",
",",
"pri",
")",
")",
"sizes",
"=",
"pipe",
".",
"execute",
"(",
")",
"return",
"sum",
"(",
"size",
"for",
"size",
"in",
"sizes",
"if",
"isinstance",
"(",
"size",
",",
"numbers",
".",
"Integral",
")",
")"
] |
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/kombu/transport/redis.py#L745-L752
|
||||
jobovy/galpy
|
8e6a230bbe24ce16938db10053f92eb17fe4bb52
|
galpy/potential/AdiabaticContractionWrapperPotential.py
|
python
|
AdiabaticContractionWrapperPotential.__init__
|
(self,amp=1.,pot=None,baryonpot=None,
method='cautun',f_bar=0.157,rmin=None,rmax=50.,
ro=None,vo=None)
|
NAME:
__init__
PURPOSE:
initialize a AdiabaticContractionWrapper Potential
INPUT:
amp - amplitude to be applied to the potential (default: 1.)
pot - Potential instance or list thereof representing the density that is adiabatically contracted
baryonpot - Potential instance or list thereof representing the density of baryons whose growth causes the contraction
method= ('cautun') Type of adiabatic-contraction formula:
* 'cautun' for that from Cautun et al. 2020 (`2020MNRAS.494.4291C <https://ui.adsabs.harvard.edu/abs/2020MNRAS.494.4291C>`__),
* 'blumenthal' for that from Blumenthal et al. 1986 (`1986ApJ...301...27B 1986ApJ...301...27B <https://ui.adsabs.harvard.edu/abs/1986ApJ...301...27B>`__)
* 'gnedin' for that from Gnedin et al. 2004 (`2004ApJ...616...16G <https://ui.adsabs.harvard.edu/abs/2004ApJ...616...16G>`__)
f_bar= (0.157) universal baryon fraction; if None, calculated from pot and baryonpot assuming that at rmax the halo contains the universal baryon fraction; leave this at the default value unless you know what you are doing
rmin= (None) minimum radius to consider (default: rmax/2500; don't set this to zero)
rmax= (50.) maximum radius to consider (can be Quantity)
ro, vo= standard unit-conversion parameters
OUTPUT:
(none)
HISTORY:
2021-03-21 - Started based on Marius Cautun's code - Bovy (UofT)
|
NAME:
|
[
"NAME",
":"
] |
def __init__(self,amp=1.,pot=None,baryonpot=None,
method='cautun',f_bar=0.157,rmin=None,rmax=50.,
ro=None,vo=None):
"""
NAME:
__init__
PURPOSE:
initialize a AdiabaticContractionWrapper Potential
INPUT:
amp - amplitude to be applied to the potential (default: 1.)
pot - Potential instance or list thereof representing the density that is adiabatically contracted
baryonpot - Potential instance or list thereof representing the density of baryons whose growth causes the contraction
method= ('cautun') Type of adiabatic-contraction formula:
* 'cautun' for that from Cautun et al. 2020 (`2020MNRAS.494.4291C <https://ui.adsabs.harvard.edu/abs/2020MNRAS.494.4291C>`__),
* 'blumenthal' for that from Blumenthal et al. 1986 (`1986ApJ...301...27B 1986ApJ...301...27B <https://ui.adsabs.harvard.edu/abs/1986ApJ...301...27B>`__)
* 'gnedin' for that from Gnedin et al. 2004 (`2004ApJ...616...16G <https://ui.adsabs.harvard.edu/abs/2004ApJ...616...16G>`__)
f_bar= (0.157) universal baryon fraction; if None, calculated from pot and baryonpot assuming that at rmax the halo contains the universal baryon fraction; leave this at the default value unless you know what you are doing
rmin= (None) minimum radius to consider (default: rmax/2500; don't set this to zero)
rmax= (50.) maximum radius to consider (can be Quantity)
ro, vo= standard unit-conversion parameters
OUTPUT:
(none)
HISTORY:
2021-03-21 - Started based on Marius Cautun's code - Bovy (UofT)
"""
# Initialize with Force just to parse (ro,vo)
Force.__init__(self,ro=ro,vo=vo)
rmax= conversion.parse_length(rmax,ro=self._ro)
rmin= conversion.parse_length(rmin,ro=self._ro) if not rmin is None \
else rmax/2500.
# Compute baryon and DM enclosed masses on radial grid
from ..potential import mass
rgrid= numpy.geomspace(rmin,rmax,301)
baryon_mass= numpy.array([mass(baryonpot,r,use_physical=False)
for r in rgrid])
dm_mass= numpy.array([mass(pot,r,use_physical=False)
for r in rgrid])
# Adiabatic contraction
if f_bar is None:
f_bar= baryon_mass[-1]/(baryon_mass[-1]+dm_mass[-1])
if method.lower() == 'cautun':
new_rforce= _contraction_Cautun2020(rgrid,dm_mass,baryon_mass,
f_bar)
elif method.lower() == 'gnedin':
new_rforce= \
_contraction_Gnedin2004(rgrid,dm_mass,baryon_mass,
pot.rvir(overdens=180.,
wrtcrit=False),
f_bar)
elif method.lower() == 'blumenthal':
new_rforce= _contraction_Blumenthal1986(rgrid,dm_mass,
baryon_mass,f_bar)
else: # pragma: no cover
raise ValueError("Adiabatic contraction method '{}' not recognized".format(method))
# Add central point
rgrid= numpy.concatenate(([0.],rgrid))
new_rforce= numpy.concatenate(([0.],new_rforce))
new_rforce_func= lambda r: -numpy.interp(r,rgrid,new_rforce)
# Potential at zero = int_0^inf dr rforce, and enc. mass constant
# outside of last rgrid point
Phi0= integrate.quad(new_rforce_func,rgrid[0],rgrid[-1])[0]\
-new_rforce[-1]*rgrid[-1]
interpSphericalPotential.__init__(self,
rforce=new_rforce_func,
rgrid=rgrid,
Phi0=Phi0,
ro=ro,vo=vo)
|
[
"def",
"__init__",
"(",
"self",
",",
"amp",
"=",
"1.",
",",
"pot",
"=",
"None",
",",
"baryonpot",
"=",
"None",
",",
"method",
"=",
"'cautun'",
",",
"f_bar",
"=",
"0.157",
",",
"rmin",
"=",
"None",
",",
"rmax",
"=",
"50.",
",",
"ro",
"=",
"None",
",",
"vo",
"=",
"None",
")",
":",
"# Initialize with Force just to parse (ro,vo)",
"Force",
".",
"__init__",
"(",
"self",
",",
"ro",
"=",
"ro",
",",
"vo",
"=",
"vo",
")",
"rmax",
"=",
"conversion",
".",
"parse_length",
"(",
"rmax",
",",
"ro",
"=",
"self",
".",
"_ro",
")",
"rmin",
"=",
"conversion",
".",
"parse_length",
"(",
"rmin",
",",
"ro",
"=",
"self",
".",
"_ro",
")",
"if",
"not",
"rmin",
"is",
"None",
"else",
"rmax",
"/",
"2500.",
"# Compute baryon and DM enclosed masses on radial grid",
"from",
".",
".",
"potential",
"import",
"mass",
"rgrid",
"=",
"numpy",
".",
"geomspace",
"(",
"rmin",
",",
"rmax",
",",
"301",
")",
"baryon_mass",
"=",
"numpy",
".",
"array",
"(",
"[",
"mass",
"(",
"baryonpot",
",",
"r",
",",
"use_physical",
"=",
"False",
")",
"for",
"r",
"in",
"rgrid",
"]",
")",
"dm_mass",
"=",
"numpy",
".",
"array",
"(",
"[",
"mass",
"(",
"pot",
",",
"r",
",",
"use_physical",
"=",
"False",
")",
"for",
"r",
"in",
"rgrid",
"]",
")",
"# Adiabatic contraction",
"if",
"f_bar",
"is",
"None",
":",
"f_bar",
"=",
"baryon_mass",
"[",
"-",
"1",
"]",
"/",
"(",
"baryon_mass",
"[",
"-",
"1",
"]",
"+",
"dm_mass",
"[",
"-",
"1",
"]",
")",
"if",
"method",
".",
"lower",
"(",
")",
"==",
"'cautun'",
":",
"new_rforce",
"=",
"_contraction_Cautun2020",
"(",
"rgrid",
",",
"dm_mass",
",",
"baryon_mass",
",",
"f_bar",
")",
"elif",
"method",
".",
"lower",
"(",
")",
"==",
"'gnedin'",
":",
"new_rforce",
"=",
"_contraction_Gnedin2004",
"(",
"rgrid",
",",
"dm_mass",
",",
"baryon_mass",
",",
"pot",
".",
"rvir",
"(",
"overdens",
"=",
"180.",
",",
"wrtcrit",
"=",
"False",
")",
",",
"f_bar",
")",
"elif",
"method",
".",
"lower",
"(",
")",
"==",
"'blumenthal'",
":",
"new_rforce",
"=",
"_contraction_Blumenthal1986",
"(",
"rgrid",
",",
"dm_mass",
",",
"baryon_mass",
",",
"f_bar",
")",
"else",
":",
"# pragma: no cover",
"raise",
"ValueError",
"(",
"\"Adiabatic contraction method '{}' not recognized\"",
".",
"format",
"(",
"method",
")",
")",
"# Add central point",
"rgrid",
"=",
"numpy",
".",
"concatenate",
"(",
"(",
"[",
"0.",
"]",
",",
"rgrid",
")",
")",
"new_rforce",
"=",
"numpy",
".",
"concatenate",
"(",
"(",
"[",
"0.",
"]",
",",
"new_rforce",
")",
")",
"new_rforce_func",
"=",
"lambda",
"r",
":",
"-",
"numpy",
".",
"interp",
"(",
"r",
",",
"rgrid",
",",
"new_rforce",
")",
"# Potential at zero = int_0^inf dr rforce, and enc. mass constant",
"# outside of last rgrid point",
"Phi0",
"=",
"integrate",
".",
"quad",
"(",
"new_rforce_func",
",",
"rgrid",
"[",
"0",
"]",
",",
"rgrid",
"[",
"-",
"1",
"]",
")",
"[",
"0",
"]",
"-",
"new_rforce",
"[",
"-",
"1",
"]",
"*",
"rgrid",
"[",
"-",
"1",
"]",
"interpSphericalPotential",
".",
"__init__",
"(",
"self",
",",
"rforce",
"=",
"new_rforce_func",
",",
"rgrid",
"=",
"rgrid",
",",
"Phi0",
"=",
"Phi0",
",",
"ro",
"=",
"ro",
",",
"vo",
"=",
"vo",
")"
] |
https://github.com/jobovy/galpy/blob/8e6a230bbe24ce16938db10053f92eb17fe4bb52/galpy/potential/AdiabaticContractionWrapperPotential.py#L23-L107
|
||
sopel-irc/sopel
|
787baa6e39f9dad57d94600c92e10761c41b21ef
|
sopel/plugins/handlers.py
|
python
|
PyFilePlugin._load
|
(self)
|
return mod
|
[] |
def _load(self):
# The current implementation uses `imp.load_module` to perform the
# load action, which also reloads the module. However, `imp` is
# deprecated in Python 3, so that might need to be changed when the
# support for Python 2 is dropped.
#
# However, the solution for Python 3 is non-trivial, since the
# `importlib` built-in module does not have a similar function,
# therefore requires to dive into its public internals
# (``importlib.machinery`` and ``importlib.util``).
#
# All of that is doable, but represents a lot of work. As long as
# Python 2 is supported, we can keep it for now.
#
# TODO: switch to ``importlib`` when Python2 support is dropped.
if self.module_type == imp.PY_SOURCE:
with open(self.path) as mod:
description = ('.py', 'U', self.module_type)
mod = imp.load_module(self.name, mod, self.path, description)
elif self.module_type == imp.PKG_DIRECTORY:
description = ('', '', self.module_type)
mod = imp.load_module(self.name, None, self.path, description)
else:
raise TypeError('Unsupported module type')
return mod
|
[
"def",
"_load",
"(",
"self",
")",
":",
"# The current implementation uses `imp.load_module` to perform the",
"# load action, which also reloads the module. However, `imp` is",
"# deprecated in Python 3, so that might need to be changed when the",
"# support for Python 2 is dropped.",
"#",
"# However, the solution for Python 3 is non-trivial, since the",
"# `importlib` built-in module does not have a similar function,",
"# therefore requires to dive into its public internals",
"# (``importlib.machinery`` and ``importlib.util``).",
"#",
"# All of that is doable, but represents a lot of work. As long as",
"# Python 2 is supported, we can keep it for now.",
"#",
"# TODO: switch to ``importlib`` when Python2 support is dropped.",
"if",
"self",
".",
"module_type",
"==",
"imp",
".",
"PY_SOURCE",
":",
"with",
"open",
"(",
"self",
".",
"path",
")",
"as",
"mod",
":",
"description",
"=",
"(",
"'.py'",
",",
"'U'",
",",
"self",
".",
"module_type",
")",
"mod",
"=",
"imp",
".",
"load_module",
"(",
"self",
".",
"name",
",",
"mod",
",",
"self",
".",
"path",
",",
"description",
")",
"elif",
"self",
".",
"module_type",
"==",
"imp",
".",
"PKG_DIRECTORY",
":",
"description",
"=",
"(",
"''",
",",
"''",
",",
"self",
".",
"module_type",
")",
"mod",
"=",
"imp",
".",
"load_module",
"(",
"self",
".",
"name",
",",
"None",
",",
"self",
".",
"path",
",",
"description",
")",
"else",
":",
"raise",
"TypeError",
"(",
"'Unsupported module type'",
")",
"return",
"mod"
] |
https://github.com/sopel-irc/sopel/blob/787baa6e39f9dad57d94600c92e10761c41b21ef/sopel/plugins/handlers.py#L445-L470
|
|||
jython/frozen-mirror
|
b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99
|
Lib/xml/Uri.py
|
python
|
BaseJoin
|
(base, uriRef)
|
Merges a base URI reference with another URI reference, returning a
new URI reference.
It behaves exactly the same as Absolutize(), except the arguments
are reversed, and it accepts any URI reference (even a relative URI)
as the base URI. If the base has no scheme component, it is
evaluated as if it did, and then the scheme component of the result
is removed from the result, unless the uriRef had a scheme. Thus, if
neither argument has a scheme component, the result won't have one.
This function is named BaseJoin because it is very much like
urllib.basejoin(), but it follows the current rfc3986 algorithms
for path merging, dot segment elimination, and inheritance of query
and fragment components.
WARNING: This function exists for 2 reasons: (1) because of a need
within the 4Suite repository to perform URI reference absolutization
using base URIs that are stored (inappropriately) as absolute paths
in the subjects of statements in the RDF model, and (2) because of
a similar need to interpret relative repo paths in a 4Suite product
setup.xml file as being relative to a path that can be set outside
the document. When these needs go away, this function probably will,
too, so it is not advisable to use it.
|
Merges a base URI reference with another URI reference, returning a
new URI reference.
|
[
"Merges",
"a",
"base",
"URI",
"reference",
"with",
"another",
"URI",
"reference",
"returning",
"a",
"new",
"URI",
"reference",
"."
] |
def BaseJoin(base, uriRef):
"""
Merges a base URI reference with another URI reference, returning a
new URI reference.
It behaves exactly the same as Absolutize(), except the arguments
are reversed, and it accepts any URI reference (even a relative URI)
as the base URI. If the base has no scheme component, it is
evaluated as if it did, and then the scheme component of the result
is removed from the result, unless the uriRef had a scheme. Thus, if
neither argument has a scheme component, the result won't have one.
This function is named BaseJoin because it is very much like
urllib.basejoin(), but it follows the current rfc3986 algorithms
for path merging, dot segment elimination, and inheritance of query
and fragment components.
WARNING: This function exists for 2 reasons: (1) because of a need
within the 4Suite repository to perform URI reference absolutization
using base URIs that are stored (inappropriately) as absolute paths
in the subjects of statements in the RDF model, and (2) because of
a similar need to interpret relative repo paths in a 4Suite product
setup.xml file as being relative to a path that can be set outside
the document. When these needs go away, this function probably will,
too, so it is not advisable to use it.
"""
if IsAbsolute(base):
return Absolutize(uriRef, base)
else:
dummyscheme = 'basejoin'
res = Absolutize(uriRef, '%s:%s' % (dummyscheme, base))
if IsAbsolute(uriRef):
# scheme will be inherited from uriRef
return res
else:
# no scheme in, no scheme out
return res[len(dummyscheme)+1:]
|
[
"def",
"BaseJoin",
"(",
"base",
",",
"uriRef",
")",
":",
"if",
"IsAbsolute",
"(",
"base",
")",
":",
"return",
"Absolutize",
"(",
"uriRef",
",",
"base",
")",
"else",
":",
"dummyscheme",
"=",
"'basejoin'",
"res",
"=",
"Absolutize",
"(",
"uriRef",
",",
"'%s:%s'",
"%",
"(",
"dummyscheme",
",",
"base",
")",
")",
"if",
"IsAbsolute",
"(",
"uriRef",
")",
":",
"# scheme will be inherited from uriRef",
"return",
"res",
"else",
":",
"# no scheme in, no scheme out",
"return",
"res",
"[",
"len",
"(",
"dummyscheme",
")",
"+",
"1",
":",
"]"
] |
https://github.com/jython/frozen-mirror/blob/b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99/Lib/xml/Uri.py#L255-L291
|
||
Netflix/dispatch
|
f734b7cb91cba0e3a95b4d0adaa7198bfc94552b
|
src/dispatch/incident/service.py
|
python
|
delete
|
(*, db_session, incident_id: int)
|
Deletes an existing incident.
|
Deletes an existing incident.
|
[
"Deletes",
"an",
"existing",
"incident",
"."
] |
def delete(*, db_session, incident_id: int):
"""Deletes an existing incident."""
db_session.query(Incident).filter(Incident.id == incident_id).delete()
db_session.commit()
|
[
"def",
"delete",
"(",
"*",
",",
"db_session",
",",
"incident_id",
":",
"int",
")",
":",
"db_session",
".",
"query",
"(",
"Incident",
")",
".",
"filter",
"(",
"Incident",
".",
"id",
"==",
"incident_id",
")",
".",
"delete",
"(",
")",
"db_session",
".",
"commit",
"(",
")"
] |
https://github.com/Netflix/dispatch/blob/f734b7cb91cba0e3a95b4d0adaa7198bfc94552b/src/dispatch/incident/service.py#L315-L318
|
||
mesalock-linux/mesapy
|
ed546d59a21b36feb93e2309d5c6b75aa0ad95c9
|
lib-python/2.7/distutils/command/install.py
|
python
|
install.create_home_path
|
(self)
|
Create directories under ~
|
Create directories under ~
|
[
"Create",
"directories",
"under",
"~"
] |
def create_home_path(self):
"""Create directories under ~
"""
if not self.user:
return
home = convert_path(os.path.expanduser("~"))
for name, path in self.config_vars.iteritems():
if path.startswith(home) and not os.path.isdir(path):
self.debug_print("os.makedirs('%s', 0700)" % path)
os.makedirs(path, 0700)
|
[
"def",
"create_home_path",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"user",
":",
"return",
"home",
"=",
"convert_path",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"\"~\"",
")",
")",
"for",
"name",
",",
"path",
"in",
"self",
".",
"config_vars",
".",
"iteritems",
"(",
")",
":",
"if",
"path",
".",
"startswith",
"(",
"home",
")",
"and",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"self",
".",
"debug_print",
"(",
"\"os.makedirs('%s', 0700)\"",
"%",
"path",
")",
"os",
".",
"makedirs",
"(",
"path",
",",
"0700",
")"
] |
https://github.com/mesalock-linux/mesapy/blob/ed546d59a21b36feb93e2309d5c6b75aa0ad95c9/lib-python/2.7/distutils/command/install.py#L556-L565
|
||
albertogeniola/MerossIot
|
35abe51dbc97f1aadcba7ec52b58b88711a6a0ef
|
meross_iot/device_factory.py
|
python
|
_lookup_cached_type
|
(device_type: str, hardware_version: str, firmware_version: str)
|
return _dynamic_types.get(lookup_string)
|
Returns the cached dynamic type for the specific device, if any was already built for that one.
:param device_type:
:param hardware_version:
:param firmware_version:
:return:
|
Returns the cached dynamic type for the specific device, if any was already built for that one.
:param device_type:
:param hardware_version:
:param firmware_version:
:return:
|
[
"Returns",
"the",
"cached",
"dynamic",
"type",
"for",
"the",
"specific",
"device",
"if",
"any",
"was",
"already",
"built",
"for",
"that",
"one",
".",
":",
"param",
"device_type",
":",
":",
"param",
"hardware_version",
":",
":",
"param",
"firmware_version",
":",
":",
"return",
":"
] |
def _lookup_cached_type(device_type: str, hardware_version: str, firmware_version: str) -> Optional[type]:
"""
Returns the cached dynamic type for the specific device, if any was already built for that one.
:param device_type:
:param hardware_version:
:param firmware_version:
:return:
"""
lookup_string = _caclulate_device_type_name(device_type, hardware_version, firmware_version).strip(":")
return _dynamic_types.get(lookup_string)
|
[
"def",
"_lookup_cached_type",
"(",
"device_type",
":",
"str",
",",
"hardware_version",
":",
"str",
",",
"firmware_version",
":",
"str",
")",
"->",
"Optional",
"[",
"type",
"]",
":",
"lookup_string",
"=",
"_caclulate_device_type_name",
"(",
"device_type",
",",
"hardware_version",
",",
"firmware_version",
")",
".",
"strip",
"(",
"\":\"",
")",
"return",
"_dynamic_types",
".",
"get",
"(",
"lookup_string",
")"
] |
https://github.com/albertogeniola/MerossIot/blob/35abe51dbc97f1aadcba7ec52b58b88711a6a0ef/meross_iot/device_factory.py#L85-L94
|
|
deepgully/me
|
f7ad65edc2fe435310c6676bc2e322cfe5d4c8f0
|
libs/markdown/treeprocessors.py
|
python
|
Treeprocessor.run
|
(self, root)
|
Subclasses of Treeprocessor should implement a `run` method, which
takes a root ElementTree. This method can return another ElementTree
object, and the existing root ElementTree will be replaced, or it can
modify the current tree and return None.
|
Subclasses of Treeprocessor should implement a `run` method, which
takes a root ElementTree. This method can return another ElementTree
object, and the existing root ElementTree will be replaced, or it can
modify the current tree and return None.
|
[
"Subclasses",
"of",
"Treeprocessor",
"should",
"implement",
"a",
"run",
"method",
"which",
"takes",
"a",
"root",
"ElementTree",
".",
"This",
"method",
"can",
"return",
"another",
"ElementTree",
"object",
"and",
"the",
"existing",
"root",
"ElementTree",
"will",
"be",
"replaced",
"or",
"it",
"can",
"modify",
"the",
"current",
"tree",
"and",
"return",
"None",
"."
] |
def run(self, root):
"""
Subclasses of Treeprocessor should implement a `run` method, which
takes a root ElementTree. This method can return another ElementTree
object, and the existing root ElementTree will be replaced, or it can
modify the current tree and return None.
"""
pass
|
[
"def",
"run",
"(",
"self",
",",
"root",
")",
":",
"pass"
] |
https://github.com/deepgully/me/blob/f7ad65edc2fe435310c6676bc2e322cfe5d4c8f0/libs/markdown/treeprocessors.py#L34-L41
|
||
JiYou/openstack
|
8607dd488bde0905044b303eb6e52bdea6806923
|
chap19/monitor/python-monitorclient-1.1/build/lib.linux-x86_64-2.7/monitorclient/v1/monitor_types.py
|
python
|
ServiceManageTypeManager.get
|
(self, monitor_type)
|
return self._get("/types/%s" % base.getid(monitor_type), "monitor_type")
|
Get a specific monitor type.
:param monitor_type: The ID of the :class:`ServiceManageType` to get.
:rtype: :class:`ServiceManageType`
|
Get a specific monitor type.
|
[
"Get",
"a",
"specific",
"monitor",
"type",
"."
] |
def get(self, monitor_type):
"""
Get a specific monitor type.
:param monitor_type: The ID of the :class:`ServiceManageType` to get.
:rtype: :class:`ServiceManageType`
"""
return self._get("/types/%s" % base.getid(monitor_type), "monitor_type")
|
[
"def",
"get",
"(",
"self",
",",
"monitor_type",
")",
":",
"return",
"self",
".",
"_get",
"(",
"\"/types/%s\"",
"%",
"base",
".",
"getid",
"(",
"monitor_type",
")",
",",
"\"monitor_type\"",
")"
] |
https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/chap19/monitor/python-monitorclient-1.1/build/lib.linux-x86_64-2.7/monitorclient/v1/monitor_types.py#L91-L98
|
|
mozillazg/pypy
|
2ff5cd960c075c991389f842c6d59e71cf0cb7d0
|
lib-python/2.7/lib-tk/turtle.py
|
python
|
ScrolledCanvas.unbind
|
(self, *args, **kwargs)
|
'forward' method, which canvas itself has inherited...
|
'forward' method, which canvas itself has inherited...
|
[
"forward",
"method",
"which",
"canvas",
"itself",
"has",
"inherited",
"..."
] |
def unbind(self, *args, **kwargs):
""" 'forward' method, which canvas itself has inherited...
"""
self._canvas.unbind(*args, **kwargs)
|
[
"def",
"unbind",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_canvas",
".",
"unbind",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/lib-python/2.7/lib-tk/turtle.py#L442-L445
|
||
scipy/scipy
|
e0a749f01e79046642ccfdc419edbf9e7ca141ad
|
scipy/optimize/_dual_annealing.py
|
python
|
VisitingDistribution.visiting
|
(self, x, step, temperature)
|
return x_visit
|
Based on the step in the strategy chain, new coordinated are
generated by changing all components is the same time or only
one of them, the new values are computed with visit_fn method
|
Based on the step in the strategy chain, new coordinated are
generated by changing all components is the same time or only
one of them, the new values are computed with visit_fn method
|
[
"Based",
"on",
"the",
"step",
"in",
"the",
"strategy",
"chain",
"new",
"coordinated",
"are",
"generated",
"by",
"changing",
"all",
"components",
"is",
"the",
"same",
"time",
"or",
"only",
"one",
"of",
"them",
"the",
"new",
"values",
"are",
"computed",
"with",
"visit_fn",
"method"
] |
def visiting(self, x, step, temperature):
""" Based on the step in the strategy chain, new coordinated are
generated by changing all components is the same time or only
one of them, the new values are computed with visit_fn method
"""
dim = x.size
if step < dim:
# Changing all coordinates with a new visiting value
visits = self.visit_fn(temperature, dim)
upper_sample, lower_sample = self.rand_gen.uniform(size=2)
visits[visits > self.TAIL_LIMIT] = self.TAIL_LIMIT * upper_sample
visits[visits < -self.TAIL_LIMIT] = -self.TAIL_LIMIT * lower_sample
x_visit = visits + x
a = x_visit - self.lower
b = np.fmod(a, self.bound_range) + self.bound_range
x_visit = np.fmod(b, self.bound_range) + self.lower
x_visit[np.fabs(
x_visit - self.lower) < self.MIN_VISIT_BOUND] += 1.e-10
else:
# Changing only one coordinate at a time based on strategy
# chain step
x_visit = np.copy(x)
visit = self.visit_fn(temperature, 1)[0]
if visit > self.TAIL_LIMIT:
visit = self.TAIL_LIMIT * self.rand_gen.uniform()
elif visit < -self.TAIL_LIMIT:
visit = -self.TAIL_LIMIT * self.rand_gen.uniform()
index = step - dim
x_visit[index] = visit + x[index]
a = x_visit[index] - self.lower[index]
b = np.fmod(a, self.bound_range[index]) + self.bound_range[index]
x_visit[index] = np.fmod(b, self.bound_range[
index]) + self.lower[index]
if np.fabs(x_visit[index] - self.lower[
index]) < self.MIN_VISIT_BOUND:
x_visit[index] += self.MIN_VISIT_BOUND
return x_visit
|
[
"def",
"visiting",
"(",
"self",
",",
"x",
",",
"step",
",",
"temperature",
")",
":",
"dim",
"=",
"x",
".",
"size",
"if",
"step",
"<",
"dim",
":",
"# Changing all coordinates with a new visiting value",
"visits",
"=",
"self",
".",
"visit_fn",
"(",
"temperature",
",",
"dim",
")",
"upper_sample",
",",
"lower_sample",
"=",
"self",
".",
"rand_gen",
".",
"uniform",
"(",
"size",
"=",
"2",
")",
"visits",
"[",
"visits",
">",
"self",
".",
"TAIL_LIMIT",
"]",
"=",
"self",
".",
"TAIL_LIMIT",
"*",
"upper_sample",
"visits",
"[",
"visits",
"<",
"-",
"self",
".",
"TAIL_LIMIT",
"]",
"=",
"-",
"self",
".",
"TAIL_LIMIT",
"*",
"lower_sample",
"x_visit",
"=",
"visits",
"+",
"x",
"a",
"=",
"x_visit",
"-",
"self",
".",
"lower",
"b",
"=",
"np",
".",
"fmod",
"(",
"a",
",",
"self",
".",
"bound_range",
")",
"+",
"self",
".",
"bound_range",
"x_visit",
"=",
"np",
".",
"fmod",
"(",
"b",
",",
"self",
".",
"bound_range",
")",
"+",
"self",
".",
"lower",
"x_visit",
"[",
"np",
".",
"fabs",
"(",
"x_visit",
"-",
"self",
".",
"lower",
")",
"<",
"self",
".",
"MIN_VISIT_BOUND",
"]",
"+=",
"1.e-10",
"else",
":",
"# Changing only one coordinate at a time based on strategy",
"# chain step",
"x_visit",
"=",
"np",
".",
"copy",
"(",
"x",
")",
"visit",
"=",
"self",
".",
"visit_fn",
"(",
"temperature",
",",
"1",
")",
"[",
"0",
"]",
"if",
"visit",
">",
"self",
".",
"TAIL_LIMIT",
":",
"visit",
"=",
"self",
".",
"TAIL_LIMIT",
"*",
"self",
".",
"rand_gen",
".",
"uniform",
"(",
")",
"elif",
"visit",
"<",
"-",
"self",
".",
"TAIL_LIMIT",
":",
"visit",
"=",
"-",
"self",
".",
"TAIL_LIMIT",
"*",
"self",
".",
"rand_gen",
".",
"uniform",
"(",
")",
"index",
"=",
"step",
"-",
"dim",
"x_visit",
"[",
"index",
"]",
"=",
"visit",
"+",
"x",
"[",
"index",
"]",
"a",
"=",
"x_visit",
"[",
"index",
"]",
"-",
"self",
".",
"lower",
"[",
"index",
"]",
"b",
"=",
"np",
".",
"fmod",
"(",
"a",
",",
"self",
".",
"bound_range",
"[",
"index",
"]",
")",
"+",
"self",
".",
"bound_range",
"[",
"index",
"]",
"x_visit",
"[",
"index",
"]",
"=",
"np",
".",
"fmod",
"(",
"b",
",",
"self",
".",
"bound_range",
"[",
"index",
"]",
")",
"+",
"self",
".",
"lower",
"[",
"index",
"]",
"if",
"np",
".",
"fabs",
"(",
"x_visit",
"[",
"index",
"]",
"-",
"self",
".",
"lower",
"[",
"index",
"]",
")",
"<",
"self",
".",
"MIN_VISIT_BOUND",
":",
"x_visit",
"[",
"index",
"]",
"+=",
"self",
".",
"MIN_VISIT_BOUND",
"return",
"x_visit"
] |
https://github.com/scipy/scipy/blob/e0a749f01e79046642ccfdc419edbf9e7ca141ad/scipy/optimize/_dual_annealing.py#L75-L111
|
|
devopshq/tfs
|
56644a36dd34457dec6922eb144c21db320f16e7
|
tfs/resources.py
|
python
|
Identity.__init__
|
(self, tfs, raw=None, listVersion=False)
|
[] |
def __init__(self, tfs, raw=None, listVersion=False):
super().__init__(tfs, raw, 'identities/{0}', underProject=False, listVersion=listVersion)
|
[
"def",
"__init__",
"(",
"self",
",",
"tfs",
",",
"raw",
"=",
"None",
",",
"listVersion",
"=",
"False",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"tfs",
",",
"raw",
",",
"'identities/{0}'",
",",
"underProject",
"=",
"False",
",",
"listVersion",
"=",
"listVersion",
")"
] |
https://github.com/devopshq/tfs/blob/56644a36dd34457dec6922eb144c21db320f16e7/tfs/resources.py#L458-L459
|
||||
earthgecko/skyline
|
12754424de72593e29eb21009fb1ae3f07f3abff
|
skyline/functions/smtp/send_email.py
|
python
|
send_email
|
(current_skyline_app, to, cc, subject, body, log=True)
|
return
|
Send a plain text email.
:param current_skyline_app: the app calling the function
:param to: the to address
:param cc: the cc addresses
:param subject: the subject
:param body: the body
:type current_skyline_app: str
:type to: str
:type cc: list
:type body: str
:type log: boolean
:return: sent
:rtype: boolean
|
Send a plain text email.
|
[
"Send",
"a",
"plain",
"text",
"email",
"."
] |
def send_email(current_skyline_app, to, cc, subject, body, log=True):
"""
Send a plain text email.
:param current_skyline_app: the app calling the function
:param to: the to address
:param cc: the cc addresses
:param subject: the subject
:param body: the body
:type current_skyline_app: str
:type to: str
:type cc: list
:type body: str
:type log: boolean
:return: sent
:rtype: boolean
"""
function_str = 'functions.smtp.send_email'
if log:
current_skyline_app_logger = current_skyline_app + 'Log'
current_logger = logging.getLogger(current_skyline_app_logger)
else:
current_logger = None
sender = settings.SMTP_OPTS['sender']
primary_recipient = to
cc_recipients = False
recipients = [to]
current_logger.info(
'%s - will send to primary_recipient :: %s, cc :: %s' %
(function_str, str(primary_recipient), str(cc)))
if len(cc) > 0:
recipients = recipients + cc
if recipients:
for i_recipient in recipients:
if not primary_recipient:
primary_recipient = str(i_recipient)
if primary_recipient != i_recipient:
if not cc_recipients:
cc_recipients = str(i_recipient)
else:
new_cc_recipients = '%s,%s' % (str(cc_recipients), str(i_recipient))
cc_recipients = str(new_cc_recipients)
current_logger.info(
'%s - will send to primary_recipient :: %s, cc_recipients :: %s' %
(function_str, str(primary_recipient), str(cc_recipients)))
send_email_alert = True
if primary_recipient:
try:
msg = MIMEMultipart('mixed')
cs_ = charset.Charset('utf-8')
cs_.header_encoding = charset.QP
cs_.body_encoding = charset.QP
msg.set_charset(cs_)
msg['Subject'] = str(subject)
msg['From'] = sender
msg['To'] = primary_recipient
if cc_recipients:
msg['Cc'] = cc_recipients
html_body = '<h3><font color="#dd3023">Sky</font><font color="#6698FF">line</font><font color="black"></font></h3><br>'
html_body += '%s' % str(body)
# msg.attach(MIMEText(str(body), 'text'))
msg.attach(MIMEText(html_body, 'html'))
msg.replace_header('content-transfer-encoding', 'quoted-printable')
if settings.DOCKER_FAKE_EMAIL_ALERTS:
current_logger.info('alert_smtp - DOCKER_FAKE_EMAIL_ALERTS is set to %s, not executing SMTP command' % str(settings.DOCKER_FAKE_EMAIL_ALERTS))
send_email_alert = False
except Exception as e:
current_logger.error(traceback.format_exc())
current_logger.error(
'error :: %s :: could not send email to primary_recipient :: %s, cc_recipients :: %s - %s' %
(str(function_str), str(primary_recipient), str(cc_recipients), e))
send_email_alert = False
if send_email_alert:
try:
s = SMTP('127.0.0.1')
if cc_recipients:
s.sendmail(sender, [primary_recipient, cc_recipients], msg.as_string())
else:
s.sendmail(sender, primary_recipient, msg.as_string())
current_logger.info('%s :: email sent - %s - primary_recipient :: %s, cc_recipients :: %s' % (
str(function_str), subject, str(primary_recipient), str(cc_recipients)))
except Exception as e:
current_logger.error(traceback.format_exc())
current_logger.error(
'error :: %s :: could not send email to primary_recipient :: %s, cc_recipients :: %s - %s' % (
str(function_str), str(primary_recipient), str(cc_recipients), e))
s.quit()
else:
current_logger.info(
'alert_smtp - send_email_alert was set to %s message was not sent to primary_recipient :: %s, cc_recipients :: %s' % (
str(send_email_alert), str(primary_recipient), str(cc_recipients)))
return
|
[
"def",
"send_email",
"(",
"current_skyline_app",
",",
"to",
",",
"cc",
",",
"subject",
",",
"body",
",",
"log",
"=",
"True",
")",
":",
"function_str",
"=",
"'functions.smtp.send_email'",
"if",
"log",
":",
"current_skyline_app_logger",
"=",
"current_skyline_app",
"+",
"'Log'",
"current_logger",
"=",
"logging",
".",
"getLogger",
"(",
"current_skyline_app_logger",
")",
"else",
":",
"current_logger",
"=",
"None",
"sender",
"=",
"settings",
".",
"SMTP_OPTS",
"[",
"'sender'",
"]",
"primary_recipient",
"=",
"to",
"cc_recipients",
"=",
"False",
"recipients",
"=",
"[",
"to",
"]",
"current_logger",
".",
"info",
"(",
"'%s - will send to primary_recipient :: %s, cc :: %s'",
"%",
"(",
"function_str",
",",
"str",
"(",
"primary_recipient",
")",
",",
"str",
"(",
"cc",
")",
")",
")",
"if",
"len",
"(",
"cc",
")",
">",
"0",
":",
"recipients",
"=",
"recipients",
"+",
"cc",
"if",
"recipients",
":",
"for",
"i_recipient",
"in",
"recipients",
":",
"if",
"not",
"primary_recipient",
":",
"primary_recipient",
"=",
"str",
"(",
"i_recipient",
")",
"if",
"primary_recipient",
"!=",
"i_recipient",
":",
"if",
"not",
"cc_recipients",
":",
"cc_recipients",
"=",
"str",
"(",
"i_recipient",
")",
"else",
":",
"new_cc_recipients",
"=",
"'%s,%s'",
"%",
"(",
"str",
"(",
"cc_recipients",
")",
",",
"str",
"(",
"i_recipient",
")",
")",
"cc_recipients",
"=",
"str",
"(",
"new_cc_recipients",
")",
"current_logger",
".",
"info",
"(",
"'%s - will send to primary_recipient :: %s, cc_recipients :: %s'",
"%",
"(",
"function_str",
",",
"str",
"(",
"primary_recipient",
")",
",",
"str",
"(",
"cc_recipients",
")",
")",
")",
"send_email_alert",
"=",
"True",
"if",
"primary_recipient",
":",
"try",
":",
"msg",
"=",
"MIMEMultipart",
"(",
"'mixed'",
")",
"cs_",
"=",
"charset",
".",
"Charset",
"(",
"'utf-8'",
")",
"cs_",
".",
"header_encoding",
"=",
"charset",
".",
"QP",
"cs_",
".",
"body_encoding",
"=",
"charset",
".",
"QP",
"msg",
".",
"set_charset",
"(",
"cs_",
")",
"msg",
"[",
"'Subject'",
"]",
"=",
"str",
"(",
"subject",
")",
"msg",
"[",
"'From'",
"]",
"=",
"sender",
"msg",
"[",
"'To'",
"]",
"=",
"primary_recipient",
"if",
"cc_recipients",
":",
"msg",
"[",
"'Cc'",
"]",
"=",
"cc_recipients",
"html_body",
"=",
"'<h3><font color=\"#dd3023\">Sky</font><font color=\"#6698FF\">line</font><font color=\"black\"></font></h3><br>'",
"html_body",
"+=",
"'%s'",
"%",
"str",
"(",
"body",
")",
"# msg.attach(MIMEText(str(body), 'text'))",
"msg",
".",
"attach",
"(",
"MIMEText",
"(",
"html_body",
",",
"'html'",
")",
")",
"msg",
".",
"replace_header",
"(",
"'content-transfer-encoding'",
",",
"'quoted-printable'",
")",
"if",
"settings",
".",
"DOCKER_FAKE_EMAIL_ALERTS",
":",
"current_logger",
".",
"info",
"(",
"'alert_smtp - DOCKER_FAKE_EMAIL_ALERTS is set to %s, not executing SMTP command'",
"%",
"str",
"(",
"settings",
".",
"DOCKER_FAKE_EMAIL_ALERTS",
")",
")",
"send_email_alert",
"=",
"False",
"except",
"Exception",
"as",
"e",
":",
"current_logger",
".",
"error",
"(",
"traceback",
".",
"format_exc",
"(",
")",
")",
"current_logger",
".",
"error",
"(",
"'error :: %s :: could not send email to primary_recipient :: %s, cc_recipients :: %s - %s'",
"%",
"(",
"str",
"(",
"function_str",
")",
",",
"str",
"(",
"primary_recipient",
")",
",",
"str",
"(",
"cc_recipients",
")",
",",
"e",
")",
")",
"send_email_alert",
"=",
"False",
"if",
"send_email_alert",
":",
"try",
":",
"s",
"=",
"SMTP",
"(",
"'127.0.0.1'",
")",
"if",
"cc_recipients",
":",
"s",
".",
"sendmail",
"(",
"sender",
",",
"[",
"primary_recipient",
",",
"cc_recipients",
"]",
",",
"msg",
".",
"as_string",
"(",
")",
")",
"else",
":",
"s",
".",
"sendmail",
"(",
"sender",
",",
"primary_recipient",
",",
"msg",
".",
"as_string",
"(",
")",
")",
"current_logger",
".",
"info",
"(",
"'%s :: email sent - %s - primary_recipient :: %s, cc_recipients :: %s'",
"%",
"(",
"str",
"(",
"function_str",
")",
",",
"subject",
",",
"str",
"(",
"primary_recipient",
")",
",",
"str",
"(",
"cc_recipients",
")",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"current_logger",
".",
"error",
"(",
"traceback",
".",
"format_exc",
"(",
")",
")",
"current_logger",
".",
"error",
"(",
"'error :: %s :: could not send email to primary_recipient :: %s, cc_recipients :: %s - %s'",
"%",
"(",
"str",
"(",
"function_str",
")",
",",
"str",
"(",
"primary_recipient",
")",
",",
"str",
"(",
"cc_recipients",
")",
",",
"e",
")",
")",
"s",
".",
"quit",
"(",
")",
"else",
":",
"current_logger",
".",
"info",
"(",
"'alert_smtp - send_email_alert was set to %s message was not sent to primary_recipient :: %s, cc_recipients :: %s'",
"%",
"(",
"str",
"(",
"send_email_alert",
")",
",",
"str",
"(",
"primary_recipient",
")",
",",
"str",
"(",
"cc_recipients",
")",
")",
")",
"return"
] |
https://github.com/earthgecko/skyline/blob/12754424de72593e29eb21009fb1ae3f07f3abff/skyline/functions/smtp/send_email.py#L12-L114
|
|
caiiiac/Machine-Learning-with-Python
|
1a26c4467da41ca4ebc3d5bd789ea942ef79422f
|
MachineLearning/venv/lib/python3.5/site-packages/pandas/core/dtypes/inference.py
|
python
|
is_sequence
|
(obj)
|
Check if the object is a sequence of objects.
String types are not included as sequences here.
Parameters
----------
obj : The object to check.
Returns
-------
is_sequence : bool
Whether `obj` is a sequence of objects.
Examples
--------
>>> l = [1, 2, 3]
>>>
>>> is_sequence(l)
True
>>> is_sequence(iter(l))
False
|
Check if the object is a sequence of objects.
String types are not included as sequences here.
|
[
"Check",
"if",
"the",
"object",
"is",
"a",
"sequence",
"of",
"objects",
".",
"String",
"types",
"are",
"not",
"included",
"as",
"sequences",
"here",
"."
] |
def is_sequence(obj):
"""
Check if the object is a sequence of objects.
String types are not included as sequences here.
Parameters
----------
obj : The object to check.
Returns
-------
is_sequence : bool
Whether `obj` is a sequence of objects.
Examples
--------
>>> l = [1, 2, 3]
>>>
>>> is_sequence(l)
True
>>> is_sequence(iter(l))
False
"""
try:
iter(obj) # Can iterate over it.
len(obj) # Has a length associated with it.
return not isinstance(obj, string_and_binary_types)
except (TypeError, AttributeError):
return False
|
[
"def",
"is_sequence",
"(",
"obj",
")",
":",
"try",
":",
"iter",
"(",
"obj",
")",
"# Can iterate over it.",
"len",
"(",
"obj",
")",
"# Has a length associated with it.",
"return",
"not",
"isinstance",
"(",
"obj",
",",
"string_and_binary_types",
")",
"except",
"(",
"TypeError",
",",
"AttributeError",
")",
":",
"return",
"False"
] |
https://github.com/caiiiac/Machine-Learning-with-Python/blob/1a26c4467da41ca4ebc3d5bd789ea942ef79422f/MachineLearning/venv/lib/python3.5/site-packages/pandas/core/dtypes/inference.py#L396-L425
|
||
benoitc/couchdbkit
|
6be148640c00b54ee87a2f2d502e9d67fa5b45a8
|
couchdbkit/ext/django/schema.py
|
python
|
Options.__str__
|
(self)
|
return "%s.%s" % (smart_str(self.app_label), smart_str(self.module_name))
|
[] |
def __str__(self):
return "%s.%s" % (smart_str(self.app_label), smart_str(self.module_name))
|
[
"def",
"__str__",
"(",
"self",
")",
":",
"return",
"\"%s.%s\"",
"%",
"(",
"smart_str",
"(",
"self",
".",
"app_label",
")",
",",
"smart_str",
"(",
"self",
".",
"module_name",
")",
")"
] |
https://github.com/benoitc/couchdbkit/blob/6be148640c00b54ee87a2f2d502e9d67fa5b45a8/couchdbkit/ext/django/schema.py#L96-L97
|
|||
securityclippy/elasticintel
|
aa08d3e9f5ab1c000128e95161139ce97ff0e334
|
ingest_feed_lambda/pandas/io/formats/format.py
|
python
|
LatexFormatter._format_multicolumn
|
(self, row, ilevels)
|
return row2
|
Combine columns belonging to a group to a single multicolumn entry
according to self.multicolumn_format
e.g.:
a & & & b & c &
will become
\multicolumn{3}{l}{a} & b & \multicolumn{2}{l}{c}
|
Combine columns belonging to a group to a single multicolumn entry
according to self.multicolumn_format
|
[
"Combine",
"columns",
"belonging",
"to",
"a",
"group",
"to",
"a",
"single",
"multicolumn",
"entry",
"according",
"to",
"self",
".",
"multicolumn_format"
] |
def _format_multicolumn(self, row, ilevels):
"""
Combine columns belonging to a group to a single multicolumn entry
according to self.multicolumn_format
e.g.:
a & & & b & c &
will become
\multicolumn{3}{l}{a} & b & \multicolumn{2}{l}{c}
"""
row2 = list(row[:ilevels])
ncol = 1
coltext = ''
def append_col():
# write multicolumn if needed
if ncol > 1:
row2.append('\\multicolumn{{{ncol:d}}}{{{fmt:s}}}{{{txt:s}}}'
.format(ncol=ncol, fmt=self.multicolumn_format,
txt=coltext.strip()))
# don't modify where not needed
else:
row2.append(coltext)
for c in row[ilevels:]:
# if next col has text, write the previous
if c.strip():
if coltext:
append_col()
coltext = c
ncol = 1
# if not, add it to the previous multicolumn
else:
ncol += 1
# write last column name
if coltext:
append_col()
return row2
|
[
"def",
"_format_multicolumn",
"(",
"self",
",",
"row",
",",
"ilevels",
")",
":",
"row2",
"=",
"list",
"(",
"row",
"[",
":",
"ilevels",
"]",
")",
"ncol",
"=",
"1",
"coltext",
"=",
"''",
"def",
"append_col",
"(",
")",
":",
"# write multicolumn if needed",
"if",
"ncol",
">",
"1",
":",
"row2",
".",
"append",
"(",
"'\\\\multicolumn{{{ncol:d}}}{{{fmt:s}}}{{{txt:s}}}'",
".",
"format",
"(",
"ncol",
"=",
"ncol",
",",
"fmt",
"=",
"self",
".",
"multicolumn_format",
",",
"txt",
"=",
"coltext",
".",
"strip",
"(",
")",
")",
")",
"# don't modify where not needed",
"else",
":",
"row2",
".",
"append",
"(",
"coltext",
")",
"for",
"c",
"in",
"row",
"[",
"ilevels",
":",
"]",
":",
"# if next col has text, write the previous",
"if",
"c",
".",
"strip",
"(",
")",
":",
"if",
"coltext",
":",
"append_col",
"(",
")",
"coltext",
"=",
"c",
"ncol",
"=",
"1",
"# if not, add it to the previous multicolumn",
"else",
":",
"ncol",
"+=",
"1",
"# write last column name",
"if",
"coltext",
":",
"append_col",
"(",
")",
"return",
"row2"
] |
https://github.com/securityclippy/elasticintel/blob/aa08d3e9f5ab1c000128e95161139ce97ff0e334/ingest_feed_lambda/pandas/io/formats/format.py#L984-L1020
|
|
sagemath/sage
|
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
|
src/sage/quadratic_forms/quadratic_form__mass__Conway_Sloane_masses.py
|
python
|
conway_species_list_at_odd_prime
|
(self, p)
|
return species_list
|
Returns an integer called the 'species' which determines the type
of the orthogonal group over the finite field `F_p`.
This assumes that the given quadratic form is a unimodular Jordan
block at an odd prime `p`. When the dimension is odd then this
number is always positive, otherwise it may be positive or
negative (or zero, but that is considered positive by convention).
Note: The species of a zero dim'l form is always 0+, so we
interpret the return value of zero as positive here! =)
INPUT:
a positive prime number
OUTPUT:
a list of integers
EXAMPLES::
sage: Q = DiagonalQuadraticForm(ZZ, range(1,10))
sage: Q.conway_species_list_at_odd_prime(3)
[6, 2, 1]
::
sage: Q = DiagonalQuadraticForm(ZZ, range(1,8))
sage: Q.conway_species_list_at_odd_prime(3)
[5, 2]
sage: Q.conway_species_list_at_odd_prime(5)
[-6, 1]
|
Returns an integer called the 'species' which determines the type
of the orthogonal group over the finite field `F_p`.
|
[
"Returns",
"an",
"integer",
"called",
"the",
"species",
"which",
"determines",
"the",
"type",
"of",
"the",
"orthogonal",
"group",
"over",
"the",
"finite",
"field",
"F_p",
"."
] |
def conway_species_list_at_odd_prime(self, p):
"""
Returns an integer called the 'species' which determines the type
of the orthogonal group over the finite field `F_p`.
This assumes that the given quadratic form is a unimodular Jordan
block at an odd prime `p`. When the dimension is odd then this
number is always positive, otherwise it may be positive or
negative (or zero, but that is considered positive by convention).
Note: The species of a zero dim'l form is always 0+, so we
interpret the return value of zero as positive here! =)
INPUT:
a positive prime number
OUTPUT:
a list of integers
EXAMPLES::
sage: Q = DiagonalQuadraticForm(ZZ, range(1,10))
sage: Q.conway_species_list_at_odd_prime(3)
[6, 2, 1]
::
sage: Q = DiagonalQuadraticForm(ZZ, range(1,8))
sage: Q.conway_species_list_at_odd_prime(3)
[5, 2]
sage: Q.conway_species_list_at_odd_prime(5)
[-6, 1]
"""
## Sanity Check:
if not ((p>2) and is_prime(p)):
raise TypeError("Oops! We are assuming that p is an odd positive prime number.")
## Deal with the zero-dim'l form
if self.dim() == 0:
return [0]
## List the (unscaled/unimodular) Jordan blocks by their scale power
jordan_list = self.jordan_blocks_in_unimodular_list_by_scale_power(p)
## Make a list of species (including the two zero-dim'l forms missing at either end of the list of Jordan blocks)
species_list = []
for tmp_Q in jordan_list:
## Some useful variables
n = tmp_Q.dim()
d = tmp_Q.det()
## Determine the species
if (n % 2 != 0): ## Deal with odd dim'l forms
species = n
elif (n % 4 == 2) and (p % 4 == 3): ## Deal with even dim'l forms
species = (-1) * legendre_symbol(d, p) * n
else:
species = legendre_symbol(d, p) * n
## Append the species to the list
species_list.append(species)
## Return the species list
return species_list
|
[
"def",
"conway_species_list_at_odd_prime",
"(",
"self",
",",
"p",
")",
":",
"## Sanity Check:",
"if",
"not",
"(",
"(",
"p",
">",
"2",
")",
"and",
"is_prime",
"(",
"p",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"Oops! We are assuming that p is an odd positive prime number.\"",
")",
"## Deal with the zero-dim'l form",
"if",
"self",
".",
"dim",
"(",
")",
"==",
"0",
":",
"return",
"[",
"0",
"]",
"## List the (unscaled/unimodular) Jordan blocks by their scale power",
"jordan_list",
"=",
"self",
".",
"jordan_blocks_in_unimodular_list_by_scale_power",
"(",
"p",
")",
"## Make a list of species (including the two zero-dim'l forms missing at either end of the list of Jordan blocks)",
"species_list",
"=",
"[",
"]",
"for",
"tmp_Q",
"in",
"jordan_list",
":",
"## Some useful variables",
"n",
"=",
"tmp_Q",
".",
"dim",
"(",
")",
"d",
"=",
"tmp_Q",
".",
"det",
"(",
")",
"## Determine the species",
"if",
"(",
"n",
"%",
"2",
"!=",
"0",
")",
":",
"## Deal with odd dim'l forms",
"species",
"=",
"n",
"elif",
"(",
"n",
"%",
"4",
"==",
"2",
")",
"and",
"(",
"p",
"%",
"4",
"==",
"3",
")",
":",
"## Deal with even dim'l forms",
"species",
"=",
"(",
"-",
"1",
")",
"*",
"legendre_symbol",
"(",
"d",
",",
"p",
")",
"*",
"n",
"else",
":",
"species",
"=",
"legendre_symbol",
"(",
"d",
",",
"p",
")",
"*",
"n",
"## Append the species to the list",
"species_list",
".",
"append",
"(",
"species",
")",
"## Return the species list",
"return",
"species_list"
] |
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/quadratic_forms/quadratic_form__mass__Conway_Sloane_masses.py#L155-L222
|
|
indico/indico
|
1579ea16235bbe5f22a308b79c5902c85374721f
|
indico/util/string.py
|
python
|
strip_tags
|
(text)
|
return do_striptags(text)
|
Strip HTML tags and replace adjacent whitespace by one space.
|
Strip HTML tags and replace adjacent whitespace by one space.
|
[
"Strip",
"HTML",
"tags",
"and",
"replace",
"adjacent",
"whitespace",
"by",
"one",
"space",
"."
] |
def strip_tags(text):
"""Strip HTML tags and replace adjacent whitespace by one space."""
return do_striptags(text)
|
[
"def",
"strip_tags",
"(",
"text",
")",
":",
"return",
"do_striptags",
"(",
"text",
")"
] |
https://github.com/indico/indico/blob/1579ea16235bbe5f22a308b79c5902c85374721f/indico/util/string.py#L133-L135
|
|
krintoxi/NoobSec-Toolkit
|
38738541cbc03cedb9a3b3ed13b629f781ad64f6
|
NoobSecToolkit /scripts/sshbackdoors/backdoors/shell/pupy/pupy/packages/windows/amd64/psutil/__init__.py
|
python
|
TimeoutExpired.__init__
|
(self, seconds, pid=None, name=None)
|
[] |
def __init__(self, seconds, pid=None, name=None):
Error.__init__(self, "timeout after %s seconds" % seconds)
self.seconds = seconds
self.pid = pid
self.name = name
if (pid is not None) and (name is not None):
self.msg += " (pid=%s, name=%s)" % (pid, repr(name))
elif (pid is not None):
self.msg += " (pid=%s)" % self.pid
|
[
"def",
"__init__",
"(",
"self",
",",
"seconds",
",",
"pid",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"Error",
".",
"__init__",
"(",
"self",
",",
"\"timeout after %s seconds\"",
"%",
"seconds",
")",
"self",
".",
"seconds",
"=",
"seconds",
"self",
".",
"pid",
"=",
"pid",
"self",
".",
"name",
"=",
"name",
"if",
"(",
"pid",
"is",
"not",
"None",
")",
"and",
"(",
"name",
"is",
"not",
"None",
")",
":",
"self",
".",
"msg",
"+=",
"\" (pid=%s, name=%s)\"",
"%",
"(",
"pid",
",",
"repr",
"(",
"name",
")",
")",
"elif",
"(",
"pid",
"is",
"not",
"None",
")",
":",
"self",
".",
"msg",
"+=",
"\" (pid=%s)\"",
"%",
"self",
".",
"pid"
] |
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit /scripts/sshbackdoors/backdoors/shell/pupy/pupy/packages/windows/amd64/psutil/__init__.py#L269-L277
|
||||
eirannejad/pyRevit
|
49c0b7eb54eb343458ce1365425e6552d0c47d44
|
site-packages/sqlalchemy/engine/interfaces.py
|
python
|
Dialect._get_default_schema_name
|
(self, connection)
|
Return the string name of the currently selected schema from
the given connection.
This is used by the default implementation to populate the
"default_schema_name" attribute and is called exactly
once upon first connect.
|
Return the string name of the currently selected schema from
the given connection.
|
[
"Return",
"the",
"string",
"name",
"of",
"the",
"currently",
"selected",
"schema",
"from",
"the",
"given",
"connection",
"."
] |
def _get_default_schema_name(self, connection):
"""Return the string name of the currently selected schema from
the given connection.
This is used by the default implementation to populate the
"default_schema_name" attribute and is called exactly
once upon first connect.
"""
raise NotImplementedError()
|
[
"def",
"_get_default_schema_name",
"(",
"self",
",",
"connection",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] |
https://github.com/eirannejad/pyRevit/blob/49c0b7eb54eb343458ce1365425e6552d0c47d44/site-packages/sqlalchemy/engine/interfaces.py#L477-L487
|
||
sosreport/sos
|
900e8bea7f3cd36c1dd48f3cbb351ab92f766654
|
sos/collector/clusters/__init__.py
|
python
|
Cluster.set_node_label
|
(self, node)
|
return ''
|
This may be overridden by clusters profiles subclassing this class
If there is a distinction between primaries and nodes, or types of
nodes, then this can be used to label the sosreport archive differently
|
This may be overridden by clusters profiles subclassing this class
|
[
"This",
"may",
"be",
"overridden",
"by",
"clusters",
"profiles",
"subclassing",
"this",
"class"
] |
def set_node_label(self, node):
"""This may be overridden by clusters profiles subclassing this class
If there is a distinction between primaries and nodes, or types of
nodes, then this can be used to label the sosreport archive differently
"""
return ''
|
[
"def",
"set_node_label",
"(",
"self",
",",
"node",
")",
":",
"return",
"''"
] |
https://github.com/sosreport/sos/blob/900e8bea7f3cd36c1dd48f3cbb351ab92f766654/sos/collector/clusters/__init__.py#L271-L277
|
|
opsmop/opsmop
|
376ca587f8c5f9ca8ed1829909d075c339066034
|
opsmop/core/errors.py
|
python
|
ValidationError.__init__
|
(self, resource=None, msg=None)
|
[] |
def __init__(self, resource=None, msg=None):
self.resource = resource
self.msg = msg
|
[
"def",
"__init__",
"(",
"self",
",",
"resource",
"=",
"None",
",",
"msg",
"=",
"None",
")",
":",
"self",
".",
"resource",
"=",
"resource",
"self",
".",
"msg",
"=",
"msg"
] |
https://github.com/opsmop/opsmop/blob/376ca587f8c5f9ca8ed1829909d075c339066034/opsmop/core/errors.py#L37-L39
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.