code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def hull(self):
"""
Bounding polygon as a convex hull.
"""
from scipy.spatial import ConvexHull
if len(self.coordinates) >= 4:
inds = ConvexHull(self.coordinates).vertices
return self.coordinates[inds]
else:
return self.coordinates | Bounding polygon as a convex hull. |
def lagcrp_helper(egg, match='exact', distance='euclidean',
ts=None, features=None):
"""
Computes probabilities for each transition distance (probability that a word
recalled will be a given distance--in presentation order--from the previous
recalled word).
Parameters
--------... | Computes probabilities for each transition distance (probability that a word
recalled will be a given distance--in presentation order--from the previous
recalled word).
Parameters
----------
egg : quail.Egg
Data to analyze
match : str (exact, best or smooth)
Matching approach t... |
def import_teamocil(sconf):
"""Return tmuxp config from a `teamocil`_ yaml config.
.. _teamocil: https://github.com/remiprev/teamocil
Parameters
----------
sconf : dict
python dict for session configuration
Notes
-----
Todos:
- change 'root' to a cd or start_directory
... | Return tmuxp config from a `teamocil`_ yaml config.
.. _teamocil: https://github.com/remiprev/teamocil
Parameters
----------
sconf : dict
python dict for session configuration
Notes
-----
Todos:
- change 'root' to a cd or start_directory
- width in pane -> main-pain-wid... |
def _swap_optimizer_allows(self, p1, p2):
"""Identify easily discarded meaningless swaps.
This is motivated by the cost of millions of swaps being simulated.
"""
# setup local shortcuts
a = self._array
tile1 = a[p1]
tile2 = a[p2]
# 1) disallow same tiles
... | Identify easily discarded meaningless swaps.
This is motivated by the cost of millions of swaps being simulated. |
def order_by(self, key):
"""
Returns new Enumerable sorted in ascending order by given key
:param key: key to sort by as lambda expression
:return: new Enumerable object
"""
if key is None:
raise NullArgumentError(u"No key for sorting given")
kf = [Ord... | Returns new Enumerable sorted in ascending order by given key
:param key: key to sort by as lambda expression
:return: new Enumerable object |
def thread_safe(method):
""" wraps method with lock acquire/release cycle
decorator requires class instance to have field self.lock of type threading.Lock or threading.RLock """
@functools.wraps(method)
def _locker(self, *args, **kwargs):
assert hasattr(self, 'lock'), \
'thread_saf... | wraps method with lock acquire/release cycle
decorator requires class instance to have field self.lock of type threading.Lock or threading.RLock |
def save_task(task, broker):
"""
Saves the task package to Django or the cache
"""
# SAVE LIMIT < 0 : Don't save success
if not task.get('save', Conf.SAVE_LIMIT >= 0) and task['success']:
return
# enqueues next in a chain
if task.get('chain', None):
django_q.tasks.async_chain... | Saves the task package to Django or the cache |
def save(self, **kwargs):
"""
Create a ``FormEntry`` instance and related ``FieldEntry``
instances for each form field.
"""
entry = super(FormForForm, self).save(commit=False)
entry.form = self.form
entry.entry_time = now()
entry.save()
entry_field... | Create a ``FormEntry`` instance and related ``FieldEntry``
instances for each form field. |
def add_subtract(st, max_iter=7, max_npart='calc', max_mem=2e8,
always_check_remove=False, **kwargs):
"""
Automatically adds and subtracts missing & extra particles.
Operates by removing bad particles then adding missing particles on
repeat, until either no particles are added/removed ... | Automatically adds and subtracts missing & extra particles.
Operates by removing bad particles then adding missing particles on
repeat, until either no particles are added/removed or after `max_iter`
attempts.
Parameters
----------
st: :class:`peri.states.State`
The state to add and su... |
def transform_y(self, tfms:TfmList=None, **kwargs):
"Set `tfms` to be applied to the targets only."
_check_kwargs(self.y, tfms, **kwargs)
self.tfm_y=True
if tfms is None:
self.tfms_y = list(filter(lambda t: t.use_on_y, listify(self.tfms)))
self.tfmargs_y = {**self... | Set `tfms` to be applied to the targets only. |
def write(self, str):
'''Write string str to the underlying file.
Note that due to buffering, flush() or close() may be needed before
the file on disk reflects the data written.'''
if self.closed: raise ValueError('File closed')
if self._mode in _allowed_read:
raise... | Write string str to the underlying file.
Note that due to buffering, flush() or close() may be needed before
the file on disk reflects the data written. |
def exists(self):
""":type: bool
True when the object actually exists (and can be accessed by
the current user) in Fedora
"""
# If we made the object under the pretext that it doesn't exist in
# fedora yet, then assume it doesn't exist in fedora yet.
if self._cr... | :type: bool
True when the object actually exists (and can be accessed by
the current user) in Fedora |
def fetch(self):
"""
Fetch a ChallengeInstance
:returns: Fetched ChallengeInstance
:rtype: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeInstance
"""
params = values.of({})
payload = self._version.fetch(
'GET',
self._uri,
... | Fetch a ChallengeInstance
:returns: Fetched ChallengeInstance
:rtype: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeInstance |
def add_row(self, label, row_data, columns=""):
"""
Add a row with data.
If any new keys are present in row_data dictionary,
that column will be added to the dataframe.
This is done inplace
"""
# use provided column order, making sure you don't lose any values
... | Add a row with data.
If any new keys are present in row_data dictionary,
that column will be added to the dataframe.
This is done inplace |
def set_cell(self, index, value):
"""
Sets the value of a single cell. If the index is not in the current index then a new index will be created.
:param index: index value
:param value: value to set
:return: nothing
"""
if self._sort:
exists, i = sort... | Sets the value of a single cell. If the index is not in the current index then a new index will be created.
:param index: index value
:param value: value to set
:return: nothing |
def returner(ret):
'''
Signal a Django server that a return is available
'''
signaled = dispatch.Signal(providing_args=['ret']).send(sender='returner', ret=ret)
for signal in signaled:
log.debug(
'Django returner function \'returner\' signaled %s '
'which responded w... | Signal a Django server that a return is available |
def norm_package_version(version):
"""Normalize a version by removing extra spaces and parentheses."""
if version:
version = ','.join(v.strip() for v in version.split(',')).strip()
if version.startswith('(') and version.endswith(')'):
version = version[1:-1]
version = ''.jo... | Normalize a version by removing extra spaces and parentheses. |
def dict_array_bytes(ary, template):
"""
Return the number of bytes required by an array
Arguments
---------------
ary : dict
Dictionary representation of an array
template : dict
A dictionary of key-values, used to replace any
string values in the array with concrete in... | Return the number of bytes required by an array
Arguments
---------------
ary : dict
Dictionary representation of an array
template : dict
A dictionary of key-values, used to replace any
string values in the array with concrete integral
values
Returns
----------... |
def check(a, b):
"""
Checks to see if the two values are equal to each other.
:param a | <str>
b | <str>
:return <bool>
"""
aencrypt = encrypt(a)
bencrypt = encrypt(b)
return a == b or a == bencrypt or aencrypt == b | Checks to see if the two values are equal to each other.
:param a | <str>
b | <str>
:return <bool> |
def from_shapely(polygon_shapely, label=None):
"""
Create a polygon from a Shapely polygon.
Note: This will remove any holes in the Shapely polygon.
Parameters
----------
polygon_shapely : shapely.geometry.Polygon
The shapely polygon.
label : None ... | Create a polygon from a Shapely polygon.
Note: This will remove any holes in the Shapely polygon.
Parameters
----------
polygon_shapely : shapely.geometry.Polygon
The shapely polygon.
label : None or str, optional
The label of the new polygon.
... |
def delete(self, *keys):
"""Removes the specified keys. A key is ignored if it does not exist.
Returns :data:`True` if all keys are removed.
.. note::
**Time complexity**: ``O(N)`` where ``N`` is the number of keys that
will be removed. When a key to remove holds a value ... | Removes the specified keys. A key is ignored if it does not exist.
Returns :data:`True` if all keys are removed.
.. note::
**Time complexity**: ``O(N)`` where ``N`` is the number of keys that
will be removed. When a key to remove holds a value other than a
string, the ... |
def _handle_ping(client, topic, dct):
"""Internal method that will be called when receiving ping message."""
if dct['type'] == 'request':
resp = {
'type': 'answer',
'name': client.name,
'source': dct
}
client.publish('p... | Internal method that will be called when receiving ping message. |
def __system_multiCall(calls, **kwargs):
"""
Call multiple RPC methods at once.
:param calls: An array of struct like {"methodName": string, "params": array }
:param kwargs: Internal data
:type calls: list
:type kwargs: dict
:return:
"""
if not isinstance(calls, list):
raise... | Call multiple RPC methods at once.
:param calls: An array of struct like {"methodName": string, "params": array }
:param kwargs: Internal data
:type calls: list
:type kwargs: dict
:return: |
def serialize(self, obj, method='json', beautify=False, raise_exception=False):
"""Alias of helper.string.serialization.serialize"""
return self.helper.string.serialization.serialize(
obj=obj, method=method, beautify=beautify, raise_exception=raise_exception) | Alias of helper.string.serialization.serialize |
def cidr_to_ipv4_netmask(cidr_bits):
'''
Returns an IPv4 netmask
'''
try:
cidr_bits = int(cidr_bits)
if not 1 <= cidr_bits <= 32:
return ''
except ValueError:
return ''
netmask = ''
for idx in range(4):
if idx:
netmask += '.'
i... | Returns an IPv4 netmask |
def _parse_rd(self, config):
""" _parse_rd scans the provided configuration block and extracts
the vrf rd. The return dict is intended to be merged into the response
dict.
Args:
config (str): The vrf configuration block from the nodes running
configuration
... | _parse_rd scans the provided configuration block and extracts
the vrf rd. The return dict is intended to be merged into the response
dict.
Args:
config (str): The vrf configuration block from the nodes running
configuration
Returns:
dict: resourc... |
def SkyCoord(self,*args,**kwargs):
"""
NAME:
SkyCoord
PURPOSE:
return the position as an astropy SkyCoord
INPUT:
t - (optional) time at which to get the position
obs=[X,Y,Z] - (optional) position of observer (in kpc)
(... | NAME:
SkyCoord
PURPOSE:
return the position as an astropy SkyCoord
INPUT:
t - (optional) time at which to get the position
obs=[X,Y,Z] - (optional) position of observer (in kpc)
(default=Object-wide default)
O... |
def d3logpdf_df3(self, f, y, Y_metadata=None):
"""
Evaluates the link function link(f) then computes the third derivative of log likelihood using it
Uses the Faa di Bruno's formula for the chain rule
.. math::
\\frac{d^{3}\\log p(y|\\lambda(f))}{df^{3}} = \\frac{d^{3}\\log p... | Evaluates the link function link(f) then computes the third derivative of log likelihood using it
Uses the Faa di Bruno's formula for the chain rule
.. math::
\\frac{d^{3}\\log p(y|\\lambda(f))}{df^{3}} = \\frac{d^{3}\\log p(y|\\lambda(f)}{d\\lambda(f)^{3}}\\left(\\frac{d\\lambda(f)}{df}\\r... |
def canonical_url(configs, endpoint_type=PUBLIC):
"""Returns the correct HTTP URL to this host given the state of HTTPS
configuration, hacluster and charm configuration.
:param configs: OSTemplateRenderer config templating object to inspect
for a complete https context.
:param endpo... | Returns the correct HTTP URL to this host given the state of HTTPS
configuration, hacluster and charm configuration.
:param configs: OSTemplateRenderer config templating object to inspect
for a complete https context.
:param endpoint_type: str endpoint type to resolve.
:param return... |
def setVersion(self, date_issued, version_id=None):
"""
Legacy function...
should use the other set_* for version and date
as of 2016-10-20 used in:
dipper/sources/HPOAnnotations.py 139:
dipper/sources/CTD.py 99:
dipper/sources/BioGrid.py ... | Legacy function...
should use the other set_* for version and date
as of 2016-10-20 used in:
dipper/sources/HPOAnnotations.py 139:
dipper/sources/CTD.py 99:
dipper/sources/BioGrid.py 100:
dipper/sources/MGI.py 255:
dipper/sourc... |
def _dict_rpartition(
in_dict,
keys,
delimiter=DEFAULT_TARGET_DELIM,
ordered_dict=False):
'''
Helper function to:
- Ensure all but the last key in `keys` exist recursively in `in_dict`.
- Return the dict at the one-to-last key, and the last key
:param dict in_dict: T... | Helper function to:
- Ensure all but the last key in `keys` exist recursively in `in_dict`.
- Return the dict at the one-to-last key, and the last key
:param dict in_dict: The dict to work with.
:param str keys: The delimited string with one or more keys.
:param str delimiter: The delimiter to use ... |
def plane_intersection(strike1, dip1, strike2, dip2):
"""
Finds the intersection of two planes. Returns a plunge/bearing of the linear
intersection of the two planes.
Also accepts sequences of strike1s, dip1s, strike2s, dip2s.
Parameters
----------
strike1, dip1 : numbers or sequences of n... | Finds the intersection of two planes. Returns a plunge/bearing of the linear
intersection of the two planes.
Also accepts sequences of strike1s, dip1s, strike2s, dip2s.
Parameters
----------
strike1, dip1 : numbers or sequences of numbers
The strike and dip (in degrees, following the right... |
def _openResources(self):
""" Opens the root Dataset.
"""
logger.info("Opening: {}".format(self._fileName))
self._ncGroup = Dataset(self._fileName) | Opens the root Dataset. |
def uuid_from_time(time_arg, node=None, clock_seq=None):
"""
Converts a datetime or timestamp to a type 1 :class:`uuid.UUID`.
:param time_arg:
The time to use for the timestamp portion of the UUID.
This can either be a :class:`datetime` object or a timestamp
in seconds (as returned from :... | Converts a datetime or timestamp to a type 1 :class:`uuid.UUID`.
:param time_arg:
The time to use for the timestamp portion of the UUID.
This can either be a :class:`datetime` object or a timestamp
in seconds (as returned from :meth:`time.time()`).
:type datetime: :class:`datetime` or timesta... |
def Or(*xs, simplify=True):
"""Expression disjunction (sum, OR) operator
If *simplify* is ``True``, return a simplified expression.
"""
xs = [Expression.box(x).node for x in xs]
y = exprnode.or_(*xs)
if simplify:
y = y.simplify()
return _expr(y) | Expression disjunction (sum, OR) operator
If *simplify* is ``True``, return a simplified expression. |
def delete(self, path):
"""
Ensure that roots of our managers can't be deleted. This should be
enforced by https://github.com/ipython/ipython/pull/8168, but rogue
implementations might override this behavior.
"""
path = normalize_api_path(path)
if path in self.ma... | Ensure that roots of our managers can't be deleted. This should be
enforced by https://github.com/ipython/ipython/pull/8168, but rogue
implementations might override this behavior. |
def _sign_block(self, block):
""" The block should be complete and the final
signature from the publishing validator (this validator) needs to
be added.
"""
block_header = block.block_header
header_bytes = block_header.SerializeToString()
signature = self._identit... | The block should be complete and the final
signature from the publishing validator (this validator) needs to
be added. |
def get_contents_static(self, block_alias, context):
"""Returns contents of a static block."""
if 'request' not in context:
# No use in further actions as we won't ever know current URL.
return ''
current_url = context['request'].path
# Resolve current view nam... | Returns contents of a static block. |
def messages(self):
""" Messages generated by server, see http://legacy.python.org/dev/peps/pep-0249/#cursor-messages
"""
if self._session:
result = []
for msg in self._session.messages:
ex = _create_exception_by_message(msg)
result.append(... | Messages generated by server, see http://legacy.python.org/dev/peps/pep-0249/#cursor-messages |
def lowwrap(self, fname):
"""
Wraps the fname method when the C code expects a different kind of
callback than we have in the fusepy API. (The wrapper is usually for
performing some checks or transfromations which could be done in C but
is simpler if done in Python.)
Cur... | Wraps the fname method when the C code expects a different kind of
callback than we have in the fusepy API. (The wrapper is usually for
performing some checks or transfromations which could be done in C but
is simpler if done in Python.)
Currently `open` and `create` are wrapped: a bool... |
def order_target_value(self,
asset,
target,
limit_price=None,
stop_price=None,
style=None):
"""Place an order to adjust a position to a target value. If
the position doe... | Place an order to adjust a position to a target value. If
the position doesn't already exist, this is equivalent to placing a new
order. If the position does exist, this is equivalent to placing an
order for the difference between the target value and the
current value.
If the As... |
def geojson_handler(geojson, hType='map'):
"""Restructure a GeoJSON object in preparation to be added directly by add_map_data or add_data_set methods.
The geojson will be broken down to fit a specific Highcharts (highmaps) type, either map, mapline or mappoint.
Meta data in GeoJSON's properties object wi... | Restructure a GeoJSON object in preparation to be added directly by add_map_data or add_data_set methods.
The geojson will be broken down to fit a specific Highcharts (highmaps) type, either map, mapline or mappoint.
Meta data in GeoJSON's properties object will be copied directly over to object['properties']... |
def list_unique(cls):
'''Return all unique namespaces
:returns: a list of all predicates
:rtype: list of ckan.model.semantictag.Predicate objects
'''
query = meta.Session.query(Predicate).distinct(Predicate.namespace)
return query.all() | Return all unique namespaces
:returns: a list of all predicates
:rtype: list of ckan.model.semantictag.Predicate objects |
def list_security_groups(call=None):
'''
Lists all security groups available to the user and the user's groups.
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt-cloud -f list_security_groups opennebula
'''
if call == 'action':
raise SaltCloudSystemExit(
... | Lists all security groups available to the user and the user's groups.
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt-cloud -f list_security_groups opennebula |
def __to_file(self, message_no):
""" Write a single message to file """
filename = self.__create_file_name(message_no)
try:
with codecs.open(filename, mode='w',
encoding=self.messages[message_no].encoding)\
as file__:
f... | Write a single message to file |
def absolute_path(path=None, base_dir=None):
"""
Return absolute path if path is local.
Parameters:
-----------
path : path to file
base_dir : base directory used for absolute path
Returns:
--------
absolute path
"""
if path_is_remote(path):
return path
else:
... | Return absolute path if path is local.
Parameters:
-----------
path : path to file
base_dir : base directory used for absolute path
Returns:
--------
absolute path |
def start(self):
"""Starts the advertise loop.
Returns the result of the first ad request.
"""
if self.running:
raise Exception('Advertiser is already running')
if self.io_loop is None:
self.io_loop = tornado.ioloop.IOLoop.current()
self.running ... | Starts the advertise loop.
Returns the result of the first ad request. |
def apply_handler_to_all_logs(handler: logging.Handler,
remove_existing: bool = False) -> None:
"""
Applies a handler to all logs, optionally removing existing handlers.
Should ONLY be called from the ``if __name__ == 'main'`` script;
see https://docs.python.org/3.4/howto/... | Applies a handler to all logs, optionally removing existing handlers.
Should ONLY be called from the ``if __name__ == 'main'`` script;
see https://docs.python.org/3.4/howto/logging.html#library-config.
Generally MORE SENSIBLE just to apply a handler to the root logger.
Args:
handler: the hand... |
def _save_or_update(self):
"""Save or update the private state needed by the cloud provider.
"""
with self._resource_lock:
if not self._config or not self._config._storage_path:
raise Exception("self._config._storage path is undefined")
if not self._config... | Save or update the private state needed by the cloud provider. |
def by_image_seq(blocks, image_seq):
"""Filter blocks to return only those associated with the provided image_seq number.
Argument:
List:blocks -- List of block objects to sort.
Int:image_seq -- image_seq number found in ec_hdr.
Returns:
List -- List of block indexes matchi... | Filter blocks to return only those associated with the provided image_seq number.
Argument:
List:blocks -- List of block objects to sort.
Int:image_seq -- image_seq number found in ec_hdr.
Returns:
List -- List of block indexes matching image_seq number. |
def subscribe_to_events(config, subscriber, events, model=None):
""" Helper function to subscribe to group of events.
:param config: Pyramid contig instance.
:param subscriber: Event subscriber function.
:param events: Sequence of events to subscribe to.
:param model: Model predicate value.
"""... | Helper function to subscribe to group of events.
:param config: Pyramid contig instance.
:param subscriber: Event subscriber function.
:param events: Sequence of events to subscribe to.
:param model: Model predicate value. |
def ssh_cmd(self, name, ssh_command):
"""
SSH into given container and executre command if given
"""
if not self.container_exists(name=name):
exit("Unknown container {0}".format(name))
if not self.container_running(name=name):
exit("Container {0} is not r... | SSH into given container and executre command if given |
def open_bucket(bucket_name,
aws_access_key_id=None, aws_secret_access_key=None,
aws_profile=None):
"""Open an S3 Bucket resource.
Parameters
----------
bucket_name : `str`
Name of the S3 bucket.
aws_access_key_id : `str`, optional
The access key for ... | Open an S3 Bucket resource.
Parameters
----------
bucket_name : `str`
Name of the S3 bucket.
aws_access_key_id : `str`, optional
The access key for your AWS account. Also set
``aws_secret_access_key``.
aws_secret_access_key : `str`, optional
The secret key for your A... |
def detrend(arr, x=None, deg=5, tol=1e-3, maxloop=10):
"""Compute a baseline trend of a signal"""
xx = numpy.arange(len(arr)) if x is None else x
base = arr.copy()
trend = base
pol = numpy.ones((deg + 1,))
for _ in range(maxloop):
pol_new = numpy.polyfit(xx, base, deg)
pol_norm ... | Compute a baseline trend of a signal |
def refresh(self):
"""
Refresh this model from the server.
Updates attributes with the server-defined values. This is useful where the Model
instance came from a partial response (eg. a list query) and additional details
are required.
Existing attribute values will be o... | Refresh this model from the server.
Updates attributes with the server-defined values. This is useful where the Model
instance came from a partial response (eg. a list query) and additional details
are required.
Existing attribute values will be overwritten. |
def update_host_datetime(host, username, password, protocol=None, port=None, host_names=None):
'''
Update the date/time on the given host or list of host_names. This function should be
used with caution since network delays and execution delays can result in time skews.
host
The location of the... | Update the date/time on the given host or list of host_names. This function should be
used with caution since network delays and execution delays can result in time skews.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
... |
def send_file(self, fp, headers=None, cb=None, num_cb=10,
query_args=None, chunked_transfer=False, size=None):
"""
Upload a file to a key into a bucket on S3.
:type fp: file
:param fp: The file pointer to upload. The file pointer must point
point at ... | Upload a file to a key into a bucket on S3.
:type fp: file
:param fp: The file pointer to upload. The file pointer must point
point at the offset from which you wish to upload.
ie. if uploading the full file, it should point at the
start of the f... |
def _list_metric_descriptors(args, _):
"""Lists the metric descriptors in the project."""
project_id = args['project']
pattern = args['type'] or '*'
descriptors = gcm.MetricDescriptors(project_id=project_id)
dataframe = descriptors.as_dataframe(pattern=pattern)
return _render_dataframe(dataframe) | Lists the metric descriptors in the project. |
def bootstrap_paginate(parser, token):
"""
Renders a Page object as a Twitter Bootstrap styled pagination bar.
Compatible with Bootstrap 3.x and 4.x only.
Example::
{% bootstrap_paginate page_obj range=10 %}
Named Parameters::
range - The size of the pagination bar (ie, if set t... | Renders a Page object as a Twitter Bootstrap styled pagination bar.
Compatible with Bootstrap 3.x and 4.x only.
Example::
{% bootstrap_paginate page_obj range=10 %}
Named Parameters::
range - The size of the pagination bar (ie, if set to 10 then, at most,
10 page numbers... |
def get_countries(is_legacy_xml=False):
"""
The function to generate a dictionary containing ISO_3166-1 country codes
to names.
Args:
is_legacy_xml (:obj:`bool`): Whether to use the older country code
list (iso_3166-1_list_en.xml).
Returns:
dict: A mapping of country co... | The function to generate a dictionary containing ISO_3166-1 country codes
to names.
Args:
is_legacy_xml (:obj:`bool`): Whether to use the older country code
list (iso_3166-1_list_en.xml).
Returns:
dict: A mapping of country codes as the keys to the country names as
... |
def get_romfile_path(game, inttype=Integrations.DEFAULT):
"""
Return the path to a given game's romfile
"""
for extension in EMU_EXTENSIONS.keys():
possible_path = get_file_path(game, "rom" + extension, inttype)
if possible_path:
return possible_path
raise FileNotFoundEr... | Return the path to a given game's romfile |
def mac_address_table_static_mac_address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
mac_address_table = ET.SubElement(config, "mac-address-table", xmlns="urn:brocade.com:mgmt:brocade-mac-address-table")
static = ET.SubElement(mac_address_table, "sta... | Auto Generated Code |
def send_wrapped(self, text):
"""
Send text padded and wrapped to the user's screen width.
"""
lines = word_wrap(text, self.columns)
for line in lines:
self.send_cc(line + '\n') | Send text padded and wrapped to the user's screen width. |
def date_this_century(self, before_today=True, after_today=False):
"""
Gets a Date object for the current century.
:param before_today: include days in current century before today
:param after_today: include days in current century after today
:example Date('2012-04-04')
... | Gets a Date object for the current century.
:param before_today: include days in current century before today
:param after_today: include days in current century after today
:example Date('2012-04-04')
:return Date |
def char(self, c: str) -> None:
"""Parse the specified character.
Args:
c: One-character string.
Raises:
EndOfInput: If past the end of `self.input`.
UnexpectedInput: If the next character is different from `c`.
"""
if self.peek() == c:
... | Parse the specified character.
Args:
c: One-character string.
Raises:
EndOfInput: If past the end of `self.input`.
UnexpectedInput: If the next character is different from `c`. |
def import_locations(self, gpx_file):
"""Import GPX data files.
``import_locations()`` returns a list with :class:`~gpx.Waypoint`
objects.
It expects data files in GPX format, as specified in `GPX 1.1 Schema
Documentation`_, which is XML such as::
<?xml version="1.... | Import GPX data files.
``import_locations()`` returns a list with :class:`~gpx.Waypoint`
objects.
It expects data files in GPX format, as specified in `GPX 1.1 Schema
Documentation`_, which is XML such as::
<?xml version="1.0" encoding="utf-8" standalone="no"?>
... |
def is_reversible(P):
""" Returns if P is reversible on its weakly connected sets """
import msmtools.analysis as msmana
# treat each weakly connected set separately
sets = connected_sets(P, strong=False)
for s in sets:
Ps = P[s, :][:, s]
if not msmana.is_transition_matrix(Ps):
... | Returns if P is reversible on its weakly connected sets |
def get_operation_pattern(server_url, request_url_pattern):
"""Return an updated request URL pattern with the server URL removed."""
if server_url[-1] == "/":
# operations have to start with a slash, so do not remove it
server_url = server_url[:-1]
if is_absolute(server_url):
return ... | Return an updated request URL pattern with the server URL removed. |
def create_mon_path(path, uid=-1, gid=-1):
"""create the mon path if it does not exist"""
if not os.path.exists(path):
os.makedirs(path)
os.chown(path, uid, gid); | create the mon path if it does not exist |
def get_first_comments_or_remarks(recID=-1,
ln=CFG_SITE_LANG,
nb_comments='all',
nb_reviews='all',
voted=-1,
reported=-1,
... | Gets nb number comments/reviews or remarks.
In the case of comments, will get both comments and reviews
Comments and remarks sorted by most recent date, reviews sorted by highest helpful score
:param recID: record id
:param ln: language
:param nb_comments: number of comment or remarks to get
:pa... |
async def set_failover_mode(mode):
"""Example of printing the current upstream."""
jar = aiohttp.CookieJar(unsafe=True)
websession = aiohttp.ClientSession(cookie_jar=jar)
try:
modem = eternalegypt.Modem(hostname=sys.argv[1], websession=websession)
await modem.login(password=sys.argv[2])... | Example of printing the current upstream. |
def seektime(self, disk):
"""
Gives seek latency on disk which is a very good indication to the `type` of the disk.
it's a very good way to verify if the underlying disk type is SSD or HDD
:param disk: disk path or name (/dev/sda, or sda)
:return: a dict as follows {'device': '<... | Gives seek latency on disk which is a very good indication to the `type` of the disk.
it's a very good way to verify if the underlying disk type is SSD or HDD
:param disk: disk path or name (/dev/sda, or sda)
:return: a dict as follows {'device': '<device-path>', 'elapsed': <seek-time in us', '... |
def bootstrapping_dtrajs(dtrajs, lag, N_full, nbs=10000, active_set=None):
"""
Perform trajectory based re-sampling.
Parameters
----------
dtrajs : list of discrete trajectories
lag : int
lag time
N_full : int
Number of states in discrete trajectories.
nbs : int, optio... | Perform trajectory based re-sampling.
Parameters
----------
dtrajs : list of discrete trajectories
lag : int
lag time
N_full : int
Number of states in discrete trajectories.
nbs : int, optional
Number of bootstrapping samples
active_set : ndarray
Indices of... |
def file_md5(self, resource):
"""Deprecated alias for *resource_md5*."""
warnings.warn(
"file_md5 is deprecated; use resource_md5 instead",
DeprecationWarning, stacklevel=2)
return self.resource_md5(resource) | Deprecated alias for *resource_md5*. |
def enterEvent(self, event):
"""
Mark the hovered state as being true.
:param event | <QtCore.QEnterEvent>
"""
super(XViewPanelItem, self).enterEvent(event)
# store the hover state and mark for a repaint
self._hovered = True
self.update() | Mark the hovered state as being true.
:param event | <QtCore.QEnterEvent> |
def reboot(name, call=None):
'''
reboot a machine by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
datacenter_id = get_datacenter_i... | reboot a machine by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name |
def _get(self, uri, params=None, headers=None):
"""
Simple GET request for a given path.
"""
if not headers:
headers = self._get_headers()
logging.debug("URI=" + str(uri))
logging.debug("HEADERS=" + str(headers))
response = self.session.get(uri, head... | Simple GET request for a given path. |
def create_install_template_skin(self):
"""
Create an example ckan extension for this environment and install it
"""
ckan_extension_template(self.name, self.target)
self.install_package_develop('ckanext-' + self.name + 'theme') | Create an example ckan extension for this environment and install it |
def to_xdr_object(self):
"""Creates an XDR Operation object that represents this
:class:`CreatePassiveOffer`.
"""
selling = self.selling.to_xdr_object()
buying = self.buying.to_xdr_object()
price = Operation.to_xdr_price(self.price)
price = Xdr.types.Price(price... | Creates an XDR Operation object that represents this
:class:`CreatePassiveOffer`. |
def email_domain_disposable(value):
"""
Confirms that the email address is not using a disposable service.
@param {str} value
@returns {None}
@raises AssertionError
"""
domain = helpers.get_domain_from_email_address(value)
if domain.lower() in disposable_domains:
raise Validati... | Confirms that the email address is not using a disposable service.
@param {str} value
@returns {None}
@raises AssertionError |
def get_tags(self):
"""
::
GET /:login/machines/:id/tags
:Returns: complete set of tags for this machine
:rtype: :py:class:`dict`
A local copy is not kept because these are essentially search keys.
"""
j, _ = self.datacenter... | ::
GET /:login/machines/:id/tags
:Returns: complete set of tags for this machine
:rtype: :py:class:`dict`
A local copy is not kept because these are essentially search keys. |
def delete_location(self, location_name):
"""
Remove location with name location_name from self.locations.
If the location had any sites, change site.location to "".
"""
location = self.find_by_name(location_name, self.locations)
if not location:
return False
... | Remove location with name location_name from self.locations.
If the location had any sites, change site.location to "". |
def get(self, remote, local=None):
""" Gets the file from FTP server
local can be:
a file: opened for writing, left open
a string: path to output file
None: contents are returned
"""
if isinstance(local, file_type): # open file, leave... | Gets the file from FTP server
local can be:
a file: opened for writing, left open
a string: path to output file
None: contents are returned |
def expiry_time(ns, cavs):
''' Returns the minimum time of any time-before caveats found
in the given list or None if no such caveats were found.
The ns parameter is
:param ns: used to determine the standard namespace prefix - if
the standard namespace is not found, the empty prefix is assumed.
... | Returns the minimum time of any time-before caveats found
in the given list or None if no such caveats were found.
The ns parameter is
:param ns: used to determine the standard namespace prefix - if
the standard namespace is not found, the empty prefix is assumed.
:param cavs: a list of pymacaroons... |
def Enumerate():
"""See base class."""
hid_guid = GUID()
hid.HidD_GetHidGuid(ctypes.byref(hid_guid))
devices = setupapi.SetupDiGetClassDevsA(
ctypes.byref(hid_guid), None, None, 0x12)
index = 0
interface_info = DeviceInterfaceData()
interface_info.cbSize = ctypes.sizeof(DeviceInterf... | See base class. |
def _get_socket_addresses(self):
"""Get Socket address information.
:rtype: list
"""
family = socket.AF_UNSPEC
if not socket.has_ipv6:
family = socket.AF_INET
try:
addresses = socket.getaddrinfo(self._parameters['hostname'],
... | Get Socket address information.
:rtype: list |
def _compose_chapters(self):
"""
Creates a chapters
and appends them to list
"""
for count in range(self.chapter_count):
chapter_num = count + 1
c = Chapter(self.markov, chapter_num)
self.chapters.append(c) | Creates a chapters
and appends them to list |
def iter_markers(self):
"""
Generate a (marker_code, segment_offset) 2-tuple for each marker in
the JPEG *stream*, in the order they occur in the stream.
"""
marker_finder = _MarkerFinder.from_stream(self._stream)
start = 0
marker_code = None
while marker_... | Generate a (marker_code, segment_offset) 2-tuple for each marker in
the JPEG *stream*, in the order they occur in the stream. |
def _deep_value(*args, **kwargs):
""" Drills down into tree using the keys
"""
node, keys = args[0], args[1:]
for key in keys:
node = node.get(key, {})
default = kwargs.get('default', {})
if node in ({}, [], None):
node = default
return node | Drills down into tree using the keys |
def row_contributions(self, X):
"""Returns the row contributions towards each principal component.
Each row contribution towards each principal component is equivalent to the amount of
inertia it contributes. This is calculated by dividing the squared row coordinates by the
eigenvalue a... | Returns the row contributions towards each principal component.
Each row contribution towards each principal component is equivalent to the amount of
inertia it contributes. This is calculated by dividing the squared row coordinates by the
eigenvalue associated to each principal component. |
def unpickler(zone, utcoffset=None, dstoffset=None, tzname=None):
"""Factory function for unpickling pytz tzinfo instances.
This is shared for both StaticTzInfo and DstTzInfo instances, because
database changes could cause a zones implementation to switch between
these two base classes and we can't bre... | Factory function for unpickling pytz tzinfo instances.
This is shared for both StaticTzInfo and DstTzInfo instances, because
database changes could cause a zones implementation to switch between
these two base classes and we can't break pickles on a pytz version
upgrade. |
def save(self, filename, format=None):
"""
Save the SFrame to a file system for later use.
Parameters
----------
filename : string
The location to save the SFrame. Either a local directory or a
remote URL. If the format is 'binary', a directory will be cr... | Save the SFrame to a file system for later use.
Parameters
----------
filename : string
The location to save the SFrame. Either a local directory or a
remote URL. If the format is 'binary', a directory will be created
at the location which will contain the sf... |
def add_identity_parser(subparsers, parent_parser):
"""Creates the arg parsers needed for the identity command and
its subcommands.
"""
# identity
parser = subparsers.add_parser(
'identity',
help='Works with optional roles, policies, and permissions',
description='Provides su... | Creates the arg parsers needed for the identity command and
its subcommands. |
def _isinstance(expr, classname):
"""Check whether `expr` is an instance of the class with name
`classname`
This is like the builtin `isinstance`, but it take the `classname` a
string, instead of the class directly. Useful for when we don't want to
import the class for which we ... | Check whether `expr` is an instance of the class with name
`classname`
This is like the builtin `isinstance`, but it take the `classname` a
string, instead of the class directly. Useful for when we don't want to
import the class for which we want to check (also, remember that
pr... |
def _watchdog_queue(self):
"""
从queue里取出字符执行命令
"""
while not self.quit:
k = self.queue.get()
if k == 'q': # 退出
self.quit = True
self.switch_queue.put('main') | 从queue里取出字符执行命令 |
def _SGraphFromJsonTree(json_str):
"""
Convert the Json Tree to SGraph
"""
g = json.loads(json_str)
vertices = [_Vertex(x['id'],
dict([(str(k), v) for k, v in _six.iteritems(x) if k != 'id']))
for x in g['vertices']]
edges = [... | Convert the Json Tree to SGraph |
def generate_payload(self, config=None, context=None):
"""
Generate payload by iterating over registered plugins. Merges .
:param context: current context.
:param config: honeybadger configuration.
:return: a dict with the generated payload.
"""
for name, plugin i... | Generate payload by iterating over registered plugins. Merges .
:param context: current context.
:param config: honeybadger configuration.
:return: a dict with the generated payload. |
def __make_id(receiver):
"""Generate an identifier for a callable signal receiver.
This is used when disconnecting receivers, where we need to correctly
establish equivalence between the input receiver and the receivers assigned
to a signal.
Args:
receiver: A callable object.
Returns:... | Generate an identifier for a callable signal receiver.
This is used when disconnecting receivers, where we need to correctly
establish equivalence between the input receiver and the receivers assigned
to a signal.
Args:
receiver: A callable object.
Returns:
An identifier for the r... |
def do_authorization(self, transactionid, amt):
"""Shortcut for the DoAuthorization method.
Use the TRANSACTIONID from DoExpressCheckoutPayment for the
``transactionid``. The latest version of the API does not support the
creation of an Order from `DoDirectPayment`.
The `amt` s... | Shortcut for the DoAuthorization method.
Use the TRANSACTIONID from DoExpressCheckoutPayment for the
``transactionid``. The latest version of the API does not support the
creation of an Order from `DoDirectPayment`.
The `amt` should be the same as passed to `DoExpressCheckoutPayment`.
... |
def __detect_os_identity_api_version(self):
"""
Return preferred OpenStack Identity API version (either one of the two strings ``'2'`` or ``'3'``) or ``None``.
The following auto-detection strategies are tried (in this order):
#. Read the environmental variable `OS_IDENTITY_API_VERSION... | Return preferred OpenStack Identity API version (either one of the two strings ``'2'`` or ``'3'``) or ``None``.
The following auto-detection strategies are tried (in this order):
#. Read the environmental variable `OS_IDENTITY_API_VERSION` and check if its value is one of the two strings ``'2'`` or ``... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.