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
mahmoud/lithoxyl
b4bfa92c54df85b4bd5935fe270e2aa3fb25c412
misc/tabulate.py
python
_format_table
(fmt, headers, rows, colwidths, colaligns)
return "\n".join(lines)
Produce a plain-text representation of the table.
Produce a plain-text representation of the table.
[ "Produce", "a", "plain", "-", "text", "representation", "of", "the", "table", "." ]
def _format_table(fmt, headers, rows, colwidths, colaligns): """Produce a plain-text representation of the table.""" lines = [] hidden = fmt.with_header_hide if (headers and fmt.with_header_hide) else [] pad = fmt.padding headerrow = fmt.headerrow padded_widths = [(w + 2*pad) for w in colwidths] padded_headers = _pad_row(headers, pad) padded_rows = [_pad_row(row, pad) for row in rows] if fmt.lineabove and "lineabove" not in hidden: lines.append(_build_line(padded_widths, colaligns, fmt.lineabove)) if padded_headers: lines.append(_build_row(padded_headers, padded_widths, colaligns, headerrow)) if fmt.linebelowheader and "linebelowheader" not in hidden: lines.append(_build_line(padded_widths, colaligns, fmt.linebelowheader)) if padded_rows and fmt.linebetweenrows and "linebetweenrows" not in hidden: # initial rows with a line below for row in padded_rows[:-1]: lines.append(_build_row(row, padded_widths, colaligns, fmt.datarow)) lines.append(_build_line(padded_widths, colaligns, fmt.linebetweenrows)) # the last row without a line below lines.append(_build_row(padded_rows[-1], padded_widths, colaligns, fmt.datarow)) else: for row in padded_rows: lines.append(_build_row(row, padded_widths, colaligns, fmt.datarow)) if fmt.linebelow and "linebelow" not in hidden: lines.append(_build_line(padded_widths, colaligns, fmt.linebelow)) return "\n".join(lines)
[ "def", "_format_table", "(", "fmt", ",", "headers", ",", "rows", ",", "colwidths", ",", "colaligns", ")", ":", "lines", "=", "[", "]", "hidden", "=", "fmt", ".", "with_header_hide", "if", "(", "headers", "and", "fmt", ".", "with_header_hide", ")", "else"...
https://github.com/mahmoud/lithoxyl/blob/b4bfa92c54df85b4bd5935fe270e2aa3fb25c412/misc/tabulate.py#L999-L1032
PythonCharmers/python-future
80523f383fbba1c6de0551e19d0277e73e69573c
src/future/standard_library/__init__.py
python
scrub_py2_sys_modules
()
return scrubbed
Removes any Python 2 standard library modules from ``sys.modules`` that would interfere with Py3-style imports using import hooks. Examples are modules with the same names (like urllib or email). (Note that currently import hooks are disabled for modules like these with ambiguous names anyway ...)
Removes any Python 2 standard library modules from ``sys.modules`` that would interfere with Py3-style imports using import hooks. Examples are modules with the same names (like urllib or email).
[ "Removes", "any", "Python", "2", "standard", "library", "modules", "from", "sys", ".", "modules", "that", "would", "interfere", "with", "Py3", "-", "style", "imports", "using", "import", "hooks", ".", "Examples", "are", "modules", "with", "the", "same", "nam...
def scrub_py2_sys_modules(): """ Removes any Python 2 standard library modules from ``sys.modules`` that would interfere with Py3-style imports using import hooks. Examples are modules with the same names (like urllib or email). (Note that currently import hooks are disabled for modules like these with ambiguous names anyway ...) """ if PY3: return {} scrubbed = {} for modulename in REPLACED_MODULES & set(RENAMES.keys()): if not modulename in sys.modules: continue module = sys.modules[modulename] if is_py2_stdlib_module(module): flog.debug('Deleting (Py2) {} from sys.modules'.format(modulename)) scrubbed[modulename] = sys.modules[modulename] del sys.modules[modulename] return scrubbed
[ "def", "scrub_py2_sys_modules", "(", ")", ":", "if", "PY3", ":", "return", "{", "}", "scrubbed", "=", "{", "}", "for", "modulename", "in", "REPLACED_MODULES", "&", "set", "(", "RENAMES", ".", "keys", "(", ")", ")", ":", "if", "not", "modulename", "in",...
https://github.com/PythonCharmers/python-future/blob/80523f383fbba1c6de0551e19d0277e73e69573c/src/future/standard_library/__init__.py#L372-L394
spyder-ide/spyder
55da47c032dfcf519600f67f8b30eab467f965e7
spyder/app/mainwindow.py
python
MainWindow.set_splash
(self, message)
Set splash message
Set splash message
[ "Set", "splash", "message" ]
def set_splash(self, message): """Set splash message""" if self.splash is None: return if message: logger.info(message) self.splash.show() self.splash.showMessage(message, int(Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute), QColor(Qt.white)) QApplication.processEvents()
[ "def", "set_splash", "(", "self", ",", "message", ")", ":", "if", "self", ".", "splash", "is", "None", ":", "return", "if", "message", ":", "logger", ".", "info", "(", "message", ")", "self", ".", "splash", ".", "show", "(", ")", "self", ".", "spla...
https://github.com/spyder-ide/spyder/blob/55da47c032dfcf519600f67f8b30eab467f965e7/spyder/app/mainwindow.py#L1464-L1475
python-discord/bot
26c5587ac13e5414361bb6e7ada42983b81014d2
bot/exts/backend/sync/_cog.py
python
Sync.sync_roles_command
(self, ctx: Context)
Manually synchronise the guild's roles with the roles on the site.
Manually synchronise the guild's roles with the roles on the site.
[ "Manually", "synchronise", "the", "guild", "s", "roles", "with", "the", "roles", "on", "the", "site", "." ]
async def sync_roles_command(self, ctx: Context) -> None: """Manually synchronise the guild's roles with the roles on the site.""" await _syncers.RoleSyncer.sync(ctx.guild, ctx)
[ "async", "def", "sync_roles_command", "(", "self", ",", "ctx", ":", "Context", ")", "->", "None", ":", "await", "_syncers", ".", "RoleSyncer", ".", "sync", "(", "ctx", ".", "guild", ",", "ctx", ")" ]
https://github.com/python-discord/bot/blob/26c5587ac13e5414361bb6e7ada42983b81014d2/bot/exts/backend/sync/_cog.py#L170-L172
hyperledger/aries-cloudagent-python
2f36776e99f6053ae92eed8123b5b1b2e891c02a
aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_ack_handler.py
python
CredentialAckHandler.handle
(self, context: RequestContext, responder: BaseResponder)
Message handler logic for credential acks. Args: context: request context responder: responder callback
Message handler logic for credential acks.
[ "Message", "handler", "logic", "for", "credential", "acks", "." ]
async def handle(self, context: RequestContext, responder: BaseResponder): """ Message handler logic for credential acks. Args: context: request context responder: responder callback """ r_time = get_timer() self._logger.debug("CredentialAckHandler called with context %s", context) assert isinstance(context.message, CredentialAck) self._logger.info( "Received credential ack message: %s", context.message.serialize(as_string=True), ) if not context.connection_ready: raise HandlerException("No connection established for credential ack") credential_manager = CredentialManager(context.profile) await credential_manager.receive_credential_ack( context.message, context.connection_record.connection_id ) trace_event( context.settings, context.message, outcome="CredentialAckHandler.handle.END", perf_counter=r_time, )
[ "async", "def", "handle", "(", "self", ",", "context", ":", "RequestContext", ",", "responder", ":", "BaseResponder", ")", ":", "r_time", "=", "get_timer", "(", ")", "self", ".", "_logger", ".", "debug", "(", "\"CredentialAckHandler called with context %s\"", ",...
https://github.com/hyperledger/aries-cloudagent-python/blob/2f36776e99f6053ae92eed8123b5b1b2e891c02a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_ack_handler.py#L15-L45
Stiivi/bubbles
b3c9332b8a9534655bd77821586e45a5086b1ddc
bubbles/backends/sql/objects.py
python
SQLStatement.representations
(self)
return ["sql", "rows", "records"]
Return list of possible object representations
Return list of possible object representations
[ "Return", "list", "of", "possible", "object", "representations" ]
def representations(self): """Return list of possible object representations""" return ["sql", "rows", "records"]
[ "def", "representations", "(", "self", ")", ":", "return", "[", "\"sql\"", ",", "\"rows\"", ",", "\"records\"", "]" ]
https://github.com/Stiivi/bubbles/blob/b3c9332b8a9534655bd77821586e45a5086b1ddc/bubbles/backends/sql/objects.py#L544-L546
SpamScope/mail-parser
87ad78f1f1028b509bce7fe684117619d84d0d40
mailparser/mailparser.py
python
MailParser._make_mail
(self, complete=True)
return mail
This method assigns the right values to all tokens of email. Returns a parsed object Keyword Arguments: complete {bool} -- If True returns all mails parts (default: {True}) Returns: dict -- Parsed email object
This method assigns the right values to all tokens of email. Returns a parsed object
[ "This", "method", "assigns", "the", "right", "values", "to", "all", "tokens", "of", "email", ".", "Returns", "a", "parsed", "object" ]
def _make_mail(self, complete=True): """ This method assigns the right values to all tokens of email. Returns a parsed object Keyword Arguments: complete {bool} -- If True returns all mails parts (default: {True}) Returns: dict -- Parsed email object """ mail = {} keys = get_mail_keys(self.message, complete) for i in keys: log.debug("Getting header or part {!r}".format(i)) value = getattr(self, i) if value: mail[i] = value # add defects mail["has_defects"] = self.has_defects if self.has_defects: mail["defects"] = self.defects mail["defects_categories"] = list(self.defects_categories) return mail
[ "def", "_make_mail", "(", "self", ",", "complete", "=", "True", ")", ":", "mail", "=", "{", "}", "keys", "=", "get_mail_keys", "(", "self", ".", "message", ",", "complete", ")", "for", "i", "in", "keys", ":", "log", ".", "debug", "(", "\"Getting head...
https://github.com/SpamScope/mail-parser/blob/87ad78f1f1028b509bce7fe684117619d84d0d40/mailparser/mailparser.py#L284-L312
robotlearn/pyrobolearn
9cd7c060723fda7d2779fa255ac998c2c82b8436
pyrobolearn/simulators/bullet.py
python
Bullet.get_camera_image
(self, width, height, view_matrix=None, projection_matrix=None, light_direction=None, light_color=None, light_distance=None, shadow=None, light_ambient_coeff=None, light_diffuse_coeff=None, light_specular_coeff=None, renderer=None, flags=None)
return width, height, rgba, depth, segmentation
The `get_camera_image` API will return a RGB image, a depth buffer and a segmentation mask buffer with body unique ids of visible objects for each pixel. Note that PyBullet can be compiled using the numpy option: using numpy will improve the performance of copying the camera pixels from C to Python. Note that copying pixels from C/C++ to Python can be really slow for large images, unless you compile PyBullet using NumPy. You can check if NumPy is enabled using `PyBullet.isNumpyEnabled()`. `pip install pybullet` has NumPy enabled, if available on the system. Args: width (int): horizontal image resolution in pixels height (int): vertical image resolution in pixels view_matrix (np.array[float[4,4]]): 4x4 view matrix, see `compute_view_matrix` projection_matrix (np.array[float[4,4]]): 4x4 projection matrix, see `compute_projection` light_direction (np.array[float[3]]): `light_direction` specifies the world position of the light source, the direction is from the light source position to the origin of the world frame. light_color (np.array[float[3]]): directional light color in [RED,GREEN,BLUE] in range 0..1 light_distance (float): distance of the light along the normalized `light_direction` shadow (bool): True for shadows, False for no shadows light_ambient_coeff (float): light ambient coefficient light_diffuse_coeff (float): light diffuse coefficient light_specular_coeff (float): light specular coefficient renderer (int): ER_BULLET_HARDWARE_OPENGL (=131072) or ER_TINY_RENDERER (=65536). Note that DIRECT (=2) mode has no OpenGL, so it requires ER_TINY_RENDERER (=65536). flags (int): ER_SEGMENTATION_MASK_OBJECT_AND_LINKINDEX (=1), See below in description of segmentationMaskBuffer and example code. Use ER_NO_SEGMENTATION_MASK (=4) to avoid calculating the segmentation mask. Returns: int: width image resolution in pixels (horizontal) int: height image resolution in pixels (vertical) np.array[int[width, height, 4]]: RBGA pixels (each pixel is in the range [0..255] for each channel). np.array[float[width, height]]: Depth buffer. Bullet uses OpenGL to render, and the convention is non-linear z-buffer. See https://stackoverflow.com/questions/6652253/getting-the-true-z-value-from-the-depth-buffer Using the projection matrix, the depth is computed as: `depth = far * near / (far - (far - near) * depthImg)`, where `depthImg` is the depth from Bullet `get_camera_image`, far=1000. and near=0.01. np.array[int[width, height]]: Segmentation mask buffer. For each pixels the visible object unique id. If ER_SEGMENTATION_MASK_OBJECT_AND_LINKINDEX (=1) is used, the segmentationMaskBuffer combines the object unique id and link index as follows: value = objectUniqueId + (linkIndex+1)<<24. So for a free floating body without joints/links, the segmentation mask is equal to its body unique id, since its link index is -1.
The `get_camera_image` API will return a RGB image, a depth buffer and a segmentation mask buffer with body unique ids of visible objects for each pixel. Note that PyBullet can be compiled using the numpy option: using numpy will improve the performance of copying the camera pixels from C to Python.
[ "The", "get_camera_image", "API", "will", "return", "a", "RGB", "image", "a", "depth", "buffer", "and", "a", "segmentation", "mask", "buffer", "with", "body", "unique", "ids", "of", "visible", "objects", "for", "each", "pixel", ".", "Note", "that", "PyBullet...
def get_camera_image(self, width, height, view_matrix=None, projection_matrix=None, light_direction=None, light_color=None, light_distance=None, shadow=None, light_ambient_coeff=None, light_diffuse_coeff=None, light_specular_coeff=None, renderer=None, flags=None): """ The `get_camera_image` API will return a RGB image, a depth buffer and a segmentation mask buffer with body unique ids of visible objects for each pixel. Note that PyBullet can be compiled using the numpy option: using numpy will improve the performance of copying the camera pixels from C to Python. Note that copying pixels from C/C++ to Python can be really slow for large images, unless you compile PyBullet using NumPy. You can check if NumPy is enabled using `PyBullet.isNumpyEnabled()`. `pip install pybullet` has NumPy enabled, if available on the system. Args: width (int): horizontal image resolution in pixels height (int): vertical image resolution in pixels view_matrix (np.array[float[4,4]]): 4x4 view matrix, see `compute_view_matrix` projection_matrix (np.array[float[4,4]]): 4x4 projection matrix, see `compute_projection` light_direction (np.array[float[3]]): `light_direction` specifies the world position of the light source, the direction is from the light source position to the origin of the world frame. light_color (np.array[float[3]]): directional light color in [RED,GREEN,BLUE] in range 0..1 light_distance (float): distance of the light along the normalized `light_direction` shadow (bool): True for shadows, False for no shadows light_ambient_coeff (float): light ambient coefficient light_diffuse_coeff (float): light diffuse coefficient light_specular_coeff (float): light specular coefficient renderer (int): ER_BULLET_HARDWARE_OPENGL (=131072) or ER_TINY_RENDERER (=65536). Note that DIRECT (=2) mode has no OpenGL, so it requires ER_TINY_RENDERER (=65536). flags (int): ER_SEGMENTATION_MASK_OBJECT_AND_LINKINDEX (=1), See below in description of segmentationMaskBuffer and example code. Use ER_NO_SEGMENTATION_MASK (=4) to avoid calculating the segmentation mask. Returns: int: width image resolution in pixels (horizontal) int: height image resolution in pixels (vertical) np.array[int[width, height, 4]]: RBGA pixels (each pixel is in the range [0..255] for each channel). np.array[float[width, height]]: Depth buffer. Bullet uses OpenGL to render, and the convention is non-linear z-buffer. See https://stackoverflow.com/questions/6652253/getting-the-true-z-value-from-the-depth-buffer Using the projection matrix, the depth is computed as: `depth = far * near / (far - (far - near) * depthImg)`, where `depthImg` is the depth from Bullet `get_camera_image`, far=1000. and near=0.01. np.array[int[width, height]]: Segmentation mask buffer. For each pixels the visible object unique id. If ER_SEGMENTATION_MASK_OBJECT_AND_LINKINDEX (=1) is used, the segmentationMaskBuffer combines the object unique id and link index as follows: value = objectUniqueId + (linkIndex+1)<<24. So for a free floating body without joints/links, the segmentation mask is equal to its body unique id, since its link index is -1. """ kwargs = {} if view_matrix is not None: if isinstance(view_matrix, np.ndarray): kwargs['viewMatrix'] = view_matrix.T.ravel().tolist() else: kwargs['viewMatrix'] = view_matrix if projection_matrix is not None: if isinstance(projection_matrix, np.ndarray): kwargs['projectionMatrix'] = projection_matrix.T.ravel().tolist() else: kwargs['projectionMatrix'] = projection_matrix if light_direction is not None: if isinstance(light_direction, np.ndarray): kwargs['lightDirection'] = light_direction.ravel().tolist() else: kwargs['lightDirection'] = light_direction if light_color is not None: if isinstance(light_color, np.ndarray): kwargs['lightColor'] = light_color else: kwargs['lightColor'] = light_color if light_distance is not None: kwargs['lightDistance'] = light_distance if shadow is not None: kwargs['shadow'] = int(shadow) if light_ambient_coeff is not None: kwargs['lightAmbientCoeff'] = light_ambient_coeff if light_diffuse_coeff is not None: kwargs['lightDiffuseCoeff'] = light_diffuse_coeff if light_specular_coeff is not None: kwargs['lightSpecularCoeff'] = light_specular_coeff if renderer is not None: kwargs['renderer'] = renderer if flags is not None: kwargs['flags'] = flags width, height = int(width), int(height) width, height, rgba, depth, segmentation = self.sim.getCameraImage(width, height, **kwargs) rgba = np.asarray(rgba).reshape(width, height, 4) depth = np.asarray(depth).reshape(width, height) segmentation = np.asarray(segmentation).reshape(width, height) return width, height, rgba, depth, segmentation
[ "def", "get_camera_image", "(", "self", ",", "width", ",", "height", ",", "view_matrix", "=", "None", ",", "projection_matrix", "=", "None", ",", "light_direction", "=", "None", ",", "light_color", "=", "None", ",", "light_distance", "=", "None", ",", "shado...
https://github.com/robotlearn/pyrobolearn/blob/9cd7c060723fda7d2779fa255ac998c2c82b8436/pyrobolearn/simulators/bullet.py#L2689-L2776
evennia/evennia
fa79110ba6b219932f22297838e8ac72ebc0be0e
evennia/locks/lockfuncs.py
python
has_account
(accessing_obj, accessed_obj, *args, **kwargs)
return hasattr(accessing_obj, "has_account") and accessing_obj.has_account
Only returns true if accessing_obj has_account is true, that is, this is an account-controlled object. It fails on actual accounts! This is a useful lock for traverse-locking Exits to restrain NPC mobiles from moving outside their areas.
Only returns true if accessing_obj has_account is true, that is, this is an account-controlled object. It fails on actual accounts!
[ "Only", "returns", "true", "if", "accessing_obj", "has_account", "is", "true", "that", "is", "this", "is", "an", "account", "-", "controlled", "object", ".", "It", "fails", "on", "actual", "accounts!" ]
def has_account(accessing_obj, accessed_obj, *args, **kwargs): """ Only returns true if accessing_obj has_account is true, that is, this is an account-controlled object. It fails on actual accounts! This is a useful lock for traverse-locking Exits to restrain NPC mobiles from moving outside their areas. """ return hasattr(accessing_obj, "has_account") and accessing_obj.has_account
[ "def", "has_account", "(", "accessing_obj", ",", "accessed_obj", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "hasattr", "(", "accessing_obj", ",", "\"has_account\"", ")", "and", "accessing_obj", ".", "has_account" ]
https://github.com/evennia/evennia/blob/fa79110ba6b219932f22297838e8ac72ebc0be0e/evennia/locks/lockfuncs.py#L663-L671
sympy/sympy
d822fcba181155b85ff2b29fe525adbafb22b448
sympy/strategies/rl.py
python
sort
(key, new=new)
return sort_rl
Create a rule to sort by a key function. Examples ======== >>> from sympy.strategies import sort >>> from sympy import Basic, S >>> sort_rl = sort(str) >>> sort_rl(Basic(S(3), S(1), S(2))) Basic(1, 2, 3)
Create a rule to sort by a key function.
[ "Create", "a", "rule", "to", "sort", "by", "a", "key", "function", "." ]
def sort(key, new=new): """ Create a rule to sort by a key function. Examples ======== >>> from sympy.strategies import sort >>> from sympy import Basic, S >>> sort_rl = sort(str) >>> sort_rl(Basic(S(3), S(1), S(2))) Basic(1, 2, 3) """ def sort_rl(expr): return new(expr.__class__, *sorted(expr.args, key=key)) return sort_rl
[ "def", "sort", "(", "key", ",", "new", "=", "new", ")", ":", "def", "sort_rl", "(", "expr", ")", ":", "return", "new", "(", "expr", ".", "__class__", ",", "*", "sorted", "(", "expr", ".", "args", ",", "key", "=", "key", ")", ")", "return", "sor...
https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/strategies/rl.py#L81-L96
polakowo/vectorbt
6638735c131655760474d72b9f045d1dbdbd8fe9
vectorbt/base/combine_fns.py
python
to_2d_one_nb
(a: tp.Array)
return np.expand_dims(a, axis=1)
Expand the dimensions of array `a` along axis 1. !!! note * `a` must be strictly homogeneous
Expand the dimensions of array `a` along axis 1.
[ "Expand", "the", "dimensions", "of", "array", "a", "along", "axis", "1", "." ]
def to_2d_one_nb(a: tp.Array) -> tp.Array2d: """Expand the dimensions of array `a` along axis 1. !!! note * `a` must be strictly homogeneous""" if a.ndim > 1: return a return np.expand_dims(a, axis=1)
[ "def", "to_2d_one_nb", "(", "a", ":", "tp", ".", "Array", ")", "->", "tp", ".", "Array2d", ":", "if", "a", ".", "ndim", ">", "1", ":", "return", "a", "return", "np", ".", "expand_dims", "(", "a", ",", "axis", "=", "1", ")" ]
https://github.com/polakowo/vectorbt/blob/6638735c131655760474d72b9f045d1dbdbd8fe9/vectorbt/base/combine_fns.py#L67-L74
kiryha/Houdini
a9a45325042755295096d66c06c6728089600eec
Eve/tools/houdini/asset_manager.py
python
AssetManager.__init__
(self)
[]
def __init__(self): super(AssetManager, self).__init__() self.setupUi(self) self.setParent(hou.ui.mainQtWindow(), QtCore.Qt.Window) # Setup environment self.eve_root = os.environ['EVE_ROOT'] self.project_name = os.environ['EVE_PROJECT_NAME'] self.SQL_FILE_PATH = settings.SQL_FILE_PATH.format(self.eve_root) # Get Project Manager data self.eve_data = None self.project = None self.model_assets = None # Get asset data self.asset_data = None self.init_asset_manager() # Setup UI functionality self.btnAssetCrete.clicked.connect(self.create_asset_scene) self.btnAssetOpen.clicked.connect(self.open_asset_scene)
[ "def", "__init__", "(", "self", ")", ":", "super", "(", "AssetManager", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "setupUi", "(", "self", ")", "self", ".", "setParent", "(", "hou", ".", "ui", ".", "mainQtWindow", "(", ")", ",", "QtC...
https://github.com/kiryha/Houdini/blob/a9a45325042755295096d66c06c6728089600eec/Eve/tools/houdini/asset_manager.py#L18-L39
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/forked_daapd/media_player.py
python
ForkedDaapdMaster._update_callback
(self, available)
Call update method.
Call update method.
[ "Call", "update", "method", "." ]
def _update_callback(self, available): """Call update method.""" self._available = available self.async_write_ha_state()
[ "def", "_update_callback", "(", "self", ",", "available", ")", ":", "self", ".", "_available", "=", "available", "self", ".", "async_write_ha_state", "(", ")" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/forked_daapd/media_player.py#L315-L318
mesonbuild/meson
a22d0f9a0a787df70ce79b05d0c45de90a970048
mesonbuild/dependencies/dev.py
python
GTestDependencyPC.__init__
(self, name: str, environment: 'Environment', kwargs: T.Dict[str, T.Any])
[]
def __init__(self, name: str, environment: 'Environment', kwargs: T.Dict[str, T.Any]): assert name == 'gtest' if kwargs.get('main'): name = 'gtest_main' super().__init__(name, environment, kwargs)
[ "def", "__init__", "(", "self", ",", "name", ":", "str", ",", "environment", ":", "'Environment'", ",", "kwargs", ":", "T", ".", "Dict", "[", "str", ",", "T", ".", "Any", "]", ")", ":", "assert", "name", "==", "'gtest'", "if", "kwargs", ".", "get",...
https://github.com/mesonbuild/meson/blob/a22d0f9a0a787df70ce79b05d0c45de90a970048/mesonbuild/dependencies/dev.py#L112-L116
glouppe/info8006-introduction-to-ai
8360cc9a8c418559e402be1454ec885b6c1062d7
projects/project1/pacman_module/graphicsDisplay.py
python
PacmanGraphics.swapImages
(self, agentIndex, newState)
Changes an image from a ghost to a pacman or vis versa (for capture)
Changes an image from a ghost to a pacman or vis versa (for capture)
[ "Changes", "an", "image", "from", "a", "ghost", "to", "a", "pacman", "or", "vis", "versa", "(", "for", "capture", ")" ]
def swapImages(self, agentIndex, newState): """ Changes an image from a ghost to a pacman or vis versa (for capture) """ prevState, prevImage = self.agentImages[agentIndex] for item in prevImage: remove_from_screen(item) if newState.isPacman: image = self.drawPacman(newState, agentIndex) self.agentImages[agentIndex] = (newState, image) else: image = self.drawGhost(newState, agentIndex) self.agentImages[agentIndex] = (newState, image) refresh()
[ "def", "swapImages", "(", "self", ",", "agentIndex", ",", "newState", ")", ":", "prevState", ",", "prevImage", "=", "self", ".", "agentImages", "[", "agentIndex", "]", "for", "item", "in", "prevImage", ":", "remove_from_screen", "(", "item", ")", "if", "ne...
https://github.com/glouppe/info8006-introduction-to-ai/blob/8360cc9a8c418559e402be1454ec885b6c1062d7/projects/project1/pacman_module/graphicsDisplay.py#L246-L259
epfl-lts2/pygsp
a3412ce7696c02c8a55439e89d0c9ab8ae863269
pygsp/filters/approximations.py
python
compute_jackson_cheby_coeff
(filter_bounds, delta_lambda, m)
return ch, jch
r""" To compute the m+1 coefficients of the polynomial approximation of an ideal band-pass between a and b, between a range of values defined by lambda_min and lambda_max. Parameters ---------- filter_bounds : list [a, b] delta_lambda : list [lambda_min, lambda_max] m : int Returns ------- ch : ndarray jch : ndarray References ---------- :cite:`tremblay2016compressive`
r""" To compute the m+1 coefficients of the polynomial approximation of an ideal band-pass between a and b, between a range of values defined by lambda_min and lambda_max.
[ "r", "To", "compute", "the", "m", "+", "1", "coefficients", "of", "the", "polynomial", "approximation", "of", "an", "ideal", "band", "-", "pass", "between", "a", "and", "b", "between", "a", "range", "of", "values", "defined", "by", "lambda_min", "and", "...
def compute_jackson_cheby_coeff(filter_bounds, delta_lambda, m): r""" To compute the m+1 coefficients of the polynomial approximation of an ideal band-pass between a and b, between a range of values defined by lambda_min and lambda_max. Parameters ---------- filter_bounds : list [a, b] delta_lambda : list [lambda_min, lambda_max] m : int Returns ------- ch : ndarray jch : ndarray References ---------- :cite:`tremblay2016compressive` """ # Parameters check if delta_lambda[0] > filter_bounds[0] or delta_lambda[1] < filter_bounds[1]: _logger.error("Bounds of the filter are out of the lambda values") raise() elif delta_lambda[0] > delta_lambda[1]: _logger.error("lambda_min is greater than lambda_max") raise() # Scaling and translating to standard cheby interval a1 = (delta_lambda[1]-delta_lambda[0])/2 a2 = (delta_lambda[1]+delta_lambda[0])/2 # Scaling bounds of the band pass according to lrange filter_bounds[0] = (filter_bounds[0]-a2)/a1 filter_bounds[1] = (filter_bounds[1]-a2)/a1 # First compute cheby coeffs ch = np.empty(m+1, dtype=float) ch[0] = (2/(np.pi))*(np.arccos(filter_bounds[0])-np.arccos(filter_bounds[1])) for i in range(1, len(ch)): ch[i] = (2/(np.pi * i)) * \ (np.sin(i * np.arccos(filter_bounds[0])) - np.sin(i * np.arccos(filter_bounds[1]))) # Then compute jackson coeffs jch = np.empty(m+1, dtype=float) alpha = (np.pi/(m+2)) for i in range(len(jch)): jch[i] = (1/np.sin(alpha)) * \ ((1 - i/(m+2)) * np.sin(alpha) * np.cos(i * alpha) + (1/(m+2)) * np.cos(alpha) * np.sin(i * alpha)) # Combine jackson and cheby coeffs jch = ch * jch return ch, jch
[ "def", "compute_jackson_cheby_coeff", "(", "filter_bounds", ",", "delta_lambda", ",", "m", ")", ":", "# Parameters check", "if", "delta_lambda", "[", "0", "]", ">", "filter_bounds", "[", "0", "]", "or", "delta_lambda", "[", "1", "]", "<", "filter_bounds", "[",...
https://github.com/epfl-lts2/pygsp/blob/a3412ce7696c02c8a55439e89d0c9ab8ae863269/pygsp/filters/approximations.py#L166-L222
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/celery-4.2.1/celery/bin/celery.py
python
report.__init__
(self, *args, **kwargs)
Custom initialization for report command. We need this custom initialization to make sure that everything is loaded when running a report. There has been some issues when printing Django's settings because Django is not properly setup when running the report.
Custom initialization for report command.
[ "Custom", "initialization", "for", "report", "command", "." ]
def __init__(self, *args, **kwargs): """Custom initialization for report command. We need this custom initialization to make sure that everything is loaded when running a report. There has been some issues when printing Django's settings because Django is not properly setup when running the report. """ super(report, self).__init__(*args, **kwargs) self.app.loader.import_default_modules()
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", "report", ",", "self", ")", ".", "__init__", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "app", ".", "loader", ".", "import_defaul...
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/celery-4.2.1/celery/bin/celery.py#L358-L368
IJDykeman/wangTiles
7c1ee2095ebdf7f72bce07d94c6484915d5cae8b
experimental_code/tiles_3d/venv_mac/lib/python2.7/site-packages/pip/_vendor/pyparsing.py
python
ParseResults.asList
( self )
return [res.asList() if isinstance(res,ParseResults) else res for res in self.__toklist]
Returns the parse results as a nested list of matching tokens, all converted to strings. Example:: patt = OneOrMore(Word(alphas)) result = patt.parseString("sldkj lsdkj sldkj") # even though the result prints in string-like form, it is actually a pyparsing ParseResults print(type(result), result) # -> <class 'pyparsing.ParseResults'> ['sldkj', 'lsdkj', 'sldkj'] # Use asList() to create an actual list result_list = result.asList() print(type(result_list), result_list) # -> <class 'list'> ['sldkj', 'lsdkj', 'sldkj']
Returns the parse results as a nested list of matching tokens, all converted to strings.
[ "Returns", "the", "parse", "results", "as", "a", "nested", "list", "of", "matching", "tokens", "all", "converted", "to", "strings", "." ]
def asList( self ): """ Returns the parse results as a nested list of matching tokens, all converted to strings. Example:: patt = OneOrMore(Word(alphas)) result = patt.parseString("sldkj lsdkj sldkj") # even though the result prints in string-like form, it is actually a pyparsing ParseResults print(type(result), result) # -> <class 'pyparsing.ParseResults'> ['sldkj', 'lsdkj', 'sldkj'] # Use asList() to create an actual list result_list = result.asList() print(type(result_list), result_list) # -> <class 'list'> ['sldkj', 'lsdkj', 'sldkj'] """ return [res.asList() if isinstance(res,ParseResults) else res for res in self.__toklist]
[ "def", "asList", "(", "self", ")", ":", "return", "[", "res", ".", "asList", "(", ")", "if", "isinstance", "(", "res", ",", "ParseResults", ")", "else", "res", "for", "res", "in", "self", ".", "__toklist", "]" ]
https://github.com/IJDykeman/wangTiles/blob/7c1ee2095ebdf7f72bce07d94c6484915d5cae8b/experimental_code/tiles_3d/venv_mac/lib/python2.7/site-packages/pip/_vendor/pyparsing.py#L681-L695
pinterest/pymemcache
071191455363943e7d5919701465455e78bb64ae
pymemcache/client/base.py
python
Client.cache_memlimit
(self, memlimit)
return True
The memcached "cache_memlimit" command. Args: memlimit: int, the number of megabytes to set as the new cache memory limit. Returns: If no exception is raised, always returns True.
The memcached "cache_memlimit" command.
[ "The", "memcached", "cache_memlimit", "command", "." ]
def cache_memlimit(self, memlimit): """ The memcached "cache_memlimit" command. Args: memlimit: int, the number of megabytes to set as the new cache memory limit. Returns: If no exception is raised, always returns True. """ memlimit = self._check_integer(memlimit, "memlimit") self._fetch_cmd(b"cache_memlimit", [memlimit], False) return True
[ "def", "cache_memlimit", "(", "self", ",", "memlimit", ")", ":", "memlimit", "=", "self", ".", "_check_integer", "(", "memlimit", ",", "\"memlimit\"", ")", "self", ".", "_fetch_cmd", "(", "b\"cache_memlimit\"", ",", "[", "memlimit", "]", ",", "False", ")", ...
https://github.com/pinterest/pymemcache/blob/071191455363943e7d5919701465455e78bb64ae/pymemcache/client/base.py#L839-L852
librahfacebook/Detection
84504d086634950224716f4de0e4c8a684493c34
object_detection/utils/visualization_utils.py
python
save_image_array_as_png
(image, output_path)
Saves an image (represented as a numpy array) to PNG. Args: image: a numpy array with shape [height, width, 3]. output_path: path to which image should be written.
Saves an image (represented as a numpy array) to PNG.
[ "Saves", "an", "image", "(", "represented", "as", "a", "numpy", "array", ")", "to", "PNG", "." ]
def save_image_array_as_png(image, output_path): """Saves an image (represented as a numpy array) to PNG. Args: image: a numpy array with shape [height, width, 3]. output_path: path to which image should be written. """ image_pil = Image.fromarray(np.uint8(image)).convert('RGB') with tf.gfile.Open(output_path, 'w') as fid: image_pil.save(fid, 'PNG')
[ "def", "save_image_array_as_png", "(", "image", ",", "output_path", ")", ":", "image_pil", "=", "Image", ".", "fromarray", "(", "np", ".", "uint8", "(", "image", ")", ")", ".", "convert", "(", "'RGB'", ")", "with", "tf", ".", "gfile", ".", "Open", "(",...
https://github.com/librahfacebook/Detection/blob/84504d086634950224716f4de0e4c8a684493c34/object_detection/utils/visualization_utils.py#L71-L80
manolomartinez/greg
b781656bd1a749c9dce6988a37e0345d31bed267
greg/aux_functions.py
python
tag
(placeholders)
Tag the file at podpath with the information in podcast and entry
Tag the file at podpath with the information in podcast and entry
[ "Tag", "the", "file", "at", "podpath", "with", "the", "information", "in", "podcast", "and", "entry" ]
def tag(placeholders): """ Tag the file at podpath with the information in podcast and entry """ # We first recover the name of the file to be tagged... template = placeholders.feed.retrieve_config("file_to_tag", "{filename}") filename = substitute_placeholders(template, placeholders) podpath = os.path.join(placeholders.directory, filename) # ... and this is it # now we create a dictionary of tags and values tagdict = placeholders.feed.defaulttagdict # these are the defaults try: # We do as if there was a section with potential tag info feedoptions = placeholders.feed.config.options(placeholders.name) # this monstruous concatenation of classes... surely a bad idea. tags = [[option.replace("tag_", ""), placeholders.feed.config[ placeholders.name][option]] for option in feedoptions if "tag_" in option] # these are the tags to be filled if tags: for tag in tags: tagdict[tag[0]] = tag[1] except configparser.NoSectionError: pass for tag in tagdict: metadata = substitute_placeholders(tagdict[tag], placeholders) tagdict[tag] = metadata file_to_tag = eyed3.load(podpath) if file_to_tag.tag == None: file_to_tag.initTag() for mytag in tagdict: try: attribute = getattr(file_to_tag.tag, mytag) if isinstance(attribute, eyed3.id3.tag.DltAccessor): attribute.set(tagdict[mytag]) else: setattr(file_to_tag.tag, mytag, tagdict[mytag]) except AttributeError: setattr(file_to_tag.tag, mytag, tagdict[mytag]) file_to_tag.tag.save()
[ "def", "tag", "(", "placeholders", ")", ":", "# We first recover the name of the file to be tagged...", "template", "=", "placeholders", ".", "feed", ".", "retrieve_config", "(", "\"file_to_tag\"", ",", "\"{filename}\"", ")", "filename", "=", "substitute_placeholders", "(...
https://github.com/manolomartinez/greg/blob/b781656bd1a749c9dce6988a37e0345d31bed267/greg/aux_functions.py#L170-L208
ironport/shrapnel
9496a64c46271b0c5cef0feb8f2cdf33cb752bb6
coro/ssh/keys/openssh_authorized_keys.py
python
OpenSSH_Authorized_Keys.write
(self)
write() -> None Writes the keyfile to disk, safely overwriting the keyfile that already exists.
write() -> None Writes the keyfile to disk, safely overwriting the keyfile that already exists.
[ "write", "()", "-", ">", "None", "Writes", "the", "keyfile", "to", "disk", "safely", "overwriting", "the", "keyfile", "that", "already", "exists", "." ]
def write(self): """write() -> None Writes the keyfile to disk, safely overwriting the keyfile that already exists. """ # Avoid concurrent races here? tmp_filename = self.filename + '.tmp' fd = os.open(tmp_filename, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0644) write = lambda x, y=fd: os.write(y, x) map(write, map(self.keydict_to_string, self.keys)) os.close(fd) os.rename(tmp_filename, self.filename)
[ "def", "write", "(", "self", ")", ":", "# Avoid concurrent races here?", "tmp_filename", "=", "self", ".", "filename", "+", "'.tmp'", "fd", "=", "os", ".", "open", "(", "tmp_filename", ",", "os", ".", "O_WRONLY", "|", "os", ".", "O_CREAT", "|", "os", "."...
https://github.com/ironport/shrapnel/blob/9496a64c46271b0c5cef0feb8f2cdf33cb752bb6/coro/ssh/keys/openssh_authorized_keys.py#L208-L219
httpie/httpie
4c56d894ba9e2bb1c097a3a6067006843ac2944d
httpie/output/lexers/http.py
python
request_method
(lexer, match, ctx)
[]
def request_method(lexer, match, ctx): response_type = precise( lexer, RESPONSE_TYPES.get(match.group()), pygments.token.Name.Function ) yield match.start(), response_type, match.group()
[ "def", "request_method", "(", "lexer", ",", "match", ",", "ctx", ")", ":", "response_type", "=", "precise", "(", "lexer", ",", "RESPONSE_TYPES", ".", "get", "(", "match", ".", "group", "(", ")", ")", ",", "pygments", ".", "token", ".", "Name", ".", "...
https://github.com/httpie/httpie/blob/4c56d894ba9e2bb1c097a3a6067006843ac2944d/httpie/output/lexers/http.py#L45-L51
frappe/frappe
b64cab6867dfd860f10ccaf41a4ec04bc890b583
frappe/integrations/doctype/connected_app/connected_app.py
python
ConnectedApp.get_user_token
(self, user=None, success_uri=None)
return redirect
Return an existing user token or initiate a Web Application Flow.
Return an existing user token or initiate a Web Application Flow.
[ "Return", "an", "existing", "user", "token", "or", "initiate", "a", "Web", "Application", "Flow", "." ]
def get_user_token(self, user=None, success_uri=None): """Return an existing user token or initiate a Web Application Flow.""" user = user or frappe.session.user token_cache = self.get_token_cache(user) if token_cache: return token_cache redirect = self.initiate_web_application_flow(user, success_uri) frappe.local.response['type'] = 'redirect' frappe.local.response['location'] = redirect return redirect
[ "def", "get_user_token", "(", "self", ",", "user", "=", "None", ",", "success_uri", "=", "None", ")", ":", "user", "=", "user", "or", "frappe", ".", "session", ".", "user", "token_cache", "=", "self", ".", "get_token_cache", "(", "user", ")", "if", "to...
https://github.com/frappe/frappe/blob/b64cab6867dfd860f10ccaf41a4ec04bc890b583/frappe/integrations/doctype/connected_app/connected_app.py#L75-L86
zhaoolee/StarsAndClown
b2d4039cad2f9232b691e5976f787b49a0a2c113
node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/mac_tool.py
python
MacTool._Relink
(self, dest, link)
Creates a symlink to |dest| named |link|. If |link| already exists, it is overwritten.
Creates a symlink to |dest| named |link|. If |link| already exists, it is overwritten.
[ "Creates", "a", "symlink", "to", "|dest|", "named", "|link|", ".", "If", "|link|", "already", "exists", "it", "is", "overwritten", "." ]
def _Relink(self, dest, link): """Creates a symlink to |dest| named |link|. If |link| already exists, it is overwritten.""" if os.path.lexists(link): os.remove(link) os.symlink(dest, link)
[ "def", "_Relink", "(", "self", ",", "dest", ",", "link", ")", ":", "if", "os", ".", "path", ".", "lexists", "(", "link", ")", ":", "os", ".", "remove", "(", "link", ")", "os", ".", "symlink", "(", "dest", ",", "link", ")" ]
https://github.com/zhaoolee/StarsAndClown/blob/b2d4039cad2f9232b691e5976f787b49a0a2c113/node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/mac_tool.py#L285-L290
EmbarkStudios/blender-tools
68e5c367bc040b6f327ad9507aab4c7b5b0a559b
utils/ui.py
python
get_icon
(name)
Get an internal Blender icon ID from an icon name.
Get an internal Blender icon ID from an icon name.
[ "Get", "an", "internal", "Blender", "icon", "ID", "from", "an", "icon", "name", "." ]
def get_icon(name): """Get an internal Blender icon ID from an icon name.""" try: return __icon_manager__.icons[name].icon_id except KeyError: print(f"Error: Failed to find icon named '{name}'!") return None
[ "def", "get_icon", "(", "name", ")", ":", "try", ":", "return", "__icon_manager__", ".", "icons", "[", "name", "]", ".", "icon_id", "except", "KeyError", ":", "print", "(", "f\"Error: Failed to find icon named '{name}'!\"", ")", "return", "None" ]
https://github.com/EmbarkStudios/blender-tools/blob/68e5c367bc040b6f327ad9507aab4c7b5b0a559b/utils/ui.py#L35-L41
vshymanskyy/blynk-library-python
fee389f17e84b17e6655c571100f49688b453307
BlynkTimer.py
python
BlynkTimer.set_timeout
(self, value, func)
return timer.id
Runs function once after timeout
Runs function once after timeout
[ "Runs", "function", "once", "after", "timeout" ]
def set_timeout(self, value, func): '''Runs function once after timeout''' timer = self._add(func, post_run=self._delete) timer.set_interval(value) return timer.id
[ "def", "set_timeout", "(", "self", ",", "value", ",", "func", ")", ":", "timer", "=", "self", ".", "_add", "(", "func", ",", "post_run", "=", "self", ".", "_delete", ")", "timer", ".", "set_interval", "(", "value", ")", "return", "timer", ".", "id" ]
https://github.com/vshymanskyy/blynk-library-python/blob/fee389f17e84b17e6655c571100f49688b453307/BlynkTimer.py#L67-L71
csparpa/pyowm
0474b61cc67fa3c95f9e572b96d3248031828fce
pyowm/agroapi10/agro_manager.py
python
AgroManager.soil_data
(self, polygon)
return Soil.from_dict(the_dict)
Retrieves the latest soil data on the specified polygon :param polygon: the reference polygon you want soil data for :type polygon: `pyowm.agro10.polygon.Polygon` instance :returns: a `pyowm.agro10.soil.Soil` instance
Retrieves the latest soil data on the specified polygon
[ "Retrieves", "the", "latest", "soil", "data", "on", "the", "specified", "polygon" ]
def soil_data(self, polygon): """ Retrieves the latest soil data on the specified polygon :param polygon: the reference polygon you want soil data for :type polygon: `pyowm.agro10.polygon.Polygon` instance :returns: a `pyowm.agro10.soil.Soil` instance """ assert polygon is not None assert isinstance(polygon, Polygon) polyd = polygon.id status, data = self.http_client.get_json( SOIL_URI, params={'appid': self.API_key, 'polyid': polyd}, headers={'Content-Type': 'application/json'}) the_dict = { 'reference_time': data['dt'], 'surface_temp': data['t0'], 'ten_cm_temp': data['t10'], 'moisture': data['moisture'], 'polygon_id': polyd, } return Soil.from_dict(the_dict)
[ "def", "soil_data", "(", "self", ",", "polygon", ")", ":", "assert", "polygon", "is", "not", "None", "assert", "isinstance", "(", "polygon", ",", "Polygon", ")", "polyd", "=", "polygon", ".", "id", "status", ",", "data", "=", "self", ".", "http_client", ...
https://github.com/csparpa/pyowm/blob/0474b61cc67fa3c95f9e572b96d3248031828fce/pyowm/agroapi10/agro_manager.py#L132-L157
elyra-ai/elyra
5bb2009a7c475bda63f1cc2767eb8c4dfba9a239
elyra/pipeline/validation.py
python
ValidationResponse.response
(self)
return self._response
:return: The dict of validation errors and warnings found in the pipeline
:return: The dict of validation errors and warnings found in the pipeline
[ ":", "return", ":", "The", "dict", "of", "validation", "errors", "and", "warnings", "found", "in", "the", "pipeline" ]
def response(self) -> Dict: """ :return: The dict of validation errors and warnings found in the pipeline """ return self._response
[ "def", "response", "(", "self", ")", "->", "Dict", ":", "return", "self", ".", "_response" ]
https://github.com/elyra-ai/elyra/blob/5bb2009a7c475bda63f1cc2767eb8c4dfba9a239/elyra/pipeline/validation.py#L59-L63
fox-it/dissect.cstruct
c28f864acbcf943fc1cb8a03ac792bf32d6b1581
dissect/cstruct/types/instance.py
python
Instance.dumps
(self)
return s.getvalue()
Dump this structure to a byte string. Returns: The raw bytes of this structure.
Dump this structure to a byte string.
[ "Dump", "this", "structure", "to", "a", "byte", "string", "." ]
def dumps(self): """Dump this structure to a byte string. Returns: The raw bytes of this structure. """ s = BytesIO() self.write(s) return s.getvalue()
[ "def", "dumps", "(", "self", ")", ":", "s", "=", "BytesIO", "(", ")", "self", ".", "write", "(", "s", ")", "return", "s", ".", "getvalue", "(", ")" ]
https://github.com/fox-it/dissect.cstruct/blob/c28f864acbcf943fc1cb8a03ac792bf32d6b1581/dissect/cstruct/types/instance.py#L60-L68
Arelle/Arelle
20f3d8a8afd41668e1520799acd333349ce0ba17
arelle/webserver/bottle-no2to3.py
python
SimpleTemplate.re_pytokens
(cls)
return re.compile(r''' (''(?!')|""(?!")|'{6}|"{6} # Empty strings (all 4 types) |'(?:[^\\']|\\.)+?' # Single quotes (') |"(?:[^\\"]|\\.)+?" # Double quotes (") |'{3}(?:[^\\]|\\.|\n)+?'{3} # Triple-quoted strings (') |"{3}(?:[^\\]|\\.|\n)+?"{3} # Triple-quoted strings (") |\#.* # Comments )''', re.VERBOSE)
This matches comments and all kinds of quoted strings but does NOT match comments (#...) within quoted strings. (trust me)
This matches comments and all kinds of quoted strings but does NOT match comments (#...) within quoted strings. (trust me)
[ "This", "matches", "comments", "and", "all", "kinds", "of", "quoted", "strings", "but", "does", "NOT", "match", "comments", "(", "#", "...", ")", "within", "quoted", "strings", ".", "(", "trust", "me", ")" ]
def re_pytokens(cls): ''' This matches comments and all kinds of quoted strings but does NOT match comments (#...) within quoted strings. (trust me) ''' return re.compile(r''' (''(?!')|""(?!")|'{6}|"{6} # Empty strings (all 4 types) |'(?:[^\\']|\\.)+?' # Single quotes (') |"(?:[^\\"]|\\.)+?" # Double quotes (") |'{3}(?:[^\\]|\\.|\n)+?'{3} # Triple-quoted strings (') |"{3}(?:[^\\]|\\.|\n)+?"{3} # Triple-quoted strings (") |\#.* # Comments )''', re.VERBOSE)
[ "def", "re_pytokens", "(", "cls", ")", ":", "return", "re", ".", "compile", "(", "r'''\n (''(?!')|\"\"(?!\")|'{6}|\"{6} # Empty strings (all 4 types)\n |'(?:[^\\\\']|\\\\.)+?' # Single quotes (')\n |\"(?:[^\\\\\"]|\\\\.)+?\" # Double quot...
https://github.com/Arelle/Arelle/blob/20f3d8a8afd41668e1520799acd333349ce0ba17/arelle/webserver/bottle-no2to3.py#L2629-L2639
Azure/azure-devops-cli-extension
11334cd55806bef0b99c3bee5a438eed71e44037
azure-devops/azext_devops/devops_sdk/v5_1/dashboard/dashboard_client.py
python
DashboardClient.get_dashboards
(self, team_context)
return self._deserialize('DashboardGroup', response)
GetDashboards. [Preview API] Get a list of dashboards. :param :class:`<TeamContext> <azure.devops.v5_1.dashboard.models.TeamContext>` team_context: The team context for the operation :rtype: :class:`<DashboardGroup> <azure.devops.v5_1.dashboard.models.DashboardGroup>`
GetDashboards. [Preview API] Get a list of dashboards. :param :class:`<TeamContext> <azure.devops.v5_1.dashboard.models.TeamContext>` team_context: The team context for the operation :rtype: :class:`<DashboardGroup> <azure.devops.v5_1.dashboard.models.DashboardGroup>`
[ "GetDashboards", ".", "[", "Preview", "API", "]", "Get", "a", "list", "of", "dashboards", ".", ":", "param", ":", "class", ":", "<TeamContext", ">", "<azure", ".", "devops", ".", "v5_1", ".", "dashboard", ".", "models", ".", "TeamContext", ">", "team_con...
def get_dashboards(self, team_context): """GetDashboards. [Preview API] Get a list of dashboards. :param :class:`<TeamContext> <azure.devops.v5_1.dashboard.models.TeamContext>` team_context: The team context for the operation :rtype: :class:`<DashboardGroup> <azure.devops.v5_1.dashboard.models.DashboardGroup>` """ project = None team = None if team_context is not None: if team_context.project_id: project = team_context.project_id else: project = team_context.project if team_context.team_id: team = team_context.team_id else: team = team_context.team route_values = {} if project is not None: route_values['project'] = self._serialize.url('project', project, 'string') if team is not None: route_values['team'] = self._serialize.url('team', team, 'string') response = self._send(http_method='GET', location_id='454b3e51-2e6e-48d4-ad81-978154089351', version='5.1-preview.2', route_values=route_values) return self._deserialize('DashboardGroup', response)
[ "def", "get_dashboards", "(", "self", ",", "team_context", ")", ":", "project", "=", "None", "team", "=", "None", "if", "team_context", "is", "not", "None", ":", "if", "team_context", ".", "project_id", ":", "project", "=", "team_context", ".", "project_id",...
https://github.com/Azure/azure-devops-cli-extension/blob/11334cd55806bef0b99c3bee5a438eed71e44037/azure-devops/azext_devops/devops_sdk/v5_1/dashboard/dashboard_client.py#L122-L149
allegro/ralph
1e4a9e1800d5f664abaef2624b8bf7512df279ce
src/ralph/networks/forms.py
python
SimpleNetworkForm._validate_ip_uniquness
(self, address)
Validate if there is any IP with passed address (exluding current ip).
Validate if there is any IP with passed address (exluding current ip).
[ "Validate", "if", "there", "is", "any", "IP", "with", "passed", "address", "(", "exluding", "current", "ip", ")", "." ]
def _validate_ip_uniquness(self, address): """ Validate if there is any IP with passed address (exluding current ip). """ qs = IPAddress.objects.filter(address=address) if self.ip: qs = qs.exclude(pk=self.ip.pk) if qs.exists(): raise ValidationError( _('Address %(ip)s already exist.'), params={'ip': address}, )
[ "def", "_validate_ip_uniquness", "(", "self", ",", "address", ")", ":", "qs", "=", "IPAddress", ".", "objects", ".", "filter", "(", "address", "=", "address", ")", "if", "self", ".", "ip", ":", "qs", "=", "qs", ".", "exclude", "(", "pk", "=", "self",...
https://github.com/allegro/ralph/blob/1e4a9e1800d5f664abaef2624b8bf7512df279ce/src/ralph/networks/forms.py#L112-L123
modflowpy/flopy
eecd1ad193c5972093c9712e5c4b7a83284f0688
flopy/mf6/mfbase.py
python
MFFileMgmt.get_sim_path
(self, last_loaded_path=False)
Get the simulation path.
Get the simulation path.
[ "Get", "the", "simulation", "path", "." ]
def get_sim_path(self, last_loaded_path=False): """Get the simulation path.""" if last_loaded_path: return self._last_loaded_sim_path else: return self._sim_path
[ "def", "get_sim_path", "(", "self", ",", "last_loaded_path", "=", "False", ")", ":", "if", "last_loaded_path", ":", "return", "self", ".", "_last_loaded_sim_path", "else", ":", "return", "self", ".", "_sim_path" ]
https://github.com/modflowpy/flopy/blob/eecd1ad193c5972093c9712e5c4b7a83284f0688/flopy/mf6/mfbase.py#L372-L377
jgagneastro/coffeegrindsize
22661ebd21831dba4cf32bfc6ba59fe3d49f879c
App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/PIL/ImageMorph.py
python
LutBuilder._string_permute
(self, pattern, permutation)
return ''.join(pattern[p] for p in permutation)
string_permute takes a pattern and a permutation and returns the string permuted according to the permutation list.
string_permute takes a pattern and a permutation and returns the string permuted according to the permutation list.
[ "string_permute", "takes", "a", "pattern", "and", "a", "permutation", "and", "returns", "the", "string", "permuted", "according", "to", "the", "permutation", "list", "." ]
def _string_permute(self, pattern, permutation): """string_permute takes a pattern and a permutation and returns the string permuted according to the permutation list. """ assert(len(permutation) == 9) return ''.join(pattern[p] for p in permutation)
[ "def", "_string_permute", "(", "self", ",", "pattern", ",", "permutation", ")", ":", "assert", "(", "len", "(", "permutation", ")", "==", "9", ")", "return", "''", ".", "join", "(", "pattern", "[", "p", "]", "for", "p", "in", "permutation", ")" ]
https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/PIL/ImageMorph.py#L87-L92
minimaxir/automl-gs
62773ce361c72e890829b476ba4aa5490b000de4
automl_gs/utils_automl.py
python
get_input_types
(df, col_types, target_field)
return field_types
Get the input types for each field in the DataFrame that corresponds to an input type to be fed into the model. Valid values are ['text', 'categorical', 'numeric', 'datetime', 'ignore'] # Arguments: df: A pandas DataFrame. col_types: A dict of explicitly defined {field_name: type} mappings. target_field: string indicating the target field # Returns: A dict of {field_name: type} mappings.
Get the input types for each field in the DataFrame that corresponds to an input type to be fed into the model.
[ "Get", "the", "input", "types", "for", "each", "field", "in", "the", "DataFrame", "that", "corresponds", "to", "an", "input", "type", "to", "be", "fed", "into", "the", "model", "." ]
def get_input_types(df, col_types, target_field): """Get the input types for each field in the DataFrame that corresponds to an input type to be fed into the model. Valid values are ['text', 'categorical', 'numeric', 'datetime', 'ignore'] # Arguments: df: A pandas DataFrame. col_types: A dict of explicitly defined {field_name: type} mappings. target_field: string indicating the target field # Returns: A dict of {field_name: type} mappings. """ fields = df.columns nrows = df.shape[0] avg_spaces = -1 field_types = OrderedDict() for field in fields: if field in col_types: field_types[field] = col_types[field] continue field_type = df[field].dtype num_unique_values = df[field].nunique() if field_type == 'object': avg_spaces = df[field].str.count(' ').mean() # Automatically ignore `id`-related fields if field.lower() in ['id', 'uuid', 'guid', 'pk', 'name']: field_types[field] = 'ignore' # Foreign key fields are always categorical # else if "_id" in field or "_uuid" in field: # field_types[field] = 'categorical' # Datetime is a straightforward data type. elif field_type == 'datetime64[ns]': field_types[field] = 'datetime' # Assume a float is always numeric. elif field_type == 'float64': field_types[field] = 'numeric' # If it's an object where the contents has # many spaces on average, it's text elif field_type == 'object' and avg_spaces >= 2.0: field_types[field] = 'text' # If the field has very few distinct values, it's categorical elif num_unique_values <= 10: field_types[field] = 'categorical' # If the field has many distinct integers, assume numeric. elif field_type == 'int64': field_types[field] = 'numeric' # If the field has many distinct nonintegers, it's not helpful. elif num_unique_values > 0.9 * nrows: field_types[field] = 'ignore' # The rest (e.g. bool) is categorical else: field_types[field] = 'categorical' # Print to console for user-level debugging print("Modeling with field specifications:") print("\n".join(["{}: {}".format(k, v) for k, v in field_types.items() if k != target_field])) field_types = {k: v for k, v in field_types.items() if v != 'ignore'} return field_types
[ "def", "get_input_types", "(", "df", ",", "col_types", ",", "target_field", ")", ":", "fields", "=", "df", ".", "columns", "nrows", "=", "df", ".", "shape", "[", "0", "]", "avg_spaces", "=", "-", "1", "field_types", "=", "OrderedDict", "(", ")", "for",...
https://github.com/minimaxir/automl-gs/blob/62773ce361c72e890829b476ba4aa5490b000de4/automl_gs/utils_automl.py#L16-L89
HonglinChu/SiamTrackers
8471660b14f970578a43f077b28207d44a27e867
SiamMask/SiamMask-pysot/toolkit/datasets/lasot.py
python
LaSOTVideo.load_tracker
(self, path, tracker_names=None, store=True)
Args: path(str): path to result tracker_name(list): name of tracker
Args: path(str): path to result tracker_name(list): name of tracker
[ "Args", ":", "path", "(", "str", ")", ":", "path", "to", "result", "tracker_name", "(", "list", ")", ":", "name", "of", "tracker" ]
def load_tracker(self, path, tracker_names=None, store=True): """ Args: path(str): path to result tracker_name(list): name of tracker """ if not tracker_names: tracker_names = [x.split('/')[-1] for x in glob(path) if os.path.isdir(x)] if isinstance(tracker_names, str): tracker_names = [tracker_names] for name in tracker_names: traj_file = os.path.join(path, name, self.name+'.txt') if os.path.exists(traj_file): with open(traj_file, 'r') as f : pred_traj = [list(map(float, x.strip().split(','))) for x in f.readlines()] else: print("File not exists: ", traj_file) if self.name == 'monkey-17': pred_traj = pred_traj[:len(self.gt_traj)] if store: self.pred_trajs[name] = pred_traj else: return pred_traj self.tracker_names = list(self.pred_trajs.keys())
[ "def", "load_tracker", "(", "self", ",", "path", ",", "tracker_names", "=", "None", ",", "store", "=", "True", ")", ":", "if", "not", "tracker_names", ":", "tracker_names", "=", "[", "x", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "for", "x...
https://github.com/HonglinChu/SiamTrackers/blob/8471660b14f970578a43f077b28207d44a27e867/SiamMask/SiamMask-pysot/toolkit/datasets/lasot.py#L28-L53
zsdonghao/text-to-image
c1fbfa4349f5aa1c74c9fe17743cc0cff34f1aab
tensorlayer/layers.py
python
Conv2d
(net, n_filter=32, filter_size=(3, 3), strides=(1, 1), act = None, padding='SAME', W_init = tf.truncated_normal_initializer(stddev=0.02), b_init = tf.constant_initializer(value=0.0), W_init_args = {}, b_init_args = {}, name ='conv2d',)
return net
Wrapper for :class:`Conv2dLayer`, if you don't understand how to use :class:`Conv2dLayer`, this function may be easier. Parameters ---------- net : TensorLayer layer. n_filter : number of filter. filter_size : tuple (height, width) for filter size. strides : tuple (height, width) for strides. act : None or activation function. others : see :class:`Conv2dLayer`. Examples -------- >>> w_init = tf.truncated_normal_initializer(stddev=0.01) >>> b_init = tf.constant_initializer(value=0.0) >>> inputs = InputLayer(x, name='inputs') >>> conv1 = Conv2d(inputs, 64, (3, 3), act=tf.nn.relu, padding='SAME', W_init=w_init, b_init=b_init, name='conv1_1') >>> conv1 = Conv2d(conv1, 64, (3, 3), act=tf.nn.relu, padding='SAME', W_init=w_init, b_init=b_init, name='conv1_2') >>> pool1 = MaxPool2d(conv1, (2, 2), padding='SAME', name='pool1') >>> conv2 = Conv2d(pool1, 128, (3, 3), act=tf.nn.relu, padding='SAME', W_init=w_init, b_init=b_init, name='conv2_1') >>> conv2 = Conv2d(conv2, 128, (3, 3), act=tf.nn.relu, padding='SAME', W_init=w_init, b_init=b_init, name='conv2_2') >>> pool2 = MaxPool2d(conv2, (2, 2), padding='SAME', name='pool2')
Wrapper for :class:`Conv2dLayer`, if you don't understand how to use :class:`Conv2dLayer`, this function may be easier.
[ "Wrapper", "for", ":", "class", ":", "Conv2dLayer", "if", "you", "don", "t", "understand", "how", "to", "use", ":", "class", ":", "Conv2dLayer", "this", "function", "may", "be", "easier", "." ]
def Conv2d(net, n_filter=32, filter_size=(3, 3), strides=(1, 1), act = None, padding='SAME', W_init = tf.truncated_normal_initializer(stddev=0.02), b_init = tf.constant_initializer(value=0.0), W_init_args = {}, b_init_args = {}, name ='conv2d',): """Wrapper for :class:`Conv2dLayer`, if you don't understand how to use :class:`Conv2dLayer`, this function may be easier. Parameters ---------- net : TensorLayer layer. n_filter : number of filter. filter_size : tuple (height, width) for filter size. strides : tuple (height, width) for strides. act : None or activation function. others : see :class:`Conv2dLayer`. Examples -------- >>> w_init = tf.truncated_normal_initializer(stddev=0.01) >>> b_init = tf.constant_initializer(value=0.0) >>> inputs = InputLayer(x, name='inputs') >>> conv1 = Conv2d(inputs, 64, (3, 3), act=tf.nn.relu, padding='SAME', W_init=w_init, b_init=b_init, name='conv1_1') >>> conv1 = Conv2d(conv1, 64, (3, 3), act=tf.nn.relu, padding='SAME', W_init=w_init, b_init=b_init, name='conv1_2') >>> pool1 = MaxPool2d(conv1, (2, 2), padding='SAME', name='pool1') >>> conv2 = Conv2d(pool1, 128, (3, 3), act=tf.nn.relu, padding='SAME', W_init=w_init, b_init=b_init, name='conv2_1') >>> conv2 = Conv2d(conv2, 128, (3, 3), act=tf.nn.relu, padding='SAME', W_init=w_init, b_init=b_init, name='conv2_2') >>> pool2 = MaxPool2d(conv2, (2, 2), padding='SAME', name='pool2') """ assert len(strides) == 2, "len(strides) should be 2, Conv2d and Conv2dLayer are different." if act is None: act = tf.identity net = Conv2dLayer(net, act = act, shape = [filter_size[0], filter_size[1], int(net.outputs.get_shape()[-1]), n_filter], # 32 features for each 5x5 patch strides = [1, strides[0], strides[1], 1], padding = padding, W_init = W_init, W_init_args = W_init_args, b_init = b_init, b_init_args = b_init_args, name = name) return net
[ "def", "Conv2d", "(", "net", ",", "n_filter", "=", "32", ",", "filter_size", "=", "(", "3", ",", "3", ")", ",", "strides", "=", "(", "1", ",", "1", ")", ",", "act", "=", "None", ",", "padding", "=", "'SAME'", ",", "W_init", "=", "tf", ".", "t...
https://github.com/zsdonghao/text-to-image/blob/c1fbfa4349f5aa1c74c9fe17743cc0cff34f1aab/tensorlayer/layers.py#L1830-L1869
WeblateOrg/weblate
8126f3dda9d24f2846b755955132a8b8410866c8
weblate/trans/validators.py
python
validate_check_flags
(val)
Validate check influencing flags.
Validate check influencing flags.
[ "Validate", "check", "influencing", "flags", "." ]
def validate_check_flags(val): """Validate check influencing flags.""" try: flags = Flags(val) except (ParseException, re.error) as error: raise ValidationError(_("Failed to parse flags: %s") % error) flags.validate()
[ "def", "validate_check_flags", "(", "val", ")", ":", "try", ":", "flags", "=", "Flags", "(", "val", ")", "except", "(", "ParseException", ",", "re", ".", "error", ")", "as", "error", ":", "raise", "ValidationError", "(", "_", "(", "\"Failed to parse flags:...
https://github.com/WeblateOrg/weblate/blob/8126f3dda9d24f2846b755955132a8b8410866c8/weblate/trans/validators.py#L47-L53
dmlc/dgl
8d14a739bc9e446d6c92ef83eafe5782398118de
examples/pytorch/ogb/line/model.py
python
async_update
(num_threads, model, queue)
Asynchronous embedding update for entity embeddings.
Asynchronous embedding update for entity embeddings.
[ "Asynchronous", "embedding", "update", "for", "entity", "embeddings", "." ]
def async_update(num_threads, model, queue): """ Asynchronous embedding update for entity embeddings. """ torch.set_num_threads(num_threads) print("async start") while True: (grad_u, grad_v, grad_v_neg, nodes, neg_nodes, first_flag) = queue.get() if grad_u is None: return with torch.no_grad(): if first_flag: model.fst_u_embeddings.weight.data.index_add_(0, nodes[:, 0], grad_u) model.fst_u_embeddings.weight.data.index_add_(0, nodes[:, 1], grad_v) if neg_nodes is not None: model.fst_u_embeddings.weight.data.index_add_(0, neg_nodes, grad_v_neg) else: model.snd_u_embeddings.weight.data.index_add_(0, nodes[:, 0], grad_u) model.snd_v_embeddings.weight.data.index_add_(0, nodes[:, 1], grad_v) if neg_nodes is not None: model.snd_v_embeddings.weight.data.index_add_(0, neg_nodes, grad_v_neg)
[ "def", "async_update", "(", "num_threads", ",", "model", ",", "queue", ")", ":", "torch", ".", "set_num_threads", "(", "num_threads", ")", "print", "(", "\"async start\"", ")", "while", "True", ":", "(", "grad_u", ",", "grad_v", ",", "grad_v_neg", ",", "no...
https://github.com/dmlc/dgl/blob/8d14a739bc9e446d6c92ef83eafe5782398118de/examples/pytorch/ogb/line/model.py#L45-L64
huawei-noah/vega
d9f13deede7f2b584e4b1d32ffdb833856129989
vega/security/load_pickle.py
python
restricted_loads
(file, fix_imports=True, encoding="ASCII", errors="strict", security=False)
return RestrictedUnpickler(file, fix_imports=fix_imports, encoding=encoding, errors=errors, security=security).load()
Load obj.
Load obj.
[ "Load", "obj", "." ]
def restricted_loads(file, fix_imports=True, encoding="ASCII", errors="strict", security=False): """Load obj.""" return RestrictedUnpickler(file, fix_imports=fix_imports, encoding=encoding, errors=errors, security=security).load()
[ "def", "restricted_loads", "(", "file", ",", "fix_imports", "=", "True", ",", "encoding", "=", "\"ASCII\"", ",", "errors", "=", "\"strict\"", ",", "security", "=", "False", ")", ":", "return", "RestrictedUnpickler", "(", "file", ",", "fix_imports", "=", "fix...
https://github.com/huawei-noah/vega/blob/d9f13deede7f2b584e4b1d32ffdb833856129989/vega/security/load_pickle.py#L54-L57
KhronosGroup/OpenXR-SDK-Source
76756e2e7849b15466d29bee7d80cada92865550
specification/scripts/spec_tools/consistency_tools.py
python
XMLChecker.check_command
(self, name, info)
Check a command's XML data for consistency. Called from check. May extend.
Check a command's XML data for consistency.
[ "Check", "a", "command", "s", "XML", "data", "for", "consistency", "." ]
def check_command(self, name, info): """Check a command's XML data for consistency. Called from check. May extend.""" elem = info.elem self.check_params(elem.findall('param')) # Some minimal return code checking errorcodes = elem.get("errorcodes") if errorcodes: errorcodes = errorcodes.split(",") else: errorcodes = [] successcodes = elem.get("successcodes") if successcodes: successcodes = successcodes.split(",") else: successcodes = [] if not successcodes and not errorcodes: # Early out if no return codes. return # Create a set for each group of codes, and check that # they aren't duplicated within or between groups. errorcodes_set = set(errorcodes) if len(errorcodes) != len(errorcodes_set): self.record_error("Contains a duplicate in errorcodes") successcodes_set = set(successcodes) if len(successcodes) != len(successcodes_set): self.record_error("Contains a duplicate in successcodes") if not successcodes_set.isdisjoint(errorcodes_set): self.record_error("Has errorcodes and successcodes that overlap") self.check_command_return_codes_basic( name, info, successcodes_set, errorcodes_set) # Continue to further return code checking if not "complicated" if not self.should_skip_checking_codes(name): codes_set = successcodes_set.union(errorcodes_set) self.check_command_return_codes( name, info, successcodes_set, errorcodes_set, codes_set)
[ "def", "check_command", "(", "self", ",", "name", ",", "info", ")", ":", "elem", "=", "info", ".", "elem", "self", ".", "check_params", "(", "elem", ".", "findall", "(", "'param'", ")", ")", "# Some minimal return code checking", "errorcodes", "=", "elem", ...
https://github.com/KhronosGroup/OpenXR-SDK-Source/blob/76756e2e7849b15466d29bee7d80cada92865550/specification/scripts/spec_tools/consistency_tools.py#L375-L422
LabPy/lantz
3e878e3f765a4295b0089d04e241d4beb7b8a65b
lantz/drivers/andor/ccd.py
python
CCD.EM_gain_range
(self)
return (mini.value, maxi.value)
Returns the minimum and maximum values of the current selected EM Gain mode and temperature of the sensor.
Returns the minimum and maximum values of the current selected EM Gain mode and temperature of the sensor.
[ "Returns", "the", "minimum", "and", "maximum", "values", "of", "the", "current", "selected", "EM", "Gain", "mode", "and", "temperature", "of", "the", "sensor", "." ]
def EM_gain_range(self): """Returns the minimum and maximum values of the current selected EM Gain mode and temperature of the sensor. """ mini, maxi = ct.c_int(), ct.c_int() self.lib.GetEMGainRange(ct.pointer(mini), ct.pointer(maxi)) return (mini.value, maxi.value)
[ "def", "EM_gain_range", "(", "self", ")", ":", "mini", ",", "maxi", "=", "ct", ".", "c_int", "(", ")", ",", "ct", ".", "c_int", "(", ")", "self", ".", "lib", ".", "GetEMGainRange", "(", "ct", ".", "pointer", "(", "mini", ")", ",", "ct", ".", "p...
https://github.com/LabPy/lantz/blob/3e878e3f765a4295b0089d04e241d4beb7b8a65b/lantz/drivers/andor/ccd.py#L1399-L1406
pyansys/pymapdl
c07291fc062b359abf0e92b95a92d753a95ef3d7
ansys/mapdl/core/_commands/solution/analysis_options.py
python
AnalysisOptions.thopt
( self, refopt="", reformtol="", ntabpoints="", tempmin="", tempmax="", algo="", **kwargs, )
return self.run(command, **kwargs)
Specifies nonlinear transient thermal solution options. APDL Command: THOPT Parameters ---------- refopt Matrix reform option. FULL - Use the full Newton-Raphson solution option (default). All subsequent input values are ignored. QUASI - Use a selective reform solution option based on REFORMTOL. reformtol Property change tolerance for Matrix Reformation (.05 default). The thermal matrices are reformed if the maximum material property change in an element (from the previous reform time) is greater than the reform tolerance. Valid only when Refopt = QUASI. ntabpoints Number of points in Fast Material Table (64 default). Valid only when Refopt = QUASI. tempmin Minimum temperature for Fast Material Table. Defaults to the minimum temperature defined by the MPTEMP command for any material property defined. Valid only when Refopt = QUASI. tempmax Maximum temperature for Fast Material Table. Defaults to the maximum temperature defined by the MPTEMP command for any material property defined. Valid only when Refopt = QUASI. -- Reserved field. algo Specifies which solution algorithm to apply: 0 - Multipass (default). 1 - Iterative. Notes ----- The QUASI matrix reform option is supported by the ICCG, JCG, and sparse solvers only (EQSLV). For Refopt = QUASI: Results from a restart may be different than results from a single run because the stiffness matrices are always recreated in a restart run, but may or may not be in a single run (depending on the behavior resulting from the REFORMTOL setting). Additionally, results may differ between two single runs as well, if the matrices are reformed as a result of the REFORMTOL setting. Midside node temperatures are not calculated if 20-node thermal solid elements (SOLID90 or SOLID279) are used. For more information, see Solution Algorithms Used in Transient Thermal Analysis in the Thermal Analysis Guide.
Specifies nonlinear transient thermal solution options.
[ "Specifies", "nonlinear", "transient", "thermal", "solution", "options", "." ]
def thopt( self, refopt="", reformtol="", ntabpoints="", tempmin="", tempmax="", algo="", **kwargs, ): """Specifies nonlinear transient thermal solution options. APDL Command: THOPT Parameters ---------- refopt Matrix reform option. FULL - Use the full Newton-Raphson solution option (default). All subsequent input values are ignored. QUASI - Use a selective reform solution option based on REFORMTOL. reformtol Property change tolerance for Matrix Reformation (.05 default). The thermal matrices are reformed if the maximum material property change in an element (from the previous reform time) is greater than the reform tolerance. Valid only when Refopt = QUASI. ntabpoints Number of points in Fast Material Table (64 default). Valid only when Refopt = QUASI. tempmin Minimum temperature for Fast Material Table. Defaults to the minimum temperature defined by the MPTEMP command for any material property defined. Valid only when Refopt = QUASI. tempmax Maximum temperature for Fast Material Table. Defaults to the maximum temperature defined by the MPTEMP command for any material property defined. Valid only when Refopt = QUASI. -- Reserved field. algo Specifies which solution algorithm to apply: 0 - Multipass (default). 1 - Iterative. Notes ----- The QUASI matrix reform option is supported by the ICCG, JCG, and sparse solvers only (EQSLV). For Refopt = QUASI: Results from a restart may be different than results from a single run because the stiffness matrices are always recreated in a restart run, but may or may not be in a single run (depending on the behavior resulting from the REFORMTOL setting). Additionally, results may differ between two single runs as well, if the matrices are reformed as a result of the REFORMTOL setting. Midside node temperatures are not calculated if 20-node thermal solid elements (SOLID90 or SOLID279) are used. For more information, see Solution Algorithms Used in Transient Thermal Analysis in the Thermal Analysis Guide. """ command = f"THOPT,{refopt},{reformtol},{ntabpoints},{tempmin},{tempmax},{algo}" return self.run(command, **kwargs)
[ "def", "thopt", "(", "self", ",", "refopt", "=", "\"\"", ",", "reformtol", "=", "\"\"", ",", "ntabpoints", "=", "\"\"", ",", "tempmin", "=", "\"\"", ",", "tempmax", "=", "\"\"", ",", "algo", "=", "\"\"", ",", "*", "*", "kwargs", ",", ")", ":", "c...
https://github.com/pyansys/pymapdl/blob/c07291fc062b359abf0e92b95a92d753a95ef3d7/ansys/mapdl/core/_commands/solution/analysis_options.py#L3475-L3550
dmlc/dgl
8d14a739bc9e446d6c92ef83eafe5782398118de
python/dgl/nn/pytorch/conv/egatconv.py
python
EGATConv.reset_parameters
(self)
Reinitialize learnable parameters.
Reinitialize learnable parameters.
[ "Reinitialize", "learnable", "parameters", "." ]
def reset_parameters(self): """ Reinitialize learnable parameters. """ gain = init.calculate_gain('relu') init.xavier_normal_(self.fc_node.weight, gain=gain) init.xavier_normal_(self.fc_ni.weight, gain=gain) init.xavier_normal_(self.fc_fij.weight, gain=gain) init.xavier_normal_(self.fc_nj.weight, gain=gain) init.xavier_normal_(self.attn, gain=gain) init.constant_(self.bias, 0)
[ "def", "reset_parameters", "(", "self", ")", ":", "gain", "=", "init", ".", "calculate_gain", "(", "'relu'", ")", "init", ".", "xavier_normal_", "(", "self", ".", "fc_node", ".", "weight", ",", "gain", "=", "gain", ")", "init", ".", "xavier_normal_", "("...
https://github.com/dmlc/dgl/blob/8d14a739bc9e446d6c92ef83eafe5782398118de/python/dgl/nn/pytorch/conv/egatconv.py#L94-L104
replit-archive/empythoned
977ec10ced29a3541a4973dc2b59910805695752
dist/lib/python2.7/email/message.py
python
Message.get_content_maintype
(self)
return ctype.split('/')[0]
Return the message's main content type. This is the `maintype' part of the string returned by get_content_type().
Return the message's main content type.
[ "Return", "the", "message", "s", "main", "content", "type", "." ]
def get_content_maintype(self): """Return the message's main content type. This is the `maintype' part of the string returned by get_content_type(). """ ctype = self.get_content_type() return ctype.split('/')[0]
[ "def", "get_content_maintype", "(", "self", ")", ":", "ctype", "=", "self", ".", "get_content_type", "(", ")", "return", "ctype", ".", "split", "(", "'/'", ")", "[", "0", "]" ]
https://github.com/replit-archive/empythoned/blob/977ec10ced29a3541a4973dc2b59910805695752/dist/lib/python2.7/email/message.py#L456-L463
QUANTAXIS/QUANTAXIS
d6eccb97c8385854aa596d6ba8d70ec0655519ff
QUANTAXIS/QAFetch/QATdx.py
python
QA_fetch_get_future_min
(code, start, end, frequence='1min', ip=None, port=None)
期货数据 分钟线
期货数据 分钟线
[ "期货数据", "分钟线" ]
def QA_fetch_get_future_min(code, start, end, frequence='1min', ip=None, port=None): '期货数据 分钟线' ip, port = get_extensionmarket_ip(ip, port) apix = TdxExHq_API(raise_exception=True) type_ = '' start_date = str(start)[0:10] today_ = datetime.date.today() lens = QA_util_get_trade_gap(start_date, today_) global extension_market_list extension_market_list = QA_fetch_get_extensionmarket_list( ) if extension_market_list is None else extension_market_list if str(frequence) in ['5', '5m', '5min', 'five']: frequence, type_ = 0, '5min' lens = 48 * lens * 2.5 elif str(frequence) in ['1', '1m', '1min', 'one']: frequence, type_ = 8, '1min' lens = 240 * lens * 2.5 elif str(frequence) in ['15', '15m', '15min', 'fifteen']: frequence, type_ = 1, '15min' lens = 16 * lens * 2.5 elif str(frequence) in ['30', '30m', '30min', 'half']: frequence, type_ = 2, '30min' lens = 8 * lens * 2.5 elif str(frequence) in ['60', '60m', '60min', '1h']: frequence, type_ = 3, '60min' lens = 4 * lens * 2.5 if lens > 20800: lens = 20800 # print(lens) with apix.connect(ip, port): code_market = extension_market_list.query( 'code=="{}"'.format(code)).iloc[0] data = pd.concat([apix.to_df( apix.get_instrument_bars(frequence, int(code_market.market), str( code), (int(lens / 700) - i) * 700, 700)) for i in range(int(lens / 700) + 1)], axis=0, sort=False) # print(data) # print(data.datetime) data = data \ .assign(tradetime=data['datetime'].apply(str), code=str(code), datetime=pd.to_datetime( data['datetime'].apply(QA_util_future_to_realdatetime, 1), utc=False)) \ .drop(['year', 'month', 'day', 'hour', 'minute'], axis=1, inplace=False) \ .assign(date=data['datetime'].apply(lambda x: str(x)[0:10]), date_stamp=data['datetime'].apply( lambda x: QA_util_date_stamp(x)), time_stamp=data['datetime'].apply( lambda x: QA_util_time_stamp(x)), type=type_).set_index('datetime', drop=False, inplace=False) return data.assign(datetime=data['datetime'].apply(lambda x: str(x)))[ start:end].sort_index()
[ "def", "QA_fetch_get_future_min", "(", "code", ",", "start", ",", "end", ",", "frequence", "=", "'1min'", ",", "ip", "=", "None", ",", "port", "=", "None", ")", ":", "ip", ",", "port", "=", "get_extensionmarket_ip", "(", "ip", ",", "port", ")", "apix",...
https://github.com/QUANTAXIS/QUANTAXIS/blob/d6eccb97c8385854aa596d6ba8d70ec0655519ff/QUANTAXIS/QAFetch/QATdx.py#L2495-L2551
spyder-ide/spyder
55da47c032dfcf519600f67f8b30eab467f965e7
spyder/plugins/ipythonconsole/plugin.py
python
IPythonConsole.set_spyder_breakpoints
(self)
Set Spyder breakpoints into all clients
Set Spyder breakpoints into all clients
[ "Set", "Spyder", "breakpoints", "into", "all", "clients" ]
def set_spyder_breakpoints(self): """Set Spyder breakpoints into all clients""" self.get_widget().set_spyder_breakpoints()
[ "def", "set_spyder_breakpoints", "(", "self", ")", ":", "self", ".", "get_widget", "(", ")", ".", "set_spyder_breakpoints", "(", ")" ]
https://github.com/spyder-ide/spyder/blob/55da47c032dfcf519600f67f8b30eab467f965e7/spyder/plugins/ipythonconsole/plugin.py#L790-L792
kubeflow/pipelines
bea751c9259ff0ae85290f873170aae89284ba8e
sdk/python/kfp/dsl/dsl_utils.py
python
resolve_cmd_lines
(cmds: Optional[List[_CommandlineArgumentType]], is_output_parameter: Callable[[str], bool])
Resolves a list of commands/args.
Resolves a list of commands/args.
[ "Resolves", "a", "list", "of", "commands", "/", "args", "." ]
def resolve_cmd_lines(cmds: Optional[List[_CommandlineArgumentType]], is_output_parameter: Callable[[str], bool]) -> None: """Resolves a list of commands/args.""" def _resolve_cmd(cmd: Optional[_CommandlineArgumentType]) -> Optional[str]: """Resolves a single command line cmd/arg.""" if cmd is None: return None elif isinstance(cmd, (str, float, int)): return str(cmd) elif isinstance(cmd, _structures.InputValuePlaceholder): return _input_parameter_placeholder(cmd.input_name) elif isinstance(cmd, _structures.InputPathPlaceholder): return _input_artifact_path_placeholder(cmd.input_name) elif isinstance(cmd, _structures.InputUriPlaceholder): return _input_artifact_uri_placeholder(cmd.input_name) elif isinstance(cmd, _structures.OutputPathPlaceholder): if is_output_parameter(cmd.output_name): return _output_parameter_path_placeholder(cmd.output_name) else: return _output_artifact_path_placeholder(cmd.output_name) elif isinstance(cmd, _structures.OutputUriPlaceholder): return _output_artifact_uri_placeholder(cmd.output_name) elif isinstance(cmd, _structures.ExecutorInputPlaceholder): return _executor_input_placeholder() else: raise TypeError('Got unexpected placeholder type for %s' % cmd) if not cmds: return for idx, cmd in enumerate(cmds): cmds[idx] = _resolve_cmd(cmd)
[ "def", "resolve_cmd_lines", "(", "cmds", ":", "Optional", "[", "List", "[", "_CommandlineArgumentType", "]", "]", ",", "is_output_parameter", ":", "Callable", "[", "[", "str", "]", ",", "bool", "]", ")", "->", "None", ":", "def", "_resolve_cmd", "(", "cmd"...
https://github.com/kubeflow/pipelines/blob/bea751c9259ff0ae85290f873170aae89284ba8e/sdk/python/kfp/dsl/dsl_utils.py#L106-L137
allenai/allennlp
a3d71254fcc0f3615910e9c3d48874515edf53e0
allennlp/commands/subcommand.py
python
Subcommand.name
(self)
return self._reverse_registry[self.__class__]
[]
def name(self) -> str: return self._reverse_registry[self.__class__]
[ "def", "name", "(", "self", ")", "->", "str", ":", "return", "self", ".", "_reverse_registry", "[", "self", ".", "__class__", "]" ]
https://github.com/allenai/allennlp/blob/a3d71254fcc0f3615910e9c3d48874515edf53e0/allennlp/commands/subcommand.py#L54-L55
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/wagtail_bak/wagtailcore/query.py
python
PageQuerySet.exact_type
(self, model)
return self.filter(self.exact_type_q(model))
This filters the QuerySet to only contain pages that are an instance of the specified model (matching the model exactly, not subclasses).
This filters the QuerySet to only contain pages that are an instance of the specified model (matching the model exactly, not subclasses).
[ "This", "filters", "the", "QuerySet", "to", "only", "contain", "pages", "that", "are", "an", "instance", "of", "the", "specified", "model", "(", "matching", "the", "model", "exactly", "not", "subclasses", ")", "." ]
def exact_type(self, model): """ This filters the QuerySet to only contain pages that are an instance of the specified model (matching the model exactly, not subclasses). """ return self.filter(self.exact_type_q(model))
[ "def", "exact_type", "(", "self", ",", "model", ")", ":", "return", "self", ".", "filter", "(", "self", ".", "exact_type_q", "(", "model", ")", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/wagtail_bak/wagtailcore/query.py#L201-L206
mozillazg/pypy
2ff5cd960c075c991389f842c6d59e71cf0cb7d0
rpython/tool/setuptools_msvc.py
python
SystemInfo._find_dot_net_versions
(self, bits)
Find Microsoft .NET Framework versions. Parameters ---------- bits: int Platform number of bits: 32 or 64. Return ------ tuple of str versions
Find Microsoft .NET Framework versions.
[ "Find", "Microsoft", ".", "NET", "Framework", "versions", "." ]
def _find_dot_net_versions(self, bits): """ Find Microsoft .NET Framework versions. Parameters ---------- bits: int Platform number of bits: 32 or 64. Return ------ tuple of str versions """ # Find actual .NET version in registry reg_ver = self.ri.lookup(self.ri.vc, 'frameworkver%d' % bits) dot_net_dir = getattr(self, 'FrameworkDir%d' % bits) ver = reg_ver or self._use_last_dir_name(dot_net_dir, 'v') or '' # Set .NET versions for specified MSVC++ version if self.vs_ver >= 12.0: return ver, 'v4.0' elif self.vs_ver >= 10.0: return 'v4.0.30319' if ver.lower()[:2] != 'v4' else ver, 'v3.5' elif self.vs_ver == 9.0: return 'v3.5', 'v2.0.50727' elif self.vs_ver == 8.0: return 'v3.0', 'v2.0.50727'
[ "def", "_find_dot_net_versions", "(", "self", ",", "bits", ")", ":", "# Find actual .NET version in registry", "reg_ver", "=", "self", ".", "ri", ".", "lookup", "(", "self", ".", "ri", ".", "vc", ",", "'frameworkver%d'", "%", "bits", ")", "dot_net_dir", "=", ...
https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/rpython/tool/setuptools_msvc.py#L1002-L1029
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-windows/x86/ldap3/utils/conv.py
python
json_hook
(obj)
return obj
[]
def json_hook(obj): if hasattr(obj, 'keys') and len(list(obj.keys())) == 2 and 'encoding' in obj.keys() and 'encoded' in obj.keys(): return b64decode(obj['encoded']) return obj
[ "def", "json_hook", "(", "obj", ")", ":", "if", "hasattr", "(", "obj", ",", "'keys'", ")", "and", "len", "(", "list", "(", "obj", ".", "keys", "(", ")", ")", ")", "==", "2", "and", "'encoding'", "in", "obj", ".", "keys", "(", ")", "and", "'enco...
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-windows/x86/ldap3/utils/conv.py#L178-L182
lukalabs/cakechat
844507281b30d81b3fe3674895fe27826dba8438
cakechat/dialog_model/factory.py
python
get_trained_model
(is_reverse_model=False, reverse_model=None, fetch_from_s3=True)
return model
Get a trained model, direct or reverse. :param is_reverse_model: boolean, if True, a reverse trained model will be returned to be used during inference in direct model in *_reranking modes; if False, a direct trained model is returned :param reverse_model: object of a reverse model to be used in direct model in *_reranking inference modes :param fetch_from_s3: boolean, if True, download trained model from Amazon S3 if the the model is not found locally; if False, the model presence will be checked only locally :return:
Get a trained model, direct or reverse. :param is_reverse_model: boolean, if True, a reverse trained model will be returned to be used during inference in direct model in *_reranking modes; if False, a direct trained model is returned :param reverse_model: object of a reverse model to be used in direct model in *_reranking inference modes :param fetch_from_s3: boolean, if True, download trained model from Amazon S3 if the the model is not found locally; if False, the model presence will be checked only locally :return:
[ "Get", "a", "trained", "model", "direct", "or", "reverse", ".", ":", "param", "is_reverse_model", ":", "boolean", "if", "True", "a", "reverse", "trained", "model", "will", "be", "returned", "to", "be", "used", "during", "inference", "in", "direct", "model", ...
def get_trained_model(is_reverse_model=False, reverse_model=None, fetch_from_s3=True): """ Get a trained model, direct or reverse. :param is_reverse_model: boolean, if True, a reverse trained model will be returned to be used during inference in direct model in *_reranking modes; if False, a direct trained model is returned :param reverse_model: object of a reverse model to be used in direct model in *_reranking inference modes :param fetch_from_s3: boolean, if True, download trained model from Amazon S3 if the the model is not found locally; if False, the model presence will be checked only locally :return: """ if fetch_from_s3: resolver_factory = get_s3_model_resolver(S3_MODELS_BUCKET_NAME, S3_NN_MODEL_REMOTE_DIR) else: resolver_factory = None w2v_model_id = get_w2v_model_id() if USE_PRETRAINED_W2V_EMBEDDINGS_LAYER else None model = InferenceCakeChatModel( index_to_token=_get_index_to_token(fetch_from_s3), index_to_condition=_get_index_to_condition(fetch_from_s3), training_data_param=ModelParam(value=None, id=TRAIN_CORPUS_NAME), validation_data_param=ModelParam(value=None, id=get_validation_data_id(get_validation_sets_names())), w2v_model_param=ModelParam(value=None, id=w2v_model_id), model_resolver=resolver_factory, is_reverse_model=is_reverse_model, reverse_model=reverse_model) model.init_model() model.resolve_model() return model
[ "def", "get_trained_model", "(", "is_reverse_model", "=", "False", ",", "reverse_model", "=", "None", ",", "fetch_from_s3", "=", "True", ")", ":", "if", "fetch_from_s3", ":", "resolver_factory", "=", "get_s3_model_resolver", "(", "S3_MODELS_BUCKET_NAME", ",", "S3_NN...
https://github.com/lukalabs/cakechat/blob/844507281b30d81b3fe3674895fe27826dba8438/cakechat/dialog_model/factory.py#L49-L78
OpenNMT/OpenNMT-py
4815f07fcd482af9a1fe1d3b620d144197178bc5
onmt/bin/server.py
python
_get_parser
()
return parser
[]
def _get_parser(): parser = configargparse.ArgumentParser( config_file_parser_class=configargparse.YAMLConfigFileParser, description="OpenNMT-py REST Server") parser.add_argument("--ip", type=str, default="0.0.0.0") parser.add_argument("--port", type=int, default="5000") parser.add_argument("--url_root", type=str, default="/translator") parser.add_argument("--debug", "-d", action="store_true") parser.add_argument("--config", "-c", type=str, default="./available_models/conf.json") return parser
[ "def", "_get_parser", "(", ")", ":", "parser", "=", "configargparse", ".", "ArgumentParser", "(", "config_file_parser_class", "=", "configargparse", ".", "YAMLConfigFileParser", ",", "description", "=", "\"OpenNMT-py REST Server\"", ")", "parser", ".", "add_argument", ...
https://github.com/OpenNMT/OpenNMT-py/blob/4815f07fcd482af9a1fe1d3b620d144197178bc5/onmt/bin/server.py#L136-L146
orestis/pysmell
14382f377f7759a1b6505120990898dd51f175e6
pysmell/codefinder.py
python
ModuleDict.enterClass
(self, klass, bases, docstring)
[]
def enterClass(self, klass, bases, docstring): fullClass = "%s.%s" % (self.currentModule, klass) self['CLASSES'][fullClass] = {} self['CLASSES'][fullClass]['methods'] = [] self['CLASSES'][fullClass]['properties'] = [] self['CLASSES'][fullClass]['constructor'] = [] self['CLASSES'][fullClass]['bases'] = bases self['CLASSES'][fullClass]['docstring'] = docstring
[ "def", "enterClass", "(", "self", ",", "klass", ",", "bases", ",", "docstring", ")", ":", "fullClass", "=", "\"%s.%s\"", "%", "(", "self", ".", "currentModule", ",", "klass", ")", "self", "[", "'CLASSES'", "]", "[", "fullClass", "]", "=", "{", "}", "...
https://github.com/orestis/pysmell/blob/14382f377f7759a1b6505120990898dd51f175e6/pysmell/codefinder.py#L33-L40
openai/mujoco-worldgen
39f52b1b47aed499925a6a214b58bdbdb4e2f75e
mujoco_worldgen/objs/obj.py
python
Obj.generate_xml_dict
(self)
Generate XML DOM nodes needed for MuJoCo model. doc - XML Document, used to create elements/nodes name_indexes - dictionary to keep track of names, see obj_util.get_name_index() for internals Returns a dictionary with keys as names of top-level nodes: e.g. 'worldbody', 'materials', 'assets' And the values are lists of XML DOM nodes
Generate XML DOM nodes needed for MuJoCo model. doc - XML Document, used to create elements/nodes name_indexes - dictionary to keep track of names, see obj_util.get_name_index() for internals Returns a dictionary with keys as names of top-level nodes: e.g. 'worldbody', 'materials', 'assets' And the values are lists of XML DOM nodes
[ "Generate", "XML", "DOM", "nodes", "needed", "for", "MuJoCo", "model", ".", "doc", "-", "XML", "Document", "used", "to", "create", "elements", "/", "nodes", "name_indexes", "-", "dictionary", "to", "keep", "track", "of", "names", "see", "obj_util", ".", "g...
def generate_xml_dict(self): ''' Generate XML DOM nodes needed for MuJoCo model. doc - XML Document, used to create elements/nodes name_indexes - dictionary to keep track of names, see obj_util.get_name_index() for internals Returns a dictionary with keys as names of top-level nodes: e.g. 'worldbody', 'materials', 'assets' And the values are lists of XML DOM nodes ''' raise NotImplementedError('Implement in subclasses!')
[ "def", "generate_xml_dict", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "'Implement in subclasses!'", ")" ]
https://github.com/openai/mujoco-worldgen/blob/39f52b1b47aed499925a6a214b58bdbdb4e2f75e/mujoco_worldgen/objs/obj.py#L500-L510
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/sympy/polys/partfrac.py
python
apart_full_decomposition
(P, Q)
return assemble_partfrac_list(apart_list(P/Q, P.gens[0]))
Bronstein's full partial fraction decomposition algorithm. Given a univariate rational function ``f``, performing only GCD operations over the algebraic closure of the initial ground domain of definition, compute full partial fraction decomposition with fractions having linear denominators. Note that no factorization of the initial denominator of ``f`` is performed. The final decomposition is formed in terms of a sum of :class:`RootSum` instances. References ========== 1. [Bronstein93]_
Bronstein's full partial fraction decomposition algorithm.
[ "Bronstein", "s", "full", "partial", "fraction", "decomposition", "algorithm", "." ]
def apart_full_decomposition(P, Q): """ Bronstein's full partial fraction decomposition algorithm. Given a univariate rational function ``f``, performing only GCD operations over the algebraic closure of the initial ground domain of definition, compute full partial fraction decomposition with fractions having linear denominators. Note that no factorization of the initial denominator of ``f`` is performed. The final decomposition is formed in terms of a sum of :class:`RootSum` instances. References ========== 1. [Bronstein93]_ """ return assemble_partfrac_list(apart_list(P/Q, P.gens[0]))
[ "def", "apart_full_decomposition", "(", "P", ",", "Q", ")", ":", "return", "assemble_partfrac_list", "(", "apart_list", "(", "P", "/", "Q", ",", "P", ".", "gens", "[", "0", "]", ")", ")" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/polys/partfrac.py#L169-L188
line/line-bot-sdk-python
d97d488876d504ab3cb6ecfc1574ea42bd669565
linebot/api.py
python
LineBotApi.delete_rich_menu
(self, rich_menu_id, timeout=None)
Call delete rich menu API. https://developers.line.biz/en/reference/messaging-api/#delete-rich-menu :param str rich_menu_id: ID of an uploaded rich menu :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a (connect timeout, read timeout) float tuple. Default is self.http_client.timeout :type timeout: float | tuple(float, float)
Call delete rich menu API.
[ "Call", "delete", "rich", "menu", "API", "." ]
def delete_rich_menu(self, rich_menu_id, timeout=None): """Call delete rich menu API. https://developers.line.biz/en/reference/messaging-api/#delete-rich-menu :param str rich_menu_id: ID of an uploaded rich menu :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a (connect timeout, read timeout) float tuple. Default is self.http_client.timeout :type timeout: float | tuple(float, float) """ self._delete( '/v2/bot/richmenu/{rich_menu_id}'.format(rich_menu_id=rich_menu_id), timeout=timeout )
[ "def", "delete_rich_menu", "(", "self", ",", "rich_menu_id", ",", "timeout", "=", "None", ")", ":", "self", ".", "_delete", "(", "'/v2/bot/richmenu/{rich_menu_id}'", ".", "format", "(", "rich_menu_id", "=", "rich_menu_id", ")", ",", "timeout", "=", "timeout", ...
https://github.com/line/line-bot-sdk-python/blob/d97d488876d504ab3cb6ecfc1574ea42bd669565/linebot/api.py#L778-L793
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/py4j-0.9/src/py4j/java_gateway.py
python
JavaGateway.__init__
( self, gateway_client=None, auto_field=False, python_proxy_port=DEFAULT_PYTHON_PROXY_PORT, start_callback_server=False, auto_convert=False, eager_load=False, gateway_parameters=None, callback_server_parameters=None)
:param gateway_parameters: An instance of `GatewayParameters` used to configure the various options of the gateway. :param callback_server_parameters: An instance of `CallbackServerParameters` used to configure various options of the gateway server. Must be provided to start a gateway server. Otherwise, callbacks won"t be available.
:param gateway_parameters: An instance of `GatewayParameters` used to configure the various options of the gateway.
[ ":", "param", "gateway_parameters", ":", "An", "instance", "of", "GatewayParameters", "used", "to", "configure", "the", "various", "options", "of", "the", "gateway", "." ]
def __init__( self, gateway_client=None, auto_field=False, python_proxy_port=DEFAULT_PYTHON_PROXY_PORT, start_callback_server=False, auto_convert=False, eager_load=False, gateway_parameters=None, callback_server_parameters=None): """ :param gateway_parameters: An instance of `GatewayParameters` used to configure the various options of the gateway. :param callback_server_parameters: An instance of `CallbackServerParameters` used to configure various options of the gateway server. Must be provided to start a gateway server. Otherwise, callbacks won"t be available. """ self.gateway_parameters = gateway_parameters if not gateway_parameters: self.gateway_parameters = GatewayParameters( auto_field=auto_field, auto_convert=auto_convert, eager_load=eager_load) self.callback_server_parameters = callback_server_parameters if not callback_server_parameters: # No parameters were provided so do not autostart callback server. self.callback_server_parameters = CallbackServerParameters( port=python_proxy_port, eager_load=False) # Check for deprecation warnings if auto_field: deprecated("JavaGateway.auto_field", "1.0", "GatewayParameters") if auto_convert: deprecated("JavaGateway.auto_convert", "1.0", "GatewayParameters") if eager_load: deprecated("JavaGateway.eager_load", "1.0", "GatewayParameters") if start_callback_server: deprecated( "JavaGateway.start_callback_server and python_proxy_port", "1.0", "CallbackServerParameters") self.callback_server_parameters.eager_load = True if gateway_client: deprecated("JavaGateway.gateway_client", "1.0", "GatewayParameters") else: gateway_client = GatewayClient( address=self.gateway_parameters.address, port=self.gateway_parameters.port, auto_close=self.gateway_parameters.auto_close) self.gateway_property = GatewayProperty( self.gateway_parameters.auto_field, PythonProxyPool()) self._python_proxy_port = python_proxy_port # Setup gateway client self.set_gateway_client(gateway_client) # Setup callback server property self._callback_server = None if self.gateway_parameters.eager_load: self._eager_load() if self.callback_server_parameters.eager_load: self.start_callback_server(self.callback_server_parameters)
[ "def", "__init__", "(", "self", ",", "gateway_client", "=", "None", ",", "auto_field", "=", "False", ",", "python_proxy_port", "=", "DEFAULT_PYTHON_PROXY_PORT", ",", "start_callback_server", "=", "False", ",", "auto_convert", "=", "False", ",", "eager_load", "=", ...
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/py4j-0.9/src/py4j/java_gateway.py#L1225-L1290
lordmauve/pgzero
46a889fb918ccd606d39ba63680386d7f8fcbc5a
examples/basic/demo3.py
python
set_alien_normal
()
Set the current alien sprite to the normal image.
Set the current alien sprite to the normal image.
[ "Set", "the", "current", "alien", "sprite", "to", "the", "normal", "image", "." ]
def set_alien_normal(): """Set the current alien sprite to the normal image.""" alien.image = 'alien'
[ "def", "set_alien_normal", "(", ")", ":", "alien", ".", "image", "=", "'alien'" ]
https://github.com/lordmauve/pgzero/blob/46a889fb918ccd606d39ba63680386d7f8fcbc5a/examples/basic/demo3.py#L41-L43
x0rz/EQGRP_Lost_in_Translation
6692b1486f562f027567a49523b8c151a4050988
windows/fuzzbunch/pyreadline/modes/notemacs.py
python
NotEmacsMode.prefix_meta
(self, e)
Metafy the next character typed. This is for keyboards without a meta key. Typing ESC f is equivalent to typing M-f.
Metafy the next character typed. This is for keyboards without a meta key. Typing ESC f is equivalent to typing M-f.
[ "Metafy", "the", "next", "character", "typed", ".", "This", "is", "for", "keyboards", "without", "a", "meta", "key", ".", "Typing", "ESC", "f", "is", "equivalent", "to", "typing", "M", "-", "f", "." ]
def prefix_meta(self, e): # (ESC) '''Metafy the next character typed. This is for keyboards without a meta key. Typing ESC f is equivalent to typing M-f. ''' self.next_meta = True
[ "def", "prefix_meta", "(", "self", ",", "e", ")", ":", "# (ESC)", "self", ".", "next_meta", "=", "True" ]
https://github.com/x0rz/EQGRP_Lost_in_Translation/blob/6692b1486f562f027567a49523b8c151a4050988/windows/fuzzbunch/pyreadline/modes/notemacs.py#L492-L495
mozillazg/pypy
2ff5cd960c075c991389f842c6d59e71cf0cb7d0
pypy/module/zlib/interp_zlib.py
python
crc32
(space, string, start = rzlib.CRC32_DEFAULT_START)
return space.newint(checksum)
crc32(string[, start]) -- Compute a CRC-32 checksum of string. An optional starting value can be specified. The returned checksum is an integer.
crc32(string[, start]) -- Compute a CRC-32 checksum of string.
[ "crc32", "(", "string", "[", "start", "]", ")", "--", "Compute", "a", "CRC", "-", "32", "checksum", "of", "string", "." ]
def crc32(space, string, start = rzlib.CRC32_DEFAULT_START): """ crc32(string[, start]) -- Compute a CRC-32 checksum of string. An optional starting value can be specified. The returned checksum is an integer. """ ustart = r_uint(start) checksum = rzlib.crc32(string, ustart) # This is, perhaps, a little stupid. zlib returns the checksum unsigned. # CPython exposes it as a signed value, though. -exarkun # Note that in CPython < 2.6 on 64-bit platforms the result is # actually unsigned, but it was considered to be a bug so we stick to # the 2.6 behavior and always return a number in range(-2**31, 2**31). checksum = unsigned_to_signed_32bit(checksum) return space.newint(checksum)
[ "def", "crc32", "(", "space", ",", "string", ",", "start", "=", "rzlib", ".", "CRC32_DEFAULT_START", ")", ":", "ustart", "=", "r_uint", "(", "start", ")", "checksum", "=", "rzlib", ".", "crc32", "(", "string", ",", "ustart", ")", "# This is, perhaps, a lit...
https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/pypy/module/zlib/interp_zlib.py#L23-L40
pythonarcade/arcade
1ee3eb1900683213e8e8df93943327c2ea784564
arcade/gl/program.py
python
Program._setup_out_attributes
(self)
Set up transform feedback varyings
Set up transform feedback varyings
[ "Set", "up", "transform", "feedback", "varyings" ]
def _setup_out_attributes(self): """Set up transform feedback varyings""" if not self._out_attributes: return # Covert names to char** c_array = (c_char_p * len(self._out_attributes))() for i, name in enumerate(self._out_attributes): c_array[i] = name.encode() ptr = cast(c_array, POINTER(POINTER(c_char))) # NOTE: We only support interleaved attributes for now gl.glTransformFeedbackVaryings( self._glo, # program len( self._out_attributes ), # number of varying variables used for transform feedback ptr, # zero-terminated strings specifying the names of the varying variables gl.GL_INTERLEAVED_ATTRIBS, )
[ "def", "_setup_out_attributes", "(", "self", ")", ":", "if", "not", "self", ".", "_out_attributes", ":", "return", "# Covert names to char**", "c_array", "=", "(", "c_char_p", "*", "len", "(", "self", ".", "_out_attributes", ")", ")", "(", ")", "for", "i", ...
https://github.com/pythonarcade/arcade/blob/1ee3eb1900683213e8e8df93943327c2ea784564/arcade/gl/program.py#L252-L272
beer-garden/beer-garden
7b1b7dd64ab1f19f370451c9438362d11f3a06e4
src/app/beer_garden/api/http/handlers/vbeta/file.py
python
RawFileAPI.delete
(self, file_id)
--- summary: Delete a file parameters: - name: file_name in: path required: true description: The file ID type: string responses: 204: description: The file and all of its contents have been removed. schema: $ref: '#/definitions/FileStatus' 400: $ref: '#/definitions/400Error' 50x: $ref: '#/definitions/50xError' tags: - Files
--- summary: Delete a file parameters: - name: file_name in: path required: true description: The file ID type: string responses: 204: description: The file and all of its contents have been removed. schema: $ref: '#/definitions/FileStatus' 400: $ref: '#/definitions/400Error' 50x: $ref: '#/definitions/50xError' tags: - Files
[ "---", "summary", ":", "Delete", "a", "file", "parameters", ":", "-", "name", ":", "file_name", "in", ":", "path", "required", ":", "true", "description", ":", "The", "file", "ID", "type", ":", "string", "responses", ":", "204", ":", "description", ":", ...
async def delete(self, file_id): """ --- summary: Delete a file parameters: - name: file_name in: path required: true description: The file ID type: string responses: 204: description: The file and all of its contents have been removed. schema: $ref: '#/definitions/FileStatus' 400: $ref: '#/definitions/400Error' 50x: $ref: '#/definitions/50xError' tags: - Files """ db_file = RawFile.objects.get(id=file_id) db_file.file.delete() db_file.save() self.set_status(204)
[ "async", "def", "delete", "(", "self", ",", "file_id", ")", ":", "db_file", "=", "RawFile", ".", "objects", ".", "get", "(", "id", "=", "file_id", ")", "db_file", ".", "file", ".", "delete", "(", ")", "db_file", ".", "save", "(", ")", "self", ".", ...
https://github.com/beer-garden/beer-garden/blob/7b1b7dd64ab1f19f370451c9438362d11f3a06e4/src/app/beer_garden/api/http/handlers/vbeta/file.py#L40-L66
languitar/pass-git-helper
0ccb8e5bcc4252dcb131468a2453eb4d2e051b7f
passgithelper.py
python
parse_mapping
(mapping_file: Optional[IO])
Parse the file containing the mappings from hosts to pass entries. Args: mapping_file: Name of the file to parse. If ``None``, the default file from the XDG location is used.
Parse the file containing the mappings from hosts to pass entries.
[ "Parse", "the", "file", "containing", "the", "mappings", "from", "hosts", "to", "pass", "entries", "." ]
def parse_mapping(mapping_file: Optional[IO]) -> configparser.ConfigParser: """ Parse the file containing the mappings from hosts to pass entries. Args: mapping_file: Name of the file to parse. If ``None``, the default file from the XDG location is used. """ LOGGER.debug("Parsing mapping file. Command line: %s", mapping_file) def parse(mapping_file: IO) -> configparser.ConfigParser: config = configparser.ConfigParser() config.read_file(mapping_file) return config # give precedence to the user-specified file if mapping_file is not None: LOGGER.debug("Parsing command line mapping file") return parse(mapping_file) # fall back on XDG config location xdg_config_dir = xdg.BaseDirectory.load_first_config("pass-git-helper") if xdg_config_dir is None: raise RuntimeError( "No mapping configured so far at any XDG config location. " "Please create {config_file}".format(config_file=DEFAULT_CONFIG_FILE) ) default_file = os.path.join(xdg_config_dir, CONFIG_FILE_NAME) LOGGER.debug("Parsing mapping file %s", mapping_file) with open(default_file, "r") as file_handle: return parse(file_handle)
[ "def", "parse_mapping", "(", "mapping_file", ":", "Optional", "[", "IO", "]", ")", "->", "configparser", ".", "ConfigParser", ":", "LOGGER", ".", "debug", "(", "\"Parsing mapping file. Command line: %s\"", ",", "mapping_file", ")", "def", "parse", "(", "mapping_fi...
https://github.com/languitar/pass-git-helper/blob/0ccb8e5bcc4252dcb131468a2453eb4d2e051b7f/passgithelper.py#L77-L108
cournape/Bento
37de23d784407a7c98a4a15770ffc570d5f32d70
bento/core/pkg_objects.py
python
PathOption.__init__
(self, name, default_value, description=None)
[]
def __init__(self, name, default_value, description=None): self.name = name self.default_value = default_value self.description = description
[ "def", "__init__", "(", "self", ",", "name", ",", "default_value", ",", "description", "=", "None", ")", ":", "self", ".", "name", "=", "name", "self", ".", "default_value", "=", "default_value", "self", ".", "description", "=", "description" ]
https://github.com/cournape/Bento/blob/37de23d784407a7c98a4a15770ffc570d5f32d70/bento/core/pkg_objects.py#L19-L22
CouchPotato/CouchPotatoV1
135b3331d1b88ef645e29b76f2d4cc4a732c9232
library/sqlalchemy/dialects/mysql/base.py
python
TINYINT.__init__
(self, display_width=None, **kw)
Construct a TINYINT. Note: following the usual MySQL conventions, TINYINT(1) columns reflected during Table(..., autoload=True) are treated as Boolean columns. :param display_width: Optional, maximum display width for this number. :param unsigned: a boolean, optional. :param zerofill: Optional. If true, values will be stored as strings left-padded with zeros. Note that this does not effect the values returned by the underlying database API, which continue to be numeric.
Construct a TINYINT.
[ "Construct", "a", "TINYINT", "." ]
def __init__(self, display_width=None, **kw): """Construct a TINYINT. Note: following the usual MySQL conventions, TINYINT(1) columns reflected during Table(..., autoload=True) are treated as Boolean columns. :param display_width: Optional, maximum display width for this number. :param unsigned: a boolean, optional. :param zerofill: Optional. If true, values will be stored as strings left-padded with zeros. Note that this does not effect the values returned by the underlying database API, which continue to be numeric. """ super(TINYINT, self).__init__(display_width=display_width, **kw)
[ "def", "__init__", "(", "self", ",", "display_width", "=", "None", ",", "*", "*", "kw", ")", ":", "super", "(", "TINYINT", ",", "self", ")", ".", "__init__", "(", "display_width", "=", "display_width", ",", "*", "*", "kw", ")" ]
https://github.com/CouchPotato/CouchPotatoV1/blob/135b3331d1b88ef645e29b76f2d4cc4a732c9232/library/sqlalchemy/dialects/mysql/base.py#L483-L500
utiasSTARS/liegroups
fe1d376b7d33809dec78724b456f01833507c305
liegroups/torch/so3.py
python
SO3Matrix.rotx
(cls, angle_in_radians)
return cls(mat.squeeze_())
Form a rotation matrix given an angle in rad about the x-axis.
Form a rotation matrix given an angle in rad about the x-axis.
[ "Form", "a", "rotation", "matrix", "given", "an", "angle", "in", "rad", "about", "the", "x", "-", "axis", "." ]
def rotx(cls, angle_in_radians): """Form a rotation matrix given an angle in rad about the x-axis.""" s = angle_in_radians.sin() c = angle_in_radians.cos() mat = angle_in_radians.new_empty( angle_in_radians.shape[0], cls.dim, cls.dim).zero_() mat[:, 0, 0] = 1. mat[:, 1, 1] = c mat[:, 1, 2] = -s mat[:, 2, 1] = s mat[:, 2, 2] = c return cls(mat.squeeze_())
[ "def", "rotx", "(", "cls", ",", "angle_in_radians", ")", ":", "s", "=", "angle_in_radians", ".", "sin", "(", ")", "c", "=", "angle_in_radians", ".", "cos", "(", ")", "mat", "=", "angle_in_radians", ".", "new_empty", "(", "angle_in_radians", ".", "shape", ...
https://github.com/utiasSTARS/liegroups/blob/fe1d376b7d33809dec78724b456f01833507c305/liegroups/torch/so3.py#L248-L261
tensorflow/tfx
b4a6b83269815ed12ba9df9e9154c7376fef2ea0
tfx/utils/kube_utils.py
python
is_inside_kfp
()
return ( is_inside_cluster() and KFP_POD_NAME in os.environ and KFP_NAMESPACE in os.environ )
Whether current running environment is inside the KFP runtime.
Whether current running environment is inside the KFP runtime.
[ "Whether", "current", "running", "environment", "is", "inside", "the", "KFP", "runtime", "." ]
def is_inside_kfp() -> bool: """Whether current running environment is inside the KFP runtime.""" return ( is_inside_cluster() and KFP_POD_NAME in os.environ and KFP_NAMESPACE in os.environ )
[ "def", "is_inside_kfp", "(", ")", "->", "bool", ":", "return", "(", "is_inside_cluster", "(", ")", "and", "KFP_POD_NAME", "in", "os", ".", "environ", "and", "KFP_NAMESPACE", "in", "os", ".", "environ", ")" ]
https://github.com/tensorflow/tfx/blob/b4a6b83269815ed12ba9df9e9154c7376fef2ea0/tfx/utils/kube_utils.py#L232-L238
Thinklab-SJTU/R3Det_Tensorflow
3e092fa65dee2b9f7722b0985b3791811a1de5ae
libs/networks/mobilenet/conv_blocks.py
python
_split_divisible
(num, num_ways, divisible_by=8)
return result
Evenly splits num, num_ways so each piece is a multiple of divisible_by.
Evenly splits num, num_ways so each piece is a multiple of divisible_by.
[ "Evenly", "splits", "num", "num_ways", "so", "each", "piece", "is", "a", "multiple", "of", "divisible_by", "." ]
def _split_divisible(num, num_ways, divisible_by=8): """Evenly splits num, num_ways so each piece is a multiple of divisible_by.""" assert num % divisible_by == 0 assert num / num_ways >= divisible_by # Note: want to round down, we adjust each split to match the total. base = num // num_ways // divisible_by * divisible_by result = [] accumulated = 0 for i in range(num_ways): r = base while accumulated + r < num * (i + 1) / num_ways: r += divisible_by result.append(r) accumulated += r assert accumulated == num return result
[ "def", "_split_divisible", "(", "num", ",", "num_ways", ",", "divisible_by", "=", "8", ")", ":", "assert", "num", "%", "divisible_by", "==", "0", "assert", "num", "/", "num_ways", ">=", "divisible_by", "# Note: want to round down, we adjust each split to match the tot...
https://github.com/Thinklab-SJTU/R3Det_Tensorflow/blob/3e092fa65dee2b9f7722b0985b3791811a1de5ae/libs/networks/mobilenet/conv_blocks.py#L60-L75
ssjssh/algorithm
2db90930340ba4a9bf5a37b3386e9dbb48673e28
src/ssj/graph/weighted_graph.py
python
WeightedGraph.lws
(self, from_node, to_node)
return __lws[Edge(from_node, to_node)]
在有向无环带权图里面查找最长路径 令list(s,t)是从s到t的最长带权路径。 那么可以使用递归式表示这个问题 list(s,t) = max(list(s,t-1))+list(t-1,t)(唯一) 用动态规划自下而上解决,因为自上而下解决首先遇到的问题就是 查找指向一个节点的节点在邻接表中比较困难 :param from_node: :param to_node: :return:
在有向无环带权图里面查找最长路径 令list(s,t)是从s到t的最长带权路径。 那么可以使用递归式表示这个问题 list(s,t) = max(list(s,t-1))+list(t-1,t)(唯一) 用动态规划自下而上解决,因为自上而下解决首先遇到的问题就是 查找指向一个节点的节点在邻接表中比较困难 :param from_node: :param to_node: :return:
[ "在有向无环带权图里面查找最长路径", "令list", "(", "s", "t", ")", "是从s到t的最长带权路径。", "那么可以使用递归式表示这个问题", "list", "(", "s", "t", ")", "=", "max", "(", "list", "(", "s", "t", "-", "1", "))", "+", "list", "(", "t", "-", "1", "t", ")", "(", "唯一", ")", "用动态规划自下而上解决,因为自上而下解...
def lws(self, from_node, to_node): """ 在有向无环带权图里面查找最长路径 令list(s,t)是从s到t的最长带权路径。 那么可以使用递归式表示这个问题 list(s,t) = max(list(s,t-1))+list(t-1,t)(唯一) 用动态规划自下而上解决,因为自上而下解决首先遇到的问题就是 查找指向一个节点的节点在邻接表中比较困难 :param from_node: :param to_node: :return: """ __lws = {} # 为了计算方便,这里把开始节点到开始节点插入字典中, zero_edge = Edge(from_node, from_node) __lws[zero_edge] = 0 graph_stack = Queue() graph_stack.enter(from_node) while not graph_stack.empty(): cur_node = graph_stack.exit() cur_edge_list = self.__adj_list.get(cur_node) if cur_edge_list is None: print ",".join(map(lambda edge: str(edge), __lws.iteritems())) print ",".join(map(lambda edge: str(edge), __lws)) return __lws[Edge(from_node, to_node)] for edge_end_node in cur_edge_list: graph_stack.enter(edge_end_node.key) last_weighted_length = __lws[Edge(from_node, cur_node)] cur_edge = Edge(from_node, edge_end_node.key) cur_weight_length = last_weighted_length + edge_end_node.weight # 如果不存在这个边,那么就插入 if cur_edge not in __lws: __lws[cur_edge] = cur_weight_length # 如果存在,那么就把最大值插入 elif cur_weight_length > __lws[cur_edge]: __lws[cur_edge] = cur_weight_length print ",".join(map(lambda edge: str(edge), __lws.iteritems())) print ",".join(map(lambda edge: str(edge), __lws)) return __lws[Edge(from_node, to_node)]
[ "def", "lws", "(", "self", ",", "from_node", ",", "to_node", ")", ":", "__lws", "=", "{", "}", "# 为了计算方便,这里把开始节点到开始节点插入字典中,", "zero_edge", "=", "Edge", "(", "from_node", ",", "from_node", ")", "__lws", "[", "zero_edge", "]", "=", "0", "graph_stack", "=", ...
https://github.com/ssjssh/algorithm/blob/2db90930340ba4a9bf5a37b3386e9dbb48673e28/src/ssj/graph/weighted_graph.py#L83-L121
hyperledger/aries-cloudagent-python
2f36776e99f6053ae92eed8123b5b1b2e891c02a
aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_issue_handler.py
python
V20CredIssueHandler.handle
(self, context: RequestContext, responder: BaseResponder)
Message handler logic for credential offers. Args: context: request context responder: responder callback
Message handler logic for credential offers.
[ "Message", "handler", "logic", "for", "credential", "offers", "." ]
async def handle(self, context: RequestContext, responder: BaseResponder): """ Message handler logic for credential offers. Args: context: request context responder: responder callback """ r_time = get_timer() self._logger.debug("V20CredIssueHandler called with context %s", context) assert isinstance(context.message, V20CredIssue) self._logger.info( "Received v2.0 credential issue message: %s", context.message.serialize(as_string=True), ) if not context.connection_ready: raise HandlerException("No connection established for credential issue") cred_manager = V20CredManager(context.profile) cred_ex_record = await cred_manager.receive_credential( context.message, context.connection_record.connection_id ) # mgr only finds, saves record: on exception, saving null state is hopeless r_time = trace_event( context.settings, context.message, outcome="V20CredIssueHandler.handle.END", perf_counter=r_time, ) # Automatically move to next state if flag is set if context.settings.get("debug.auto_store_credential"): try: cred_ex_record = await cred_manager.store_credential(cred_ex_record) except ( BaseModelError, IndyHolderError, StorageError, V20CredManagerError, ) as err: # treat failure to store as mangled on receipt hence protocol error self._logger.exception(err) if cred_ex_record: async with context.profile.session() as session: await cred_ex_record.save_error_state( session, reason=err.roll_up, # us: be specific ) await responder.send_reply( problem_report_for_record( cred_ex_record, ProblemReportReason.ISSUANCE_ABANDONED.value, # them: vague ) ) cred_ack_message = await cred_manager.send_cred_ack(cred_ex_record) trace_event( context.settings, cred_ack_message, outcome="V20CredIssueHandler.handle.STORE", perf_counter=r_time, )
[ "async", "def", "handle", "(", "self", ",", "context", ":", "RequestContext", ",", "responder", ":", "BaseResponder", ")", ":", "r_time", "=", "get_timer", "(", ")", "self", ".", "_logger", ".", "debug", "(", "\"V20CredIssueHandler called with context %s\"", ","...
https://github.com/hyperledger/aries-cloudagent-python/blob/2f36776e99f6053ae92eed8123b5b1b2e891c02a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_issue_handler.py#L20-L85
cyverse/atmosphere
4a3e522f1f7b58abd9fa944c10b7455dc5cddac1
core/plugins.py
python
AllocationSourcePluginManager.ensure_user_allocation_sources
(cls, user, provider=None)
return _has_valid_allocation_sources
Load each Allocation Source Plugin and call `plugin.ensure_user_allocation_source(user)` Depending on the plugin this may create allocation sources if they don't already exist. :param user: The user to check :type user: core.models.AtmosphereUser :param provider: The provider (optional, not used by all plugins) :type provider: core.models.Provider :return: Whether the user has valid allocation sources :rtype: bool
Load each Allocation Source Plugin and call `plugin.ensure_user_allocation_source(user)`
[ "Load", "each", "Allocation", "Source", "Plugin", "and", "call", "plugin", ".", "ensure_user_allocation_source", "(", "user", ")" ]
def ensure_user_allocation_sources(cls, user, provider=None): """Load each Allocation Source Plugin and call `plugin.ensure_user_allocation_source(user)` Depending on the plugin this may create allocation sources if they don't already exist. :param user: The user to check :type user: core.models.AtmosphereUser :param provider: The provider (optional, not used by all plugins) :type provider: core.models.Provider :return: Whether the user has valid allocation sources :rtype: bool """ _has_valid_allocation_sources = False for AllocationSourcePlugin in cls.load_plugins(cls.list_of_classes): plugin = AllocationSourcePlugin() try: inspect.getcallargs( getattr(plugin, 'ensure_user_allocation_source'), user=user, provider=provider ) except AttributeError: logger.info( "Allocation Source plugin %s missing method 'ensure_user_allocation_source'", AllocationSourcePlugin ) except TypeError: logger.info( "Allocation Source plugin %s does not accept kwargs `user` & `provider`", AllocationSourcePlugin ) _has_valid_allocation_sources = plugin.ensure_user_allocation_source( user=user, provider=provider ) if _has_valid_allocation_sources: return _has_valid_allocation_sources return _has_valid_allocation_sources
[ "def", "ensure_user_allocation_sources", "(", "cls", ",", "user", ",", "provider", "=", "None", ")", ":", "_has_valid_allocation_sources", "=", "False", "for", "AllocationSourcePlugin", "in", "cls", ".", "load_plugins", "(", "cls", ".", "list_of_classes", ")", ":"...
https://github.com/cyverse/atmosphere/blob/4a3e522f1f7b58abd9fa944c10b7455dc5cddac1/core/plugins.py#L139-L174
PacktPublishing/Mastering-OpenCV-4-with-Python
ea5372c6d8758ebc56ef5c775f9785d4427f81e6
Chapter08/01-chapter-content/contours_shape_recognition.py
python
draw_contour_outline
(img, cnts, color, thickness=1)
Draws contours outlines of each contour
Draws contours outlines of each contour
[ "Draws", "contours", "outlines", "of", "each", "contour" ]
def draw_contour_outline(img, cnts, color, thickness=1): """Draws contours outlines of each contour""" for cnt in cnts: cv2.drawContours(img, [cnt], 0, color, thickness)
[ "def", "draw_contour_outline", "(", "img", ",", "cnts", ",", "color", ",", "thickness", "=", "1", ")", ":", "for", "cnt", "in", "cnts", ":", "cv2", ".", "drawContours", "(", "img", ",", "[", "cnt", "]", ",", "0", ",", "color", ",", "thickness", ")"...
https://github.com/PacktPublishing/Mastering-OpenCV-4-with-Python/blob/ea5372c6d8758ebc56ef5c775f9785d4427f81e6/Chapter08/01-chapter-content/contours_shape_recognition.py#L85-L89
TheAlgorithms/Python
9af2eef9b3761bf51580dedfb6fa7136ca0c5c2c
bit_manipulation/single_bit_manipulation_operations.py
python
flip_bit
(number: int, position: int)
return number ^ (1 << position)
Flip the bit at position. Details: perform bitwise xor for given number and X. Where X is a number with all the bits – zeroes and bit on given position – one. >>> flip_bit(0b101, 1) # 0b111 7 >>> flip_bit(0b101, 0) # 0b100 4
Flip the bit at position.
[ "Flip", "the", "bit", "at", "position", "." ]
def flip_bit(number: int, position: int) -> int: """ Flip the bit at position. Details: perform bitwise xor for given number and X. Where X is a number with all the bits – zeroes and bit on given position – one. >>> flip_bit(0b101, 1) # 0b111 7 >>> flip_bit(0b101, 0) # 0b100 4 """ return number ^ (1 << position)
[ "def", "flip_bit", "(", "number", ":", "int", ",", "position", ":", "int", ")", "->", "int", ":", "return", "number", "^", "(", "1", "<<", "position", ")" ]
https://github.com/TheAlgorithms/Python/blob/9af2eef9b3761bf51580dedfb6fa7136ca0c5c2c/bit_manipulation/single_bit_manipulation_operations.py#L40-L53
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/packages/site-packages/sqlalchemy/engine/interfaces.py
python
Dialect.get_foreign_keys
(self, connection, table_name, schema=None, **kw)
Return information about foreign_keys in `table_name`. Given a :class:`.Connection`, a string `table_name`, and an optional string `schema`, return foreign key information as a list of dicts with these keys: name the constraint's name constrained_columns a list of column names that make up the foreign key referred_schema the name of the referred schema referred_table the name of the referred table referred_columns a list of column names in the referred table that correspond to constrained_columns
Return information about foreign_keys in `table_name`.
[ "Return", "information", "about", "foreign_keys", "in", "table_name", "." ]
def get_foreign_keys(self, connection, table_name, schema=None, **kw): """Return information about foreign_keys in `table_name`. Given a :class:`.Connection`, a string `table_name`, and an optional string `schema`, return foreign key information as a list of dicts with these keys: name the constraint's name constrained_columns a list of column names that make up the foreign key referred_schema the name of the referred schema referred_table the name of the referred table referred_columns a list of column names in the referred table that correspond to constrained_columns """ raise NotImplementedError()
[ "def", "get_foreign_keys", "(", "self", ",", "connection", ",", "table_name", ",", "schema", "=", "None", ",", "*", "*", "kw", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/packages/site-packages/sqlalchemy/engine/interfaces.py#L294-L318
ym2011/POC-EXP
206b22d3a6b2a172359678df33bbc5b2ad04b6c3
K8/Web-Exp/sqlmap/tamper/symboliclogical.py
python
tamper
(payload, **kwargs)
return retVal
Replaces AND and OR logical operators with their symbolic counterparts (&& and ||) >>> tamper("1 AND '1'='1") "1 %26%26 '1'='1"
Replaces AND and OR logical operators with their symbolic counterparts (&& and ||)
[ "Replaces", "AND", "and", "OR", "logical", "operators", "with", "their", "symbolic", "counterparts", "(", "&&", "and", "||", ")" ]
def tamper(payload, **kwargs): """ Replaces AND and OR logical operators with their symbolic counterparts (&& and ||) >>> tamper("1 AND '1'='1") "1 %26%26 '1'='1" """ retVal = payload if payload: retVal = re.sub(r"(?i)\bAND\b", "%26%26", re.sub(r"(?i)\bOR\b", "%7C%7C", payload)) return retVal
[ "def", "tamper", "(", "payload", ",", "*", "*", "kwargs", ")", ":", "retVal", "=", "payload", "if", "payload", ":", "retVal", "=", "re", ".", "sub", "(", "r\"(?i)\\bAND\\b\"", ",", "\"%26%26\"", ",", "re", ".", "sub", "(", "r\"(?i)\\bOR\\b\"", ",", "\"...
https://github.com/ym2011/POC-EXP/blob/206b22d3a6b2a172359678df33bbc5b2ad04b6c3/K8/Web-Exp/sqlmap/tamper/symboliclogical.py#L17-L30
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/encodings/mac_iceland.py
python
getregentry
()
return codecs.CodecInfo( name='mac-iceland', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, )
[]
def getregentry(): return codecs.CodecInfo( name='mac-iceland', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, )
[ "def", "getregentry", "(", ")", ":", "return", "codecs", ".", "CodecInfo", "(", "name", "=", "'mac-iceland'", ",", "encode", "=", "Codec", "(", ")", ".", "encode", ",", "decode", "=", "Codec", "(", ")", ".", "decode", ",", "incrementalencoder", "=", "I...
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/encodings/mac_iceland.py#L33-L42
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit - MAC OSX/tools/sqli/plugins/dbms/mysql/syntax.py
python
Syntax.__init__
(self)
[]
def __init__(self): GenericSyntax.__init__(self)
[ "def", "__init__", "(", "self", ")", ":", "GenericSyntax", ".", "__init__", "(", "self", ")" ]
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/tools/sqli/plugins/dbms/mysql/syntax.py#L14-L15
exaile/exaile
a7b58996c5c15b3aa7b9975ac13ee8f784ef4689
xl/radio.py
python
RadioList.__str__
(self)
return self.name
Returns a string representation of the list
Returns a string representation of the list
[ "Returns", "a", "string", "representation", "of", "the", "list" ]
def __str__(self): """ Returns a string representation of the list """ return self.name
[ "def", "__str__", "(", "self", ")", ":", "return", "self", ".", "name" ]
https://github.com/exaile/exaile/blob/a7b58996c5c15b3aa7b9975ac13ee8f784ef4689/xl/radio.py#L127-L131
fuzzbunch/fuzzbunch
4b60a6c7cf9f84cf389d3fcdb9281de84ffb5802
fuzzbunch/pyreadline/modes/notemacs.py
python
NotEmacsMode.tab_insert
(self, e)
Insert a tab character.
Insert a tab character.
[ "Insert", "a", "tab", "character", "." ]
def tab_insert(self, e): # (M-TAB) '''Insert a tab character. ''' ws = ' ' * (self.tabstop - (self.line_cursor%self.tabstop)) self.insert_text(ws)
[ "def", "tab_insert", "(", "self", ",", "e", ")", ":", "# (M-TAB)", "ws", "=", "' '", "*", "(", "self", ".", "tabstop", "-", "(", "self", ".", "line_cursor", "%", "self", ".", "tabstop", ")", ")", "self", ".", "insert_text", "(", "ws", ")" ]
https://github.com/fuzzbunch/fuzzbunch/blob/4b60a6c7cf9f84cf389d3fcdb9281de84ffb5802/fuzzbunch/pyreadline/modes/notemacs.py#L273-L276
Kkevsterrr/backdoorme
f9755ca6cec600335e681752e7a1c5c617bb5a39
backdoors/shell/__pupy/pupy/packages/windows/x86/psutil/_psosx.py
python
per_cpu_times
()
return ret
Return system CPU times as a named tuple
Return system CPU times as a named tuple
[ "Return", "system", "CPU", "times", "as", "a", "named", "tuple" ]
def per_cpu_times(): """Return system CPU times as a named tuple""" ret = [] for cpu_t in cext.per_cpu_times(): user, nice, system, idle = cpu_t item = scputimes(user, nice, system, idle) ret.append(item) return ret
[ "def", "per_cpu_times", "(", ")", ":", "ret", "=", "[", "]", "for", "cpu_t", "in", "cext", ".", "per_cpu_times", "(", ")", ":", "user", ",", "nice", ",", "system", ",", "idle", "=", "cpu_t", "item", "=", "scputimes", "(", "user", ",", "nice", ",", ...
https://github.com/Kkevsterrr/backdoorme/blob/f9755ca6cec600335e681752e7a1c5c617bb5a39/backdoors/shell/__pupy/pupy/packages/windows/x86/psutil/_psosx.py#L100-L107
dmlc/dgl
8d14a739bc9e446d6c92ef83eafe5782398118de
python/dgl/_deprecate/graph.py
python
DGLGraph.recv
(self, v=ALL, reduce_func="default", apply_node_func="default", inplace=False)
Receive and reduce incoming messages and update the features of node(s) :math:`v`. Optionally, apply a function to update the node features after receive. * `reduce_func` will be skipped for nodes with no incoming message. * If all ``v`` have no incoming message, this will downgrade to an :func:`apply_nodes`. * If some ``v`` have no incoming message, their new feature value will be calculated by the column initializer (see :func:`set_n_initializer`). The feature shapes and dtypes will be inferred. The node features will be updated by the result of the ``reduce_func``. Messages are consumed once received. The provided UDF maybe called multiple times so it is recommended to provide function with no side effect. Parameters ---------- v : node, container or tensor, optional The node to be updated. Default is receiving all the nodes. reduce_func : callable, optional Reduce function on the node. The function should be a :mod:`Node UDF <dgl.udf>`. apply_node_func : callable Apply function on the nodes. The function should be a :mod:`Node UDF <dgl.udf>`. inplace: bool, optional If True, update will be done in place, but autograd will break. Examples -------- Create a graph object for demo. .. note:: Here we use pytorch syntax for demo. The general idea applies to other frameworks with minor syntax change (e.g. replace ``torch.tensor`` with ``mxnet.ndarray``). >>> import torch as th >>> g = dgl.DGLGraph() >>> g.add_nodes(3) >>> g.ndata['x'] = th.tensor([[1.], [2.], [3.]]) >>> g.add_edges([0, 1], [1, 2]) >>> # Define the function for sending node features as messages. >>> def send_source(edges): return {'m': edges.src['x']} >>> # Set the function defined to be the default message function. >>> g.register_message_func(send_source) >>> # Sum the messages received and use this to replace the original node feature. >>> def simple_reduce(nodes): return {'x': nodes.mailbox['m'].sum(1)} >>> # Set the function defined to be the default message reduce function. >>> g.register_reduce_func(simple_reduce) Send and receive messages. Note that although node :math:`0` has no incoming edges, its feature gets changed from :math:`1` to :math:`0` as it is also included in ``g.nodes()``. >>> g.send(g.edges()) >>> g.recv(g.nodes()) >>> g.ndata['x'] tensor([[0.], [1.], [2.]]) Once messages are received, one will need another call of :func:`send` again before another call of :func:`recv`. Otherwise, nothing will happen. >>> g.recv(g.nodes()) >>> g.ndata['x'] tensor([[0.], [1.], [2.]])
Receive and reduce incoming messages and update the features of node(s) :math:`v`.
[ "Receive", "and", "reduce", "incoming", "messages", "and", "update", "the", "features", "of", "node", "(", "s", ")", ":", "math", ":", "v", "." ]
def recv(self, v=ALL, reduce_func="default", apply_node_func="default", inplace=False): """Receive and reduce incoming messages and update the features of node(s) :math:`v`. Optionally, apply a function to update the node features after receive. * `reduce_func` will be skipped for nodes with no incoming message. * If all ``v`` have no incoming message, this will downgrade to an :func:`apply_nodes`. * If some ``v`` have no incoming message, their new feature value will be calculated by the column initializer (see :func:`set_n_initializer`). The feature shapes and dtypes will be inferred. The node features will be updated by the result of the ``reduce_func``. Messages are consumed once received. The provided UDF maybe called multiple times so it is recommended to provide function with no side effect. Parameters ---------- v : node, container or tensor, optional The node to be updated. Default is receiving all the nodes. reduce_func : callable, optional Reduce function on the node. The function should be a :mod:`Node UDF <dgl.udf>`. apply_node_func : callable Apply function on the nodes. The function should be a :mod:`Node UDF <dgl.udf>`. inplace: bool, optional If True, update will be done in place, but autograd will break. Examples -------- Create a graph object for demo. .. note:: Here we use pytorch syntax for demo. The general idea applies to other frameworks with minor syntax change (e.g. replace ``torch.tensor`` with ``mxnet.ndarray``). >>> import torch as th >>> g = dgl.DGLGraph() >>> g.add_nodes(3) >>> g.ndata['x'] = th.tensor([[1.], [2.], [3.]]) >>> g.add_edges([0, 1], [1, 2]) >>> # Define the function for sending node features as messages. >>> def send_source(edges): return {'m': edges.src['x']} >>> # Set the function defined to be the default message function. >>> g.register_message_func(send_source) >>> # Sum the messages received and use this to replace the original node feature. >>> def simple_reduce(nodes): return {'x': nodes.mailbox['m'].sum(1)} >>> # Set the function defined to be the default message reduce function. >>> g.register_reduce_func(simple_reduce) Send and receive messages. Note that although node :math:`0` has no incoming edges, its feature gets changed from :math:`1` to :math:`0` as it is also included in ``g.nodes()``. >>> g.send(g.edges()) >>> g.recv(g.nodes()) >>> g.ndata['x'] tensor([[0.], [1.], [2.]]) Once messages are received, one will need another call of :func:`send` again before another call of :func:`recv`. Otherwise, nothing will happen. >>> g.recv(g.nodes()) >>> g.ndata['x'] tensor([[0.], [1.], [2.]]) """ if reduce_func == "default": reduce_func = self._reduce_func if apply_node_func == "default": apply_node_func = self._apply_node_func assert reduce_func is not None if is_all(v): v = F.arange(0, self.number_of_nodes()) elif isinstance(v, int): v = [v] v = utils.toindex(v) if len(v) == 0: # no vertex to be triggered. return with ir.prog() as prog: scheduler.schedule_recv(graph=AdaptedDGLGraph(self), recv_nodes=v, reduce_func=reduce_func, apply_func=apply_node_func, inplace=inplace) Runtime.run(prog)
[ "def", "recv", "(", "self", ",", "v", "=", "ALL", ",", "reduce_func", "=", "\"default\"", ",", "apply_node_func", "=", "\"default\"", ",", "inplace", "=", "False", ")", ":", "if", "reduce_func", "==", "\"default\"", ":", "reduce_func", "=", "self", ".", ...
https://github.com/dmlc/dgl/blob/8d14a739bc9e446d6c92ef83eafe5782398118de/python/dgl/_deprecate/graph.py#L2830-L2930
treeio/treeio
bae3115f4015aad2cbc5ab45572232ceec990495
treeio/services/forms.py
python
MassActionForm.__init__
(self, user, *args, **kwargs)
Sets allowed values
Sets allowed values
[ "Sets", "allowed", "values" ]
def __init__(self, user, *args, **kwargs): "Sets allowed values" if 'instance' in kwargs: self.instance = kwargs['instance'] del kwargs['instance'] super(MassActionForm, self).__init__(*args, **kwargs) self.fields['status'].queryset = Object.filter_permitted( user, TicketStatus.objects, mode='x') self.fields['status'].label = _("Status") self.fields['service'].queryset = Object.filter_permitted( user, Service.objects, mode='x') self.fields['service'].label = _("Service") self.fields['queue'].queryset = Object.filter_permitted( user, TicketQueue.objects, mode='x') self.fields['queue'].label = _("Queue") self.fields['delete'] = forms.ChoiceField(label=_("Delete"), choices=(('', '-----'), ('delete', _( 'Delete Completely')), ('trash', _('Move to Trash'))), required=False)
[ "def", "__init__", "(", "self", ",", "user", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "'instance'", "in", "kwargs", ":", "self", ".", "instance", "=", "kwargs", "[", "'instance'", "]", "del", "kwargs", "[", "'instance'", "]", "super...
https://github.com/treeio/treeio/blob/bae3115f4015aad2cbc5ab45572232ceec990495/treeio/services/forms.py#L126-L147
QUANTAXIS/QUANTAXIS
d6eccb97c8385854aa596d6ba8d70ec0655519ff
QUANTAXIS/QAFetch/QAhuobi_realtime.py
python
QA_Fetch_Huobi.run_subscription_batch_jobs
(self)
请求 KLine 实时数据
请求 KLine 实时数据
[ "请求", "KLine", "实时数据" ]
def run_subscription_batch_jobs(self): """ 请求 KLine 实时数据 """ websocket.enableTrace(False) self.__ws = websocket.WebSocketApp( self.HUOBIPRO_WEBSOCKET_URL, on_message=self.on_message, on_open=self.on_open, on_error=self.on_error, on_close=self.on_close ) self.__locked = True # 如果意外退出,等待10秒重新运行 while (True): self.__ws.run_forever() QA_util_log_expection("FTW! it quit! Retry 10 seconds later...") time.sleep(10)
[ "def", "run_subscription_batch_jobs", "(", "self", ")", ":", "websocket", ".", "enableTrace", "(", "False", ")", "self", ".", "__ws", "=", "websocket", ".", "WebSocketApp", "(", "self", ".", "HUOBIPRO_WEBSOCKET_URL", ",", "on_message", "=", "self", ".", "on_me...
https://github.com/QUANTAXIS/QUANTAXIS/blob/d6eccb97c8385854aa596d6ba8d70ec0655519ff/QUANTAXIS/QAFetch/QAhuobi_realtime.py#L747-L765
errbotio/errbot
66e1de8e1d7daa62be7f9ed1b2ac8832f09fa25d
errbot/core_plugins/plugins.py
python
Plugins.plugin_reload
(self, _, args)
reload a plugin: reload the code of the plugin leaving the activation status intact.
reload a plugin: reload the code of the plugin leaving the activation status intact.
[ "reload", "a", "plugin", ":", "reload", "the", "code", "of", "the", "plugin", "leaving", "the", "activation", "status", "intact", "." ]
def plugin_reload(self, _, args): """reload a plugin: reload the code of the plugin leaving the activation status intact.""" name = args.strip() if not name: yield ( f"Please tell me which of the following plugins to reload:\n" f"{self.formatted_plugin_list(active_only=False)}" ) return if name not in self._bot.plugin_manager.get_all_plugin_names(): yield ( f"{name} isn't a valid plugin name. " f"The current plugins are:\n{self.formatted_plugin_list(active_only=False)}" ) return if name not in self._bot.plugin_manager.get_all_active_plugin_names(): answer = f"Warning: plugin {name} is currently not activated. " answer += f"Use `{self._bot.prefix}plugin activate {name}` to activate it." yield answer try: self._bot.plugin_manager.reload_plugin_by_name(name) yield f"Plugin {name} reloaded." except PluginActivationException as pae: yield f"Error activating plugin {name}: {pae}."
[ "def", "plugin_reload", "(", "self", ",", "_", ",", "args", ")", ":", "name", "=", "args", ".", "strip", "(", ")", "if", "not", "name", ":", "yield", "(", "f\"Please tell me which of the following plugins to reload:\\n\"", "f\"{self.formatted_plugin_list(active_only=F...
https://github.com/errbotio/errbot/blob/66e1de8e1d7daa62be7f9ed1b2ac8832f09fa25d/errbot/core_plugins/plugins.py#L229-L254
kuri65536/python-for-android
26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891
python3-alpha/python-libs/gdata/sites/client.py
python
SitesClient.get_revision_feed
(self, entry_or_uri_or_id, auth_token=None, **kwargs)
return self.get_feed(uri, desired_class=gdata.sites.data.RevisionFeed, auth_token=auth_token, **kwargs)
Retrieves the revision feed containing the revision history for a node. Args: entry_or_uri_or_id: string or gdata.sites.data.ContentEntry A full URI, content entry node ID, or a content entry object of the entry to retrieve revision information for. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. kwargs: Other parameters to pass to self.get_feed(). Returns: gdata.sites.data.RevisionFeed
Retrieves the revision feed containing the revision history for a node.
[ "Retrieves", "the", "revision", "feed", "containing", "the", "revision", "history", "for", "a", "node", "." ]
def get_revision_feed(self, entry_or_uri_or_id, auth_token=None, **kwargs): """Retrieves the revision feed containing the revision history for a node. Args: entry_or_uri_or_id: string or gdata.sites.data.ContentEntry A full URI, content entry node ID, or a content entry object of the entry to retrieve revision information for. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. kwargs: Other parameters to pass to self.get_feed(). Returns: gdata.sites.data.RevisionFeed """ uri = self.make_revision_feed_uri() if isinstance(entry_or_uri_or_id, gdata.sites.data.ContentEntry): uri = entry_or_uri_or_id.FindRevisionLink() elif entry_or_uri_or_id.find('/') == -1: uri += entry_or_uri_or_id else: uri = entry_or_uri_or_id return self.get_feed(uri, desired_class=gdata.sites.data.RevisionFeed, auth_token=auth_token, **kwargs)
[ "def", "get_revision_feed", "(", "self", ",", "entry_or_uri_or_id", ",", "auth_token", "=", "None", ",", "*", "*", "kwargs", ")", ":", "uri", "=", "self", ".", "make_revision_feed_uri", "(", ")", "if", "isinstance", "(", "entry_or_uri_or_id", ",", "gdata", "...
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python3-alpha/python-libs/gdata/sites/client.py#L159-L181
FSecureLABS/drozer
df11e6e63fbaefa9b58ed1e42533ddf76241d7e1
src/mwr/common/console.py
python
_get_size_linux
()
return int(cr[1]), int(cr[0])
Attempt to discover the dimensions of a terminal window, on Linux.
Attempt to discover the dimensions of a terminal window, on Linux.
[ "Attempt", "to", "discover", "the", "dimensions", "of", "a", "terminal", "window", "on", "Linux", "." ]
def _get_size_linux(): """ Attempt to discover the dimensions of a terminal window, on Linux. """ def ioctl_GWINSZ(fd): """ Attempt to discover the dimensions of a terminal window, using IOCTL. """ try: import fcntl, termios cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ,'1234')) except: return None return cr cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2) if not cr: try: fd = os.open(os.ctermid(), os.O_RDONLY) cr = ioctl_GWINSZ(fd) os.close(fd) except: pass if not cr: try: cr = (env['LINES'], env['COLUMNS']) except: return None return int(cr[1]), int(cr[0])
[ "def", "_get_size_linux", "(", ")", ":", "def", "ioctl_GWINSZ", "(", "fd", ")", ":", "\"\"\"\n Attempt to discover the dimensions of a terminal window, using IOCTL.\n \"\"\"", "try", ":", "import", "fcntl", ",", "termios", "cr", "=", "struct", ".", "unpack",...
https://github.com/FSecureLABS/drozer/blob/df11e6e63fbaefa9b58ed1e42533ddf76241d7e1/src/mwr/common/console.py#L106-L139
google/macops
8442745359c0c941cd4e4e7d243e43bd16b40dec
gmacpyutil/gmacpyutil/macdisk.py
python
MountedVolumes
()
return volumes
Returns a list of all Disk objects that are mounted volumes.
Returns a list of all Disk objects that are mounted volumes.
[ "Returns", "a", "list", "of", "all", "Disk", "objects", "that", "are", "mounted", "volumes", "." ]
def MountedVolumes(): """Returns a list of all Disk objects that are mounted volumes.""" volumes = [] volumenames = MountedVolumeNames() for partition in Partitions(): if partition.volumename in volumenames: volumes.append(partition) return volumes
[ "def", "MountedVolumes", "(", ")", ":", "volumes", "=", "[", "]", "volumenames", "=", "MountedVolumeNames", "(", ")", "for", "partition", "in", "Partitions", "(", ")", ":", "if", "partition", ".", "volumename", "in", "volumenames", ":", "volumes", ".", "ap...
https://github.com/google/macops/blob/8442745359c0c941cd4e4e7d243e43bd16b40dec/gmacpyutil/gmacpyutil/macdisk.py#L439-L446
Blizzard/heroprotocol
3d36eaf44fc4c8ff3331c2ae2f1dc08a94535f1c
heroprotocol/versions/protocol84249.py
python
decode_replay_tracker_events
(contents)
Decodes and yields each tracker event from the contents byte string.
Decodes and yields each tracker event from the contents byte string.
[ "Decodes", "and", "yields", "each", "tracker", "event", "from", "the", "contents", "byte", "string", "." ]
def decode_replay_tracker_events(contents): """Decodes and yields each tracker event from the contents byte string.""" decoder = VersionedDecoder(contents, typeinfos) for event in _decode_event_stream(decoder, tracker_eventid_typeid, tracker_event_types, decode_user_id=False): yield event
[ "def", "decode_replay_tracker_events", "(", "contents", ")", ":", "decoder", "=", "VersionedDecoder", "(", "contents", ",", "typeinfos", ")", "for", "event", "in", "_decode_event_stream", "(", "decoder", ",", "tracker_eventid_typeid", ",", "tracker_event_types", ",", ...
https://github.com/Blizzard/heroprotocol/blob/3d36eaf44fc4c8ff3331c2ae2f1dc08a94535f1c/heroprotocol/versions/protocol84249.py#L424-L431
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/packages/site-packages/sphinx/domains/cpp.py
python
ASTBase.prefix_nested_name
(self, prefix)
Prefix a name node (a node returned by :meth:`get_name`).
Prefix a name node (a node returned by :meth:`get_name`).
[ "Prefix", "a", "name", "node", "(", "a", "node", "returned", "by", ":", "meth", ":", "get_name", ")", "." ]
def prefix_nested_name(self, prefix): """Prefix a name node (a node returned by :meth:`get_name`).""" raise NotImplementedError(repr(self))
[ "def", "prefix_nested_name", "(", "self", ",", "prefix", ")", ":", "raise", "NotImplementedError", "(", "repr", "(", "self", ")", ")" ]
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/packages/site-packages/sphinx/domains/cpp.py#L527-L529
damnever/pigar
2a4f66c4a8125ffa30d5e11d1a0945b511ed1f79
pigar/core.py
python
search_packages_by_names
(names)
Search package information by names(`import XXX`).
Search package information by names(`import XXX`).
[ "Search", "package", "information", "by", "names", "(", "import", "XXX", ")", "." ]
def search_packages_by_names(names): """Search package information by names(`import XXX`). """ downloader = Downloader() results = collections.defaultdict(list) not_found = list() installed_pkgs = parse_installed_packages() for name in names: logger.debug('Searching package name for "{0}" ...'.format(name)) # If exists in local environment, do not check on the PyPI. if name in installed_pkgs: results[name].append(list(installed_pkgs[name]) + ['local']) # Check information on the PyPI. else: rows = None with database() as db: rows = db.query_all(name) if rows: for row in rows: try: version = downloader.download_package(row.package ).version() results[name].append((row.package, version, 'PyPI')) except HTTPError as e: logger.error('checking %s failed: %e', row.package, e) else: not_found.append(name) for name in results: print('Found package(s) for "{0}":'.format(Color.GREEN(name))) print_table(results[name], headers=['PACKAGE', 'VERSION', 'WHERE']) if not_found: msg = '"{0}" not found.\n'.format(Color.RED(', '.join(not_found))) msg += 'Maybe you need to update the database.' print(Color.YELLOW(msg))
[ "def", "search_packages_by_names", "(", "names", ")", ":", "downloader", "=", "Downloader", "(", ")", "results", "=", "collections", ".", "defaultdict", "(", "list", ")", "not_found", "=", "list", "(", ")", "installed_pkgs", "=", "parse_installed_packages", "(",...
https://github.com/damnever/pigar/blob/2a4f66c4a8125ffa30d5e11d1a0945b511ed1f79/pigar/core.py#L257-L292
Rayhane-mamah/Tacotron-2
ab5cb08a931fc842d3892ebeb27c8b8734ddd4b8
tacotron/models/tacotron.py
python
Tacotron.add_loss
(self)
Adds loss to the model. Sets "loss" field. initialize must have been called.
Adds loss to the model. Sets "loss" field. initialize must have been called.
[ "Adds", "loss", "to", "the", "model", ".", "Sets", "loss", "field", ".", "initialize", "must", "have", "been", "called", "." ]
def add_loss(self): '''Adds loss to the model. Sets "loss" field. initialize must have been called.''' hp = self._hparams self.tower_before_loss = [] self.tower_after_loss= [] self.tower_stop_token_loss = [] self.tower_regularization_loss = [] self.tower_linear_loss = [] self.tower_loss = [] total_before_loss = 0 total_after_loss= 0 total_stop_token_loss = 0 total_regularization_loss = 0 total_linear_loss = 0 total_loss = 0 gpus = ["/gpu:{}".format(i) for i in range(hp.tacotron_num_gpus)] for i in range(hp.tacotron_num_gpus): with tf.device(tf.train.replica_device_setter(ps_tasks=1, ps_device="/cpu:0", worker_device=gpus[i])): with tf.variable_scope('loss') as scope: if hp.mask_decoder: # Compute loss of predictions before postnet before = MaskedMSE(self.tower_mel_targets[i], self.tower_decoder_output[i], self.tower_targets_lengths[i], hparams=self._hparams) # Compute loss after postnet after = MaskedMSE(self.tower_mel_targets[i], self.tower_mel_outputs[i], self.tower_targets_lengths[i], hparams=self._hparams) #Compute <stop_token> loss (for learning dynamic generation stop) stop_token_loss = MaskedSigmoidCrossEntropy(self.tower_stop_token_targets[i], self.tower_stop_token_prediction[i], self.tower_targets_lengths[i], hparams=self._hparams) #Compute masked linear loss if hp.predict_linear: #Compute Linear L1 mask loss (priority to low frequencies) linear_loss = MaskedLinearLoss(self.tower_linear_targets[i], self.tower_linear_outputs[i], self.targets_lengths, hparams=self._hparams) else: linear_loss=0. else: # Compute loss of predictions before postnet before = tf.losses.mean_squared_error(self.tower_mel_targets[i], self.tower_decoder_output[i]) # Compute loss after postnet after = tf.losses.mean_squared_error(self.tower_mel_targets[i], self.tower_mel_outputs[i]) #Compute <stop_token> loss (for learning dynamic generation stop) stop_token_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits( labels=self.tower_stop_token_targets[i], logits=self.tower_stop_token_prediction[i])) if hp.predict_linear: #Compute linear loss #From https://github.com/keithito/tacotron/blob/tacotron2-work-in-progress/models/tacotron.py #Prioritize loss for frequencies under 2000 Hz. l1 = tf.abs(self.tower_linear_targets[i] - self.tower_linear_outputs[i]) n_priority_freq = int(2000 / (hp.sample_rate * 0.5) * hp.num_freq) linear_loss = 0.5 * tf.reduce_mean(l1) + 0.5 * tf.reduce_mean(l1[:,:,0:n_priority_freq]) else: linear_loss = 0. # Compute the regularization weight if hp.tacotron_scale_regularization: reg_weight_scaler = 1. / (2 * hp.max_abs_value) if hp.symmetric_mels else 1. / (hp.max_abs_value) reg_weight = hp.tacotron_reg_weight * reg_weight_scaler else: reg_weight = hp.tacotron_reg_weight # Regularize variables # Exclude all types of bias, RNN (Bengio et al. On the difficulty of training recurrent neural networks), embeddings and prediction projection layers. # Note that we consider attention mechanism v_a weights as a prediction projection layer and we don't regularize it. (This gave better stability) regularization = tf.add_n([tf.nn.l2_loss(v) for v in self.all_vars if not('bias' in v.name or 'Bias' in v.name or '_projection' in v.name or 'inputs_embedding' in v.name or 'RNN' in v.name or 'LSTM' in v.name)]) * reg_weight # Compute final loss term self.tower_before_loss.append(before) self.tower_after_loss.append(after) self.tower_stop_token_loss.append(stop_token_loss) self.tower_regularization_loss.append(regularization) self.tower_linear_loss.append(linear_loss) tower_loss = before + after + stop_token_loss + regularization + linear_loss self.tower_loss.append(tower_loss) total_before_loss += before total_after_loss += after total_stop_token_loss += stop_token_loss total_regularization_loss += regularization total_linear_loss += linear_loss total_loss += tower_loss self.before_loss = total_before_loss / hp.tacotron_num_gpus self.after_loss = total_after_loss / hp.tacotron_num_gpus self.stop_token_loss = total_stop_token_loss / hp.tacotron_num_gpus self.regularization_loss = total_regularization_loss / hp.tacotron_num_gpus self.linear_loss = total_linear_loss / hp.tacotron_num_gpus self.loss = total_loss / hp.tacotron_num_gpus
[ "def", "add_loss", "(", "self", ")", ":", "hp", "=", "self", ".", "_hparams", "self", ".", "tower_before_loss", "=", "[", "]", "self", ".", "tower_after_loss", "=", "[", "]", "self", ".", "tower_stop_token_loss", "=", "[", "]", "self", ".", "tower_regula...
https://github.com/Rayhane-mamah/Tacotron-2/blob/ab5cb08a931fc842d3892ebeb27c8b8734ddd4b8/tacotron/models/tacotron.py#L273-L369
JulianEberius/SublimePythonIDE
d70e40abc0c9f347af3204c7b910e0d6bfd6e459
server/lib/python2/rope/base/libutils.py
python
analyze_modules
(project, task_handle=taskhandle.NullTaskHandle())
Perform static object analysis on all python files in the project Note that this might be really time consuming.
Perform static object analysis on all python files in the project
[ "Perform", "static", "object", "analysis", "on", "all", "python", "files", "in", "the", "project" ]
def analyze_modules(project, task_handle=taskhandle.NullTaskHandle()): """Perform static object analysis on all python files in the project Note that this might be really time consuming. """ resources = project.pycore.get_python_files() job_set = task_handle.create_jobset('Analyzing Modules', len(resources)) for resource in resources: job_set.started_job(resource.path) project.pycore.analyze_module(resource) job_set.finished_job()
[ "def", "analyze_modules", "(", "project", ",", "task_handle", "=", "taskhandle", ".", "NullTaskHandle", "(", ")", ")", ":", "resources", "=", "project", ".", "pycore", ".", "get_python_files", "(", ")", "job_set", "=", "task_handle", ".", "create_jobset", "(",...
https://github.com/JulianEberius/SublimePythonIDE/blob/d70e40abc0c9f347af3204c7b910e0d6bfd6e459/server/lib/python2/rope/base/libutils.py#L55-L65
nvaccess/nvda
20d5a25dced4da34338197f0ef6546270ebca5d0
source/gui/guiHelper.py
python
BoxSizerHelper.addLabeledControl
(self, labelText, wxCtrlClass, **kwargs)
return labeledControl.control
Convenience method to create a labeled control @param labelText: Text to use when constructing the wx.StaticText to label the control. @type LabelText: String @param wxCtrlClass: Control class to construct and associate with the label @type wxCtrlClass: Some wx control type EG wx.TextCtrl @param kwargs: keyword arguments used to construct the wxCtrlClass. As taken by guiHelper.LabeledControlHelper Relies on guiHelper.LabeledControlHelper and thus guiHelper.associateElements, and therefore inherits any limitations from there.
Convenience method to create a labeled control @param labelText: Text to use when constructing the wx.StaticText to label the control. @type LabelText: String @param wxCtrlClass: Control class to construct and associate with the label @type wxCtrlClass: Some wx control type EG wx.TextCtrl @param kwargs: keyword arguments used to construct the wxCtrlClass. As taken by guiHelper.LabeledControlHelper
[ "Convenience", "method", "to", "create", "a", "labeled", "control", "@param", "labelText", ":", "Text", "to", "use", "when", "constructing", "the", "wx", ".", "StaticText", "to", "label", "the", "control", ".", "@type", "LabelText", ":", "String", "@param", ...
def addLabeledControl(self, labelText, wxCtrlClass, **kwargs): """ Convenience method to create a labeled control @param labelText: Text to use when constructing the wx.StaticText to label the control. @type LabelText: String @param wxCtrlClass: Control class to construct and associate with the label @type wxCtrlClass: Some wx control type EG wx.TextCtrl @param kwargs: keyword arguments used to construct the wxCtrlClass. As taken by guiHelper.LabeledControlHelper Relies on guiHelper.LabeledControlHelper and thus guiHelper.associateElements, and therefore inherits any limitations from there. """ parent = self._parent if isinstance(self.sizer, wx.StaticBoxSizer): parent = self.sizer.GetStaticBox() labeledControl = LabeledControlHelper(parent, labelText, wxCtrlClass, **kwargs) if(isinstance(labeledControl.control, (wx.ListCtrl,wx.ListBox,wx.TreeCtrl))): self.addItem(labeledControl.sizer, flag=wx.EXPAND, proportion=1) else: self.addItem(labeledControl.sizer) return labeledControl.control
[ "def", "addLabeledControl", "(", "self", ",", "labelText", ",", "wxCtrlClass", ",", "*", "*", "kwargs", ")", ":", "parent", "=", "self", ".", "_parent", "if", "isinstance", "(", "self", ".", "sizer", ",", "wx", ".", "StaticBoxSizer", ")", ":", "parent", ...
https://github.com/nvaccess/nvda/blob/20d5a25dced4da34338197f0ef6546270ebca5d0/source/gui/guiHelper.py#L318-L337
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
src/transformers/trainer_tf.py
python
TFTrainer.setup_comet
(self)
Setup the optional Comet.ml integration. Environment: COMET_MODE: (Optional): str - "OFFLINE", "ONLINE", or "DISABLED" COMET_PROJECT_NAME: (Optional): str - Comet.ml project name for experiments COMET_OFFLINE_DIRECTORY: (Optional): str - folder to use for saving offline experiments when `COMET_MODE` is "OFFLINE" For a number of configurable items in the environment, see `here <https://www.comet.ml/docs/python-sdk/advanced/#comet-configuration-variables>`__
Setup the optional Comet.ml integration.
[ "Setup", "the", "optional", "Comet", ".", "ml", "integration", "." ]
def setup_comet(self): """ Setup the optional Comet.ml integration. Environment: COMET_MODE: (Optional): str - "OFFLINE", "ONLINE", or "DISABLED" COMET_PROJECT_NAME: (Optional): str - Comet.ml project name for experiments COMET_OFFLINE_DIRECTORY: (Optional): str - folder to use for saving offline experiments when `COMET_MODE` is "OFFLINE" For a number of configurable items in the environment, see `here <https://www.comet.ml/docs/python-sdk/advanced/#comet-configuration-variables>`__ """ comet_mode = os.getenv("COMET_MODE", "ONLINE").upper() args = {"project_name": os.getenv("COMET_PROJECT_NAME", "huggingface")} experiment = None if comet_mode == "ONLINE": experiment = comet_ml.Experiment(**args) logger.info("Automatic Comet.ml online logging enabled") elif comet_mode == "OFFLINE": args["offline_directory"] = os.getenv("COMET_OFFLINE_DIRECTORY", "./") experiment = comet_ml.OfflineExperiment(**args) logger.info("Automatic Comet.ml offline logging enabled; use `comet upload` when finished") if experiment is not None: experiment._set_model_graph(self.model, framework="transformers") experiment._log_parameters(self.args, prefix="args/", framework="transformers") experiment._log_parameters(self.model.config, prefix="config/", framework="transformers")
[ "def", "setup_comet", "(", "self", ")", ":", "comet_mode", "=", "os", ".", "getenv", "(", "\"COMET_MODE\"", ",", "\"ONLINE\"", ")", ".", "upper", "(", ")", "args", "=", "{", "\"project_name\"", ":", "os", ".", "getenv", "(", "\"COMET_PROJECT_NAME\"", ",", ...
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/trainer_tf.py#L265-L293
O365/python-o365
7f77005c3cee8177d0141e79b8eda8a7b60c5124
O365/address_book.py
python
Contact.business_address
(self)
return self.__business_address
Business Address :getter: Get the address of contact :setter: Update the address :type: dict
Business Address
[ "Business", "Address" ]
def business_address(self): """ Business Address :getter: Get the address of contact :setter: Update the address :type: dict """ return self.__business_address
[ "def", "business_address", "(", "self", ")", ":", "return", "self", ".", "__business_address" ]
https://github.com/O365/python-o365/blob/7f77005c3cee8177d0141e79b8eda8a7b60c5124/O365/address_book.py#L341-L348
microsoft/unilm
65f15af2a307ebb64cfb25adf54375b002e6fe8d
beit/dataset_folder.py
python
has_file_allowed_extension
(filename: str, extensions: Tuple[str, ...])
return filename.lower().endswith(extensions)
Checks if a file is an allowed extension. Args: filename (string): path to a file extensions (tuple of strings): extensions to consider (lowercase) Returns: bool: True if the filename ends with one of given extensions
Checks if a file is an allowed extension.
[ "Checks", "if", "a", "file", "is", "an", "allowed", "extension", "." ]
def has_file_allowed_extension(filename: str, extensions: Tuple[str, ...]) -> bool: """Checks if a file is an allowed extension. Args: filename (string): path to a file extensions (tuple of strings): extensions to consider (lowercase) Returns: bool: True if the filename ends with one of given extensions """ return filename.lower().endswith(extensions)
[ "def", "has_file_allowed_extension", "(", "filename", ":", "str", ",", "extensions", ":", "Tuple", "[", "str", ",", "...", "]", ")", "->", "bool", ":", "return", "filename", ".", "lower", "(", ")", ".", "endswith", "(", "extensions", ")" ]
https://github.com/microsoft/unilm/blob/65f15af2a307ebb64cfb25adf54375b002e6fe8d/beit/dataset_folder.py#L20-L30
jabbalaci/Bash-Utils
c6fb115834a221c4aaba8eaa37f650beea45ef29
lib/jhash.py
python
str_to_base64
(s)
return data.decode()
>>> str_to_base64("László") 'TMOhc3psw7M='
>>> str_to_base64("László") 'TMOhc3psw7M='
[ ">>>", "str_to_base64", "(", "László", ")", "TMOhc3psw7M", "=" ]
def str_to_base64(s): """ >>> str_to_base64("László") 'TMOhc3psw7M=' """ data = base64.b64encode(s.encode()) return data.decode()
[ "def", "str_to_base64", "(", "s", ")", ":", "data", "=", "base64", ".", "b64encode", "(", "s", ".", "encode", "(", ")", ")", "return", "data", ".", "decode", "(", ")" ]
https://github.com/jabbalaci/Bash-Utils/blob/c6fb115834a221c4aaba8eaa37f650beea45ef29/lib/jhash.py#L83-L89