code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def on_service_arrival(self, svc_ref):
"""
Called when a service has been registered in the framework
:param svc_ref: A service reference
"""
with self._lock:
if svc_ref not in self.services:
# Get the key property
prop_value = svc_ref... | Called when a service has been registered in the framework
:param svc_ref: A service reference |
def _validate_allof(self, definitions, field, value):
""" {'type': 'list', 'logical': 'allof'} """
valids, _errors = \
self.__validate_logical('allof', definitions, field, value)
if valids < len(definitions):
self._error(field, errors.ALLOF, _errors,
... | {'type': 'list', 'logical': 'allof'} |
def update_ipsec_site_connection(self, ipsecsite_conn, body=None):
"""Updates an IPsecSiteConnection."""
return self.put(
self.ipsec_site_connection_path % (ipsecsite_conn), body=body
) | Updates an IPsecSiteConnection. |
def set_select(self, select_or_deselect = 'select', value=None, text=None, index=None):
"""
Private method used by select methods
@type select_or_deselect: str
@param select_or_deselect: Should I select or deselect the element
@type value: str
@type val... | Private method used by select methods
@type select_or_deselect: str
@param select_or_deselect: Should I select or deselect the element
@type value: str
@type value: Value to be selected
@type text: str
@type text: ... |
def to_user(user):
"""Serializes user to id string
:param user: object to serialize
:return: string id
"""
from sevenbridges.models.user import User
if not user:
raise SbgError('User is required!')
elif isinstance(user, User):
return user.u... | Serializes user to id string
:param user: object to serialize
:return: string id |
def get(self, name, section=None, fallback=False):
"""
Returns a previously registered preference
:param section: The section name under which the preference is registered
:type section: str.
:param name: The name of the preference. You can use dotted notation 'section.name' if ... | Returns a previously registered preference
:param section: The section name under which the preference is registered
:type section: str.
:param name: The name of the preference. You can use dotted notation 'section.name' if you want to avoid providing section param
:type name: str.
... |
def _area(sma, eps, phi, r):
"""
Compute elliptical sector area.
"""
aux = r * math.cos(phi) / sma
signal = aux / abs(aux)
if abs(aux) >= 1.:
aux = signal
return abs(sma**2 * (1.-eps) / 2. * math.acos(aux)) | Compute elliptical sector area. |
def create_pax_header(self, info, encoding):
"""Return the object as a ustar header block. If it cannot be
represented this way, prepend a pax extended header sequence
with supplement information.
"""
info["magic"] = POSIX_MAGIC
pax_headers = self.pax_headers.copy()... | Return the object as a ustar header block. If it cannot be
represented this way, prepend a pax extended header sequence
with supplement information. |
def join(self, right, on=None, how='inner'):
"""
Merge two SFrames. Merges the current (left) SFrame with the given
(right) SFrame using a SQL-style equi-join operation by columns.
Parameters
----------
right : SFrame
The SFrame to join.
on : None | ... | Merge two SFrames. Merges the current (left) SFrame with the given
(right) SFrame using a SQL-style equi-join operation by columns.
Parameters
----------
right : SFrame
The SFrame to join.
on : None | str | list | dict, optional
The column name(s) repres... |
def requires_list(self):
"""
It is important that this property is calculated lazily. Getting the
'requires' attribute may trigger a package load, which may be avoided if
this variant is reduced away before that happens.
"""
requires = self.variant.get_requires(build_requ... | It is important that this property is calculated lazily. Getting the
'requires' attribute may trigger a package load, which may be avoided if
this variant is reduced away before that happens. |
def save_history(self):
"""Save history to a text file in user home directory"""
open(self.LOG_PATH, 'w').write("\n".join( \
[to_text_string(self.pydocbrowser.url_combo.itemText(index))
for index in range(self.pydocbrowser.url_combo.count())])) | Save history to a text file in user home directory |
def from_dict(cls, d):
"""
Construct a MSONable AdfKey object from the JSON dict.
Parameters
----------
d : dict
A dict of saved attributes.
Returns
-------
adfkey : AdfKey
An AdfKey object recovered from the JSON dict ``d``.
... | Construct a MSONable AdfKey object from the JSON dict.
Parameters
----------
d : dict
A dict of saved attributes.
Returns
-------
adfkey : AdfKey
An AdfKey object recovered from the JSON dict ``d``. |
def connect(self, protocol=None, mode=None, disposition=None):
"""Connect to the card.
If protocol is not specified, connect with the default
connection protocol.
If mode is not specified, connect with SCARD_SHARE_SHARED."""
CardConnection.connect(self, protocol)
pcscpr... | Connect to the card.
If protocol is not specified, connect with the default
connection protocol.
If mode is not specified, connect with SCARD_SHARE_SHARED. |
def add_chapter(self, title):
'''
Adds a new chapter to the report.
:param str title: Title of the chapter.
'''
chap_id = 'chap%s' % self.chap_counter
self.chap_counter += 1
self.sidebar += '<a href="#%s" class="list-group-item">%s</a>\n' % (
chap_id,... | Adds a new chapter to the report.
:param str title: Title of the chapter. |
def rlmb_tiny_recurrent():
"""Tiny setting with a recurrent next-frame model."""
hparams = rlmb_ppo_tiny()
hparams.epochs = 1 # Too slow with 2 for regular runs.
hparams.generative_model = "next_frame_basic_recurrent"
hparams.generative_model_params = "next_frame_basic_recurrent"
return hparams | Tiny setting with a recurrent next-frame model. |
def commit_account_vesting(self, block_height):
"""
vest any tokens at this block height
"""
# save all state
log.debug("Commit all database state before vesting")
self.db.commit()
if block_height in self.vesting:
traceback.print_stack()
l... | vest any tokens at this block height |
def _initialize_global_state(self,
redis_address,
redis_password=None,
timeout=20):
"""Initialize the GlobalState object by connecting to Redis.
It's possible that certain keys in Redis may not have been ... | Initialize the GlobalState object by connecting to Redis.
It's possible that certain keys in Redis may not have been fully
populated yet. In this case, we will retry this method until they have
been populated or we exceed a timeout.
Args:
redis_address: The Redis address to... |
def call_method(self, service, path, interface, method, signature=None,
args=None, no_reply=False, auto_start=False, timeout=-1):
"""Call a D-BUS method and wait for its reply.
This method calls the D-BUS method with name *method* that resides on
the object at bus address *s... | Call a D-BUS method and wait for its reply.
This method calls the D-BUS method with name *method* that resides on
the object at bus address *service*, at path *path*, on interface
*interface*.
The *signature* and *args* are optional arguments that can be used to
add parameters ... |
def mark_locations(h,section,locs,markspec='or',**kwargs):
"""
Marks one or more locations on along a section. Could be used to
mark the location of a recording or electrical stimulation.
Args:
h = hocObject to interface with neuron
section = reference to section
locs = float be... | Marks one or more locations on along a section. Could be used to
mark the location of a recording or electrical stimulation.
Args:
h = hocObject to interface with neuron
section = reference to section
locs = float between 0 and 1, or array of floats
optional arguments specify de... |
def get_trips(self, timestamp, start, via, destination, departure=True, prev_advices=1, next_advices=1):
"""
Fetch trip possibilities for these parameters
http://webservices.ns.nl/ns-api-treinplanner?<parameters>
fromStation
toStation
dateTime: 2012-02-21T15:50
de... | Fetch trip possibilities for these parameters
http://webservices.ns.nl/ns-api-treinplanner?<parameters>
fromStation
toStation
dateTime: 2012-02-21T15:50
departure: true for starting at timestamp, false for arriving at timestamp
previousAdvices
nextAdvices |
def get_state(self, force_update=False):
"""
Returns 0 if off and 1 if on.
"""
if force_update or self._state is None:
return int(self.basicevent.GetBinaryState()['BinaryState'])
return self._state | Returns 0 if off and 1 if on. |
def get_conversation(self, conversation, **kwargs):
"""
Return single Conversation
:calls: `GET /api/v1/conversations/:id \
<https://canvas.instructure.com/doc/api/conversations.html#method.conversations.show>`_
:param conversation: The object or ID of the conversation.
... | Return single Conversation
:calls: `GET /api/v1/conversations/:id \
<https://canvas.instructure.com/doc/api/conversations.html#method.conversations.show>`_
:param conversation: The object or ID of the conversation.
:type conversation: :class:`canvasapi.conversation.Conversation` or int... |
def reloaded(name, jboss_config, timeout=60, interval=5):
'''
Reloads configuration of jboss server.
jboss_config:
Dict with connection properties (see state description)
timeout:
Time to wait until jboss is back in running state. Default timeout is 60s.
interval:
Interval b... | Reloads configuration of jboss server.
jboss_config:
Dict with connection properties (see state description)
timeout:
Time to wait until jboss is back in running state. Default timeout is 60s.
interval:
Interval between state checks. Default interval is 5s. Decreasing the interval m... |
def __set_variable_watch(self, tid, address, size, action):
"""
Used by L{watch_variable} and L{stalk_variable}.
@type tid: int
@param tid: Thread global ID.
@type address: int
@param address: Memory address of variable to watch.
@type size: int
@par... | Used by L{watch_variable} and L{stalk_variable}.
@type tid: int
@param tid: Thread global ID.
@type address: int
@param address: Memory address of variable to watch.
@type size: int
@param size: Size of variable to watch. The only supported sizes are:
by... |
def _check_exclude(self, val):
"""
Validate the excluded metrics. Returns the set of excluded params.
"""
if val is None:
exclude = frozenset()
elif isinstance(val, str):
exclude = frozenset([val.lower()])
else:
exclude = frozenset(map(... | Validate the excluded metrics. Returns the set of excluded params. |
async def _dump_variant(self, writer, elem, elem_type=None, params=None):
"""
Dumps variant type to the writer.
Supports both wrapped and raw variant.
:param writer:
:param elem:
:param elem_type:
:param params:
:return:
"""
if isinstance(... | Dumps variant type to the writer.
Supports both wrapped and raw variant.
:param writer:
:param elem:
:param elem_type:
:param params:
:return: |
def gaussian_polygons(points, n=10):
"""
Returns an array of approximately `n` `shapely.geometry.Polygon` objects for an array of `shapely.geometry.Point`
objects.
"""
gdf = gpd.GeoDataFrame(data={'cluster_number': classify_clusters(points, n=n)}, geometry=points)
polygons = []
for i in rang... | Returns an array of approximately `n` `shapely.geometry.Polygon` objects for an array of `shapely.geometry.Point`
objects. |
def ShowInfo(self):
"""Shows information about available hashers, parsers, plugins, etc."""
self._output_writer.Write(
'{0:=^80s}\n'.format(' log2timeline/plaso information '))
plugin_list = self._GetPluginData()
for header, data in plugin_list.items():
table_view = views.ViewsFactory.Get... | Shows information about available hashers, parsers, plugins, etc. |
def resolveWithMib(self, mibViewController):
"""Perform MIB variable ID and associated value conversion.
Parameters
----------
mibViewController : :py:class:`~pysnmp.smi.view.MibViewController`
class instance representing MIB browsing functionality.
Returns
... | Perform MIB variable ID and associated value conversion.
Parameters
----------
mibViewController : :py:class:`~pysnmp.smi.view.MibViewController`
class instance representing MIB browsing functionality.
Returns
-------
: :py:class:`~pysnmp.smi.rfc1902.ObjectT... |
def new_app(self, App, prefix=None, callable=None, **params):
"""Invoke this method in the :meth:`build` method as many times
as the number of :class:`Application` required by this
:class:`MultiApp`.
:param App: an :class:`Application` class.
:param prefix: The prefix to use for... | Invoke this method in the :meth:`build` method as many times
as the number of :class:`Application` required by this
:class:`MultiApp`.
:param App: an :class:`Application` class.
:param prefix: The prefix to use for the application,
the prefix is appended to
the a... |
def main():
"""Writes out newsfile if significant version bump"""
last_known = '0'
if os.path.isfile(metafile):
with open(metafile) as fh:
last_known = fh.read()
import mbed_cloud
current = mbed_cloud.__version__
# how significant a change in version scheme should trigger a... | Writes out newsfile if significant version bump |
def _remove_unicode_keys(dictobj):
"""Convert keys from 'unicode' to 'str' type.
workaround for <http://bugs.python.org/issue2646>
"""
if sys.version_info[:2] >= (3, 0): return dictobj
assert isinstance(dictobj, dict)
newdict = {}
for key, value in dictobj.items():
if type(key) is... | Convert keys from 'unicode' to 'str' type.
workaround for <http://bugs.python.org/issue2646> |
def post_license_request(request):
"""Submission to create a license acceptance request."""
uuid_ = request.matchdict['uuid']
posted_data = request.json
license_url = posted_data.get('license_url')
licensors = posted_data.get('licensors', [])
with db_connect() as db_conn:
with db_conn.c... | Submission to create a license acceptance request. |
def begin_data_item_live(self, data_item):
"""Begins a live state for the data item.
The live state is propagated to dependent data items.
This method is thread safe. See slow_test_dependent_data_item_removed_while_live_data_item_becomes_unlive.
"""
with self.__live_data_items_... | Begins a live state for the data item.
The live state is propagated to dependent data items.
This method is thread safe. See slow_test_dependent_data_item_removed_while_live_data_item_becomes_unlive. |
def clean_all(self, config_file, region=None, profile_name=None):
"""
Clean all provisioned artifacts from both the local file and the AWS
Greengrass service.
:param config_file: config file containing the group to clean
:param region: the region in which the group should be cle... | Clean all provisioned artifacts from both the local file and the AWS
Greengrass service.
:param config_file: config file containing the group to clean
:param region: the region in which the group should be cleaned.
[default: us-west-2]
:param profile_name: the name of the `a... |
def prep_for_deserialize(model, record, using, init_list=None): # pylint:disable=unused-argument
"""
Convert a record from SFDC (decoded JSON) to dict(model string, pk, fields)
If fixes fields of some types. If names of required fields `init_list `are
specified, then only these fields are processed.
... | Convert a record from SFDC (decoded JSON) to dict(model string, pk, fields)
If fixes fields of some types. If names of required fields `init_list `are
specified, then only these fields are processed. |
def annotate_snv(adpter, variant):
"""Annotate an SNV/INDEL variant
Args:
adapter(loqusdb.plugin.adapter)
variant(cyvcf2.Variant)
"""
variant_id = get_variant_id(variant)
variant_obj = adapter.get_variant(variant={'_id':variant_id})
annotated_variant = annotated_variant... | Annotate an SNV/INDEL variant
Args:
adapter(loqusdb.plugin.adapter)
variant(cyvcf2.Variant) |
def _is_child_wikicode(self, obj, recursive=True):
"""Return whether the given :class:`.Wikicode` is a descendant."""
def deref(nodes):
if isinstance(nodes, _ListProxy):
return nodes._parent # pylint: disable=protected-access
return nodes
target = deref(... | Return whether the given :class:`.Wikicode` is a descendant. |
def do_commander(self):
"""! @brief Handle 'commander' subcommand."""
# Flatten commands list then extract primary command and its arguments.
if self._args.commands is not None:
cmds = []
for cmd in self._args.commands:
cmds.append(flatten_args(split_comma... | ! @brief Handle 'commander' subcommand. |
def _match_tags(repex_tags, path_tags):
"""Check for matching tags between what the user provided
and the tags set in the config.
If `any` is chosen, match.
If no tags are chosen and none are configured, match.
If the user provided tags match any of the configured tags, match.
"""
if 'any' ... | Check for matching tags between what the user provided
and the tags set in the config.
If `any` is chosen, match.
If no tags are chosen and none are configured, match.
If the user provided tags match any of the configured tags, match. |
def send_message(self, *args, **kwargs):
"""See :func:`send_message`"""
return send_message(*args, **self._merge_overrides(**kwargs)).run() | See :func:`send_message` |
def header(self):
'''
Displays the scan header, as defined by self.HEADER and self.HEADER_FORMAT.
Returns None.
'''
self.config.display.format_strings(self.HEADER_FORMAT, self.RESULT_FORMAT)
self.config.display.add_custom_header(self.VERBOSE_FORMAT, self.VERBOSE)
... | Displays the scan header, as defined by self.HEADER and self.HEADER_FORMAT.
Returns None. |
def set_window_option(self, option, value):
"""
Wrapper for ``$ tmux set-window-option <option> <value>``.
Parameters
----------
option : str
option to set, e.g. 'aggressive-resize'
value : str
window option value. True/False will turn in 'on' and... | Wrapper for ``$ tmux set-window-option <option> <value>``.
Parameters
----------
option : str
option to set, e.g. 'aggressive-resize'
value : str
window option value. True/False will turn in 'on' and 'off',
also accepts string of 'on' or 'off' directl... |
def save(self, exclude_scopes: tuple = ('Optimizer',)) -> None:
"""Save model parameters to self.save_path"""
if not hasattr(self, 'sess'):
raise RuntimeError('Your TensorFlow model {} must'
' have sess attribute!'.format(self.__class__.__name__))
path ... | Save model parameters to self.save_path |
def gen_colors(img):
"""Format the output from imagemagick into a list
of hex colors."""
magick_command = has_im()
for i in range(0, 20, 1):
raw_colors = imagemagick(16 + i, img, magick_command)
if len(raw_colors) > 16:
break
elif i == 19:
logging.er... | Format the output from imagemagick into a list
of hex colors. |
def sanity_check_execution_spec(execution_spec):
"""
Sanity checks a execution_spec dict, used to define execution logic (distributed vs single, shared memories, etc..)
and distributed learning behavior of agents/models.
Throws an error or warns if mismatches are found.
Args:
execution_spec... | Sanity checks a execution_spec dict, used to define execution logic (distributed vs single, shared memories, etc..)
and distributed learning behavior of agents/models.
Throws an error or warns if mismatches are found.
Args:
execution_spec (Union[None,dict]): The spec-dict to check (or None). Dict n... |
def within_miles(self, key, point, max_distance, min_distance=None):
"""
增加查询条件,限制返回结果指定字段值的位置在某点的一段距离之内。
:param key: 查询条件字段名
:param point: 查询地理位置
:param max_distance: 最大距离限定(英里)
:param min_distance: 最小距离限定(英里)
:rtype: Query
"""
if min_distance is... | 增加查询条件,限制返回结果指定字段值的位置在某点的一段距离之内。
:param key: 查询条件字段名
:param point: 查询地理位置
:param max_distance: 最大距离限定(英里)
:param min_distance: 最小距离限定(英里)
:rtype: Query |
def get_distributed_seismicity_source_nodes(source):
"""
Returns list of nodes of attributes common to all distributed seismicity
source classes
:param source:
Seismic source as instance of :class:
`openquake.hazardlib.source.area.AreaSource` or :class:
`openquake.hazardlib.sour... | Returns list of nodes of attributes common to all distributed seismicity
source classes
:param source:
Seismic source as instance of :class:
`openquake.hazardlib.source.area.AreaSource` or :class:
`openquake.hazardlib.source.point.PointSource`
:returns:
List of instances of ... |
def print_update(self):
"""
print some status information in between.
"""
print("\r\n")
now = datetime.datetime.now()
print("Update info: (from: %s)" % now.strftime("%c"))
current_total_size = self.total_stined_bytes + self.total_new_bytes
if self.total_... | print some status information in between. |
def get_id(self, grp):
"""
Return a hash of the tuple of indices that specify the group
"""
thehash = hex(hash(grp))
if ISPY3: # use default encoding to get bytes
thehash = thehash.encode()
return self.cache.get(grp, hashlib.sha1(thehash).hexdigest()) | Return a hash of the tuple of indices that specify the group |
def get_versioning_status(self, headers=None):
"""
Returns the current status of versioning on the bucket.
:rtype: dict
:returns: A dictionary containing a key named 'Versioning'
that can have a value of either Enabled, Disabled,
or Suspended. Also, i... | Returns the current status of versioning on the bucket.
:rtype: dict
:returns: A dictionary containing a key named 'Versioning'
that can have a value of either Enabled, Disabled,
or Suspended. Also, if MFADelete has ever been enabled
on the bucket, ... |
def _co_moving2angle(self, x, y, idex):
"""
transforms co-moving distances Mpc into angles on the sky (radian)
:param x: co-moving distance
:param y: co-moving distance
:param z_lens: redshift of plane
:return: angles on the sky
"""
T_z = self._T_z_list[i... | transforms co-moving distances Mpc into angles on the sky (radian)
:param x: co-moving distance
:param y: co-moving distance
:param z_lens: redshift of plane
:return: angles on the sky |
def install_builtin (translator, do_unicode):
"""Install _() and _n() gettext methods into default namespace."""
try:
import __builtin__ as builtins
except ImportError:
# Python 3
import builtins
# Python 3 has no ugettext
has_unicode = hasattr(translator, 'ugettext')
if ... | Install _() and _n() gettext methods into default namespace. |
async def bluetooth(dev: Device, target, value):
"""Get or set bluetooth settings."""
if target and value:
await dev.set_bluetooth_settings(target, value)
print_settings(await dev.get_bluetooth_settings()) | Get or set bluetooth settings. |
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Write the data encoding the KeyWrappingSpecification struct to a
stream.
Args:
output_stream (stream): A data stream in which to encode object
data, supporting a write method; usuall... | Write the data encoding the KeyWrappingSpecification struct to a
stream.
Args:
output_stream (stream): A data stream in which to encode object
data, supporting a write method; usually a BytearrayStream
object.
kmip_version (KMIPVersion): An enumer... |
def add_external_path(self, path):
"""
Adds an external path to the combobox if it exists on the file system.
If the path is already listed in the combobox, it is removed from its
current position and added back at the end. If the maximum number of
paths is reached, the olde... | Adds an external path to the combobox if it exists on the file system.
If the path is already listed in the combobox, it is removed from its
current position and added back at the end. If the maximum number of
paths is reached, the oldest external path is removed from the list. |
def difference_of_pandas_dfs(df_self, df_other, col_names=None):
"""
Returns a dataframe with all of df_other that are not in df_self, when considering the columns specified in col_names
:param df_self: pandas Dataframe
:param df_other: pandas Dataframe
:param col_names: list of column names
:re... | Returns a dataframe with all of df_other that are not in df_self, when considering the columns specified in col_names
:param df_self: pandas Dataframe
:param df_other: pandas Dataframe
:param col_names: list of column names
:return: |
def _format_date(self, obj) -> str:
"""
Short date format.
:param obj: date or datetime or None
:return: str
"""
if obj is None:
return ''
if isinstance(obj, datetime):
obj = obj.date()
return date_format(obj, 'SHORT_DATE_FORMAT') | Short date format.
:param obj: date or datetime or None
:return: str |
def _reprJSON(self):
"""Returns a JSON serializable represenation of a ``Ci`` class instance.
Use :func:`maspy.core.Ci._fromJSON()` to generate a new ``Ci`` instance
from the return value.
:returns: a JSON serializable python object
"""
return {'__Ci__': (self.id, self.s... | Returns a JSON serializable represenation of a ``Ci`` class instance.
Use :func:`maspy.core.Ci._fromJSON()` to generate a new ``Ci`` instance
from the return value.
:returns: a JSON serializable python object |
def getAverageBuildDuration(self, package, **kwargs):
"""
Return a timedelta that Koji considers to be average for this package.
Calls "getAverageBuildDuration" XML-RPC.
:param package: ``str``, for example "ceph"
:returns: deferred that when fired returns a datetime object for... | Return a timedelta that Koji considers to be average for this package.
Calls "getAverageBuildDuration" XML-RPC.
:param package: ``str``, for example "ceph"
:returns: deferred that when fired returns a datetime object for the
estimated duration, or None if we could find no est... |
def add_layer_to_canvas(layer, name):
"""Helper method to add layer to QGIS.
:param layer: The layer.
:type layer: QgsMapLayer
:param name: Layer name.
:type name: str
"""
if qgis_version() >= 21800:
layer.setName(name)
else:
layer.setLayerName(name)
QgsProject.in... | Helper method to add layer to QGIS.
:param layer: The layer.
:type layer: QgsMapLayer
:param name: Layer name.
:type name: str |
def CROSS(A, B):
"""A<B then A>B A上穿B B下穿A
Arguments:
A {[type]} -- [description]
B {[type]} -- [description]
Returns:
[type] -- [description]
"""
var = np.where(A < B, 1, 0)
return (pd.Series(var, index=A.index).diff() < 0).apply(int) | A<B then A>B A上穿B B下穿A
Arguments:
A {[type]} -- [description]
B {[type]} -- [description]
Returns:
[type] -- [description] |
def as_xml(self,parent):
"""Create vcard-tmp XML representation of the field.
:Parameters:
- `parent`: parent node for the element
:Types:
- `parent`: `libxml2.xmlNode`
:return: xml node with the field data.
:returntype: `libxml2.xmlNode`"""
n=pa... | Create vcard-tmp XML representation of the field.
:Parameters:
- `parent`: parent node for the element
:Types:
- `parent`: `libxml2.xmlNode`
:return: xml node with the field data.
:returntype: `libxml2.xmlNode` |
def scale(s, dtype=None):
"""Non-uniform scaling along the x, y, and z axes
Parameters
----------
s : array-like, shape (3,)
Scaling in x, y, z.
dtype : dtype | None
Output type (if None, don't cast).
Returns
-------
M : ndarray
Transformation matrix describing ... | Non-uniform scaling along the x, y, and z axes
Parameters
----------
s : array-like, shape (3,)
Scaling in x, y, z.
dtype : dtype | None
Output type (if None, don't cast).
Returns
-------
M : ndarray
Transformation matrix describing the scaling. |
def convert(self, request, response, data):
"""
Performs the desired Conversion.
:param request: The webob Request object describing the
request.
:param response: The webob Response object describing the
response.
:param data: The... | Performs the desired Conversion.
:param request: The webob Request object describing the
request.
:param response: The webob Response object describing the
response.
:param data: The data dictionary returned by the prepare()
... |
def u_base(self, theta, phi, lam, q):
"""Apply U to q."""
return self.append(UBase(theta, phi, lam), [q], []) | Apply U to q. |
def build_phenotype(phenotype_id, adapter):
"""Build a small phenotype object
Build a dictionary with phenotype_id and description
Args:
phenotype_id (str): The phenotype id
adapter (scout.adapter.MongoAdapter)
Returns:
phenotype_obj (dict):
dict(
phen... | Build a small phenotype object
Build a dictionary with phenotype_id and description
Args:
phenotype_id (str): The phenotype id
adapter (scout.adapter.MongoAdapter)
Returns:
phenotype_obj (dict):
dict(
phenotype_id = str,
feature = str, # descri... |
def set(self, property_dict):
"""Attempts to set the given properties of the object.
An example of this is setting the nickname of the object::
cdb.set({"nickname": "My new nickname"})
note that there is a convenience property `cdb.nickname` that allows you to get/set the nic... | Attempts to set the given properties of the object.
An example of this is setting the nickname of the object::
cdb.set({"nickname": "My new nickname"})
note that there is a convenience property `cdb.nickname` that allows you to get/set the nickname directly. |
def group_pairs(blocks, layout_blocks_list):
"""Sort a list of layout blocks into pairs
Arguments:
List:blocks -- List of block objects
List:layout_blocks -- List of layout block indexes
Returns:
List -- Layout block pair indexes grouped in a list
"""
image_dict={}
for bloc... | Sort a list of layout blocks into pairs
Arguments:
List:blocks -- List of block objects
List:layout_blocks -- List of layout block indexes
Returns:
List -- Layout block pair indexes grouped in a list |
def _adjust_to_origin(arg, origin, unit):
"""
Helper function for to_datetime.
Adjust input argument to the specified origin
Parameters
----------
arg : list, tuple, ndarray, Series, Index
date to be adjusted
origin : 'julian' or Timestamp
origin offset for the arg
unit ... | Helper function for to_datetime.
Adjust input argument to the specified origin
Parameters
----------
arg : list, tuple, ndarray, Series, Index
date to be adjusted
origin : 'julian' or Timestamp
origin offset for the arg
unit : string
passed unit from to_datetime, must be... |
def resolved_row(objs, geomatcher):
"""Temporarily insert ``RoW`` into ``geomatcher.topology``, defined by the topo faces not used in ``objs``.
Will overwrite any existing ``RoW``.
On exiting the context manager, ``RoW`` is deleted."""
def get_locations(lst):
for elem in lst:
try:
... | Temporarily insert ``RoW`` into ``geomatcher.topology``, defined by the topo faces not used in ``objs``.
Will overwrite any existing ``RoW``.
On exiting the context manager, ``RoW`` is deleted. |
def _quadrature_expectation(p, obj1, feature1, obj2, feature2, num_gauss_hermite_points):
"""
Handling of quadrature expectations for Markov Gaussians (useful for time series)
Fallback method for missing analytic expectations wrt Markov Gaussians
Nota Bene: obj1 is always associated with x_n, whereas ob... | Handling of quadrature expectations for Markov Gaussians (useful for time series)
Fallback method for missing analytic expectations wrt Markov Gaussians
Nota Bene: obj1 is always associated with x_n, whereas obj2 always with x_{n+1}
if one requires e.g. <x_{n+1} K_{x_n, Z}>_p(x_{n:n+1}), compute ... |
def ml_acr(tree, character, prediction_method, model, states, avg_br_len, num_nodes, num_tips, freqs=None, sf=None,
kappa=None, force_joint=True):
"""
Calculates ML states on the tree and stores them in the corresponding feature.
:param states: numpy array of possible states
:param predictio... | Calculates ML states on the tree and stores them in the corresponding feature.
:param states: numpy array of possible states
:param prediction_method: str, MPPA (marginal approximation), MAP (max a posteriori) or JOINT
:param tree: ete3.Tree, the tree of interest
:param character: str, character for wh... |
def configure_root():
"""Configure the root logger."""
root_logger = logging.getLogger()
# clear any existing handles to streams because we don't want duplicate logs
# NOTE: we assume that any stream handles we find are to ROOT_LOG_STREAM, which is usually the case(because it is stdout). This is fine b... | Configure the root logger. |
def video_l1_loss(top_out, targets, model_hparams, vocab_size, weights_fn):
"""Compute loss numerator and denominator for one shard of output."""
del vocab_size # unused arg
logits = top_out
logits = tf.reshape(logits, [-1] + common_layers.shape_list(logits)[2:-1])
targets = tf.reshape(targets, [-1] + common... | Compute loss numerator and denominator for one shard of output. |
def luminosity_within_ellipse_in_units(self, major_axis : dim.Length, unit_luminosity='eps', kpc_per_arcsec=None, exposure_time=None):
"""Compute the total luminosity of the galaxy's light profiles, within an ellipse of specified major axis. This
is performed via integration of each light profile and i... | Compute the total luminosity of the galaxy's light profiles, within an ellipse of specified major axis. This
is performed via integration of each light profile and is centred, oriented and aligned with each light
model's individual geometry.
See *light_profiles.luminosity_within_ellipse* for d... |
def _build_epsf_step(self, stars, epsf=None):
"""
A single iteration of improving an ePSF.
Parameters
----------
stars : `EPSFStars` object
The stars used to build the ePSF.
epsf : `EPSFModel` object, optional
The initial ePSF model. If not inpu... | A single iteration of improving an ePSF.
Parameters
----------
stars : `EPSFStars` object
The stars used to build the ePSF.
epsf : `EPSFModel` object, optional
The initial ePSF model. If not input, then the ePSF will be
built from scratch.
... |
def connect(self, protocol_factory):
"""
Connect to the C{protocolFactory} to the AMQP broker specified by the
URI of this endpoint.
@param protocol_factory: An L{AMQFactory} building L{AMQClient} objects.
@return: A L{Deferred} that results in an L{AMQClient} upon successful
... | Connect to the C{protocolFactory} to the AMQP broker specified by the
URI of this endpoint.
@param protocol_factory: An L{AMQFactory} building L{AMQClient} objects.
@return: A L{Deferred} that results in an L{AMQClient} upon successful
connection otherwise a L{Failure} wrapping L{Co... |
def step_until_intersect(pos, field_line, sign, time, direction=None,
step_size_goal=5.,
field_step_size=None):
"""Starting at pos, method steps along magnetic unit vector direction
towards the supplied field line trace. Determines the distance of
close... | Starting at pos, method steps along magnetic unit vector direction
towards the supplied field line trace. Determines the distance of
closest approach to field line.
Routine is used when calculting the mapping of electric fields along
magnetic field lines. Voltage remains constant along the field... |
def register_metric(self, name, metric, time_bucket_in_sec):
"""Registers a given metric
:param name: name of the metric
:param metric: IMetric object to be registered
:param time_bucket_in_sec: time interval for update to the metrics manager
"""
if name in self.metrics_map:
raise Runtime... | Registers a given metric
:param name: name of the metric
:param metric: IMetric object to be registered
:param time_bucket_in_sec: time interval for update to the metrics manager |
def find_num_contigs(contig_lengths_dict):
"""
Count the total number of contigs for each strain
:param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths
:return: num_contigs_dict: dictionary of strain name: total number of contigs
"""
# Initialise the dic... | Count the total number of contigs for each strain
:param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths
:return: num_contigs_dict: dictionary of strain name: total number of contigs |
def prettyMatcherList(things):
"""Try to construct a nicely-formatted string for a list of matcher
objects. Those may be compiled regular expressions or strings..."""
norm = []
for x in makeSequence(things):
if hasattr(x, 'pattern'):
norm.append(x.pattern)
else:
n... | Try to construct a nicely-formatted string for a list of matcher
objects. Those may be compiled regular expressions or strings... |
def has_pubmed(edge_data: EdgeData) -> bool:
"""Check if the edge has a PubMed citation."""
return CITATION in edge_data and CITATION_TYPE_PUBMED == edge_data[CITATION][CITATION_TYPE] | Check if the edge has a PubMed citation. |
def sigint_handler(self, signum: int, frame) -> None:
"""Signal handler for SIGINTs which typically come from Ctrl-C events.
If you need custom SIGINT behavior, then override this function.
:param signum: signal number
:param frame
"""
if self.cur_pipe_proc_reader is no... | Signal handler for SIGINTs which typically come from Ctrl-C events.
If you need custom SIGINT behavior, then override this function.
:param signum: signal number
:param frame |
def __encode_items(self, items):
"""Encodes the InvoiceItems into a JSON serializable format
items = [('item_1',InvoiceItem(name='VIP Ticket', quantity=2,
unit_price='3500', total_price='7000',
description='VIP Tickets for party')),...]
... | Encodes the InvoiceItems into a JSON serializable format
items = [('item_1',InvoiceItem(name='VIP Ticket', quantity=2,
unit_price='3500', total_price='7000',
description='VIP Tickets for party')),...] |
def hide_arp_holder_arp_entry_mac_address_value(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hide_arp_holder = ET.SubElement(config, "hide-arp-holder", xmlns="urn:brocade.com:mgmt:brocade-arp")
arp_entry = ET.SubElement(hide_arp_holder, "arp-entry")
... | Auto Generated Code |
def alexnet(pretrained=False, ctx=cpu(),
root=os.path.join(base.data_dir(), 'models'), **kwargs):
r"""AlexNet model from the `"One weird trick..." <https://arxiv.org/abs/1404.5997>`_ paper.
Parameters
----------
pretrained : bool, default False
Whether to load the pretrained weights... | r"""AlexNet model from the `"One weird trick..." <https://arxiv.org/abs/1404.5997>`_ paper.
Parameters
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
ctx : Context, default CPU
The context in which to load the pretrained weights.
root :... |
def plot_series(self, xres, varied_data, varied_idx, **kwargs):
""" Plots the results from :meth:`solve_series`.
Parameters
----------
xres : array
Of shape ``(varied_data.size, self.nx)``.
varied_data : array
See :meth:`solve_series`.
varied_idx ... | Plots the results from :meth:`solve_series`.
Parameters
----------
xres : array
Of shape ``(varied_data.size, self.nx)``.
varied_data : array
See :meth:`solve_series`.
varied_idx : int or str
See :meth:`solve_series`.
\\*\\*kwargs :
... |
def ScanFiles(theFile, target, paths, file_tests, file_tests_search, env, graphics_extensions, targetdir, aux_files):
""" For theFile (a Node) update any file_tests and search for graphics files
then find all included files and call ScanFiles recursively for each of them"""
content = theFile.get_text_conte... | For theFile (a Node) update any file_tests and search for graphics files
then find all included files and call ScanFiles recursively for each of them |
def clear(self):
"""Removes all SSH keys from a user's system."""
r = self._h._http_resource(
method='DELETE',
resource=('user', 'keys'),
)
return r.ok | Removes all SSH keys from a user's system. |
def sbar_(self, stack_index=None, label=None, style=None, opts=None,
options={}):
"""
Get a stacked bar chart
"""
self.opts(dict(stack_index=stack_index, color_index=stack_index))
try:
if stack_index is None:
self.err(self.sbar_, "Please provide a stack index parameter")
options["stack_index"] ... | Get a stacked bar chart |
def attached_partition(self):
"""
:class:`~zhmcclient.Partition`: The partition to which this virtual
storage resource is attached.
The returned partition object has only a minimal set of properties set
('object-id', 'object-uri', 'class', 'parent').
Note that a virtual... | :class:`~zhmcclient.Partition`: The partition to which this virtual
storage resource is attached.
The returned partition object has only a minimal set of properties set
('object-id', 'object-uri', 'class', 'parent').
Note that a virtual storage resource is always attached to a partitio... |
def prettify_xml(elem):
"""Return a pretty-printed XML string for the Element.
"""
from xml.dom import minidom
import xml.etree.cElementTree as et
rough_string = et.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent=" ") | Return a pretty-printed XML string for the Element. |
def validate_unique(self, *args, **kwargs):
"""Checked whether more than one EighthSignup exists for a User on a given EighthBlock."""
super(EighthSignup, self).validate_unique(*args, **kwargs)
if self.has_conflict():
raise ValidationError({NON_FIELD_ERRORS: ("EighthSignup already e... | Checked whether more than one EighthSignup exists for a User on a given EighthBlock. |
def DEFINE_multi_enum_class( # pylint: disable=invalid-name,redefined-builtin
name,
default,
enum_class,
help,
flag_values=_flagvalues.FLAGS,
module_name=None,
**args):
"""Registers a flag whose value can be a list of enum members.
Use the flag on the command line multiple times to pla... | Registers a flag whose value can be a list of enum members.
Use the flag on the command line multiple times to place multiple
enum values into the list.
Args:
name: str, the flag name.
default: Union[Iterable[Enum], Iterable[Text], Enum, Text, None], the
default value of the flag; see
`D... |
def _fix_path(self, path):
"""
Paths are stored without trailing slash so we need to get rid off it if
needed. Also mercurial keeps filenodes as str so we need to decode
from unicode to str
"""
if path.endswith('/'):
path = path.rstrip('/')
return saf... | Paths are stored without trailing slash so we need to get rid off it if
needed. Also mercurial keeps filenodes as str so we need to decode
from unicode to str |
def next_event(self, delete=False):
"""Go to next event."""
if delete:
msg = "Delete this event? This cannot be undone."
msgbox = QMessageBox(QMessageBox.Question, 'Delete event', msg)
msgbox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
msgbox.setD... | Go to next event. |
def save(self):
""" Saves the settings contents """
content = self.dumps()
fileutils.save_text_to_file(content, self.file_path) | Saves the settings contents |
def prepend_name_scope(name, import_scope):
"""Prepends name scope to a name."""
# Based on tensorflow/python/framework/ops.py implementation.
if import_scope:
try:
str_to_replace = r"([\^]|loc:@|^)(.*)"
return re.sub(str_to_replace, r"\1" + import_scope + r"/\2",
tf.compat.as_... | Prepends name scope to a name. |
def to_model(self):
"""Return a bravado-core Error instance"""
e = ApiPool().current_server_api.model.Error(
status=self.status,
error=self.code.upper(),
error_description=str(self),
)
if self.error_id:
e.error_id = self.error_id
if... | Return a bravado-core Error instance |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.