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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
buke/GreenOdoo | 3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df | runtime/python/lib/python2.7/site-packages/South-0.7.3-py2.7.egg/south/creator/actions.py | python | AddUnique.console_line | (self) | return " + Added unique constraint for %s on %s.%s" % (
[x.name for x in self.fields],
self.model._meta.app_label,
self.model._meta.object_name,
) | Returns the string to print on the console, e.g. ' + Added field foo | Returns the string to print on the console, e.g. ' + Added field foo | [
"Returns",
"the",
"string",
"to",
"print",
"on",
"the",
"console",
"e",
".",
"g",
".",
"+",
"Added",
"field",
"foo"
] | def console_line(self):
"Returns the string to print on the console, e.g. ' + Added field foo'"
return " + Added unique constraint for %s on %s.%s" % (
[x.name for x in self.fields],
self.model._meta.app_label,
self.model._meta.object_name,
) | [
"def",
"console_line",
"(",
"self",
")",
":",
"return",
"\" + Added unique constraint for %s on %s.%s\"",
"%",
"(",
"[",
"x",
".",
"name",
"for",
"x",
"in",
"self",
".",
"fields",
"]",
",",
"self",
".",
"model",
".",
"_meta",
".",
"app_label",
",",
"self",... | https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/South-0.7.3-py2.7.egg/south/creator/actions.py#L375-L381 | |
DLR-RM/BlenderProc | e04e03f34b66702bbca45d1ac701599b6d764609 | blenderproc/python/constructor/RandomRoomConstructor.py | python | _sample_new_object_poses_on_face | (current_obj: MeshObject, face_bb, bvh_cache_for_intersection: dict,
placed_objects: List[MeshObject], wall_obj: MeshObject) | return no_collision | Sample new object poses on the current `floor_obj`.
:param face_bb:
:return: True, if there is no collision | Sample new object poses on the current `floor_obj`. | [
"Sample",
"new",
"object",
"poses",
"on",
"the",
"current",
"floor_obj",
"."
] | def _sample_new_object_poses_on_face(current_obj: MeshObject, face_bb, bvh_cache_for_intersection: dict,
placed_objects: List[MeshObject], wall_obj: MeshObject):
"""
Sample new object poses on the current `floor_obj`.
:param face_bb:
:return: True, if there is no collision
"""
random_placed_value = [random.uniform(face_bb[0][i], face_bb[1][i]) for i in range(2)]
random_placed_value.append(0.0) # floor z value
random_placed_rotation = [0, 0, random.uniform(0, np.pi * 2.0)]
current_obj.set_location(random_placed_value)
current_obj.set_rotation_euler(random_placed_rotation)
# Remove bvh cache, as object has changed
if current_obj.get_name() in bvh_cache_for_intersection:
del bvh_cache_for_intersection[current_obj.get_name()]
# perform check if object can be placed there
no_collision = CollisionUtility.check_intersections(current_obj,
bvh_cache=bvh_cache_for_intersection,
objects_to_check_against=placed_objects,
list_of_objects_with_no_inside_check=[wall_obj])
return no_collision | [
"def",
"_sample_new_object_poses_on_face",
"(",
"current_obj",
":",
"MeshObject",
",",
"face_bb",
",",
"bvh_cache_for_intersection",
":",
"dict",
",",
"placed_objects",
":",
"List",
"[",
"MeshObject",
"]",
",",
"wall_obj",
":",
"MeshObject",
")",
":",
"random_placed... | https://github.com/DLR-RM/BlenderProc/blob/e04e03f34b66702bbca45d1ac701599b6d764609/blenderproc/python/constructor/RandomRoomConstructor.py#L482-L507 | |
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/Python-2.7.9/Tools/bgen/bgen/bgenVariable.py | python | Variable.passArgument | (self) | return "/*mode?*/" + self.type.passInput(self.name) | Return the string required to pass the variable as argument.
For "in" arguments, return the variable name.
For "out" and "in out" arguments,
return its name prefixed with "&". | Return the string required to pass the variable as argument. | [
"Return",
"the",
"string",
"required",
"to",
"pass",
"the",
"variable",
"as",
"argument",
"."
] | def passArgument(self):
"""Return the string required to pass the variable as argument.
For "in" arguments, return the variable name.
For "out" and "in out" arguments,
return its name prefixed with "&".
"""
if self.mode == InMode:
return self.type.passInput(self.name)
if self.mode & RefMode:
return self.type.passReference(self.name)
if self.mode in (OutMode, InOutMode):
return self.type.passOutput(self.name)
# XXX Shouldn't get here
return "/*mode?*/" + self.type.passInput(self.name) | [
"def",
"passArgument",
"(",
"self",
")",
":",
"if",
"self",
".",
"mode",
"==",
"InMode",
":",
"return",
"self",
".",
"type",
".",
"passInput",
"(",
"self",
".",
"name",
")",
"if",
"self",
".",
"mode",
"&",
"RefMode",
":",
"return",
"self",
".",
"ty... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Tools/bgen/bgen/bgenVariable.py#L75-L89 | |
PyCQA/pylint | 3fc855f9d0fa8e6410be5a23cf954ffd5471b4eb | pylint/checkers/variables.py | python | VariablesChecker.leave_classdef | (self, _: nodes.ClassDef) | leave class: update consumption analysis variable | leave class: update consumption analysis variable | [
"leave",
"class",
":",
"update",
"consumption",
"analysis",
"variable"
] | def leave_classdef(self, _: nodes.ClassDef) -> None:
"""leave class: update consumption analysis variable"""
# do not check for not used locals here (no sense)
self._to_consume.pop() | [
"def",
"leave_classdef",
"(",
"self",
",",
"_",
":",
"nodes",
".",
"ClassDef",
")",
"->",
"None",
":",
"# do not check for not used locals here (no sense)",
"self",
".",
"_to_consume",
".",
"pop",
"(",
")"
] | https://github.com/PyCQA/pylint/blob/3fc855f9d0fa8e6410be5a23cf954ffd5471b4eb/pylint/checkers/variables.py#L939-L942 | ||
scrapinghub/spidermon | f2b21e45e70796f583bbb97f39b823c31d242b17 | spidermon/core/monitors.py | python | Monitor.order | (self) | return self.method.options.order | [] | def order(self):
return self.method.options.order | [
"def",
"order",
"(",
"self",
")",
":",
"return",
"self",
".",
"method",
".",
"options",
".",
"order"
] | https://github.com/scrapinghub/spidermon/blob/f2b21e45e70796f583bbb97f39b823c31d242b17/spidermon/core/monitors.py#L37-L38 | |||
home-assistant/core | 265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1 | homeassistant/components/motioneye/config_flow.py | python | MotionEyeOptionsFlow.__init__ | (self, config_entry: ConfigEntry) | Initialize a motionEye options flow. | Initialize a motionEye options flow. | [
"Initialize",
"a",
"motionEye",
"options",
"flow",
"."
] | def __init__(self, config_entry: ConfigEntry) -> None:
"""Initialize a motionEye options flow."""
self._config_entry = config_entry | [
"def",
"__init__",
"(",
"self",
",",
"config_entry",
":",
"ConfigEntry",
")",
"->",
"None",
":",
"self",
".",
"_config_entry",
"=",
"config_entry"
] | https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/motioneye/config_flow.py#L195-L197 | ||
wistbean/fxxkpython | 88e16d79d8dd37236ba6ecd0d0ff11d63143968c | vip/qyxuan/projects/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/pkg_resources/__init__.py | python | IMetadataProvider.has_metadata | (name) | Does the package's distribution contain the named metadata? | Does the package's distribution contain the named metadata? | [
"Does",
"the",
"package",
"s",
"distribution",
"contain",
"the",
"named",
"metadata?"
] | def has_metadata(name):
"""Does the package's distribution contain the named metadata?""" | [
"def",
"has_metadata",
"(",
"name",
")",
":"
] | https://github.com/wistbean/fxxkpython/blob/88e16d79d8dd37236ba6ecd0d0ff11d63143968c/vip/qyxuan/projects/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/pkg_resources/__init__.py#L501-L502 | ||
volatilityfoundation/community | d9fc0727266ec552bb6412142f3f31440c601664 | FrancescoPicasso/mimikatz.py | python | MemoryScanner._find_first | (self, address_space, offset, maxlen, signature) | Raw memory scanner with overlap. | Raw memory scanner with overlap. | [
"Raw",
"memory",
"scanner",
"with",
"overlap",
"."
] | def _find_first(self, address_space, offset, maxlen, signature):
"""Raw memory scanner with overlap."""
# Allow some bytes for overlapping signatures
overlap = 1024
i = offset
while i < offset + maxlen:
to_read = min(
constants.SCAN_BLOCKSIZE + overlap, offset + maxlen - i)
block = address_space.zread(i, to_read)
if block:
match = block.find(signature)
if match >= 0:
return match
i += constants.SCAN_BLOCKSIZE | [
"def",
"_find_first",
"(",
"self",
",",
"address_space",
",",
"offset",
",",
"maxlen",
",",
"signature",
")",
":",
"# Allow some bytes for overlapping signatures",
"overlap",
"=",
"1024",
"i",
"=",
"offset",
"while",
"i",
"<",
"offset",
"+",
"maxlen",
":",
"to... | https://github.com/volatilityfoundation/community/blob/d9fc0727266ec552bb6412142f3f31440c601664/FrancescoPicasso/mimikatz.py#L93-L106 | ||
shmilylty/OneForAll | 48591142a641e80f8a64ab215d11d06b696702d7 | common/utils.py | python | export_all | (alive, fmt, path, datas) | 将所有结果数据导出
:param bool alive: 只导出存活子域结果
:param str fmt: 导出文件格式
:param str path: 导出文件路径
:param list datas: 待导出的结果数据 | 将所有结果数据导出 | [
"将所有结果数据导出"
] | def export_all(alive, fmt, path, datas):
"""
将所有结果数据导出
:param bool alive: 只导出存活子域结果
:param str fmt: 导出文件格式
:param str path: 导出文件路径
:param list datas: 待导出的结果数据
"""
fmt = check_format(fmt)
timestamp = get_timestring()
name = f'all_subdomain_result_{timestamp}'
export_all_results(path, name, fmt, datas)
export_all_subdomains(alive, path, name, datas) | [
"def",
"export_all",
"(",
"alive",
",",
"fmt",
",",
"path",
",",
"datas",
")",
":",
"fmt",
"=",
"check_format",
"(",
"fmt",
")",
"timestamp",
"=",
"get_timestring",
"(",
")",
"name",
"=",
"f'all_subdomain_result_{timestamp}'",
"export_all_results",
"(",
"path"... | https://github.com/shmilylty/OneForAll/blob/48591142a641e80f8a64ab215d11d06b696702d7/common/utils.py#L352-L365 | ||
jameskermode/f90wrap | 6a6021d3d8c01125e13ecd0ef8faa52f19e5be3e | f90wrap/f90wrapgen.py | python | F90WrapperGenerator.visit_Root | (self, node) | Write a wrapper for top-level procedures. | Write a wrapper for top-level procedures. | [
"Write",
"a",
"wrapper",
"for",
"top",
"-",
"level",
"procedures",
"."
] | def visit_Root(self, node):
"""
Write a wrapper for top-level procedures.
"""
# clean up any previous wrapper files
top_level_wrapper_file = '%s%s.f90' % (self.prefix, 'toplevel')
f90_wrapper_files = (['%s%s.f90' % (self.prefix,
os.path.splitext(os.path.basename(mod.filename))[0])
for mod in node.modules] +
[top_level_wrapper_file])
for f90_wrapper_file in f90_wrapper_files:
if os.path.exists(f90_wrapper_file):
os.unlink(f90_wrapper_file)
self.code = []
self.generic_visit(node)
if len(self.code) > 0:
f90_wrapper_file = open(top_level_wrapper_file, 'w')
f90_wrapper_file.write(str(self))
f90_wrapper_file.close() | [
"def",
"visit_Root",
"(",
"self",
",",
"node",
")",
":",
"# clean up any previous wrapper files",
"top_level_wrapper_file",
"=",
"'%s%s.f90'",
"%",
"(",
"self",
".",
"prefix",
",",
"'toplevel'",
")",
"f90_wrapper_files",
"=",
"(",
"[",
"'%s%s.f90'",
"%",
"(",
"s... | https://github.com/jameskermode/f90wrap/blob/6a6021d3d8c01125e13ecd0ef8faa52f19e5be3e/f90wrap/f90wrapgen.py#L91-L110 | ||
translate/translate | 72816df696b5263abfe80ab59129b299b85ae749 | translate/convert/csv2po.py | python | convertcsv | (
inputfile,
outputfile,
templatefile,
charset=None,
columnorder=None,
duplicatestyle="msgctxt",
) | return 1 | reads in inputfile using csvl10n, converts using csv2po, writes to
outputfile | reads in inputfile using csvl10n, converts using csv2po, writes to
outputfile | [
"reads",
"in",
"inputfile",
"using",
"csvl10n",
"converts",
"using",
"csv2po",
"writes",
"to",
"outputfile"
] | def convertcsv(
inputfile,
outputfile,
templatefile,
charset=None,
columnorder=None,
duplicatestyle="msgctxt",
):
"""reads in inputfile using csvl10n, converts using csv2po, writes to
outputfile
"""
inputstore = csvl10n.csvfile(inputfile, fieldnames=columnorder)
if templatefile is None:
convertor = csv2po(charset=charset, duplicatestyle=duplicatestyle)
else:
templatestore = po.pofile(templatefile)
convertor = csv2po(
templatestore, charset=charset, duplicatestyle=duplicatestyle
)
outputstore = convertor.convertstore(inputstore)
if outputstore.isempty():
return 0
outputstore.serialize(outputfile)
return 1 | [
"def",
"convertcsv",
"(",
"inputfile",
",",
"outputfile",
",",
"templatefile",
",",
"charset",
"=",
"None",
",",
"columnorder",
"=",
"None",
",",
"duplicatestyle",
"=",
"\"msgctxt\"",
",",
")",
":",
"inputstore",
"=",
"csvl10n",
".",
"csvfile",
"(",
"inputfi... | https://github.com/translate/translate/blob/72816df696b5263abfe80ab59129b299b85ae749/translate/convert/csv2po.py#L225-L248 | |
kodi-community-addons/plugin.audio.spotify | 15cb070120a375613ca45c2a3129ea2abe43a1e8 | resources/lib/spotipy/client.py | python | Spotify.shuffle | (self, state, device_id = None) | Toggle playback shuffling.
Parameters:
- state - true or false
- device_id - device target for playback | Toggle playback shuffling. | [
"Toggle",
"playback",
"shuffling",
"."
] | def shuffle(self, state, device_id = None):
''' Toggle playback shuffling.
Parameters:
- state - true or false
- device_id - device target for playback
'''
if not isinstance(state, bool):
self._warn('state must be a boolean')
return
state = str(state).lower()
self._put(self._append_device_id("me/player/shuffle?state=%s" % state, device_id)) | [
"def",
"shuffle",
"(",
"self",
",",
"state",
",",
"device_id",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"state",
",",
"bool",
")",
":",
"self",
".",
"_warn",
"(",
"'state must be a boolean'",
")",
"return",
"state",
"=",
"str",
"(",
"stat... | https://github.com/kodi-community-addons/plugin.audio.spotify/blob/15cb070120a375613ca45c2a3129ea2abe43a1e8/resources/lib/spotipy/client.py#L1037-L1048 | ||
psychopy/psychopy | 01b674094f38d0e0bd51c45a6f66f671d7041696 | psychopy/visual/textbox/textureatlas.py | python | TextureAtlas.__init__ | (self, width=1024, height=1024, depth=1) | Initialize a new atlas of given size.
Parameters
----------
width : int
Width of the underlying texture
height : int
Height of the underlying texture
depth : 1 or 3
Depth of the underlying texture | Initialize a new atlas of given size. | [
"Initialize",
"a",
"new",
"atlas",
"of",
"given",
"size",
"."
] | def __init__(self, width=1024, height=1024, depth=1):
'''
Initialize a new atlas of given size.
Parameters
----------
width : int
Width of the underlying texture
height : int
Height of the underlying texture
depth : 1 or 3
Depth of the underlying texture
'''
super(TextureAtlas, self).__init__()
self.width = int(math.pow(2, int(math.log(width, 2) + 0.5)))
self.height = int(math.pow(2, int(math.log(height, 2) + 0.5)))
self.depth = depth
self.nodes = [(0, 0, self.width), ]
self.data = np.zeros((self.height, self.width, self.depth),
dtype=np.ubyte)
self.texid = None
self.used = 0
self.max_y = 0 | [
"def",
"__init__",
"(",
"self",
",",
"width",
"=",
"1024",
",",
"height",
"=",
"1024",
",",
"depth",
"=",
"1",
")",
":",
"super",
"(",
"TextureAtlas",
",",
"self",
")",
".",
"__init__",
"(",
")",
"self",
".",
"width",
"=",
"int",
"(",
"math",
"."... | https://github.com/psychopy/psychopy/blob/01b674094f38d0e0bd51c45a6f66f671d7041696/psychopy/visual/textbox/textureatlas.py#L48-L73 | ||
XKNX/xknx | 1deeeb3dc0978aebacf14492a84e1f1eaf0970ed | xknx/io/request_response/request_response.py | python | RequestResponse.on_error_hook | (self, knxipframe: KNXIPFrame) | Do something after having received error within given time. May be overwritten in derived class. | Do something after having received error within given time. May be overwritten in derived class. | [
"Do",
"something",
"after",
"having",
"received",
"error",
"within",
"given",
"time",
".",
"May",
"be",
"overwritten",
"in",
"derived",
"class",
"."
] | def on_error_hook(self, knxipframe: KNXIPFrame) -> None:
"""Do something after having received error within given time. May be overwritten in derived class."""
logger.debug(
"Error: KNX bus responded to request of type '%s' with error in '%s': %s",
self.__class__.__name__,
self.awaited_response_class.__name__,
knxipframe.body.status_code, # type: ignore
) | [
"def",
"on_error_hook",
"(",
"self",
",",
"knxipframe",
":",
"KNXIPFrame",
")",
"->",
"None",
":",
"logger",
".",
"debug",
"(",
"\"Error: KNX bus responded to request of type '%s' with error in '%s': %s\"",
",",
"self",
".",
"__class__",
".",
"__name__",
",",
"self",
... | https://github.com/XKNX/xknx/blob/1deeeb3dc0978aebacf14492a84e1f1eaf0970ed/xknx/io/request_response/request_response.py#L89-L96 | ||
pypa/pipenv | b21baade71a86ab3ee1429f71fbc14d4f95fb75d | pipenv/vendor/vistir/_winconsole.py | python | query_registry_value | (root, key_name, value) | [] | def query_registry_value(root, key_name, value):
try:
import winreg
except ImportError:
import _winreg as winreg
try:
with winreg.OpenKeyEx(root, key_name, 0, winreg.KEY_READ) as key:
return get_value_from_tuple(*winreg.QueryValueEx(key, value))
except OSError:
return None | [
"def",
"query_registry_value",
"(",
"root",
",",
"key_name",
",",
"value",
")",
":",
"try",
":",
"import",
"winreg",
"except",
"ImportError",
":",
"import",
"_winreg",
"as",
"winreg",
"try",
":",
"with",
"winreg",
".",
"OpenKeyEx",
"(",
"root",
",",
"key_n... | https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/vendor/vistir/_winconsole.py#L508-L517 | ||||
Jenyay/outwiker | 50530cf7b3f71480bb075b2829bc0669773b835b | src/outwiker/gui/controls/ultimatelistctrl.py | python | CommandListEvent.GetPoint | (self) | return self.m_pointDrag | Returns the position of the mouse pointer if the event is a drag event. | Returns the position of the mouse pointer if the event is a drag event. | [
"Returns",
"the",
"position",
"of",
"the",
"mouse",
"pointer",
"if",
"the",
"event",
"is",
"a",
"drag",
"event",
"."
] | def GetPoint(self):
""" Returns the position of the mouse pointer if the event is a drag event. """
return self.m_pointDrag | [
"def",
"GetPoint",
"(",
"self",
")",
":",
"return",
"self",
".",
"m_pointDrag"
] | https://github.com/Jenyay/outwiker/blob/50530cf7b3f71480bb075b2829bc0669773b835b/src/outwiker/gui/controls/ultimatelistctrl.py#L2337-L2340 | |
pypa/pipenv | b21baade71a86ab3ee1429f71fbc14d4f95fb75d | pipenv/vendor/charset_normalizer/md.py | python | TooManySymbolOrPunctuationPlugin.__init__ | (self) | [] | def __init__(self) -> None:
self._punctuation_count = 0 # type: int
self._symbol_count = 0 # type: int
self._character_count = 0 # type: int
self._last_printable_char = None # type: Optional[str]
self._frenzy_symbol_in_word = False | [
"def",
"__init__",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"_punctuation_count",
"=",
"0",
"# type: int",
"self",
".",
"_symbol_count",
"=",
"0",
"# type: int",
"self",
".",
"_character_count",
"=",
"0",
"# type: int",
"self",
".",
"_last_printable_c... | https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/vendor/charset_normalizer/md.py#L59-L65 | ||||
alan-turing-institute/sktime | 79cc513346b1257a6f3fa8e4ed855b5a2a7de716 | sktime/transformations/series/func_transform.py | python | FunctionTransformer.get_test_params | (cls) | return [params1, params2] | Return testing parameter settings for the estimator.
Returns
-------
params : dict or list of dict, default = {}
Parameters to create testing instances of the class
Each dict are parameters to construct an "interesting" test instance, i.e.,
`MyClass(**params)` or `MyClass(**params[i])` creates a valid test instance.
`create_test_instance` uses the first (or only) dictionary in `params` | Return testing parameter settings for the estimator. | [
"Return",
"testing",
"parameter",
"settings",
"for",
"the",
"estimator",
"."
] | def get_test_params(cls):
"""Return testing parameter settings for the estimator.
Returns
-------
params : dict or list of dict, default = {}
Parameters to create testing instances of the class
Each dict are parameters to construct an "interesting" test instance, i.e.,
`MyClass(**params)` or `MyClass(**params[i])` creates a valid test instance.
`create_test_instance` uses the first (or only) dictionary in `params`
"""
# default params, identity transform
params1 = {}
# log-transformer, with exp inverse
params2 = {"func": np.log1p, "inverse_func": np.expm1}
return [params1, params2] | [
"def",
"get_test_params",
"(",
"cls",
")",
":",
"# default params, identity transform",
"params1",
"=",
"{",
"}",
"# log-transformer, with exp inverse",
"params2",
"=",
"{",
"\"func\"",
":",
"np",
".",
"log1p",
",",
"\"inverse_func\"",
":",
"np",
".",
"expm1",
"}"... | https://github.com/alan-turing-institute/sktime/blob/79cc513346b1257a6f3fa8e4ed855b5a2a7de716/sktime/transformations/series/func_transform.py#L191-L208 | |
ucfopen/canvasapi | 3f1a71e23c86a49dbaa6e84f6c0e81c297b86e36 | canvasapi/outcome.py | python | OutcomeGroup.get_linked_outcomes | (self, **kwargs) | return PaginatedList(
OutcomeLink,
self._requester,
"GET",
"{}/outcome_groups/{}/outcomes".format(self.context_ref(), self.id),
_kwargs=combine_kwargs(**kwargs),
) | List linked outcomes.
:calls: `GET /api/v1/global/outcome_groups/:id/outcomes \
<https://canvas.instructure.com/doc/api/outcome_groups.html#method.outcome_groups_api.outcomes>`_
or `GET /api/v1/accounts/:account_id/outcome_groups/:id/outcomes \
<https://canvas.instructure.com/doc/api/outcome_groups.html#method.outcome_groups_api.outcomes>`_
or `GET /api/v1/courses/:course_id/outcome_groups/:id/outcomes \
<https://canvas.instructure.com/doc/api/outcome_groups.html#method.outcome_groups_api.outcomes>`_
:returns: Paginated List of Outcomes linked to the group.
:rtype: :class:`canvasapi.paginated_list.PaginatedList` of
:class:`canvasapi.outcome.OutcomeLink` | List linked outcomes. | [
"List",
"linked",
"outcomes",
"."
] | def get_linked_outcomes(self, **kwargs):
"""
List linked outcomes.
:calls: `GET /api/v1/global/outcome_groups/:id/outcomes \
<https://canvas.instructure.com/doc/api/outcome_groups.html#method.outcome_groups_api.outcomes>`_
or `GET /api/v1/accounts/:account_id/outcome_groups/:id/outcomes \
<https://canvas.instructure.com/doc/api/outcome_groups.html#method.outcome_groups_api.outcomes>`_
or `GET /api/v1/courses/:course_id/outcome_groups/:id/outcomes \
<https://canvas.instructure.com/doc/api/outcome_groups.html#method.outcome_groups_api.outcomes>`_
:returns: Paginated List of Outcomes linked to the group.
:rtype: :class:`canvasapi.paginated_list.PaginatedList` of
:class:`canvasapi.outcome.OutcomeLink`
"""
return PaginatedList(
OutcomeLink,
self._requester,
"GET",
"{}/outcome_groups/{}/outcomes".format(self.context_ref(), self.id),
_kwargs=combine_kwargs(**kwargs),
) | [
"def",
"get_linked_outcomes",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"PaginatedList",
"(",
"OutcomeLink",
",",
"self",
".",
"_requester",
",",
"\"GET\"",
",",
"\"{}/outcome_groups/{}/outcomes\"",
".",
"format",
"(",
"self",
".",
"context_ref",... | https://github.com/ucfopen/canvasapi/blob/3f1a71e23c86a49dbaa6e84f6c0e81c297b86e36/canvasapi/outcome.py#L139-L160 | |
python/mypy | 17850b3bd77ae9efb5d21f656c4e4e05ac48d894 | mypy/meet.py | python | narrow_declared_type | (declared: Type, narrowed: Type) | return narrowed | Return the declared type narrowed down to another type. | Return the declared type narrowed down to another type. | [
"Return",
"the",
"declared",
"type",
"narrowed",
"down",
"to",
"another",
"type",
"."
] | def narrow_declared_type(declared: Type, narrowed: Type) -> Type:
"""Return the declared type narrowed down to another type."""
# TODO: check infinite recursion for aliases here.
if isinstance(narrowed, TypeGuardedType): # type: ignore[misc]
# A type guard forces the new type even if it doesn't overlap the old.
return narrowed.type_guard
declared = get_proper_type(declared)
narrowed = get_proper_type(narrowed)
if declared == narrowed:
return declared
if isinstance(declared, UnionType):
return make_simplified_union([narrow_declared_type(x, narrowed)
for x in declared.relevant_items()])
elif not is_overlapping_types(declared, narrowed,
prohibit_none_typevar_overlap=True):
if state.strict_optional:
return UninhabitedType()
else:
return NoneType()
elif isinstance(narrowed, UnionType):
return make_simplified_union([narrow_declared_type(declared, x)
for x in narrowed.relevant_items()])
elif isinstance(narrowed, AnyType):
return narrowed
elif isinstance(narrowed, TypeVarType) and is_subtype(narrowed.upper_bound, declared):
return narrowed
elif isinstance(declared, TypeType) and isinstance(narrowed, TypeType):
return TypeType.make_normalized(narrow_declared_type(declared.item, narrowed.item))
elif (isinstance(declared, TypeType)
and isinstance(narrowed, Instance)
and narrowed.type.is_metaclass()):
# We'd need intersection types, so give up.
return declared
elif isinstance(declared, (Instance, TupleType, TypeType, LiteralType)):
return meet_types(declared, narrowed)
elif isinstance(declared, TypedDictType) and isinstance(narrowed, Instance):
# Special case useful for selecting TypedDicts from unions using isinstance(x, dict).
if (narrowed.type.fullname == 'builtins.dict' and
all(isinstance(t, AnyType) for t in get_proper_types(narrowed.args))):
return declared
return meet_types(declared, narrowed)
return narrowed | [
"def",
"narrow_declared_type",
"(",
"declared",
":",
"Type",
",",
"narrowed",
":",
"Type",
")",
"->",
"Type",
":",
"# TODO: check infinite recursion for aliases here.",
"if",
"isinstance",
"(",
"narrowed",
",",
"TypeGuardedType",
")",
":",
"# type: ignore[misc]",
"# A... | https://github.com/python/mypy/blob/17850b3bd77ae9efb5d21f656c4e4e05ac48d894/mypy/meet.py#L52-L95 | |
pytorch/benchmark | 5c93a5389563a5b6ccfa17d265d60f4fe7272f31 | torchbenchmark/models/speech_transformer/speech_transformer/data/data.py | python | _collate_fn | (batch, LFR_m=1, LFR_n=1) | return xs_pad, ilens, ys_pad | Args:
batch: list, len(batch) = 1. See AudioDataset.__getitem__()
Returns:
xs_pad: N x Ti x D, torch.Tensor
ilens : N, torch.Tentor
ys_pad: N x To, torch.Tensor | Args:
batch: list, len(batch) = 1. See AudioDataset.__getitem__()
Returns:
xs_pad: N x Ti x D, torch.Tensor
ilens : N, torch.Tentor
ys_pad: N x To, torch.Tensor | [
"Args",
":",
"batch",
":",
"list",
"len",
"(",
"batch",
")",
"=",
"1",
".",
"See",
"AudioDataset",
".",
"__getitem__",
"()",
"Returns",
":",
"xs_pad",
":",
"N",
"x",
"Ti",
"x",
"D",
"torch",
".",
"Tensor",
"ilens",
":",
"N",
"torch",
".",
"Tentor",... | def _collate_fn(batch, LFR_m=1, LFR_n=1):
"""
Args:
batch: list, len(batch) = 1. See AudioDataset.__getitem__()
Returns:
xs_pad: N x Ti x D, torch.Tensor
ilens : N, torch.Tentor
ys_pad: N x To, torch.Tensor
"""
# batch should be located in list
assert len(batch) == 1
batch = load_inputs_and_targets(batch[0], LFR_m=LFR_m, LFR_n=LFR_n)
xs, ys = batch
# TODO: perform subsamping
# get batch of lengths of input sequences
ilens = np.array([x.shape[0] for x in xs])
# perform padding and convert to tensor
xs_pad = pad_list([torch.from_numpy(x).float() for x in xs], 0)
ilens = torch.from_numpy(ilens)
ys_pad = pad_list([torch.from_numpy(y).long() for y in ys], IGNORE_ID)
return xs_pad, ilens, ys_pad | [
"def",
"_collate_fn",
"(",
"batch",
",",
"LFR_m",
"=",
"1",
",",
"LFR_n",
"=",
"1",
")",
":",
"# batch should be located in list",
"assert",
"len",
"(",
"batch",
")",
"==",
"1",
"batch",
"=",
"load_inputs_and_targets",
"(",
"batch",
"[",
"0",
"]",
",",
"... | https://github.com/pytorch/benchmark/blob/5c93a5389563a5b6ccfa17d265d60f4fe7272f31/torchbenchmark/models/speech_transformer/speech_transformer/data/data.py#L115-L138 | |
MeanEYE/Sunflower | 1024bbdde3b8e202ddad3553b321a7b6230bffc9 | sunflower/gui/operation_dialog.py | python | DeleteDialog._set_operation_image | (self, icon_name=None) | Set default or specified operation image | Set default or specified operation image | [
"Set",
"default",
"or",
"specified",
"operation",
"image"
] | def _set_operation_image(self, icon_name=None):
"""Set default or specified operation image"""
OperationDialog._set_operation_image(self, icon_name)
# set default icon
if icon_name is None:
self._operation_image.set_from_icon_name('edit-delete-symbolic', Gtk.IconSize.BUTTON) | [
"def",
"_set_operation_image",
"(",
"self",
",",
"icon_name",
"=",
"None",
")",
":",
"OperationDialog",
".",
"_set_operation_image",
"(",
"self",
",",
"icon_name",
")",
"# set default icon",
"if",
"icon_name",
"is",
"None",
":",
"self",
".",
"_operation_image",
... | https://github.com/MeanEYE/Sunflower/blob/1024bbdde3b8e202ddad3553b321a7b6230bffc9/sunflower/gui/operation_dialog.py#L484-L490 | ||
debian-calibre/calibre | 020fc81d3936a64b2ac51459ecb796666ab6a051 | src/calibre/utils/zipfile.py | python | ZipFile.replace | (self, filename, arcname=None, compress_type=None) | Delete arcname, and put the bytes from filename into the
archive under the name arcname. | Delete arcname, and put the bytes from filename into the
archive under the name arcname. | [
"Delete",
"arcname",
"and",
"put",
"the",
"bytes",
"from",
"filename",
"into",
"the",
"archive",
"under",
"the",
"name",
"arcname",
"."
] | def replace(self, filename, arcname=None, compress_type=None):
"""Delete arcname, and put the bytes from filename into the
archive under the name arcname."""
deleteName = arcname
if deleteName is None:
deleteName = filename
self.delete(deleteName)
self.write(filename, arcname, compress_type) | [
"def",
"replace",
"(",
"self",
",",
"filename",
",",
"arcname",
"=",
"None",
",",
"compress_type",
"=",
"None",
")",
":",
"deleteName",
"=",
"arcname",
"if",
"deleteName",
"is",
"None",
":",
"deleteName",
"=",
"filename",
"self",
".",
"delete",
"(",
"del... | https://github.com/debian-calibre/calibre/blob/020fc81d3936a64b2ac51459ecb796666ab6a051/src/calibre/utils/zipfile.py#L906-L913 | ||
plivo/plivoframework | 29fc41fb3c887d5d9022a941e87bbeb2269112ff | src/plivo/rest/freeswitch/inboundsocket.py | python | RESTInboundSocket.on_channel_hangup_complete | (self, event) | Capture Channel Hangup Complete | Capture Channel Hangup Complete | [
"Capture",
"Channel",
"Hangup",
"Complete"
] | def on_channel_hangup_complete(self, event):
"""Capture Channel Hangup Complete
"""
# if plivo_app != 'true', check b leg Dial callback
plivo_app_flag = event['variable_plivo_app'] == 'true'
if not plivo_app_flag:
# request Dial callbackUrl if needed
ck_url = event['variable_plivo_dial_callback_url']
if not ck_url:
return
ck_method = event['variable_plivo_dial_callback_method']
if not ck_method:
return
aleg_uuid = event['variable_plivo_dial_callback_aleg']
if not aleg_uuid:
return
hangup_cause = event['Hangup-Cause'] or ''
# don't send http request for B legs losing bridge race
if hangup_cause == 'LOSE_RACE':
return
bleg_uuid = event['Unique-ID']
params = {'DialBLegUUID': bleg_uuid,
'DialALegUUID': aleg_uuid,
'DialBLegStatus': 'hangup',
'DialBLegHangupCause': hangup_cause,
'CallUUID': aleg_uuid
}
# add extra params
extra_params = self.get_extra_fs_vars(event)
if extra_params:
params.update(extra_params)
spawn_raw(self.send_to_url, ck_url, params, ck_method)
return
# Get call direction
direction = event['Call-Direction']
# Handle incoming call hangup
if direction == 'inbound':
call_uuid = event['Unique-ID']
reason = event['Hangup-Cause']
# send hangup
try:
self.set_hangup_complete(None, call_uuid, reason, event, None)
except Exception, e:
self.log.error(str(e))
# Handle outgoing call hangup
else:
# check if found a request uuid
# if not, ignore hangup event
request_uuid = event['variable_plivo_request_uuid']
if not request_uuid and direction != 'outbound':
return
call_uuid = event['Unique-ID']
reason = event['Hangup-Cause']
# case GroupCall
if event['variable_plivo_group_call'] == 'true':
hangup_url = event['variable_plivo_hangup_url']
# case BulkCall and Call
else:
try:
call_req = self.call_requests[request_uuid]
except KeyError:
return
# If there are gateways to try again, spawn originate
if call_req.gateways:
self.log.debug("Call Failed for RequestUUID %s - Retrying (%s)" \
% (request_uuid, reason))
# notify try call
self.log.debug("Notify Call retry for RequestUUID %s" % request_uuid)
call_req.notify_call_try()
return
# else clean call request
hangup_url = call_req.hangup_url
# notify call end
self.log.debug("Notify Call success for RequestUUID %s" % request_uuid)
call_req.notify_call_end()
# send hangup
try:
self.set_hangup_complete(request_uuid, call_uuid, reason, event, hangup_url)
except Exception, e:
self.log.error(str(e)) | [
"def",
"on_channel_hangup_complete",
"(",
"self",
",",
"event",
")",
":",
"# if plivo_app != 'true', check b leg Dial callback",
"plivo_app_flag",
"=",
"event",
"[",
"'variable_plivo_app'",
"]",
"==",
"'true'",
"if",
"not",
"plivo_app_flag",
":",
"# request Dial callbackUrl... | https://github.com/plivo/plivoframework/blob/29fc41fb3c887d5d9022a941e87bbeb2269112ff/src/plivo/rest/freeswitch/inboundsocket.py#L357-L443 | ||
IronLanguages/ironpython3 | 7a7bb2a872eeab0d1009fc8a6e24dca43f65b693 | Src/StdLib/Lib/tkinter/__init__.py | python | OptionMenu.destroy | (self) | Destroy this widget and the associated menu. | Destroy this widget and the associated menu. | [
"Destroy",
"this",
"widget",
"and",
"the",
"associated",
"menu",
"."
] | def destroy(self):
"""Destroy this widget and the associated menu."""
Menubutton.destroy(self)
self.__menu = None | [
"def",
"destroy",
"(",
"self",
")",
":",
"Menubutton",
".",
"destroy",
"(",
"self",
")",
"self",
".",
"__menu",
"=",
"None"
] | https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/tkinter/__init__.py#L3349-L3352 | ||
demisto/content | 5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07 | Packs/ThreatGrid/Integrations/ThreatGrid/ThreatGrid.py | python | sample_to_readable | (k) | return {
'ID': demisto.get(k, 'id'),
'Filename': demisto.get(k, 'filename'),
'State': demisto.get(k, 'state'),
'Status': demisto.get(k, 'status'),
'MD5': demisto.get(k, 'md5'),
'SHA1': demisto.get(k, 'sha1'),
'SHA256': demisto.get(k, 'sha256'),
'OS': demisto.get(k, 'os'),
'SubmittedAt': demisto.get(k, 'submitted_at'),
'StartedAt': demisto.get(k, 'started_at'),
'CompletedAt': demisto.get(k, 'completed_at')
} | Convert sample request to data dictionary | Convert sample request to data dictionary | [
"Convert",
"sample",
"request",
"to",
"data",
"dictionary"
] | def sample_to_readable(k):
"""
Convert sample request to data dictionary
"""
return {
'ID': demisto.get(k, 'id'),
'Filename': demisto.get(k, 'filename'),
'State': demisto.get(k, 'state'),
'Status': demisto.get(k, 'status'),
'MD5': demisto.get(k, 'md5'),
'SHA1': demisto.get(k, 'sha1'),
'SHA256': demisto.get(k, 'sha256'),
'OS': demisto.get(k, 'os'),
'SubmittedAt': demisto.get(k, 'submitted_at'),
'StartedAt': demisto.get(k, 'started_at'),
'CompletedAt': demisto.get(k, 'completed_at')
} | [
"def",
"sample_to_readable",
"(",
"k",
")",
":",
"return",
"{",
"'ID'",
":",
"demisto",
".",
"get",
"(",
"k",
",",
"'id'",
")",
",",
"'Filename'",
":",
"demisto",
".",
"get",
"(",
"k",
",",
"'filename'",
")",
",",
"'State'",
":",
"demisto",
".",
"g... | https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/ThreatGrid/Integrations/ThreatGrid/ThreatGrid.py#L122-L138 | |
PaddlePaddle/Parakeet | 8705a2a8405e3c63f2174d69880d2b5525a6c9fd | parakeet/training/updaters/standard_updater.py | python | StandardUpdater.new_epoch | (self) | Start a new epoch. | Start a new epoch. | [
"Start",
"a",
"new",
"epoch",
"."
] | def new_epoch(self):
"""Start a new epoch."""
# NOTE: all batch sampler for distributed training should
# subclass DistributedBatchSampler and implement `set_epoch` method
batch_sampler = self.dataloader.batch_sampler
if isinstance(batch_sampler, DistributedBatchSampler):
batch_sampler.set_epoch(self.state.epoch)
self.train_iterator = iter(self.dataloader) | [
"def",
"new_epoch",
"(",
"self",
")",
":",
"# NOTE: all batch sampler for distributed training should",
"# subclass DistributedBatchSampler and implement `set_epoch` method",
"batch_sampler",
"=",
"self",
".",
"dataloader",
".",
"batch_sampler",
"if",
"isinstance",
"(",
"batch_sa... | https://github.com/PaddlePaddle/Parakeet/blob/8705a2a8405e3c63f2174d69880d2b5525a6c9fd/parakeet/training/updaters/standard_updater.py#L162-L169 | ||
LabPy/lantz | 3e878e3f765a4295b0089d04e241d4beb7b8a65b | lantz/drivers/legacy/visalib.py | python | VisaLibrary.find_resources | (self, session, query) | return find_list, return_counter.value, instrument_description.value.decode('ascii') | Queries a VISA system to locate the resources associated with a specified interface.
:param session: Unique logical identifier to a session (unused, just to uniform signatures).
:param query: A regular expression followed by an optional logical expression. Use '?*' for all.
:return: find_list, return_counter, instrument_description | Queries a VISA system to locate the resources associated with a specified interface. | [
"Queries",
"a",
"VISA",
"system",
"to",
"locate",
"the",
"resources",
"associated",
"with",
"a",
"specified",
"interface",
"."
] | def find_resources(self, session, query):
"""Queries a VISA system to locate the resources associated with a specified interface.
:param session: Unique logical identifier to a session (unused, just to uniform signatures).
:param query: A regular expression followed by an optional logical expression. Use '?*' for all.
:return: find_list, return_counter, instrument_description
"""
find_list = Types.FindList()
return_counter = Types.UInt32()
instrument_description = ct.create_string_buffer(b'', Constants.FIND_BUFLEN)
self.lib.viFindRsrc(session, query, ct.byref(find_list), ct.byref(return_counter),
instrument_description)
return find_list, return_counter.value, instrument_description.value.decode('ascii') | [
"def",
"find_resources",
"(",
"self",
",",
"session",
",",
"query",
")",
":",
"find_list",
"=",
"Types",
".",
"FindList",
"(",
")",
"return_counter",
"=",
"Types",
".",
"UInt32",
"(",
")",
"instrument_description",
"=",
"ct",
".",
"create_string_buffer",
"("... | https://github.com/LabPy/lantz/blob/3e878e3f765a4295b0089d04e241d4beb7b8a65b/lantz/drivers/legacy/visalib.py#L923-L935 | |
kamalgill/flask-appengine-template | 11760f83faccbb0d0afe416fc58e67ecfb4643c2 | src/lib/flask/blueprints.py | python | Blueprint.url_value_preprocessor | (self, f) | return f | Registers a function as URL value preprocessor for this
blueprint. It's called before the view functions are called and
can modify the url values provided. | Registers a function as URL value preprocessor for this
blueprint. It's called before the view functions are called and
can modify the url values provided. | [
"Registers",
"a",
"function",
"as",
"URL",
"value",
"preprocessor",
"for",
"this",
"blueprint",
".",
"It",
"s",
"called",
"before",
"the",
"view",
"functions",
"are",
"called",
"and",
"can",
"modify",
"the",
"url",
"values",
"provided",
"."
] | def url_value_preprocessor(self, f):
"""Registers a function as URL value preprocessor for this
blueprint. It's called before the view functions are called and
can modify the url values provided.
"""
self.record_once(lambda s: s.app.url_value_preprocessors
.setdefault(self.name, []).append(f))
return f | [
"def",
"url_value_preprocessor",
"(",
"self",
",",
"f",
")",
":",
"self",
".",
"record_once",
"(",
"lambda",
"s",
":",
"s",
".",
"app",
".",
"url_value_preprocessors",
".",
"setdefault",
"(",
"self",
".",
"name",
",",
"[",
"]",
")",
".",
"append",
"(",... | https://github.com/kamalgill/flask-appengine-template/blob/11760f83faccbb0d0afe416fc58e67ecfb4643c2/src/lib/flask/blueprints.py#L355-L362 | |
eirannejad/pyRevit | 49c0b7eb54eb343458ce1365425e6552d0c47d44 | site-packages/sqlalchemy/engine/default.py | python | DefaultExecutionContext.get_result_processor | (self, type_, colname, coltype) | return type_._cached_result_processor(self.dialect, coltype) | Return a 'result processor' for a given type as present in
cursor.description.
This has a default implementation that dialects can override
for context-sensitive result type handling. | Return a 'result processor' for a given type as present in
cursor.description. | [
"Return",
"a",
"result",
"processor",
"for",
"a",
"given",
"type",
"as",
"present",
"in",
"cursor",
".",
"description",
"."
] | def get_result_processor(self, type_, colname, coltype):
"""Return a 'result processor' for a given type as present in
cursor.description.
This has a default implementation that dialects can override
for context-sensitive result type handling.
"""
return type_._cached_result_processor(self.dialect, coltype) | [
"def",
"get_result_processor",
"(",
"self",
",",
"type_",
",",
"colname",
",",
"coltype",
")",
":",
"return",
"type_",
".",
"_cached_result_processor",
"(",
"self",
".",
"dialect",
",",
"coltype",
")"
] | https://github.com/eirannejad/pyRevit/blob/49c0b7eb54eb343458ce1365425e6552d0c47d44/site-packages/sqlalchemy/engine/default.py#L832-L840 | |
datalad/datalad | d8c8383d878a207bb586415314219a60c345f732 | datalad/support/annexrepo.py | python | AnnexRepo._call_annex | (self, args, files=None, jobs=None, protocol=StdOutErrCapture,
git_options=None, stdin=None, merge_annex_branches=True,
**kwargs) | Internal helper to run git-annex commands
Standard command options are applied in addition to the given arguments,
and certain error conditions are detected (if possible) and dedicated
exceptions are raised.
Parameters
----------
args: list
List of git-annex command arguments.
files: list, optional
If command passes list of files. If list is too long
(by number of files or overall size) it will be split, and multiple
command invocations will follow
jobs : int or 'auto', optional
If 'auto', the number of jobs will be determined automatically,
informed by the configuration setting
'datalad.runtime.max-annex-jobs'.
protocol : WitlessProtocol, optional
Protocol class to pass to GitWitlessRunner.run(). By default this is
StdOutErrCapture, which will provide default logging behavior and
guarantee that stdout/stderr are included in potential CommandError
exception.
git_options: list, optional
Additional arguments for Git to include in the git-annex call
(in a position prior to the 'annex' subcommand.
stdin: File-like, optional
stdin to connect to the git-annex process. Only used when `files`
is None.
merge_annex_branches: bool, optional
If False, annex.merge-annex-branches=false config will be set for
git-annex call. Useful for operations which are not intended to
benefit from updating information about remote git-annexes
**kwargs:
Additional arguments are passed on to the WitlessProtocol constructor
Returns
-------
dict
Return value of WitlessRunner.run(). The content of the dict is
determined by the given `protocol`. By default, it provides git-annex's
stdout and stderr (under these key names)
Raises
------
CommandError
If the call exits with a non-zero status.
OutOfSpaceError
If a corresponding statement was detected in git-annex's output on
stderr. Only supported if the given protocol captured stderr.
RemoteNotAvailableError
If a corresponding statement was detected in git-annex's output on
stderr. Only supported if the given protocol captured stderr. | Internal helper to run git-annex commands | [
"Internal",
"helper",
"to",
"run",
"git",
"-",
"annex",
"commands"
] | def _call_annex(self, args, files=None, jobs=None, protocol=StdOutErrCapture,
git_options=None, stdin=None, merge_annex_branches=True,
**kwargs):
"""Internal helper to run git-annex commands
Standard command options are applied in addition to the given arguments,
and certain error conditions are detected (if possible) and dedicated
exceptions are raised.
Parameters
----------
args: list
List of git-annex command arguments.
files: list, optional
If command passes list of files. If list is too long
(by number of files or overall size) it will be split, and multiple
command invocations will follow
jobs : int or 'auto', optional
If 'auto', the number of jobs will be determined automatically,
informed by the configuration setting
'datalad.runtime.max-annex-jobs'.
protocol : WitlessProtocol, optional
Protocol class to pass to GitWitlessRunner.run(). By default this is
StdOutErrCapture, which will provide default logging behavior and
guarantee that stdout/stderr are included in potential CommandError
exception.
git_options: list, optional
Additional arguments for Git to include in the git-annex call
(in a position prior to the 'annex' subcommand.
stdin: File-like, optional
stdin to connect to the git-annex process. Only used when `files`
is None.
merge_annex_branches: bool, optional
If False, annex.merge-annex-branches=false config will be set for
git-annex call. Useful for operations which are not intended to
benefit from updating information about remote git-annexes
**kwargs:
Additional arguments are passed on to the WitlessProtocol constructor
Returns
-------
dict
Return value of WitlessRunner.run(). The content of the dict is
determined by the given `protocol`. By default, it provides git-annex's
stdout and stderr (under these key names)
Raises
------
CommandError
If the call exits with a non-zero status.
OutOfSpaceError
If a corresponding statement was detected in git-annex's output on
stderr. Only supported if the given protocol captured stderr.
RemoteNotAvailableError
If a corresponding statement was detected in git-annex's output on
stderr. Only supported if the given protocol captured stderr.
"""
if self.git_annex_version is None:
self._check_git_annex_version()
# git portion of the command
cmd = ['git'] + self._ANNEX_GIT_COMMON_OPTIONS
if git_options:
cmd += git_options
if not self.always_commit:
cmd += ['-c', 'annex.alwayscommit=false']
if not merge_annex_branches:
cmd += ['-c', 'annex.merge-annex-branches=false']
# annex portion of the command
cmd.append('annex')
cmd += args
if lgr.getEffectiveLevel() <= 8:
cmd.append('--debug')
if self._annex_common_options:
cmd += self._annex_common_options
if jobs == 'auto':
# Limit to # of CPUs (but at least 3 to start with)
# and also an additional config constraint (by default 1
# due to https://github.com/datalad/datalad/issues/4404)
jobs = self._n_auto_jobs or min(
self.config.obtain('datalad.runtime.max-annex-jobs'),
max(3, cpu_count()))
# cache result to avoid repeated calls to cpu_count()
self._n_auto_jobs = jobs
if jobs and jobs != 1:
cmd.append('-J%d' % jobs)
runner = self._git_runner
env = None
if self.fake_dates_enabled:
env = self.add_fake_dates(runner.env)
try:
if files:
if issubclass(protocol, GeneratorMixIn):
return runner.run_on_filelist_chunks_items_(
cmd,
files,
protocol=protocol,
env=env,
**kwargs)
else:
return runner.run_on_filelist_chunks(
cmd,
files,
protocol=protocol,
env=env,
**kwargs)
else:
return runner.run(
cmd,
stdin=stdin,
protocol=protocol,
env=env,
**kwargs)
except CommandError as e:
# Note: A call might result in several 'failures', that can be or
# cannot be handled here. Detection of something, we can deal with,
# doesn't mean there's nothing else to deal with.
# OutOfSpaceError:
# Note:
# doesn't depend on anything in stdout. Therefore check this before
# dealing with stdout
out_of_space_re = re.search(
"not enough free space, need (.*) more", e.stderr
)
if out_of_space_re:
raise OutOfSpaceError(cmd=['annex'] + args,
sizemore_msg=out_of_space_re.groups()[0])
# RemoteNotAvailableError:
remote_na_re = re.search(
"there is no available git remote named \"(.*)\"", e.stderr
)
if remote_na_re:
raise RemoteNotAvailableError(cmd=['annex'] + args,
remote=remote_na_re.groups()[0])
# TEMP: Workaround for git-annex bug, where it reports success=True
# for annex add, while simultaneously complaining, that it is in
# a submodule:
# TODO: For now just reraise. But independently on this bug, it
# makes sense to have an exception for that case
in_subm_re = re.search(
"fatal: Pathspec '(.*)' is in submodule '(.*)'", e.stderr
)
if in_subm_re:
raise e
# we don't know how to handle this, just pass it on
raise | [
"def",
"_call_annex",
"(",
"self",
",",
"args",
",",
"files",
"=",
"None",
",",
"jobs",
"=",
"None",
",",
"protocol",
"=",
"StdOutErrCapture",
",",
"git_options",
"=",
"None",
",",
"stdin",
"=",
"None",
",",
"merge_annex_branches",
"=",
"True",
",",
"*",... | https://github.com/datalad/datalad/blob/d8c8383d878a207bb586415314219a60c345f732/datalad/support/annexrepo.py#L837-L997 | ||
googleapis/oauth2client | 50d20532a748f18e53f7d24ccbe6647132c979a9 | oauth2client/contrib/appengine.py | python | StorageByKeyName._get_entity | (self) | Retrieve entity from datastore.
Uses a different model method for db or ndb models.
Returns:
Instance of the model corresponding to the current storage object
and stored using the key name of the storage object. | Retrieve entity from datastore. | [
"Retrieve",
"entity",
"from",
"datastore",
"."
] | def _get_entity(self):
"""Retrieve entity from datastore.
Uses a different model method for db or ndb models.
Returns:
Instance of the model corresponding to the current storage object
and stored using the key name of the storage object.
"""
if self._is_ndb():
return self._model.get_by_id(self._key_name)
else:
return self._model.get_by_key_name(self._key_name) | [
"def",
"_get_entity",
"(",
"self",
")",
":",
"if",
"self",
".",
"_is_ndb",
"(",
")",
":",
"return",
"self",
".",
"_model",
".",
"get_by_id",
"(",
"self",
".",
"_key_name",
")",
"else",
":",
"return",
"self",
".",
"_model",
".",
"get_by_key_name",
"(",
... | https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/appengine.py#L351-L363 | ||
Marsan-Ma-zz/tf_chatbot_seq2seq_antilm | 145e78903b245050c3c31e9a162db8a54e1e91fe | ref/data_utils.py | python | create_vocabulary | (vocabulary_path, data_path, max_vocabulary_size,
tokenizer=None, normalize_digits=True) | Create vocabulary file (if it does not exist yet) from data file.
Data file is assumed to contain one sentence per line. Each sentence is
tokenized and digits are normalized (if normalize_digits is set).
Vocabulary contains the most-frequent tokens up to max_vocabulary_size.
We write it to vocabulary_path in a one-token-per-line format, so that later
token in the first line gets id=0, second line gets id=1, and so on.
Args:
vocabulary_path: path where the vocabulary will be created.
data_path: data file that will be used to create vocabulary.
max_vocabulary_size: limit on the size of the created vocabulary.
tokenizer: a function to use to tokenize each data sentence;
if None, basic_tokenizer will be used.
normalize_digits: Boolean; if true, all digits are replaced by 0s. | Create vocabulary file (if it does not exist yet) from data file. | [
"Create",
"vocabulary",
"file",
"(",
"if",
"it",
"does",
"not",
"exist",
"yet",
")",
"from",
"data",
"file",
"."
] | def create_vocabulary(vocabulary_path, data_path, max_vocabulary_size,
tokenizer=None, normalize_digits=True):
"""Create vocabulary file (if it does not exist yet) from data file.
Data file is assumed to contain one sentence per line. Each sentence is
tokenized and digits are normalized (if normalize_digits is set).
Vocabulary contains the most-frequent tokens up to max_vocabulary_size.
We write it to vocabulary_path in a one-token-per-line format, so that later
token in the first line gets id=0, second line gets id=1, and so on.
Args:
vocabulary_path: path where the vocabulary will be created.
data_path: data file that will be used to create vocabulary.
max_vocabulary_size: limit on the size of the created vocabulary.
tokenizer: a function to use to tokenize each data sentence;
if None, basic_tokenizer will be used.
normalize_digits: Boolean; if true, all digits are replaced by 0s.
"""
if not gfile.Exists(vocabulary_path):
print("Creating vocabulary %s from data %s" % (vocabulary_path, data_path))
vocab = {}
with gfile.GFile(data_path, mode="rb") as f:
counter = 0
for line in f:
counter += 1
if counter % 100000 == 0:
print(" processing line %d" % counter)
line = tf.compat.as_bytes(line)
tokens = tokenizer(line) if tokenizer else basic_tokenizer(line)
for w in tokens:
word = _DIGIT_RE.sub(b"0", w) if normalize_digits else w
if word in vocab:
vocab[word] += 1
else:
vocab[word] = 1
vocab_list = _START_VOCAB + sorted(vocab, key=vocab.get, reverse=True)
if len(vocab_list) > max_vocabulary_size:
vocab_list = vocab_list[:max_vocabulary_size]
with gfile.GFile(vocabulary_path, mode="wb") as vocab_file:
for w in vocab_list:
vocab_file.write(w + b"\n") | [
"def",
"create_vocabulary",
"(",
"vocabulary_path",
",",
"data_path",
",",
"max_vocabulary_size",
",",
"tokenizer",
"=",
"None",
",",
"normalize_digits",
"=",
"True",
")",
":",
"if",
"not",
"gfile",
".",
"Exists",
"(",
"vocabulary_path",
")",
":",
"print",
"("... | https://github.com/Marsan-Ma-zz/tf_chatbot_seq2seq_antilm/blob/145e78903b245050c3c31e9a162db8a54e1e91fe/ref/data_utils.py#L114-L154 | ||
celery/billiard | 269ef67354a3a205cea780aa8ea451e0d17cd37c | billiard/process.py | python | BaseProcess.join | (self, timeout=None) | Wait until child process terminates | Wait until child process terminates | [
"Wait",
"until",
"child",
"process",
"terminates"
] | def join(self, timeout=None):
'''
Wait until child process terminates
'''
assert self._parent_pid == os.getpid(), 'can only join a child process'
assert self._popen is not None, 'can only join a started process'
res = self._popen.wait(timeout)
if res is not None:
_children.discard(self)
self.close() | [
"def",
"join",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"assert",
"self",
".",
"_parent_pid",
"==",
"os",
".",
"getpid",
"(",
")",
",",
"'can only join a child process'",
"assert",
"self",
".",
"_popen",
"is",
"not",
"None",
",",
"'can only join... | https://github.com/celery/billiard/blob/269ef67354a3a205cea780aa8ea451e0d17cd37c/billiard/process.py#L140-L149 | ||
inventree/InvenTree | 4a5e4a88ac3e91d64a21e8cab3708ecbc6e2bd8b | InvenTree/plugin/builtin/integration/mixins.py | python | NavigationMixin.has_naviation | (self) | return bool(self.navigation) | does this plugin define navigation elements | does this plugin define navigation elements | [
"does",
"this",
"plugin",
"define",
"navigation",
"elements"
] | def has_naviation(self):
"""
does this plugin define navigation elements
"""
return bool(self.navigation) | [
"def",
"has_naviation",
"(",
"self",
")",
":",
"return",
"bool",
"(",
"self",
".",
"navigation",
")"
] | https://github.com/inventree/InvenTree/blob/4a5e4a88ac3e91d64a21e8cab3708ecbc6e2bd8b/InvenTree/plugin/builtin/integration/mixins.py#L265-L269 | |
KalleHallden/AutoTimer | 2d954216700c4930baa154e28dbddc34609af7ce | env/lib/python2.7/site-packages/objc/_convenience_mapping.py | python | popitem_setObject_forKey_ | (self) | [] | def popitem_setObject_forKey_(self):
try:
it = self.keyEnumerator()
k = container_unwrap(it.nextObject(), StopIteration)
except (StopIteration, IndexError):
raise KeyError("popitem on an empty %s" % (type(self).__name__,))
else:
result = (k, container_unwrap(self.objectForKey_(k), KeyError))
self.removeObjectForKey_(k)
return result | [
"def",
"popitem_setObject_forKey_",
"(",
"self",
")",
":",
"try",
":",
"it",
"=",
"self",
".",
"keyEnumerator",
"(",
")",
"k",
"=",
"container_unwrap",
"(",
"it",
".",
"nextObject",
"(",
")",
",",
"StopIteration",
")",
"except",
"(",
"StopIteration",
",",
... | https://github.com/KalleHallden/AutoTimer/blob/2d954216700c4930baa154e28dbddc34609af7ce/env/lib/python2.7/site-packages/objc/_convenience_mapping.py#L97-L106 | ||||
tensorflow/models | 6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3 | official/vision/beta/projects/yolo/losses/yolo_loss.py | python | ScaledLoss._build_per_path_attributes | (self) | return | Paramterization of pair wise search and grid generators.
Objects created here are used for box decoding and dynamic ground truth
association. | Paramterization of pair wise search and grid generators. | [
"Paramterization",
"of",
"pair",
"wise",
"search",
"and",
"grid",
"generators",
"."
] | def _build_per_path_attributes(self):
"""Paramterization of pair wise search and grid generators.
Objects created here are used for box decoding and dynamic ground truth
association.
"""
self._anchor_generator = loss_utils.GridGenerator(
anchors=self._anchors,
scale_anchors=self._path_stride)
if self._ignore_thresh > 0.0:
self._search_pairs = loss_utils.PairWiseSearch(
iou_type=self._loss_type, any_match=False, min_conf=0.25)
self._cls_normalizer = self._cls_normalizer * self._classes / 80
return | [
"def",
"_build_per_path_attributes",
"(",
"self",
")",
":",
"self",
".",
"_anchor_generator",
"=",
"loss_utils",
".",
"GridGenerator",
"(",
"anchors",
"=",
"self",
".",
"_anchors",
",",
"scale_anchors",
"=",
"self",
".",
"_path_stride",
")",
"if",
"self",
".",... | https://github.com/tensorflow/models/blob/6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3/official/vision/beta/projects/yolo/losses/yolo_loss.py#L461-L476 | |
simonw/datasette | 8c401ee0f054de2f568c3a8302c9223555146407 | datasette/hookspecs.py | python | menu_links | (datasette, actor, request) | Links for the navigation menu | Links for the navigation menu | [
"Links",
"for",
"the",
"navigation",
"menu"
] | def menu_links(datasette, actor, request):
"""Links for the navigation menu""" | [
"def",
"menu_links",
"(",
"datasette",
",",
"actor",
",",
"request",
")",
":"
] | https://github.com/simonw/datasette/blob/8c401ee0f054de2f568c3a8302c9223555146407/datasette/hookspecs.py#L124-L125 | ||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/lib/python2.7/site-packages/chardet/chardistribution.py | python | GB2312DistributionAnalysis.get_order | (self, byte_str) | [] | def get_order(self, byte_str):
# for GB2312 encoding, we are interested
# first byte range: 0xb0 -- 0xfe
# second byte range: 0xa1 -- 0xfe
# no validation needed here. State machine has done that
first_char, second_char = byte_str[0], byte_str[1]
if (first_char >= 0xB0) and (second_char >= 0xA1):
return 94 * (first_char - 0xB0) + second_char - 0xA1
else:
return -1 | [
"def",
"get_order",
"(",
"self",
",",
"byte_str",
")",
":",
"# for GB2312 encoding, we are interested",
"# first byte range: 0xb0 -- 0xfe",
"# second byte range: 0xa1 -- 0xfe",
"# no validation needed here. State machine has done that",
"first_char",
",",
"second_char",
"=",
"byte... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/chardet/chardistribution.py#L158-L167 | ||||
IBM/lale | b4d6829c143a4735b06083a0e6c70d2cca244162 | lale/lib/autogen/pls_canonical.py | python | _PLSCanonicalImpl.predict | (self, X) | return self._wrapped_model.predict(X) | [] | def predict(self, X):
return self._wrapped_model.predict(X) | [
"def",
"predict",
"(",
"self",
",",
"X",
")",
":",
"return",
"self",
".",
"_wrapped_model",
".",
"predict",
"(",
"X",
")"
] | https://github.com/IBM/lale/blob/b4d6829c143a4735b06083a0e6c70d2cca244162/lale/lib/autogen/pls_canonical.py#L23-L24 | |||
thinkle/gourmet | 8af29c8ded24528030e5ae2ea3461f61c1e5a575 | gourmet/plugins/nutritional_information/nutritionInfoEditor.py | python | NutritionInfoIndex.reset | (self) | Rebuild our model, regardless. | Rebuild our model, regardless. | [
"Rebuild",
"our",
"model",
"regardless",
"."
] | def reset (self):
"""Rebuild our model, regardless."""
self.search_string = 'NO ONE WOULD EVER SEARCH FOR THIS'
self.doSearch() | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"search_string",
"=",
"'NO ONE WOULD EVER SEARCH FOR THIS'",
"self",
".",
"doSearch",
"(",
")"
] | https://github.com/thinkle/gourmet/blob/8af29c8ded24528030e5ae2ea3461f61c1e5a575/gourmet/plugins/nutritional_information/nutritionInfoEditor.py#L106-L109 | ||
Chaffelson/nipyapi | d3b186fd701ce308c2812746d98af9120955e810 | nipyapi/registry/models/build_info.py | python | BuildInfo.build_revision | (self) | return self._build_revision | Gets the build_revision of this BuildInfo.
The revision used to build the version of the bundle
:return: The build_revision of this BuildInfo.
:rtype: str | Gets the build_revision of this BuildInfo.
The revision used to build the version of the bundle | [
"Gets",
"the",
"build_revision",
"of",
"this",
"BuildInfo",
".",
"The",
"revision",
"used",
"to",
"build",
"the",
"version",
"of",
"the",
"bundle"
] | def build_revision(self):
"""
Gets the build_revision of this BuildInfo.
The revision used to build the version of the bundle
:return: The build_revision of this BuildInfo.
:rtype: str
"""
return self._build_revision | [
"def",
"build_revision",
"(",
"self",
")",
":",
"return",
"self",
".",
"_build_revision"
] | https://github.com/Chaffelson/nipyapi/blob/d3b186fd701ce308c2812746d98af9120955e810/nipyapi/registry/models/build_info.py#L174-L182 | |
IronLanguages/main | a949455434b1fda8c783289e897e78a9a0caabb5 | External.LCA_RESTRICTED/Languages/IronPython/27/Doc/sphinx/builders/__init__.py | python | Builder.load_env | (self) | Set up the build environment. | Set up the build environment. | [
"Set",
"up",
"the",
"build",
"environment",
"."
] | def load_env(self):
"""Set up the build environment."""
if self.env:
return
if not self.freshenv:
try:
self.info(bold('loading pickled environment... '), nonl=True)
self.env = BuildEnvironment.frompickle(self.config,
path.join(self.doctreedir, ENV_PICKLE_FILENAME))
self.info('done')
except Exception, err:
if type(err) is IOError and err.errno == 2:
self.info('not found')
else:
self.info('failed: %s' % err)
self.env = BuildEnvironment(self.srcdir, self.doctreedir,
self.config)
self.env.find_files(self.config)
else:
self.env = BuildEnvironment(self.srcdir, self.doctreedir,
self.config)
self.env.find_files(self.config)
self.env.set_warnfunc(self.warn) | [
"def",
"load_env",
"(",
"self",
")",
":",
"if",
"self",
".",
"env",
":",
"return",
"if",
"not",
"self",
".",
"freshenv",
":",
"try",
":",
"self",
".",
"info",
"(",
"bold",
"(",
"'loading pickled environment... '",
")",
",",
"nonl",
"=",
"True",
")",
... | https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/IronPython/27/Doc/sphinx/builders/__init__.py#L202-L224 | ||
openshift/openshift-tools | 1188778e728a6e4781acf728123e5b356380fe6f | ansible/roles/lib_oa_openshift/src/lib/deploymentconfig.py | python | DeploymentConfig.exists_env_key | (self, key) | return False | return whether a key, value pair exists | return whether a key, value pair exists | [
"return",
"whether",
"a",
"key",
"value",
"pair",
"exists"
] | def exists_env_key(self, key):
''' return whether a key, value pair exists '''
results = self.get_env_vars()
if not results:
return False
for result in results:
if result['name'] == key:
return True
return False | [
"def",
"exists_env_key",
"(",
"self",
",",
"key",
")",
":",
"results",
"=",
"self",
".",
"get_env_vars",
"(",
")",
"if",
"not",
"results",
":",
"return",
"False",
"for",
"result",
"in",
"results",
":",
"if",
"result",
"[",
"'name'",
"]",
"==",
"key",
... | https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/ansible/roles/lib_oa_openshift/src/lib/deploymentconfig.py#L100-L110 | |
theotherp/nzbhydra | 4b03d7f769384b97dfc60dade4806c0fc987514e | libs/bs4/dammit.py | python | UnicodeDammit._sub_ms_char | (self, match) | return sub | Changes a MS smart quote character to an XML or HTML
entity, or an ASCII character. | Changes a MS smart quote character to an XML or HTML
entity, or an ASCII character. | [
"Changes",
"a",
"MS",
"smart",
"quote",
"character",
"to",
"an",
"XML",
"or",
"HTML",
"entity",
"or",
"an",
"ASCII",
"character",
"."
] | def _sub_ms_char(self, match):
"""Changes a MS smart quote character to an XML or HTML
entity, or an ASCII character."""
orig = match.group(1)
if self.smart_quotes_to == 'ascii':
sub = self.MS_CHARS_TO_ASCII.get(orig).encode()
else:
sub = self.MS_CHARS.get(orig)
if type(sub) == tuple:
if self.smart_quotes_to == 'xml':
sub = '&#x'.encode() + sub[1].encode() + ';'.encode()
else:
sub = '&'.encode() + sub[0].encode() + ';'.encode()
else:
sub = sub.encode()
return sub | [
"def",
"_sub_ms_char",
"(",
"self",
",",
"match",
")",
":",
"orig",
"=",
"match",
".",
"group",
"(",
"1",
")",
"if",
"self",
".",
"smart_quotes_to",
"==",
"'ascii'",
":",
"sub",
"=",
"self",
".",
"MS_CHARS_TO_ASCII",
".",
"get",
"(",
"orig",
")",
"."... | https://github.com/theotherp/nzbhydra/blob/4b03d7f769384b97dfc60dade4806c0fc987514e/libs/bs4/dammit.py#L394-L409 | |
AppScale/gts | 46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9 | AppServer/lib/django-0.96/django/utils/html.py | python | escape | (html) | return html.replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '"').replace("'", ''') | Returns the given HTML with ampersands, quotes and carets encoded | Returns the given HTML with ampersands, quotes and carets encoded | [
"Returns",
"the",
"given",
"HTML",
"with",
"ampersands",
"quotes",
"and",
"carets",
"encoded"
] | def escape(html):
"Returns the given HTML with ampersands, quotes and carets encoded"
if not isinstance(html, basestring):
html = str(html)
return html.replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '"').replace("'", ''') | [
"def",
"escape",
"(",
"html",
")",
":",
"if",
"not",
"isinstance",
"(",
"html",
",",
"basestring",
")",
":",
"html",
"=",
"str",
"(",
"html",
")",
"return",
"html",
".",
"replace",
"(",
"'&'",
",",
"'&'",
")",
".",
"replace",
"(",
"'<'",
",",
... | https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-0.96/django/utils/html.py#L24-L28 | |
holzschu/Carnets | 44effb10ddfc6aa5c8b0687582a724ba82c6b547 | Library/lib/python3.7/site-packages/matplotlib-3.0.3-py3.7-macosx-10.9-x86_64.egg/matplotlib/__init__.py | python | is_url | (filename) | return URL_REGEX.match(filename) is not None | Return True if string is an http, ftp, or file URL path. | Return True if string is an http, ftp, or file URL path. | [
"Return",
"True",
"if",
"string",
"is",
"an",
"http",
"ftp",
"or",
"file",
"URL",
"path",
"."
] | def is_url(filename):
"""Return True if string is an http, ftp, or file URL path."""
return URL_REGEX.match(filename) is not None | [
"def",
"is_url",
"(",
"filename",
")",
":",
"return",
"URL_REGEX",
".",
"match",
"(",
"filename",
")",
"is",
"not",
"None"
] | https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/matplotlib-3.0.3-py3.7-macosx-10.9-x86_64.egg/matplotlib/__init__.py#L956-L958 | |
EricssonResearch/calvin-base | bc4645c2061c30ca305a660e48dc86e3317f5b6f | calvin/runtime/south/transports/lib/twisted/base_transport.py | python | CalvinTransportBase.join | (self) | Called when the client should connect | Called when the client should connect | [
"Called",
"when",
"the",
"client",
"should",
"connect"
] | def join(self):
"""
Called when the client should connect
"""
raise NotImplementedError() | [
"def",
"join",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/EricssonResearch/calvin-base/blob/bc4645c2061c30ca305a660e48dc86e3317f5b6f/calvin/runtime/south/transports/lib/twisted/base_transport.py#L120-L124 | ||
shivasiddharth/Assistants-Pi | caf6295b01db12ef059e6f2d449323ac3d7683d8 | Alexa/apa102.py | python | APA102.clock_start_frame | (self) | Sends a start frame to the LED strip.
This method clocks out a start frame, telling the receiving LED
that it must update its own color now. | Sends a start frame to the LED strip. | [
"Sends",
"a",
"start",
"frame",
"to",
"the",
"LED",
"strip",
"."
] | def clock_start_frame(self):
"""Sends a start frame to the LED strip.
This method clocks out a start frame, telling the receiving LED
that it must update its own color now.
"""
self.spi.xfer2([0] * 4) | [
"def",
"clock_start_frame",
"(",
"self",
")",
":",
"self",
".",
"spi",
".",
"xfer2",
"(",
"[",
"0",
"]",
"*",
"4",
")"
] | https://github.com/shivasiddharth/Assistants-Pi/blob/caf6295b01db12ef059e6f2d449323ac3d7683d8/Alexa/apa102.py#L95-L101 | ||
OmkarPathak/Python-Programs | ed96a4f7b2ddcad5be6c6a0f13cff89975731b77 | Programs/P18_Logging.py | python | log | (number) | This function creates a log file if any error is reported | This function creates a log file if any error is reported | [
"This",
"function",
"creates",
"a",
"log",
"file",
"if",
"any",
"error",
"is",
"reported"
] | def log(number):
''' This function creates a log file if any error is reported '''
logging.basicConfig(filename = 'P18-logfile.txt', level = logging.INFO)
try:
if int(number) % 2 == 0:
print('Successful')
else:
print('Unsuccessful, this instance will be reported, check the log file')
logging.info('Invalid Entry')
except:
print('Please enter a valid integer') | [
"def",
"log",
"(",
"number",
")",
":",
"logging",
".",
"basicConfig",
"(",
"filename",
"=",
"'P18-logfile.txt'",
",",
"level",
"=",
"logging",
".",
"INFO",
")",
"try",
":",
"if",
"int",
"(",
"number",
")",
"%",
"2",
"==",
"0",
":",
"print",
"(",
"'... | https://github.com/OmkarPathak/Python-Programs/blob/ed96a4f7b2ddcad5be6c6a0f13cff89975731b77/Programs/P18_Logging.py#L5-L15 | ||
tern-tools/tern | 723f43dcaae2f2f0a08a63e5e8de3938031a386e | tern/classes/image.py | python | Image.__init__ | (self, repotag=None) | Initialize using the image's repo name and tag string | Initialize using the image's repo name and tag string | [
"Initialize",
"using",
"the",
"image",
"s",
"repo",
"name",
"and",
"tag",
"string"
] | def __init__(self, repotag=None):
'''Initialize using the image's repo name and tag string'''
self._repotag = repotag
self._name = ''
self._tag = ''
self._manifest = {}
self._config = {}
self._layers = []
self._load_until_layer = 0
self._total_layers = 0
self._checksum_type = ''
self._checksum = ''
self._checksums = []
self._origins = Origins() | [
"def",
"__init__",
"(",
"self",
",",
"repotag",
"=",
"None",
")",
":",
"self",
".",
"_repotag",
"=",
"repotag",
"self",
".",
"_name",
"=",
"''",
"self",
".",
"_tag",
"=",
"''",
"self",
".",
"_manifest",
"=",
"{",
"}",
"self",
".",
"_config",
"=",
... | https://github.com/tern-tools/tern/blob/723f43dcaae2f2f0a08a63e5e8de3938031a386e/tern/classes/image.py#L32-L45 | ||
SpriteLink/NIPAP | de09cd7c4c55521f26f00201d694ea9e388b21a9 | nipap-www/nipapwww/controllers/xhr.py | python | XhrController.add_vrf | (self) | return json.dumps(v, cls=NipapJSONEncoder) | Add a new VRF to NIPAP and return its data. | Add a new VRF to NIPAP and return its data. | [
"Add",
"a",
"new",
"VRF",
"to",
"NIPAP",
"and",
"return",
"its",
"data",
"."
] | def add_vrf(self):
""" Add a new VRF to NIPAP and return its data.
"""
v = VRF()
if 'rt' in request.json:
v.rt = validate_string(request.json, 'rt')
if 'name' in request.json:
v.name = validate_string(request.json, 'name')
if 'description' in request.json:
v.description = validate_string(request.json, 'description')
if 'tags' in request.json:
v.tags = request.json['tags']
if 'avps' in request.json:
v.avps = request.json['avps']
try:
v.save()
except NipapError, e:
return json.dumps({'error': 1, 'message': e.args, 'type': type(e).__name__})
return json.dumps(v, cls=NipapJSONEncoder) | [
"def",
"add_vrf",
"(",
"self",
")",
":",
"v",
"=",
"VRF",
"(",
")",
"if",
"'rt'",
"in",
"request",
".",
"json",
":",
"v",
".",
"rt",
"=",
"validate_string",
"(",
"request",
".",
"json",
",",
"'rt'",
")",
"if",
"'name'",
"in",
"request",
".",
"jso... | https://github.com/SpriteLink/NIPAP/blob/de09cd7c4c55521f26f00201d694ea9e388b21a9/nipap-www/nipapwww/controllers/xhr.py#L136-L157 | |
mediadrop/mediadrop | 59b477398fe306932cd93fc6bddb37fd45327373 | mediadrop/controllers/categories.py | python | CategoriesController.feed | (self, limit=None, **kwargs) | return dict(
media = media,
title = u'%s Media' % c.category.name,
) | Generate a media rss feed of the latest media
:param limit: the max number of results to return. Defaults to 30 | Generate a media rss feed of the latest media | [
"Generate",
"a",
"media",
"rss",
"feed",
"of",
"the",
"latest",
"media"
] | def feed(self, limit=None, **kwargs):
""" Generate a media rss feed of the latest media
:param limit: the max number of results to return. Defaults to 30
"""
if request.settings['rss_display'] != 'True':
abort(404)
response.content_type = content_type_for_response(
['application/rss+xml', 'application/xml', 'text/xml'])
media = Media.query.published()
if c.category:
media = media.in_category(c.category)
media_query = media.order_by(Media.publish_on.desc())
media = viewable_media(media_query)
if limit is not None:
media = media.limit(limit)
return dict(
media = media,
title = u'%s Media' % c.category.name,
) | [
"def",
"feed",
"(",
"self",
",",
"limit",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"request",
".",
"settings",
"[",
"'rss_display'",
"]",
"!=",
"'True'",
":",
"abort",
"(",
"404",
")",
"response",
".",
"content_type",
"=",
"content_type_fo... | https://github.com/mediadrop/mediadrop/blob/59b477398fe306932cd93fc6bddb37fd45327373/mediadrop/controllers/categories.py#L102-L127 | |
MartinThoma/algorithms | 6199cfa3446e1056c7b4d75ca6e306e9e56fd95b | ML/50-mlps/15-keras-cnn-higher-dropout/hasy_tools.py | python | _get_parser | () | return parser | Get parser object for hasy_tools.py. | Get parser object for hasy_tools.py. | [
"Get",
"parser",
"object",
"for",
"hasy_tools",
".",
"py",
"."
] | def _get_parser():
"""Get parser object for hasy_tools.py."""
import argparse
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser
parser = ArgumentParser(description=__doc__,
formatter_class=ArgumentDefaultsHelpFormatter)
parser.add_argument("--dataset",
dest="dataset",
help="specify which data to use")
parser.add_argument("--verify",
dest="verify",
action="store_true",
default=False,
help="verify PNG files")
parser.add_argument("--overview",
dest="overview",
action="store_true",
default=False,
help="Get overview of data")
parser.add_argument("--analyze_color",
dest="analyze_color",
action="store_true",
default=False,
help="Analyze the color distribution")
parser.add_argument("--class_distribution",
dest="class_distribution",
action="store_true",
default=False,
help="Analyze the class distribution")
parser.add_argument("--distances",
dest="distances",
action="store_true",
default=False,
help="Analyze the euclidean distance distribution")
parser.add_argument("--pca",
dest="pca",
action="store_true",
default=False,
help=("Show how many principal components explain "
"90%% / 95%% / 99%% of the variance"))
parser.add_argument("--variance",
dest="variance",
action="store_true",
default=False,
help="Analyze the variance of features")
parser.add_argument("--correlation",
dest="correlation",
action="store_true",
default=False,
help="Analyze the correlation of features")
parser.add_argument("--create-classification-task",
dest="create_folds",
action="store_true",
default=False,
help=argparse.SUPPRESS)
parser.add_argument("--create-verification-task",
dest="create_verification_task",
action="store_true",
default=False,
help=argparse.SUPPRESS)
parser.add_argument("--count-users",
dest="count_users",
action="store_true",
default=False,
help="Count how many different users have created "
"the dataset")
parser.add_argument("--analyze-cm",
dest="cm",
default=False,
help="Analyze a confusion matrix in JSON format.")
return parser | [
"def",
"_get_parser",
"(",
")",
":",
"import",
"argparse",
"from",
"argparse",
"import",
"ArgumentDefaultsHelpFormatter",
",",
"ArgumentParser",
"parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"__doc__",
",",
"formatter_class",
"=",
"ArgumentDefaultsHelpFormat... | https://github.com/MartinThoma/algorithms/blob/6199cfa3446e1056c7b4d75ca6e306e9e56fd95b/ML/50-mlps/15-keras-cnn-higher-dropout/hasy_tools.py#L1201-L1271 | |
CedricGuillemet/Imogen | ee417b42747ed5b46cb11b02ef0c3630000085b3 | bin/Lib/distutils/command/config.py | python | config.try_cpp | (self, body=None, headers=None, include_dirs=None, lang="c") | return ok | Construct a source file from 'body' (a string containing lines
of C/C++ code) and 'headers' (a list of header files to include)
and run it through the preprocessor. Return true if the
preprocessor succeeded, false if there were any errors.
('body' probably isn't of much use, but what the heck.) | Construct a source file from 'body' (a string containing lines
of C/C++ code) and 'headers' (a list of header files to include)
and run it through the preprocessor. Return true if the
preprocessor succeeded, false if there were any errors.
('body' probably isn't of much use, but what the heck.) | [
"Construct",
"a",
"source",
"file",
"from",
"body",
"(",
"a",
"string",
"containing",
"lines",
"of",
"C",
"/",
"C",
"++",
"code",
")",
"and",
"headers",
"(",
"a",
"list",
"of",
"header",
"files",
"to",
"include",
")",
"and",
"run",
"it",
"through",
"... | def try_cpp(self, body=None, headers=None, include_dirs=None, lang="c"):
"""Construct a source file from 'body' (a string containing lines
of C/C++ code) and 'headers' (a list of header files to include)
and run it through the preprocessor. Return true if the
preprocessor succeeded, false if there were any errors.
('body' probably isn't of much use, but what the heck.)
"""
from distutils.ccompiler import CompileError
self._check_compiler()
ok = True
try:
self._preprocess(body, headers, include_dirs, lang)
except CompileError:
ok = False
self._clean()
return ok | [
"def",
"try_cpp",
"(",
"self",
",",
"body",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"include_dirs",
"=",
"None",
",",
"lang",
"=",
"\"c\"",
")",
":",
"from",
"distutils",
".",
"ccompiler",
"import",
"CompileError",
"self",
".",
"_check_compiler",
... | https://github.com/CedricGuillemet/Imogen/blob/ee417b42747ed5b46cb11b02ef0c3630000085b3/bin/Lib/distutils/command/config.py#L173-L189 | |
metamorphose/metamorphose2 | d2bdd6a86340b9668e93b35a6a568894c9909d68 | src/MainWindow/bottomWindow.py | python | MainPanel.__set_thumb_size | (self, event) | Only re-preview if image preview is enabled and size has changed. | Only re-preview if image preview is enabled and size has changed. | [
"Only",
"re",
"-",
"preview",
"if",
"image",
"preview",
"is",
"enabled",
"and",
"size",
"has",
"changed",
"."
] | def __set_thumb_size(self, event):
"""Only re-preview if image preview is enabled and size has changed."""
if hasattr(self.main.picker.view.ItemList, 'thumbSize'):
thumbSize = self.main.picker.view.ItemList.thumbSize[0]
else:
thumbSize = int(event.GetString())
if self.imgPreview.GetValue() and int(event.GetString()) != thumbSize:
self.__refresh_picker(event) | [
"def",
"__set_thumb_size",
"(",
"self",
",",
"event",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"main",
".",
"picker",
".",
"view",
".",
"ItemList",
",",
"'thumbSize'",
")",
":",
"thumbSize",
"=",
"self",
".",
"main",
".",
"picker",
".",
"view",
"... | https://github.com/metamorphose/metamorphose2/blob/d2bdd6a86340b9668e93b35a6a568894c9909d68/src/MainWindow/bottomWindow.py#L295-L302 | ||
tomplus/kubernetes_asyncio | f028cc793e3a2c519be6a52a49fb77ff0b014c9b | kubernetes_asyncio/client/models/v1_limit_range_spec.py | python | V1LimitRangeSpec.limits | (self, limits) | Sets the limits of this V1LimitRangeSpec.
Limits is the list of LimitRangeItem objects that are enforced. # noqa: E501
:param limits: The limits of this V1LimitRangeSpec. # noqa: E501
:type: list[V1LimitRangeItem] | Sets the limits of this V1LimitRangeSpec. | [
"Sets",
"the",
"limits",
"of",
"this",
"V1LimitRangeSpec",
"."
] | def limits(self, limits):
"""Sets the limits of this V1LimitRangeSpec.
Limits is the list of LimitRangeItem objects that are enforced. # noqa: E501
:param limits: The limits of this V1LimitRangeSpec. # noqa: E501
:type: list[V1LimitRangeItem]
"""
if self.local_vars_configuration.client_side_validation and limits is None: # noqa: E501
raise ValueError("Invalid value for `limits`, must not be `None`") # noqa: E501
self._limits = limits | [
"def",
"limits",
"(",
"self",
",",
"limits",
")",
":",
"if",
"self",
".",
"local_vars_configuration",
".",
"client_side_validation",
"and",
"limits",
"is",
"None",
":",
"# noqa: E501",
"raise",
"ValueError",
"(",
"\"Invalid value for `limits`, must not be `None`\"",
"... | https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/models/v1_limit_range_spec.py#L66-L77 | ||
AppScale/gts | 46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9 | AppServer/lib/django-1.4/django/views/generic/dates.py | python | BaseWeekArchiveView.get_dated_items | (self) | return (None, qs, {'week': date}) | Return (date_list, items, extra_context) for this request. | Return (date_list, items, extra_context) for this request. | [
"Return",
"(",
"date_list",
"items",
"extra_context",
")",
"for",
"this",
"request",
"."
] | def get_dated_items(self):
"""
Return (date_list, items, extra_context) for this request.
"""
year = self.get_year()
week = self.get_week()
date_field = self.get_date_field()
week_format = self.get_week_format()
week_start = {
'%W': '1',
'%U': '0',
}[week_format]
date = _date_from_string(year, self.get_year_format(),
week_start, '%w',
week, week_format)
# Construct a date-range lookup.
first_day = date
last_day = date + datetime.timedelta(days=7)
lookup_kwargs = {
'%s__gte' % date_field: first_day,
'%s__lt' % date_field: last_day,
}
qs = self.get_dated_queryset(**lookup_kwargs)
return (None, qs, {'week': date}) | [
"def",
"get_dated_items",
"(",
"self",
")",
":",
"year",
"=",
"self",
".",
"get_year",
"(",
")",
"week",
"=",
"self",
".",
"get_week",
"(",
")",
"date_field",
"=",
"self",
".",
"get_date_field",
"(",
")",
"week_format",
"=",
"self",
".",
"get_week_format... | https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.4/django/views/generic/dates.py#L345-L372 | |
Source-Python-Dev-Team/Source.Python | d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb | addons/source-python/Python3/inspect.py | python | getlineno | (frame) | return frame.f_lineno | Get the line number from a frame object, allowing for optimization. | Get the line number from a frame object, allowing for optimization. | [
"Get",
"the",
"line",
"number",
"from",
"a",
"frame",
"object",
"allowing",
"for",
"optimization",
"."
] | def getlineno(frame):
"""Get the line number from a frame object, allowing for optimization."""
# FrameType.f_lineno is now a descriptor that grovels co_lnotab
return frame.f_lineno | [
"def",
"getlineno",
"(",
"frame",
")",
":",
"# FrameType.f_lineno is now a descriptor that grovels co_lnotab",
"return",
"frame",
".",
"f_lineno"
] | https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/Python3/inspect.py#L1427-L1430 | |
tomplus/kubernetes_asyncio | f028cc793e3a2c519be6a52a49fb77ff0b014c9b | kubernetes_asyncio/client/api/scheduling_v1beta1_api.py | python | SchedulingV1beta1Api.read_priority_class | (self, name, **kwargs) | return self.read_priority_class_with_http_info(name, **kwargs) | read_priority_class # noqa: E501
read the specified PriorityClass # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_priority_class(name, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PriorityClass (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool exact: Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'. Deprecated. Planned for removal in 1.18.
:param bool export: Should this value be exported. Export strips fields that a user can not specify. Deprecated. Planned for removal in 1.18.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1beta1PriorityClass
If the method is called asynchronously,
returns the request thread. | read_priority_class # noqa: E501 | [
"read_priority_class",
"#",
"noqa",
":",
"E501"
] | def read_priority_class(self, name, **kwargs): # noqa: E501
"""read_priority_class # noqa: E501
read the specified PriorityClass # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_priority_class(name, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PriorityClass (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool exact: Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'. Deprecated. Planned for removal in 1.18.
:param bool export: Should this value be exported. Export strips fields that a user can not specify. Deprecated. Planned for removal in 1.18.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1beta1PriorityClass
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.read_priority_class_with_http_info(name, **kwargs) | [
"def",
"read_priority_class",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"return",
"self",
".",
"read_priority_class_with_http_info",
"(",
"name",
",",
"*",
"*",
"kw... | https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/api/scheduling_v1beta1_api.py#L889-L915 | |
WerWolv/EdiZon_CheatsConfigsAndScripts | d16d36c7509c01dca770f402babd83ff2e9ae6e7 | Scripts/lib/python3.5/nntplib.py | python | _NNTPBase.set_debuglevel | (self, level) | Set the debugging level. Argument 'level' means:
0: no debugging output (default)
1: print commands and responses but not body text etc.
2: also print raw lines read and sent before stripping CR/LF | Set the debugging level. Argument 'level' means:
0: no debugging output (default)
1: print commands and responses but not body text etc.
2: also print raw lines read and sent before stripping CR/LF | [
"Set",
"the",
"debugging",
"level",
".",
"Argument",
"level",
"means",
":",
"0",
":",
"no",
"debugging",
"output",
"(",
"default",
")",
"1",
":",
"print",
"commands",
"and",
"responses",
"but",
"not",
"body",
"text",
"etc",
".",
"2",
":",
"also",
"prin... | def set_debuglevel(self, level):
"""Set the debugging level. Argument 'level' means:
0: no debugging output (default)
1: print commands and responses but not body text etc.
2: also print raw lines read and sent before stripping CR/LF"""
self.debugging = level | [
"def",
"set_debuglevel",
"(",
"self",
",",
"level",
")",
":",
"self",
".",
"debugging",
"=",
"level"
] | https://github.com/WerWolv/EdiZon_CheatsConfigsAndScripts/blob/d16d36c7509c01dca770f402babd83ff2e9ae6e7/Scripts/lib/python3.5/nntplib.py#L404-L410 | ||
googlearchive/simian | fb9c43946ff7ba29be417068d6447cfc0adfe9ef | src/simian/mac/client/flight_common.py | python | GetDiskFree | (path=None) | return st.f_frsize * st.f_bavail | Return the bytes of free space.
Args:
path: str, optional, default '/'
Returns:
int, bytes in free space available | Return the bytes of free space. | [
"Return",
"the",
"bytes",
"of",
"free",
"space",
"."
] | def GetDiskFree(path=None):
"""Return the bytes of free space.
Args:
path: str, optional, default '/'
Returns:
int, bytes in free space available
"""
if path is None:
path = '/'
try:
st = os.statvfs(path)
except OSError as e:
raise Error(str(e))
return st.f_frsize * st.f_bavail | [
"def",
"GetDiskFree",
"(",
"path",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"'/'",
"try",
":",
"st",
"=",
"os",
".",
"statvfs",
"(",
"path",
")",
"except",
"OSError",
"as",
"e",
":",
"raise",
"Error",
"(",
"str",
"(",
... | https://github.com/googlearchive/simian/blob/fb9c43946ff7ba29be417068d6447cfc0adfe9ef/src/simian/mac/client/flight_common.py#L392-L407 | |
spyder-ide/spyder | 55da47c032dfcf519600f67f8b30eab467f965e7 | spyder/plugins/pylint/main_widget.py | python | PylintWidget.get_pylintrc_path | (self, filename) | return get_pylintrc_path(search_paths=search_paths) | Get the path to the most proximate pylintrc config to the file. | Get the path to the most proximate pylintrc config to the file. | [
"Get",
"the",
"path",
"to",
"the",
"most",
"proximate",
"pylintrc",
"config",
"to",
"the",
"file",
"."
] | def get_pylintrc_path(self, filename):
"""
Get the path to the most proximate pylintrc config to the file.
"""
search_paths = [
# File"s directory
osp.dirname(filename),
# Working directory
getcwd_or_home(),
# Project directory
self.get_conf("project_dir"),
# Home directory
osp.expanduser("~"),
]
return get_pylintrc_path(search_paths=search_paths) | [
"def",
"get_pylintrc_path",
"(",
"self",
",",
"filename",
")",
":",
"search_paths",
"=",
"[",
"# File\"s directory",
"osp",
".",
"dirname",
"(",
"filename",
")",
",",
"# Working directory",
"getcwd_or_home",
"(",
")",
",",
"# Project directory",
"self",
".",
"ge... | https://github.com/spyder-ide/spyder/blob/55da47c032dfcf519600f67f8b30eab467f965e7/spyder/plugins/pylint/main_widget.py#L825-L840 | |
kengz/openai_lab | d0669d89268f2dc01c1cf878e4879775c7b6eb3c | rl/experiment.py | python | Trial.run | (self) | return trial_data | helper: run a trial for Session
a number of times times given a experiment_spec from gym_specs | helper: run a trial for Session
a number of times times given a experiment_spec from gym_specs | [
"helper",
":",
"run",
"a",
"trial",
"for",
"Session",
"a",
"number",
"of",
"times",
"times",
"given",
"a",
"experiment_spec",
"from",
"gym_specs"
] | def run(self):
'''
helper: run a trial for Session
a number of times times given a experiment_spec from gym_specs
'''
if self.is_completed():
log_trial_delimiter(self, 'Already completed')
else:
log_trial_delimiter(self, 'Run')
self.keras_session = configure_hardware(RAND_SEED)
time_start = timestamp()
sys_vars_array = [] if (self.data is None) else self.data[
'sys_vars_array']
# skip session if already has its data
s_start = len(sys_vars_array)
for s in range(s_start, self.times):
sess = Session(
trial=self, session_num=s, num_of_sessions=self.times)
sys_vars = sess.run()
lean_sys_vars = copy.deepcopy(sys_vars)
lean_sys_vars.pop('loss', None)
sys_vars_array.append(lean_sys_vars)
time_taken = timestamp_elapse(time_start, timestamp())
self.data = { # trial data
'trial_id': self.trial_id,
'metrics': {
'time_taken': time_taken,
},
'experiment_spec': self.experiment_spec,
'stats': None,
'sys_vars_array': sys_vars_array,
}
compose_data(self)
self.save() # progressive update, write per session done
del sess
import gc
gc.collect()
if self.is_completed(s):
break
log_trial_delimiter(self, 'End')
compose_data(self) # final update, for resume mode
self.save()
trial_data = copy.deepcopy(self.data)
self.clear()
return trial_data | [
"def",
"run",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_completed",
"(",
")",
":",
"log_trial_delimiter",
"(",
"self",
",",
"'Already completed'",
")",
"else",
":",
"log_trial_delimiter",
"(",
"self",
",",
"'Run'",
")",
"self",
".",
"keras_session",
"=... | https://github.com/kengz/openai_lab/blob/d0669d89268f2dc01c1cf878e4879775c7b6eb3c/rl/experiment.py#L373-L420 | |
devbisme/skidl | 458709a10b28a864d25ae2c2b44c6103d4ddb291 | skidl/net.py | python | Net.name | (self) | return self._name | Get, set and delete the name of this net.
When setting the net name, if another net with the same name
is found, the name for this net is adjusted to make it unique. | Get, set and delete the name of this net. | [
"Get",
"set",
"and",
"delete",
"the",
"name",
"of",
"this",
"net",
"."
] | def name(self):
"""
Get, set and delete the name of this net.
When setting the net name, if another net with the same name
is found, the name for this net is adjusted to make it unique.
"""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | https://github.com/devbisme/skidl/blob/458709a10b28a864d25ae2c2b44c6103d4ddb291/skidl/net.py#L714-L721 | |
pypa/pipenv | b21baade71a86ab3ee1429f71fbc14d4f95fb75d | pipenv/patched/notpip/_internal/models/direct_url.py | python | _get | (
d: Dict[str, Any], expected_type: Type[T], key: str, default: Optional[T] = None
) | return value | Get value from dictionary and verify expected type. | Get value from dictionary and verify expected type. | [
"Get",
"value",
"from",
"dictionary",
"and",
"verify",
"expected",
"type",
"."
] | def _get(
d: Dict[str, Any], expected_type: Type[T], key: str, default: Optional[T] = None
) -> Optional[T]:
"""Get value from dictionary and verify expected type."""
if key not in d:
return default
value = d[key]
if not isinstance(value, expected_type):
raise DirectUrlValidationError(
"{!r} has unexpected type for {} (expected {})".format(
value, key, expected_type
)
)
return value | [
"def",
"_get",
"(",
"d",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"expected_type",
":",
"Type",
"[",
"T",
"]",
",",
"key",
":",
"str",
",",
"default",
":",
"Optional",
"[",
"T",
"]",
"=",
"None",
")",
"->",
"Optional",
"[",
"T",
"]",
":... | https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/patched/notpip/_internal/models/direct_url.py#L25-L38 | |
beeware/ouroboros | a29123c6fab6a807caffbb7587cf548e0c370296 | ouroboros/asyncio/futures.py | python | Future.exception | (self) | return self._exception | Return the exception that was set on this future.
The exception (or None if no exception was set) is returned only if
the future is done. If the future has been cancelled, raises
CancelledError. If the future isn't done yet, raises
InvalidStateError. | Return the exception that was set on this future. | [
"Return",
"the",
"exception",
"that",
"was",
"set",
"on",
"this",
"future",
"."
] | def exception(self):
"""Return the exception that was set on this future.
The exception (or None if no exception was set) is returned only if
the future is done. If the future has been cancelled, raises
CancelledError. If the future isn't done yet, raises
InvalidStateError.
"""
if self._state == _CANCELLED:
raise CancelledError
if self._state != _FINISHED:
raise InvalidStateError('Exception is not set.')
self._log_traceback = False
if self._tb_logger is not None:
self._tb_logger.clear()
self._tb_logger = None
return self._exception | [
"def",
"exception",
"(",
"self",
")",
":",
"if",
"self",
".",
"_state",
"==",
"_CANCELLED",
":",
"raise",
"CancelledError",
"if",
"self",
".",
"_state",
"!=",
"_FINISHED",
":",
"raise",
"InvalidStateError",
"(",
"'Exception is not set.'",
")",
"self",
".",
"... | https://github.com/beeware/ouroboros/blob/a29123c6fab6a807caffbb7587cf548e0c370296/ouroboros/asyncio/futures.py#L277-L293 | |
bjmayor/hacker | e3ce2ad74839c2733b27dac6c0f495e0743e1866 | venv/lib/python3.5/site-packages/bs4/dammit.py | python | EncodingDetector.strip_byte_order_mark | (cls, data) | return data, encoding | If a byte-order mark is present, strip it and return the encoding it implies. | If a byte-order mark is present, strip it and return the encoding it implies. | [
"If",
"a",
"byte",
"-",
"order",
"mark",
"is",
"present",
"strip",
"it",
"and",
"return",
"the",
"encoding",
"it",
"implies",
"."
] | def strip_byte_order_mark(cls, data):
"""If a byte-order mark is present, strip it and return the encoding it implies."""
encoding = None
if isinstance(data, str):
# Unicode data cannot have a byte-order mark.
return data, encoding
if (len(data) >= 4) and (data[:2] == b'\xfe\xff') \
and (data[2:4] != '\x00\x00'):
encoding = 'utf-16be'
data = data[2:]
elif (len(data) >= 4) and (data[:2] == b'\xff\xfe') \
and (data[2:4] != '\x00\x00'):
encoding = 'utf-16le'
data = data[2:]
elif data[:3] == b'\xef\xbb\xbf':
encoding = 'utf-8'
data = data[3:]
elif data[:4] == b'\x00\x00\xfe\xff':
encoding = 'utf-32be'
data = data[4:]
elif data[:4] == b'\xff\xfe\x00\x00':
encoding = 'utf-32le'
data = data[4:]
return data, encoding | [
"def",
"strip_byte_order_mark",
"(",
"cls",
",",
"data",
")",
":",
"encoding",
"=",
"None",
"if",
"isinstance",
"(",
"data",
",",
"str",
")",
":",
"# Unicode data cannot have a byte-order mark.",
"return",
"data",
",",
"encoding",
"if",
"(",
"len",
"(",
"data"... | https://github.com/bjmayor/hacker/blob/e3ce2ad74839c2733b27dac6c0f495e0743e1866/venv/lib/python3.5/site-packages/bs4/dammit.py#L274-L297 | |
ialbert/plac | 00f9dbb5721ea855132fdc5994961cefb504aa56 | plac_ext.py | python | partial_call | (factory, arglist) | return plac_core.call(makeobj, arglist) | Call a container factory with the arglist and return a plac object | Call a container factory with the arglist and return a plac object | [
"Call",
"a",
"container",
"factory",
"with",
"the",
"arglist",
"and",
"return",
"a",
"plac",
"object"
] | def partial_call(factory, arglist):
"Call a container factory with the arglist and return a plac object"
a = plac_core.parser_from(factory).argspec
if a.defaults or a.varargs or a.varkw:
raise TypeError('Interpreter.call must be invoked on '
'factories with required arguments only')
required_args = ', '.join(a.args)
if required_args:
required_args += ',' # trailing comma
code = '''def makeobj(interact, %s *args):
obj = factory(%s)
obj._interact_ = interact
obj._args_ = args
return obj\n''' % (required_args, required_args)
dic = dict(factory=factory)
exec_(code, dic)
makeobj = dic['makeobj']
makeobj.add_help = False
if inspect.isclass(factory):
makeobj.__annotations__ = getattr(
factory.__init__, '__annotations__', {})
else:
makeobj.__annotations__ = getattr(
factory, '__annotations__', {})
makeobj.__annotations__['interact'] = (
'start interactive interpreter', 'flag', 'i')
return plac_core.call(makeobj, arglist) | [
"def",
"partial_call",
"(",
"factory",
",",
"arglist",
")",
":",
"a",
"=",
"plac_core",
".",
"parser_from",
"(",
"factory",
")",
".",
"argspec",
"if",
"a",
".",
"defaults",
"or",
"a",
".",
"varargs",
"or",
"a",
".",
"varkw",
":",
"raise",
"TypeError",
... | https://github.com/ialbert/plac/blob/00f9dbb5721ea855132fdc5994961cefb504aa56/plac_ext.py#L304-L330 | |
sentinel-hub/sentinelhub-py | d7ad283cf9d4bd4c8c1a8b169cdbe37c5bc8208a | sentinelhub/sentinelhub_rate_limit.py | python | PolicyBucket.is_request_bucket | (self) | return self.policy_type is PolicyType.REQUESTS | Checks if bucket counts requests | Checks if bucket counts requests | [
"Checks",
"if",
"bucket",
"counts",
"requests"
] | def is_request_bucket(self):
""" Checks if bucket counts requests
"""
return self.policy_type is PolicyType.REQUESTS | [
"def",
"is_request_bucket",
"(",
"self",
")",
":",
"return",
"self",
".",
"policy_type",
"is",
"PolicyType",
".",
"REQUESTS"
] | https://github.com/sentinel-hub/sentinelhub-py/blob/d7ad283cf9d4bd4c8c1a8b169cdbe37c5bc8208a/sentinelhub/sentinelhub_rate_limit.py#L126-L129 | |
cloudera/hue | 23f02102d4547c17c32bd5ea0eb24e9eadd657a4 | desktop/core/ext-py/gunicorn-19.9.0/docs/sitemap_gen.py | python | Filter.Apply | (self, url) | Process the URL, as above. | Process the URL, as above. | [
"Process",
"the",
"URL",
"as",
"above",
"."
] | def Apply(self, url):
""" Process the URL, as above. """
if (not url) or (not url.loc):
return None
if self._wildcard:
if fnmatch.fnmatchcase(url.loc, self._wildcard):
return self._pass
return None
if self._regexp:
if self._regexp.search(url.loc):
return self._pass
return None
assert False | [
"def",
"Apply",
"(",
"self",
",",
"url",
")",
":",
"if",
"(",
"not",
"url",
")",
"or",
"(",
"not",
"url",
".",
"loc",
")",
":",
"return",
"None",
"if",
"self",
".",
"_wildcard",
":",
"if",
"fnmatch",
".",
"fnmatchcase",
"(",
"url",
".",
"loc",
... | https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/gunicorn-19.9.0/docs/sitemap_gen.py#L708-L723 | ||
omz/PythonistaAppTemplate | f560f93f8876d82a21d108977f90583df08d55af | PythonistaAppTemplate/PythonistaKit.framework/pylib/code.py | python | interact | (banner=None, readfunc=None, local=None) | Closely emulate the interactive Python interpreter.
This is a backwards compatible interface to the InteractiveConsole
class. When readfunc is not specified, it attempts to import the
readline module to enable GNU readline if it is available.
Arguments (all optional, all default to None):
banner -- passed to InteractiveConsole.interact()
readfunc -- if not None, replaces InteractiveConsole.raw_input()
local -- passed to InteractiveInterpreter.__init__() | Closely emulate the interactive Python interpreter. | [
"Closely",
"emulate",
"the",
"interactive",
"Python",
"interpreter",
"."
] | def interact(banner=None, readfunc=None, local=None):
"""Closely emulate the interactive Python interpreter.
This is a backwards compatible interface to the InteractiveConsole
class. When readfunc is not specified, it attempts to import the
readline module to enable GNU readline if it is available.
Arguments (all optional, all default to None):
banner -- passed to InteractiveConsole.interact()
readfunc -- if not None, replaces InteractiveConsole.raw_input()
local -- passed to InteractiveInterpreter.__init__()
"""
console = InteractiveConsole(local)
if readfunc is not None:
console.raw_input = readfunc
else:
try:
import readline
except ImportError:
pass
console.interact(banner) | [
"def",
"interact",
"(",
"banner",
"=",
"None",
",",
"readfunc",
"=",
"None",
",",
"local",
"=",
"None",
")",
":",
"console",
"=",
"InteractiveConsole",
"(",
"local",
")",
"if",
"readfunc",
"is",
"not",
"None",
":",
"console",
".",
"raw_input",
"=",
"re... | https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib/code.py#L285-L307 | ||
bgavran/DNC | 668a2f1ecc676748c68cedab78dd198aca190d3b | src/task_implementations/bAbI/bAbI.py | python | bAbITask.flatten_if_list | (l) | return newl | [] | def flatten_if_list(l):
newl = []
for elem in l:
if isinstance(elem, list):
newl.extend(elem)
else:
newl.append(elem)
return newl | [
"def",
"flatten_if_list",
"(",
"l",
")",
":",
"newl",
"=",
"[",
"]",
"for",
"elem",
"in",
"l",
":",
"if",
"isinstance",
"(",
"elem",
",",
"list",
")",
":",
"newl",
".",
"extend",
"(",
"elem",
")",
"else",
":",
"newl",
".",
"append",
"(",
"elem",
... | https://github.com/bgavran/DNC/blob/668a2f1ecc676748c68cedab78dd198aca190d3b/src/task_implementations/bAbI/bAbI.py#L309-L316 | |||
spotify/luigi | c3b66f4a5fa7eaa52f9a72eb6704b1049035c789 | luigi/configuration/toml_parser.py | python | LuigiTomlParser.get | (self, section, option, default=NO_DEFAULT, **kwargs) | [] | def get(self, section, option, default=NO_DEFAULT, **kwargs):
try:
return self.data[section][option]
except KeyError:
if default is self.NO_DEFAULT:
raise
return default | [
"def",
"get",
"(",
"self",
",",
"section",
",",
"option",
",",
"default",
"=",
"NO_DEFAULT",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"self",
".",
"data",
"[",
"section",
"]",
"[",
"option",
"]",
"except",
"KeyError",
":",
"if",
"de... | https://github.com/spotify/luigi/blob/c3b66f4a5fa7eaa52f9a72eb6704b1049035c789/luigi/configuration/toml_parser.py#L64-L70 | ||||
alexmojaki/funcfinder | 3200b65044c71be73a45caa39ac9a6ed4d535e35 | funcfinder/utils.py | python | assertEqual | (a, b) | [] | def assertEqual(a, b):
assert a == b | [
"def",
"assertEqual",
"(",
"a",
",",
"b",
")",
":",
"assert",
"a",
"==",
"b"
] | https://github.com/alexmojaki/funcfinder/blob/3200b65044c71be73a45caa39ac9a6ed4d535e35/funcfinder/utils.py#L52-L53 | ||||
pydicom/pynetdicom | f57d8214c82b63c8e76638af43ce331f584a80fa | pynetdicom/dimse_primitives.py | python | N_CREATE.AttributeList | (self) | return self._dataset_variant | Return the *Attribute List* as :class:`io.BytesIO`.
Parameters
----------
io.BytesIO
The value to use for the *Attribute List* parameter. | Return the *Attribute List* as :class:`io.BytesIO`. | [
"Return",
"the",
"*",
"Attribute",
"List",
"*",
"as",
":",
"class",
":",
"io",
".",
"BytesIO",
"."
] | def AttributeList(self) -> Optional[BytesIO]:
"""Return the *Attribute List* as :class:`io.BytesIO`.
Parameters
----------
io.BytesIO
The value to use for the *Attribute List* parameter.
"""
return self._dataset_variant | [
"def",
"AttributeList",
"(",
"self",
")",
"->",
"Optional",
"[",
"BytesIO",
"]",
":",
"return",
"self",
".",
"_dataset_variant"
] | https://github.com/pydicom/pynetdicom/blob/f57d8214c82b63c8e76638af43ce331f584a80fa/pynetdicom/dimse_primitives.py#L2005-L2013 | |
Kismuz/btgym | 7fb3316e67f1d7a17c620630fb62fb29428b2cec | btgym/research/model_based/model/rec.py | python | EMA.__init__ | (self, dim, alpha) | Args:
dim: observation dimensionality
alpha: float, decaying factor in [0, 1] | [] | def __init__(self, dim, alpha):
"""
Args:
dim: observation dimensionality
alpha: float, decaying factor in [0, 1]
"""
self.dim = dim
if alpha is None:
self.alpha = 1
self.is_decayed = False
else:
self.alpha = alpha
self.is_decayed = True
self.mean = None
self.g = None
self.num_obs = 0 | [
"def",
"__init__",
"(",
"self",
",",
"dim",
",",
"alpha",
")",
":",
"self",
".",
"dim",
"=",
"dim",
"if",
"alpha",
"is",
"None",
":",
"self",
".",
"alpha",
"=",
"1",
"self",
".",
"is_decayed",
"=",
"False",
"else",
":",
"self",
".",
"alpha",
"=",... | https://github.com/Kismuz/btgym/blob/7fb3316e67f1d7a17c620630fb62fb29428b2cec/btgym/research/model_based/model/rec.py#L693-L711 | |||
DxCx/plugin.video.9anime | 34358c2f701e5ddf19d3276926374a16f63f7b6a | resources/lib/ui/js2py/es6/babel.py | python | PyJs_anonymous_1346_ | (require, module, exports, this, arguments, var=var) | [] | def PyJs_anonymous_1346_(require, module, exports, this, arguments, var=var):
var = Scope({u'this':this, u'require':require, u'exports':exports, u'module':module, u'arguments':arguments}, var)
var.registers([u'require', u'exports', u'module'])
PyJs_Object_1347_ = Js({u'default':var.get(u'require')(Js(u'core-js/library/fn/object/create')),u'__esModule':var.get(u'true')})
var.get(u'module').put(u'exports', PyJs_Object_1347_) | [
"def",
"PyJs_anonymous_1346_",
"(",
"require",
",",
"module",
",",
"exports",
",",
"this",
",",
"arguments",
",",
"var",
"=",
"var",
")",
":",
"var",
"=",
"Scope",
"(",
"{",
"u'this'",
":",
"this",
",",
"u'require'",
":",
"require",
",",
"u'exports'",
... | https://github.com/DxCx/plugin.video.9anime/blob/34358c2f701e5ddf19d3276926374a16f63f7b6a/resources/lib/ui/js2py/es6/babel.py#L16664-L16668 | ||||
google/capirca | 679e3885e3a5e5e129dc2dfab204ec44d63b26a4 | capirca/lib/windows.py | python | Term._HandlePorts | (self, src_ports, dst_ports) | return None, None | Perform implementation-specific port transforms.
Note that icmp_types or protocols are passed as parameters in case they
are to be munged prior to this function call, and may not be identical
to self.term.* parameters.
Args:
src_ports: list of source port range tuples, e.g., self.term.source_port
dst_ports: list of destination port range tuples
Returns:
A pair of lists of (icmp_types, protocols) | Perform implementation-specific port transforms. | [
"Perform",
"implementation",
"-",
"specific",
"port",
"transforms",
"."
] | def _HandlePorts(self, src_ports, dst_ports):
"""Perform implementation-specific port transforms.
Note that icmp_types or protocols are passed as parameters in case they
are to be munged prior to this function call, and may not be identical
to self.term.* parameters.
Args:
src_ports: list of source port range tuples, e.g., self.term.source_port
dst_ports: list of destination port range tuples
Returns:
A pair of lists of (icmp_types, protocols)
"""
return None, None | [
"def",
"_HandlePorts",
"(",
"self",
",",
"src_ports",
",",
"dst_ports",
")",
":",
"return",
"None",
",",
"None"
] | https://github.com/google/capirca/blob/679e3885e3a5e5e129dc2dfab204ec44d63b26a4/capirca/lib/windows.py#L164-L178 | |
leo-editor/leo-editor | 383d6776d135ef17d73d935a2f0ecb3ac0e99494 | leo/plugins/importers/csharp.py | python | Csharp_ScanState.__repr__ | (self) | return "Csharp_ScanState context: %r curlies: %s" % (
self.context, self.curlies) | Csharp_ScanState.__repr__ | Csharp_ScanState.__repr__ | [
"Csharp_ScanState",
".",
"__repr__"
] | def __repr__(self):
"""Csharp_ScanState.__repr__"""
return "Csharp_ScanState context: %r curlies: %s" % (
self.context, self.curlies) | [
"def",
"__repr__",
"(",
"self",
")",
":",
"return",
"\"Csharp_ScanState context: %r curlies: %s\"",
"%",
"(",
"self",
".",
"context",
",",
"self",
".",
"curlies",
")"
] | https://github.com/leo-editor/leo-editor/blob/383d6776d135ef17d73d935a2f0ecb3ac0e99494/leo/plugins/importers/csharp.py#L43-L46 | |
anchore/anchore-engine | bb18b70e0cbcad58beb44cd439d00067d8f7ea8b | anchore_engine/services/policy_engine/engine/vulns/mappers.py | python | VulnerabilityMapper._try_parse_advisories | (
advisories: List[Dict],
) | return advisory_objects | Best effort attempt at parsing advisories from grype response. Ignores any errors raised and chugs along | Best effort attempt at parsing advisories from grype response. Ignores any errors raised and chugs along | [
"Best",
"effort",
"attempt",
"at",
"parsing",
"advisories",
"from",
"grype",
"response",
".",
"Ignores",
"any",
"errors",
"raised",
"and",
"chugs",
"along"
] | def _try_parse_advisories(
advisories: List[Dict],
) -> List[Advisory]:
"""
Best effort attempt at parsing advisories from grype response. Ignores any errors raised and chugs along
"""
advisory_objects = []
if isinstance(advisories, list) and advisories:
for advisory_dict in advisories:
try:
# TODO format check with toolbox
advisory_objects.append(
Advisory(
id=advisory_dict.get("id"), link=advisory_dict.get("link")
)
)
except (AttributeError, ValueError):
log.debug(
"Ignoring error parsing advisory dict %s",
advisory_dict,
)
return advisory_objects | [
"def",
"_try_parse_advisories",
"(",
"advisories",
":",
"List",
"[",
"Dict",
"]",
",",
")",
"->",
"List",
"[",
"Advisory",
"]",
":",
"advisory_objects",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"advisories",
",",
"list",
")",
"and",
"advisories",
":",
"fo... | https://github.com/anchore/anchore-engine/blob/bb18b70e0cbcad58beb44cd439d00067d8f7ea8b/anchore_engine/services/policy_engine/engine/vulns/mappers.py#L339-L361 | |
pypa/setuptools | 9f37366aab9cd8f6baa23e6a77cfdb8daf97757e | pkg_resources/_vendor/pyparsing.py | python | matchOnlyAtCol | (n) | return verifyCol | Helper method for defining parse actions that require matching at a specific
column in the input text. | Helper method for defining parse actions that require matching at a specific
column in the input text. | [
"Helper",
"method",
"for",
"defining",
"parse",
"actions",
"that",
"require",
"matching",
"at",
"a",
"specific",
"column",
"in",
"the",
"input",
"text",
"."
] | def matchOnlyAtCol(n):
"""
Helper method for defining parse actions that require matching at a specific
column in the input text.
"""
def verifyCol(strg,locn,toks):
if col(locn,strg) != n:
raise ParseException(strg,locn,"matched token not at column %d" % n)
return verifyCol | [
"def",
"matchOnlyAtCol",
"(",
"n",
")",
":",
"def",
"verifyCol",
"(",
"strg",
",",
"locn",
",",
"toks",
")",
":",
"if",
"col",
"(",
"locn",
",",
"strg",
")",
"!=",
"n",
":",
"raise",
"ParseException",
"(",
"strg",
",",
"locn",
",",
"\"matched token n... | https://github.com/pypa/setuptools/blob/9f37366aab9cd8f6baa23e6a77cfdb8daf97757e/pkg_resources/_vendor/pyparsing.py#L4787-L4795 | |
librosa/librosa | 76029d35ce4c76a7475f07aab67fe2df3f73c25c | librosa/display.py | python | __coord_chroma | (n, bins_per_octave=12, **_kwargs) | return np.linspace(0, (12.0 * n) / bins_per_octave, num=n, endpoint=False) | Get chroma bin numbers | Get chroma bin numbers | [
"Get",
"chroma",
"bin",
"numbers"
] | def __coord_chroma(n, bins_per_octave=12, **_kwargs):
"""Get chroma bin numbers"""
return np.linspace(0, (12.0 * n) / bins_per_octave, num=n, endpoint=False) | [
"def",
"__coord_chroma",
"(",
"n",
",",
"bins_per_octave",
"=",
"12",
",",
"*",
"*",
"_kwargs",
")",
":",
"return",
"np",
".",
"linspace",
"(",
"0",
",",
"(",
"12.0",
"*",
"n",
")",
"/",
"bins_per_octave",
",",
"num",
"=",
"n",
",",
"endpoint",
"="... | https://github.com/librosa/librosa/blob/76029d35ce4c76a7475f07aab67fe2df3f73c25c/librosa/display.py#L1216-L1218 | |
amonapp/amon | 61ae3575ad98ec4854ea87c213aa8dfbb29a0199 | amon/apps/alerts/models/alertshistory.py | python | AlertHistoryModel.get_unsent | (self, server_id=None) | return data | [] | def get_unsent(self, server_id=None):
hour_ago = unix_utc_now()-3600
query_params = {'sent': False, "time": {"$gte": int(hour_ago)}}
if server_id:
query_params['server_id'] = server_id
results = self.collection.find(query_params)
data = {
'data': results.clone(),
'count': results.count()
}
return data | [
"def",
"get_unsent",
"(",
"self",
",",
"server_id",
"=",
"None",
")",
":",
"hour_ago",
"=",
"unix_utc_now",
"(",
")",
"-",
"3600",
"query_params",
"=",
"{",
"'sent'",
":",
"False",
",",
"\"time\"",
":",
"{",
"\"$gte\"",
":",
"int",
"(",
"hour_ago",
")"... | https://github.com/amonapp/amon/blob/61ae3575ad98ec4854ea87c213aa8dfbb29a0199/amon/apps/alerts/models/alertshistory.py#L38-L53 | |||
fortharris/Pcode | 147962d160a834c219e12cb456abc130826468e4 | rope/refactor/importutils/module_imports.py | python | _GlobalImportFinder._get_text | (self, start_line, end_line) | return '\n'.join(result) | [] | def _get_text(self, start_line, end_line):
result = []
for index in range(start_line, end_line):
result.append(self.lines.get_line(index))
return '\n'.join(result) | [
"def",
"_get_text",
"(",
"self",
",",
"start_line",
",",
"end_line",
")",
":",
"result",
"=",
"[",
"]",
"for",
"index",
"in",
"range",
"(",
"start_line",
",",
"end_line",
")",
":",
"result",
".",
"append",
"(",
"self",
".",
"lines",
".",
"get_line",
... | https://github.com/fortharris/Pcode/blob/147962d160a834c219e12cb456abc130826468e4/rope/refactor/importutils/module_imports.py#L416-L420 | |||
lingtengqiu/Deeperlab-pytorch | 5c500780a6655ff343d147477402aa20e0ed7a7c | model/deeperlab.py | python | dense_to_space.__init__ | (self,stride) | [] | def __init__(self,stride):
super(dense_to_space,self).__init__()
self.stride = stride
self.ps = torch.nn.PixelShuffle(stride) | [
"def",
"__init__",
"(",
"self",
",",
"stride",
")",
":",
"super",
"(",
"dense_to_space",
",",
"self",
")",
".",
"__init__",
"(",
")",
"self",
".",
"stride",
"=",
"stride",
"self",
".",
"ps",
"=",
"torch",
".",
"nn",
".",
"PixelShuffle",
"(",
"stride"... | https://github.com/lingtengqiu/Deeperlab-pytorch/blob/5c500780a6655ff343d147477402aa20e0ed7a7c/model/deeperlab.py#L99-L102 | ||||
ipython/ipykernel | 0ab288fe42f3155c7c7d9257c9be8cf093d175e0 | ipykernel/inprocess/blocking.py | python | BlockingInProcessChannel.get_msgs | (self) | return msgs | Get all messages that are currently ready. | Get all messages that are currently ready. | [
"Get",
"all",
"messages",
"that",
"are",
"currently",
"ready",
"."
] | def get_msgs(self):
""" Get all messages that are currently ready. """
msgs = []
while True:
try:
msgs.append(self.get_msg(block=False))
except Empty:
break
return msgs | [
"def",
"get_msgs",
"(",
"self",
")",
":",
"msgs",
"=",
"[",
"]",
"while",
"True",
":",
"try",
":",
"msgs",
".",
"append",
"(",
"self",
".",
"get_msg",
"(",
"block",
"=",
"False",
")",
")",
"except",
"Empty",
":",
"break",
"return",
"msgs"
] | https://github.com/ipython/ipykernel/blob/0ab288fe42f3155c7c7d9257c9be8cf093d175e0/ipykernel/inprocess/blocking.py#L40-L48 | |
home-assistant/core | 265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1 | homeassistant/components/stream/core.py | python | StreamOutput.idle | (self) | return self.idle_timer.idle | Return True if the output is idle. | Return True if the output is idle. | [
"Return",
"True",
"if",
"the",
"output",
"is",
"idle",
"."
] | def idle(self) -> bool:
"""Return True if the output is idle."""
return self.idle_timer.idle | [
"def",
"idle",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"self",
".",
"idle_timer",
".",
"idle"
] | https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/stream/core.py#L251-L253 | |
fengjinqi/website | 77533d0c6715e5c69eeffff1e2de9921b596ed40 | apps/forum/views.py | python | my_callback_reply | (sender, **kwargs) | 评论通知
:param sender:
:param kwargs:
:return: | 评论通知
:param sender:
:param kwargs:
:return: | [
"评论通知",
":",
"param",
"sender",
":",
":",
"param",
"kwargs",
":",
":",
"return",
":"
] | def my_callback_reply(sender, **kwargs):
"""
评论通知
:param sender:
:param kwargs:
:return:
"""
message = UserMessage()
message.user=kwargs['instance'].to_Parent_Comments
message.ids = kwargs['instance'].forums.id
message.to_user_id = kwargs['instance'].user_id
message.has_read = False
message.url =kwargs['instance'].url
message.message="你参与的%s帖子评论有人回复了,快去看看吧!"%kwargs['instance'].forums.title
message.save() | [
"def",
"my_callback_reply",
"(",
"sender",
",",
"*",
"*",
"kwargs",
")",
":",
"message",
"=",
"UserMessage",
"(",
")",
"message",
".",
"user",
"=",
"kwargs",
"[",
"'instance'",
"]",
".",
"to_Parent_Comments",
"message",
".",
"ids",
"=",
"kwargs",
"[",
"'... | https://github.com/fengjinqi/website/blob/77533d0c6715e5c69eeffff1e2de9921b596ed40/apps/forum/views.py#L359-L375 | ||
wxGlade/wxGlade | 44ed0d1cba78f27c5c0a56918112a737653b7b27 | install/update-po.py | python | catPO | (applicationDirectoryPath, listOf_extraPo, applicationDomain=None, targetDir=None, verbose=0) | Concatenate one or several PO files with the application domain files. | Concatenate one or several PO files with the application domain files. | [
"Concatenate",
"one",
"or",
"several",
"PO",
"files",
"with",
"the",
"application",
"domain",
"files",
"."
] | def catPO(applicationDirectoryPath, listOf_extraPo, applicationDomain=None, targetDir=None, verbose=0) :
"""Concatenate one or several PO files with the application domain files.
"""
if applicationDomain is None:
applicationName = fileBaseOf(applicationDirectoryPath,withPath=0)
else:
applicationName = applicationDomain
currentDir = os.getcwd()
os.chdir(applicationDirectoryPath)
languageDict = getlanguageDict()
for langCode in languageDict.keys():
if langCode == 'en':
pass
else:
langPOfileName = "%s_%s.po" % (applicationName , langCode)
if os.path.exists(langPOfileName):
fileList = ''
for fileName in listOf_extraPo:
fileList += ("%s_%s.po " % (fileName,langCode))
cmd = "msgcat -s --no-wrap %s %s > %s.cat" % (langPOfileName, fileList, langPOfileName)
if verbose: print cmd
os.system(cmd)
if targetDir is None:
pass
else:
mo_targetDir = "%s/%s/LC_MESSAGES" % (targetDir,langCode)
cmd = "msgfmt --output-file=%s/%s.mo %s_%s.po.cat" % (mo_targetDir,applicationName,applicationName,langCode)
if verbose: print cmd
os.system(cmd)
os.chdir(currentDir) | [
"def",
"catPO",
"(",
"applicationDirectoryPath",
",",
"listOf_extraPo",
",",
"applicationDomain",
"=",
"None",
",",
"targetDir",
"=",
"None",
",",
"verbose",
"=",
"0",
")",
":",
"if",
"applicationDomain",
"is",
"None",
":",
"applicationName",
"=",
"fileBaseOf",
... | https://github.com/wxGlade/wxGlade/blob/44ed0d1cba78f27c5c0a56918112a737653b7b27/install/update-po.py#L174-L206 | ||
danielgtaylor/arista | edcf2565eea92014b55c1084acd12a832aab1ca2 | arista/queue.py | python | QueueEntry.stop | (self) | Stop this queue entry from processing. | Stop this queue entry from processing. | [
"Stop",
"this",
"queue",
"entry",
"from",
"processing",
"."
] | def stop(self):
"""
Stop this queue entry from processing.
"""
if hasattr(self, "transcoder") and self.transcoder.pipe:
self.transcoder.pipe.send_event(gst.event_new_eos())
self.transcoder.start()
self.force_stopped = True | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"transcoder\"",
")",
"and",
"self",
".",
"transcoder",
".",
"pipe",
":",
"self",
".",
"transcoder",
".",
"pipe",
".",
"send_event",
"(",
"gst",
".",
"event_new_eos",
"(",
")",
... | https://github.com/danielgtaylor/arista/blob/edcf2565eea92014b55c1084acd12a832aab1ca2/arista/queue.py#L64-L72 | ||
HypothesisWorks/hypothesis | d1bfc4acc86899caa7a40f892322e1a69fbf36f4 | hypothesis-python/src/hypothesis/provisional.py | python | urls | () | return st.builds(
"{}://{}{}/{}{}".format,
schemes,
domains(),
st.just("") | ports,
paths,
st.just("") | _url_fragments_strategy,
) | A strategy for :rfc:`3986`, generating http/https URLs. | A strategy for :rfc:`3986`, generating http/https URLs. | [
"A",
"strategy",
"for",
":",
"rfc",
":",
"3986",
"generating",
"http",
"/",
"https",
"URLs",
"."
] | def urls() -> st.SearchStrategy[str]:
"""A strategy for :rfc:`3986`, generating http/https URLs."""
def url_encode(s):
return "".join(c if c in URL_SAFE_CHARACTERS else "%%%02X" % ord(c) for c in s)
schemes = st.sampled_from(["http", "https"])
ports = st.integers(min_value=0, max_value=2 ** 16 - 1).map(":{}".format)
paths = st.lists(st.text(string.printable).map(url_encode)).map("/".join)
return st.builds(
"{}://{}{}/{}{}".format,
schemes,
domains(),
st.just("") | ports,
paths,
st.just("") | _url_fragments_strategy,
) | [
"def",
"urls",
"(",
")",
"->",
"st",
".",
"SearchStrategy",
"[",
"str",
"]",
":",
"def",
"url_encode",
"(",
"s",
")",
":",
"return",
"\"\"",
".",
"join",
"(",
"c",
"if",
"c",
"in",
"URL_SAFE_CHARACTERS",
"else",
"\"%%%02X\"",
"%",
"ord",
"(",
"c",
... | https://github.com/HypothesisWorks/hypothesis/blob/d1bfc4acc86899caa7a40f892322e1a69fbf36f4/hypothesis-python/src/hypothesis/provisional.py#L149-L166 | |
1012598167/flask_mongodb_game | 60c7e0351586656ec38f851592886338e50b4110 | python_flask/venv/Lib/site-packages/gridfs/__init__.py | python | GridFS.__init__ | (self, database, collection="fs", disable_md5=False) | Create a new instance of :class:`GridFS`.
Raises :class:`TypeError` if `database` is not an instance of
:class:`~pymongo.database.Database`.
:Parameters:
- `database`: database to use
- `collection` (optional): root collection to use
- `disable_md5` (optional): When True, MD5 checksums will not be
computed for uploaded files. Useful in environments where MD5
cannot be used for regulatory or other reasons. Defaults to False.
.. versionchanged:: 3.1
Indexes are only ensured on the first write to the DB.
.. versionchanged:: 3.0
`database` must use an acknowledged
:attr:`~pymongo.database.Database.write_concern`
.. mongodoc:: gridfs | Create a new instance of :class:`GridFS`. | [
"Create",
"a",
"new",
"instance",
"of",
":",
"class",
":",
"GridFS",
"."
] | def __init__(self, database, collection="fs", disable_md5=False):
"""Create a new instance of :class:`GridFS`.
Raises :class:`TypeError` if `database` is not an instance of
:class:`~pymongo.database.Database`.
:Parameters:
- `database`: database to use
- `collection` (optional): root collection to use
- `disable_md5` (optional): When True, MD5 checksums will not be
computed for uploaded files. Useful in environments where MD5
cannot be used for regulatory or other reasons. Defaults to False.
.. versionchanged:: 3.1
Indexes are only ensured on the first write to the DB.
.. versionchanged:: 3.0
`database` must use an acknowledged
:attr:`~pymongo.database.Database.write_concern`
.. mongodoc:: gridfs
"""
if not isinstance(database, Database):
raise TypeError("database must be an instance of Database")
database = _clear_entity_type_registry(database)
if not database.write_concern.acknowledged:
raise ConfigurationError('database must use '
'acknowledged write_concern')
self.__database = database
self.__collection = database[collection]
self.__files = self.__collection.files
self.__chunks = self.__collection.chunks
self.__disable_md5 = disable_md5 | [
"def",
"__init__",
"(",
"self",
",",
"database",
",",
"collection",
"=",
"\"fs\"",
",",
"disable_md5",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"database",
",",
"Database",
")",
":",
"raise",
"TypeError",
"(",
"\"database must be an instance of ... | https://github.com/1012598167/flask_mongodb_game/blob/60c7e0351586656ec38f851592886338e50b4110/python_flask/venv/Lib/site-packages/gridfs/__init__.py#L40-L75 | ||
pypa/pipenv | b21baade71a86ab3ee1429f71fbc14d4f95fb75d | pipenv/vendor/click/utils.py | python | KeepOpenFile.__exit__ | (self, exc_type, exc_value, tb) | [] | def __exit__(self, exc_type, exc_value, tb): # type: ignore
pass | [
"def",
"__exit__",
"(",
"self",
",",
"exc_type",
",",
"exc_value",
",",
"tb",
")",
":",
"# type: ignore",
"pass"
] | https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/vendor/click/utils.py#L194-L195 | ||||
ThilinaRajapakse/simpletransformers | 9323c0398baea0157044e080617b2c4be59de7a9 | simpletransformers/seq2seq/seq2seq_utils.py | python | split_text | (text, n=100, character=" ") | return [character.join(text[i : i + n]).strip() for i in range(0, len(text), n)] | Split the text every ``n``-th occurrence of ``character`` | Split the text every ``n``-th occurrence of ``character`` | [
"Split",
"the",
"text",
"every",
"n",
"-",
"th",
"occurrence",
"of",
"character"
] | def split_text(text, n=100, character=" "):
"""Split the text every ``n``-th occurrence of ``character``"""
text = text.split(character)
return [character.join(text[i : i + n]).strip() for i in range(0, len(text), n)] | [
"def",
"split_text",
"(",
"text",
",",
"n",
"=",
"100",
",",
"character",
"=",
"\" \"",
")",
":",
"text",
"=",
"text",
".",
"split",
"(",
"character",
")",
"return",
"[",
"character",
".",
"join",
"(",
"text",
"[",
"i",
":",
"i",
"+",
"n",
"]",
... | https://github.com/ThilinaRajapakse/simpletransformers/blob/9323c0398baea0157044e080617b2c4be59de7a9/simpletransformers/seq2seq/seq2seq_utils.py#L435-L438 | |
home-assistant/core | 265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1 | homeassistant/components/smartthings/__init__.py | python | async_unload_entry | (hass: HomeAssistant, entry: ConfigEntry) | return await hass.config_entries.async_unload_platforms(entry, PLATFORMS) | Unload a config entry. | Unload a config entry. | [
"Unload",
"a",
"config",
"entry",
"."
] | async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
broker = hass.data[DOMAIN][DATA_BROKERS].pop(entry.entry_id, None)
if broker:
broker.disconnect()
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS) | [
"async",
"def",
"async_unload_entry",
"(",
"hass",
":",
"HomeAssistant",
",",
"entry",
":",
"ConfigEntry",
")",
"->",
"bool",
":",
"broker",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"DATA_BROKERS",
"]",
".",
"pop",
"(",
"entry",
".",
"entry_id"... | https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/smartthings/__init__.py#L205-L211 | |
openstack/cinder | 23494a6d6c51451688191e1847a458f1d3cdcaa5 | cinder/volume/drivers/hitachi/hbsd_common.py | python | HBSDCommon.check_param | (self) | Check parameter values and consistency among them. | Check parameter values and consistency among them. | [
"Check",
"parameter",
"values",
"and",
"consistency",
"among",
"them",
"."
] | def check_param(self):
"""Check parameter values and consistency among them."""
utils.check_opt_value(self.conf, _INHERITED_VOLUME_OPTS)
utils.check_opts(self.conf, COMMON_VOLUME_OPTS)
utils.check_opts(self.conf, self.driver_info['volume_opts'])
if self.conf.hitachi_ldev_range:
self.storage_info['ldev_range'] = self._range2list(
'hitachi_ldev_range')
if (not self.conf.hitachi_target_ports and
not self.conf.hitachi_compute_target_ports):
msg = utils.output_log(
MSG.INVALID_PARAMETER,
param='hitachi_target_ports or '
'hitachi_compute_target_ports')
raise utils.HBSDError(msg)
if (self.conf.hitachi_group_delete and
not self.conf.hitachi_group_create):
msg = utils.output_log(
MSG.INVALID_PARAMETER,
param='hitachi_group_delete or '
'hitachi_group_create')
raise utils.HBSDError(msg)
for opt in _REQUIRED_COMMON_OPTS:
if not self.conf.safe_get(opt):
msg = utils.output_log(MSG.INVALID_PARAMETER, param=opt)
raise utils.HBSDError(msg)
if self.storage_info['protocol'] == 'iSCSI':
self.check_param_iscsi() | [
"def",
"check_param",
"(",
"self",
")",
":",
"utils",
".",
"check_opt_value",
"(",
"self",
".",
"conf",
",",
"_INHERITED_VOLUME_OPTS",
")",
"utils",
".",
"check_opts",
"(",
"self",
".",
"conf",
",",
"COMMON_VOLUME_OPTS",
")",
"utils",
".",
"check_opts",
"(",... | https://github.com/openstack/cinder/blob/23494a6d6c51451688191e1847a458f1d3cdcaa5/cinder/volume/drivers/hitachi/hbsd_common.py#L456-L483 | ||
krintoxi/NoobSec-Toolkit | 38738541cbc03cedb9a3b3ed13b629f781ad64f6 | NoobSecToolkit - MAC OSX/tools/inject/thirdparty/bottle/bottle.py | python | makelist | (data) | [] | def makelist(data): # This is just to handy
if isinstance(data, (tuple, list, set, dict)): return list(data)
elif data: return [data]
else: return [] | [
"def",
"makelist",
"(",
"data",
")",
":",
"# This is just to handy",
"if",
"isinstance",
"(",
"data",
",",
"(",
"tuple",
",",
"list",
",",
"set",
",",
"dict",
")",
")",
":",
"return",
"list",
"(",
"data",
")",
"elif",
"data",
":",
"return",
"[",
"dat... | https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/tools/inject/thirdparty/bottle/bottle.py#L144-L147 | ||||
Amulet-Team/Amulet-Core | a57aeaa4216806401ff35a2dba38782a35abc42e | amulet/api/history/history_manager/object.py | python | ObjectHistoryManager.redo | (self) | Redoes the last set of changes to the object | Redoes the last set of changes to the object | [
"Redoes",
"the",
"last",
"set",
"of",
"changes",
"to",
"the",
"object"
] | def redo(self):
"""Redoes the last set of changes to the object"""
if self.redo_count > 0:
self._snapshot_index += 1
self._revision_manager.redo()
self._unpack() | [
"def",
"redo",
"(",
"self",
")",
":",
"if",
"self",
".",
"redo_count",
">",
"0",
":",
"self",
".",
"_snapshot_index",
"+=",
"1",
"self",
".",
"_revision_manager",
".",
"redo",
"(",
")",
"self",
".",
"_unpack",
"(",
")"
] | https://github.com/Amulet-Team/Amulet-Core/blob/a57aeaa4216806401ff35a2dba38782a35abc42e/amulet/api/history/history_manager/object.py#L81-L86 | ||
jython/frozen-mirror | b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99 | lib-python/2.7/cookielib.py | python | DefaultCookiePolicy.set_allowed_domains | (self, allowed_domains) | Set the sequence of allowed domains, or None. | Set the sequence of allowed domains, or None. | [
"Set",
"the",
"sequence",
"of",
"allowed",
"domains",
"or",
"None",
"."
] | def set_allowed_domains(self, allowed_domains):
"""Set the sequence of allowed domains, or None."""
if allowed_domains is not None:
allowed_domains = tuple(allowed_domains)
self._allowed_domains = allowed_domains | [
"def",
"set_allowed_domains",
"(",
"self",
",",
"allowed_domains",
")",
":",
"if",
"allowed_domains",
"is",
"not",
"None",
":",
"allowed_domains",
"=",
"tuple",
"(",
"allowed_domains",
")",
"self",
".",
"_allowed_domains",
"=",
"allowed_domains"
] | https://github.com/jython/frozen-mirror/blob/b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99/lib-python/2.7/cookielib.py#L897-L901 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.