code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def compute_aesthetics(self, plot):
"""
Return a dataframe where the columns match the
aesthetic mappings.
Transformations like 'factor(cyl)' and other
expression evaluation are made in here
"""
data = self.data
aesthetics = self.layer_mapping(plot.mappi... | Return a dataframe where the columns match the
aesthetic mappings.
Transformations like 'factor(cyl)' and other
expression evaluation are made in here |
def acknowledge_message(self, delivery_tag, **kwargs):
"""Acknowledge the message delivery from RabbitMQ by sending a
Basic.Ack RPC method for the delivery tag.
:param int delivery_tag: The delivery tag from the Basic.Deliver frame
"""
logger.info('Acknowledging message', deliv... | Acknowledge the message delivery from RabbitMQ by sending a
Basic.Ack RPC method for the delivery tag.
:param int delivery_tag: The delivery tag from the Basic.Deliver frame |
def do_PROPPATCH(self, environ, start_response):
"""Handle PROPPATCH request to set or remove a property.
@see http://www.webdav.org/specs/rfc4918.html#METHOD_PROPPATCH
"""
path = environ["PATH_INFO"]
res = self._davProvider.get_resource_inst(path, environ)
# Only accep... | Handle PROPPATCH request to set or remove a property.
@see http://www.webdav.org/specs/rfc4918.html#METHOD_PROPPATCH |
def get_splits_query(self):
""" Returns the query for all splits for this security """
query = (
self.book.session.query(Split)
.join(Account)
.filter(Account.type != AccountType.trading.value)
.filter(Account.commodity_guid == self.security.guid)
... | Returns the query for all splits for this security |
def merge_result(res):
"""
Merge all items in `res` into a list.
This command is used when sending a command to multiple nodes
and they result from each node should be merged into a single list.
"""
if not isinstance(res, dict):
raise ValueError('Value should be of dict type')
resu... | Merge all items in `res` into a list.
This command is used when sending a command to multiple nodes
and they result from each node should be merged into a single list. |
def titleForFilepath( url ):
"""
Returns a gui title for this url.
:return <str>
"""
url = nativestring(url)
if url in XdkEntryItem.TITLE_MAP:
return XdkEntryItem.TITLE_MAP.get(url)
url = nativestring(url).replace('... | Returns a gui title for this url.
:return <str> |
def parse_author(self, value):
"""
Attempts to split an author name into last and first parts.
"""
tokens = tuple([t.upper().strip() for t in value.split(',')])
if len(tokens) == 1:
tokens = value.split(' ')
if len(tokens) > 0:
if len(tokens) > 1:
... | Attempts to split an author name into last and first parts. |
def pingable_ws_connect(request=None, on_message_callback=None,
on_ping_callback=None):
"""
A variation on websocket_connect that returns a PingableWSClientConnection
with on_ping_callback.
"""
# Copy and convert the headers dict/object (see comments in
# AsyncHTTPClient.... | A variation on websocket_connect that returns a PingableWSClientConnection
with on_ping_callback. |
def dnd_endSnooze(self, **kwargs) -> SlackResponse:
"""Ends the current user's snooze mode immediately."""
self._validate_xoxp_token()
return self.api_call("dnd.endSnooze", json=kwargs) | Ends the current user's snooze mode immediately. |
def predict_percentile(self, X, ancillary_X=None, p=0.5):
"""
Returns the median lifetimes for the individuals, by default. If the survival curve of an
individual does not cross ``p``, then the result is infinity.
http://stats.stackexchange.com/questions/102986/percentile-loss-functions
... | Returns the median lifetimes for the individuals, by default. If the survival curve of an
individual does not cross ``p``, then the result is infinity.
http://stats.stackexchange.com/questions/102986/percentile-loss-functions
Parameters
----------
X: numpy array or DataFrame
... |
def five_prime(self, upstream=1, downstream=0):
"""
Creates a BED/GFF file of the 5' end of each feature represented in the
table and returns the resulting pybedtools.BedTool object. Needs an
attached database.
Parameters
----------
upstream, downstream : int
... | Creates a BED/GFF file of the 5' end of each feature represented in the
table and returns the resulting pybedtools.BedTool object. Needs an
attached database.
Parameters
----------
upstream, downstream : int
Number of basepairs up and downstream to include |
def client(self):
"""Return a lazy-instantiated pymongo client.
When running with eventlet, connection causes IO and can result in more
than one MongoDB client getting instantiatied, so we wrap the code in
a semaphore to make sure only one mongodb client is instantiated per
Simp... | Return a lazy-instantiated pymongo client.
When running with eventlet, connection causes IO and can result in more
than one MongoDB client getting instantiatied, so we wrap the code in
a semaphore to make sure only one mongodb client is instantiated per
SimplDB class. |
def split(u, axis=0):
"""
Split an array into a list of arrays on the specified axis. The length
of the list is the shape of the array on the specified axis, and the
corresponding axis is removed from each entry in the list. This function
does not have the same behaviour as :func:`numpy.split`.
... | Split an array into a list of arrays on the specified axis. The length
of the list is the shape of the array on the specified axis, and the
corresponding axis is removed from each entry in the list. This function
does not have the same behaviour as :func:`numpy.split`.
Parameters
----------
u :... |
def _find_git_info(self, gitdir):
"""
Find information about the git repository, if this file is in a clone.
:param gitdir: path to the git repo's .git directory
:type gitdir: str
:returns: information about the git clone
:rtype: dict
"""
res = {'remotes'... | Find information about the git repository, if this file is in a clone.
:param gitdir: path to the git repo's .git directory
:type gitdir: str
:returns: information about the git clone
:rtype: dict |
def end_scan(self):
"""Ends an ongoing BLE scan started by :meth:`begin_scan`.
Returns:
a :class:`ScanResults` object containing the scan results.
"""
# TODO check states before/after
self._set_state(self._STATE_GAP_END)
self.api.ble_cmd_gap_end_procedure()
... | Ends an ongoing BLE scan started by :meth:`begin_scan`.
Returns:
a :class:`ScanResults` object containing the scan results. |
def posnegtoggle(number):
"""
Toggle a number between positive and negative.
The converter works as follows:
- 1 > -1
- -1 > 1
- 0 > 0
:type number: number
:param number: The number to toggle.
"""
if bool(number > 0):
return number - number * 2
elif bool(number < 0)... | Toggle a number between positive and negative.
The converter works as follows:
- 1 > -1
- -1 > 1
- 0 > 0
:type number: number
:param number: The number to toggle. |
def sender(self, body, stamp, url, sig):
"""Validate request is from Alexa.
Verifying that the Request was Sent by Alexa: https://goo.gl/AcrzB5.
Checking the Signature of the Request: https://goo.gl/FDkjBN.
Checking the Timestamp of the Request: https://goo.gl/Z5JhqZ
Args:
... | Validate request is from Alexa.
Verifying that the Request was Sent by Alexa: https://goo.gl/AcrzB5.
Checking the Signature of the Request: https://goo.gl/FDkjBN.
Checking the Timestamp of the Request: https://goo.gl/Z5JhqZ
Args:
body: str. HTTPS request body.
s... |
def opener(self):
"A reusable connection manager"
if self._opener is None:
log.debug("Creating connection handler")
opener = build_opener()
if self._cookies:
log.debug("Appending cookies")
else:
log.debug("No cookies to appe... | A reusable connection manager |
def yule_walker_regression(dx, Y, deg, res=None):
"""
:parameter X: time vector (disabled)
:parameter Y: stationary time series
:parameter deg: AR model degree
:return:
* a : Yule Walker parameters
* sig : Standard deviation of the noise term
* aicc : corrected Akaike Infor... | :parameter X: time vector (disabled)
:parameter Y: stationary time series
:parameter deg: AR model degree
:return:
* a : Yule Walker parameters
* sig : Standard deviation of the noise term
* aicc : corrected Akaike Information Criterion
* gamma : Autocorrelation function
... |
def get(self, key):
'''Return the object in `service` named by `key` or None.
Args:
key: Key naming the object to retrieve.
Returns:
object or None
'''
key = self._service_key(key)
return self._service_ops['get'](key) | Return the object in `service` named by `key` or None.
Args:
key: Key naming the object to retrieve.
Returns:
object or None |
def stack_patches(
patch_list, nr_row, nr_col, border=None,
pad=False, bgcolor=255, viz=False, lclick_cb=None):
"""
Stacked patches into grid, to produce visualizations like the following:
.. image:: https://github.com/tensorpack/tensorpack/raw/master/examples/GAN/demo/BEGAN-CelebA-samples.... | Stacked patches into grid, to produce visualizations like the following:
.. image:: https://github.com/tensorpack/tensorpack/raw/master/examples/GAN/demo/BEGAN-CelebA-samples.jpg
Args:
patch_list(list[ndarray] or ndarray): NHW or NHWC images in [0,255].
nr_row(int), nr_col(int): rows and cols ... |
def parse_uptime(uptime_str):
"""
Extract the uptime string from the given Cisco IOS Device.
Return the uptime in seconds as an integer
"""
# Initialize to zero
(years, weeks, days, hours, minutes) = (0, 0, 0, 0, 0)
uptime_str = uptime_str.strip()
time_li... | Extract the uptime string from the given Cisco IOS Device.
Return the uptime in seconds as an integer |
def by_col(cls, df, e, b, t=None, geom_col='geometry', inplace=False, **kwargs):
"""
Compute smoothing by columns in a dataframe. The bounding box and point
information is computed from the geometry column.
Parameters
-----------
df : pandas.DataFrame
... | Compute smoothing by columns in a dataframe. The bounding box and point
information is computed from the geometry column.
Parameters
-----------
df : pandas.DataFrame
a dataframe containing the data to be smoothed
e : string or list of strings
... |
def update(self, resource, id_or_uri=None, timeout=-1):
"""
Updates the specified alert resource.
Args:
resource (dict): Object to update.
timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
in OneVie... | Updates the specified alert resource.
Args:
resource (dict): Object to update.
timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
in OneView; it just stops waiting for its completion.
Returns:
d... |
def next_event(self):
"""Simulates the queue forward one event.
This method behaves identically to a :class:`.LossQueue` if the
arriving/departing agent is anything other than a
:class:`.ResourceAgent`. The differences are;
Arriving:
* If the :class:`.ResourceAgent` ha... | Simulates the queue forward one event.
This method behaves identically to a :class:`.LossQueue` if the
arriving/departing agent is anything other than a
:class:`.ResourceAgent`. The differences are;
Arriving:
* If the :class:`.ResourceAgent` has a resource then it deletes
... |
def load_remote_dataset(self, ds_str):
'''
Returns a dataset instance for the remote resource, either OPeNDAP or SOS
:param str ds_str: URL to the remote resource
'''
if opendap.is_opendap(ds_str):
return Dataset(ds_str)
else:
# Check if the HTTP... | Returns a dataset instance for the remote resource, either OPeNDAP or SOS
:param str ds_str: URL to the remote resource |
def on_end_validation(self, event):
"""
Switch back from validation mode to main Pmag GUI mode.
Hide validation frame and show main frame.
"""
self.Enable()
self.Show()
self.magic_gui_frame.Destroy() | Switch back from validation mode to main Pmag GUI mode.
Hide validation frame and show main frame. |
def get_dataset(self, key, info=None):
"""Load a dataset."""
if key in self.cache:
return self.cache[key]
logger.debug('Reading {}'.format(key.name))
# Get the dataset
# Get metadata for given dataset
variable = self.nc['/data/{}/measured/effective_radiance'
... | Load a dataset. |
def Register():
"""Adds all known parsers to the registry."""
# pyformat: disable
# Command parsers.
parsers.SINGLE_RESPONSE_PARSER_FACTORY.Register(
"Dpkg", linux_cmd_parser.DpkgCmdParser)
parsers.SINGLE_RESPONSE_PARSER_FACTORY.Register(
"Dmidecode", linux_cmd_parser.DmidecodeCmdParser)
parser... | Adds all known parsers to the registry. |
def match(self, path):
'''Attempts to match a url to the given path. If successful, a tuple is
returned. The first item is the matchd function and the second item is
a dictionary containing items to be passed to the function parsed from
the provided path.
If the provided path do... | Attempts to match a url to the given path. If successful, a tuple is
returned. The first item is the matchd function and the second item is
a dictionary containing items to be passed to the function parsed from
the provided path.
If the provided path does not match this url rule then a
... |
def add_fragment(self, fragment, as_last=True):
"""
Add the given text fragment as the first or last child of the root node
of the text file tree.
:param fragment: the text fragment to be added
:type fragment: :class:`~aeneas.textfile.TextFragment`
:param bool as_last: ... | Add the given text fragment as the first or last child of the root node
of the text file tree.
:param fragment: the text fragment to be added
:type fragment: :class:`~aeneas.textfile.TextFragment`
:param bool as_last: if ``True`` append fragment, otherwise prepend it |
def get_module_classes(node):
"""
Return classes associated with a given module
"""
return [
child
for child in ast.walk(node)
if isinstance(child, ast.ClassDef)
] | Return classes associated with a given module |
def create_xml_path(path, **kwargs):
'''
Start a transient domain based on the XML-file path passed to the function
:param path: path to a file containing the libvirt XML definition of the domain
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:par... | Start a transient domain based on the XML-file path passed to the function
:param path: path to a file containing the libvirt XML definition of the domain
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding... |
def calculate_between_class_scatter_matrix(X, y):
"""Calculates the Between-Class Scatter matrix
Parameters:
-----------
X : array-like, shape (m, n) - the samples
y : array-like, shape (m, ) - the class labels
Returns:
--------
between_class_scatter_matrix : array-like, shape (n, ... | Calculates the Between-Class Scatter matrix
Parameters:
-----------
X : array-like, shape (m, n) - the samples
y : array-like, shape (m, ) - the class labels
Returns:
--------
between_class_scatter_matrix : array-like, shape (n, n) |
def full_exec_request_actions(actions, func=None, render_func=None):
"""Full process to execute before, during and after actions.
If func is specified, it will be called after exec_request_actions()
unless a ContextExitException was raised. If render_func is specified,
it will be called after exec_reque... | Full process to execute before, during and after actions.
If func is specified, it will be called after exec_request_actions()
unless a ContextExitException was raised. If render_func is specified,
it will be called after exec_request_actions() only if there is no
response. exec_after_request_actions() ... |
def patch_request(self, uri, body, custom_headers=None, timeout=-1):
"""Uses the PATCH to update a resource.
Only one operation can be performed in each PATCH call.
Args:
body (list): Patch request body
timeout (int): Timeout in seconds. Wait for task completion by defa... | Uses the PATCH to update a resource.
Only one operation can be performed in each PATCH call.
Args:
body (list): Patch request body
timeout (int): Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
in OneView; it jus... |
def get_image_dimensions(request):
"""
Verifies or calculates image dimensions.
:param request: OGC-type request
:type request: WmsRequest or WcsRequest
:return: horizontal and vertical dimensions of requested image
:rtype: (int or str, int or str)
"""
if... | Verifies or calculates image dimensions.
:param request: OGC-type request
:type request: WmsRequest or WcsRequest
:return: horizontal and vertical dimensions of requested image
:rtype: (int or str, int or str) |
def _to_java_object_rdd(self):
""" Return a JavaRDD of Object by unpickling
It will convert each Python object into Java object by Pyrolite, whenever the
RDD is serialized in batch or not.
"""
rdd = self._pickled()
return self.ctx._jvm.SerDeUtil.pythonToJava(rdd._jrdd, T... | Return a JavaRDD of Object by unpickling
It will convert each Python object into Java object by Pyrolite, whenever the
RDD is serialized in batch or not. |
def _expand_base_distribution_mean(self):
"""Ensures `self.distribution.mean()` has `[batch, event]` shape."""
single_draw_shape = concat_vectors(self.batch_shape_tensor(),
self.event_shape_tensor())
m = tf.reshape(
self.distribution.mean(), # A scalar.
... | Ensures `self.distribution.mean()` has `[batch, event]` shape. |
def _node_add_without_peer_leaf(self, node_sum, child_other):
'''_node_add_without_peer_leaf
Low-level api: Apply delta child_other to node_sum when there is no peer
of child_other can be found under node_sum. child_other is a leaf node.
Element node_sum will be modified during the proc... | _node_add_without_peer_leaf
Low-level api: Apply delta child_other to node_sum when there is no peer
of child_other can be found under node_sum. child_other is a leaf node.
Element node_sum will be modified during the process.
Parameters
----------
node_sum : `Element`... |
def delete_stack(awsclient, conf, feedback=True):
"""Delete the stack from AWS cloud.
:param awsclient:
:param conf:
:param feedback: print out stack events (defaults to True)
"""
client_cf = awsclient.get_client('cloudformation')
stack_name = _get_stack_name(conf)
last_event = _get_sta... | Delete the stack from AWS cloud.
:param awsclient:
:param conf:
:param feedback: print out stack events (defaults to True) |
def _get_entity(entity_id):
"""
Uses the request context to retrieve a :class:`meteorpi_model.CameraStatus`, :class:`meteorpi_model.Event` or
:class:`meteorpi_model.FileRecord` from the POSTed JSON string.
:param string entity_id:
The ID of a CameraStatus, Event or FileRecor... | Uses the request context to retrieve a :class:`meteorpi_model.CameraStatus`, :class:`meteorpi_model.Event` or
:class:`meteorpi_model.FileRecord` from the POSTed JSON string.
:param string entity_id:
The ID of a CameraStatus, Event or FileRecord contained within the request
:return:
... |
def _printAvailableCheckpoints(experimentDir):
"""List available checkpoints for the specified experiment."""
checkpointParentDir = getCheckpointParentDir(experimentDir)
if not os.path.exists(checkpointParentDir):
print "No available checkpoints."
return
checkpointDirs = [x for x in os.listdir(checkpo... | List available checkpoints for the specified experiment. |
def clean_username(self):
"""
Validate that the username is alphanumeric and is not already
in use. Don't fail if users username is provided.
"""
user = None
try:
user = User.objects.get(username__iexact=self.\
cleaned_data['username'])
... | Validate that the username is alphanumeric and is not already
in use. Don't fail if users username is provided. |
def qos_rcv_queue_multicast_threshold_traffic_class0(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com:mgmt:brocade-qos")
rcv_queue = ET.SubElement(qos, "rcv-queue")
multicast = ET.SubElemen... | Auto Generated Code |
def index_discovered_zonefiles(self, lastblock):
"""
Go through the list of zone files we discovered via Atlas, grouped by name and ordered by block height.
Find all subsequent zone files for this name, and process all subdomain operations contained within them.
"""
all_queued_zf... | Go through the list of zone files we discovered via Atlas, grouped by name and ordered by block height.
Find all subsequent zone files for this name, and process all subdomain operations contained within them. |
def update_vrf_table(self, route_dist, prefix=None, next_hop=None,
route_family=None, route_type=None, tunnel_type=None,
is_withdraw=False, redundancy_mode=None,
pmsi_tunnel_type=None, **kwargs):
"""Update a BGP route in the VRF table id... | Update a BGP route in the VRF table identified by `route_dist`
with the given `next_hop`.
If `is_withdraw` is False, which is the default, add a BGP route
to the VRF table identified by `route_dist` with the given
`next_hop`.
If `is_withdraw` is True, remove a BGP route from the... |
def to_dataframe(self, columns=None):
"""Convert a multi-dim to a pandas dataframe."""
if not isinstance(self.measured_value, DimensionedMeasuredValue):
raise TypeError(
'Only a dimensioned measurement can be converted to a DataFrame')
if columns is None:
columns = [d.name for d in self... | Convert a multi-dim to a pandas dataframe. |
def get_default_drive(self, request_drive=False):
""" Returns a Drive instance
:param request_drive: True will make an api call to retrieve the drive
data
:return: default One Drive
:rtype: Drive
"""
if request_drive is False:
return Drive(con=self.c... | Returns a Drive instance
:param request_drive: True will make an api call to retrieve the drive
data
:return: default One Drive
:rtype: Drive |
def compute_range(travel_data, attr, travel_time_attr, dist, agg=np.sum):
"""
Compute a zone-based accessibility query using the urbansim format
travel data dataframe.
Parameters
----------
travel_data : dataframe
The dataframe of urbansim format travel data. Has from_zone_id as
... | Compute a zone-based accessibility query using the urbansim format
travel data dataframe.
Parameters
----------
travel_data : dataframe
The dataframe of urbansim format travel data. Has from_zone_id as
first index, to_zone_id as second index, and different impedances
between zo... |
def build_directory():
'''
Build the directory for Whoosh database, and locale.
'''
if os.path.exists('locale'):
pass
else:
os.mkdir('locale')
if os.path.exists(WHOOSH_DB_DIR):
pass
else:
os.makedirs(WHOOSH_DB_DIR) | Build the directory for Whoosh database, and locale. |
def timeout_request_rebinding(self):
"""Timeout of request rebinding on REBINDING state.
Same comments as in
:func:`dhcpcapfsm.DHCPCAPFSM.timeout_requesting`.
"""
logger.debug("C6.2:T In %s, timeout receiving response to request.",
self.current_state)
... | Timeout of request rebinding on REBINDING state.
Same comments as in
:func:`dhcpcapfsm.DHCPCAPFSM.timeout_requesting`. |
def wait(self, timeout=None):
"""Wait for the request to finish, optionally timing out. Returns True if the request has finished or False if
it is still pending.
Raises [LinkException](AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if the request failed due to a
network related... | Wait for the request to finish, optionally timing out. Returns True if the request has finished or False if
it is still pending.
Raises [LinkException](AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if the request failed due to a
network related problem. |
def get(self, **queryparams):
"""
Get links to all other resources available in the API.
:param queryparams: The query string parameters
queryparams['fields'] = []
queryparams['exclude_fields'] = []
"""
return self._mc_client._get(url=self._build_path(), **queryp... | Get links to all other resources available in the API.
:param queryparams: The query string parameters
queryparams['fields'] = []
queryparams['exclude_fields'] = [] |
def dispose(self):
"""
Disposes every performed registration; the container can then be used again
"""
for registration in self._registrations.values():
registration.dispose()
self._registrations = {} | Disposes every performed registration; the container can then be used again |
def is_magic(self):
"""Return True iff this method is a magic method (e.g., `__str__`)."""
return (self.name.startswith('__') and
self.name.endswith('__') and
self.name not in VARIADIC_MAGIC_METHODS) | Return True iff this method is a magic method (e.g., `__str__`). |
def add_resources(self, resources):
"""
Adds new resources to the event.
*resources* can be a list of email addresses or :class:`ExchangeEventAttendee` objects.
"""
new_resources = self._build_resource_dictionary(resources)
for key in new_resources:
self._resources[key] = new_resources[k... | Adds new resources to the event.
*resources* can be a list of email addresses or :class:`ExchangeEventAttendee` objects. |
def with_pattern(pattern, regex_group_count=None):
"""Attach a regular expression pattern matcher to a custom type converter
function.
This annotates the type converter with the :attr:`pattern` attribute.
EXAMPLE:
>>> import parse
>>> @parse.with_pattern(r"\d+")
... def parse_n... | Attach a regular expression pattern matcher to a custom type converter
function.
This annotates the type converter with the :attr:`pattern` attribute.
EXAMPLE:
>>> import parse
>>> @parse.with_pattern(r"\d+")
... def parse_number(text):
... return int(text)
is equi... |
async def _pause(self, ctx):
""" Pauses/Resumes the current track. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.is_playing:
return await ctx.send('Not playing.')
if player.paused:
await player.set_pause(False)
await... | Pauses/Resumes the current track. |
def requestCheckRegularDocker(origAppliance, registryName, imageName, tag):
"""
Checks to see if an image exists using the requests library.
URL is based on the docker v2 schema described here:
https://docs.docker.com/registry/spec/manifest-v2-2/
This has the following format:
https://{website... | Checks to see if an image exists using the requests library.
URL is based on the docker v2 schema described here:
https://docs.docker.com/registry/spec/manifest-v2-2/
This has the following format:
https://{websitehostname}.io/v2/{repo}/manifests/{tag}
Does not work with the official (docker.io) ... |
def parse_prefix(prefix, default_length=128):
"""
Splits the given IP prefix into a network address and a prefix length.
If the prefix does not have a length (i.e., it is a simple IP address),
it is presumed to have the given default length.
:type prefix: string
:param prefix: An IP mask.
... | Splits the given IP prefix into a network address and a prefix length.
If the prefix does not have a length (i.e., it is a simple IP address),
it is presumed to have the given default length.
:type prefix: string
:param prefix: An IP mask.
:type default_length: long
:param default_length: The... |
def create(self, stylename, **kwargs):
""" Creates a new style which inherits from the default style,
or any other style which name is supplied to the optional template parameter.
"""
if stylename == "default":
self[stylename] = style(stylename, self._ctx, **kwargs)
... | Creates a new style which inherits from the default style,
or any other style which name is supplied to the optional template parameter. |
def email_verifier(self, email, raw=False):
"""
Verify the deliverability of a given email adress.abs
:param email: The email adress to check.
:param raw: Gives back the entire response instead of just the 'data'.
:return: Full payload of the query as a dict.
"""
... | Verify the deliverability of a given email adress.abs
:param email: The email adress to check.
:param raw: Gives back the entire response instead of just the 'data'.
:return: Full payload of the query as a dict. |
def _WriteSerializedAttributeContainerList(self, container_type):
"""Writes a serialized attribute container list.
Args:
container_type (str): attribute container type.
"""
if container_type == self._CONTAINER_TYPE_EVENT:
if not self._serialized_event_heap.data_size:
return
n... | Writes a serialized attribute container list.
Args:
container_type (str): attribute container type. |
def _send_response(self, http_code, message=None, headers=None):
"""Sends HTTP response code, message and headers."""
self.send_response(http_code, message)
if headers:
for header in headers:
self.send_header(*header)
self.end_headers() | Sends HTTP response code, message and headers. |
def make_zoom_block(min,max,count,colorkeyfields,bounds,filter_file_dictionary):
if min == '' and max == '' and not bounds == True:
return ''
if colorkeyfields == False and bounds == False:
block = '''
map.on('zoomend', function(e) {
if ( (map.getZoom() >= %s)&&(map.getZoom() <= %s) ){
if (map.hasLay... | else:
block = '''
map.on('zoomend', function(e) {
if ( (map.getZoom() >= %s)&&(map.getZoom() <= %s) ){
if (map.hasLayer(dataLayer) != true) {
map.addLayer(dataLayer)
}
}
else { map.removeLayer( dataLayer ) }
})
map.on('click',function(e) {
var skillsSelect = document.getElementById("mapStyle")... |
def splitroot(self, part, sep=sep):
"""
Splits path string into drive, root and relative path
Uses '/artifactory/' as a splitting point in URI. Everything
before it, including '/artifactory/' itself is treated as drive.
The next folder is treated as root, and everything else is ... | Splits path string into drive, root and relative path
Uses '/artifactory/' as a splitting point in URI. Everything
before it, including '/artifactory/' itself is treated as drive.
The next folder is treated as root, and everything else is taken
for relative path.
If '/artifacto... |
def remove(self, path):
"""Remove the FakeFile object at the specified file path.
Args:
path: Path to file to be removed.
Raises:
OSError: if path points to a directory.
OSError: if path does not exist.
OSError: if removal failed.
"""
... | Remove the FakeFile object at the specified file path.
Args:
path: Path to file to be removed.
Raises:
OSError: if path points to a directory.
OSError: if path does not exist.
OSError: if removal failed. |
def setOverlayName(self, ulOverlayHandle, pchName):
"""set the name to use for this overlay"""
fn = self.function_table.setOverlayName
result = fn(ulOverlayHandle, pchName)
return result | set the name to use for this overlay |
def rollback(using=None):
"""
This function does the rollback itself and resets the dirty flag.
"""
if using is None:
for using in tldap.backend.connections:
connection = tldap.backend.connections[using]
connection.rollback()
return
connection = tldap.backend.... | This function does the rollback itself and resets the dirty flag. |
def chunks(iterable, n):
"""
A python generator that yields 100-length sub-list chunks.
Input: - full_list: The input list that is to be separated in chunks of 100.
- chunk_size: Should be set to 100, unless the Twitter API changes.
Yields: - sub_list: List chunks of length 100.
"""
... | A python generator that yields 100-length sub-list chunks.
Input: - full_list: The input list that is to be separated in chunks of 100.
- chunk_size: Should be set to 100, unless the Twitter API changes.
Yields: - sub_list: List chunks of length 100. |
def delete_fallbackserver(self, serverid, data):
"""Delete Fallback server"""
return self.api_call(
ENDPOINTS['fallbackservers']['delete'],
dict(serverid=serverid),
body=data) | Delete Fallback server |
def autodoc_process_docstring(app, what, name, obj, options, lines):
"""Handler for the event emitted when autodoc processes a docstring.
See http://sphinx-doc.org/ext/autodoc.html#event-autodoc-process-docstring.
The TL;DR is that we can modify ``lines`` in-place to influence the output.
"""
# che... | Handler for the event emitted when autodoc processes a docstring.
See http://sphinx-doc.org/ext/autodoc.html#event-autodoc-process-docstring.
The TL;DR is that we can modify ``lines`` in-place to influence the output. |
def _update_physics(self):
"""r
Update physics using the current value of 'quantity'
Notes
-----
The algorithm directly writes the value of 'quantity' into the phase.
This method was implemented relaxing one of the OpenPNM rules of
algorithms not being able to wr... | r
Update physics using the current value of 'quantity'
Notes
-----
The algorithm directly writes the value of 'quantity' into the phase.
This method was implemented relaxing one of the OpenPNM rules of
algorithms not being able to write into phases. |
def _prepare_for_submission(self, tempfolder, inputdict):
"""
Create input files.
:param tempfolder: aiida.common.folders.Folder subclass where
the plugin should put all its files.
:param inputdict: dictionary of the input nodes as they would
be r... | Create input files.
:param tempfolder: aiida.common.folders.Folder subclass where
the plugin should put all its files.
:param inputdict: dictionary of the input nodes as they would
be returned by get_inputs_dict |
def renders_impl(self, template_content, context, at_paths=None,
at_encoding=anytemplate.compat.ENCODING,
**kwargs):
"""
Render given template string and return the result.
:param template_content: Template content
:param context: A dict or dict... | Render given template string and return the result.
:param template_content: Template content
:param context: A dict or dict-like object to instantiate given
template file
:param at_paths: Template search paths
:param at_encoding: Template encoding
:param kwargs: Key... |
def replace_launch_config(self, scaling_group, launch_config_type,
server_name, image, flavor, disk_config=None, metadata=None,
personality=None, networks=None, load_balancers=None,
key_name=None, config_drive=False, user_data=None):
"""
Replace an existing launch con... | Replace an existing launch configuration. All of the attributes must be
specified. If you wish to delete any of the optional attributes, pass
them in as None. |
def as_tmpfile(self, tmpdir=None):
"""
Copy the pseudopotential to a temporary a file and returns a new pseudopotential object.
Useful for unit tests in which we have to change the content of the file.
Args:
tmpdir: If None, a new temporary directory is created and files are... | Copy the pseudopotential to a temporary a file and returns a new pseudopotential object.
Useful for unit tests in which we have to change the content of the file.
Args:
tmpdir: If None, a new temporary directory is created and files are copied here
else tmpdir is used. |
def get_mainmarket_ip(ip, port):
"""[summary]
Arguments:
ip {[type]} -- [description]
port {[type]} -- [description]
Returns:
[type] -- [description]
"""
global best_ip
if ip is None and port is None and best_ip['stock']['ip'] is None and best_ip['stock']['port'] is No... | [summary]
Arguments:
ip {[type]} -- [description]
port {[type]} -- [description]
Returns:
[type] -- [description] |
def spcol(knots, order, tau):
"""Return collocation matrix.
Minimal emulation of MATLAB's ``spcol``.
Parameters:
knots:
rank-1 array, knot vector (with appropriately repeated endpoints; see `augknt`, `aptknt`)
order:
int, >= 0, order of spline
tau:
rank-1 array, collocation sit... | Return collocation matrix.
Minimal emulation of MATLAB's ``spcol``.
Parameters:
knots:
rank-1 array, knot vector (with appropriately repeated endpoints; see `augknt`, `aptknt`)
order:
int, >= 0, order of spline
tau:
rank-1 array, collocation sites
Returns:
rank-2 array A such ... |
def _parse_document(self):
"""Parse system.profile doc, copy all values to member variables."""
self._reset()
doc = self._profile_doc
self._split_tokens_calculated = True
self._split_tokens = None
self._duration_calculated = True
self._duration = doc[u'millis']... | Parse system.profile doc, copy all values to member variables. |
def _filterCopy(self, dataFile, newStart, newEnd, newDataDir):
"""
Copies the data file to a new file in the tmp dir, filtering it according to newStart and newEnd and adjusting
the times as appropriate so it starts from 0.
:param dataFile: the input file.
:param newStart: the n... | Copies the data file to a new file in the tmp dir, filtering it according to newStart and newEnd and adjusting
the times as appropriate so it starts from 0.
:param dataFile: the input file.
:param newStart: the new start time.
:param newEnd: the new end time.
:param newDataDir: ... |
def _get_repo_path(pathname, levels=None):
"""
Given a file or directory name, determine the root of the git repository
this path is under. If given, this won't look any higher than ``levels``
(that is, if ``levels=0`` then the given path must be the root of the git
repository and is returned if so... | Given a file or directory name, determine the root of the git repository
this path is under. If given, this won't look any higher than ``levels``
(that is, if ``levels=0`` then the given path must be the root of the git
repository and is returned if so.
Returns `None` if the given path could not be de... |
def write_how_many(self, file):
""" Writes component numbers to a table.
"""
report = CaseReport(self.case)
# Map component labels to attribute names
components = [("Bus", "n_buses"), ("Generator", "n_generators"),
("Committed Generator", "n_online_generators"),
... | Writes component numbers to a table. |
def clone_to(self, target_catalog):
"""need to clone both the enclosed object + the wrapping asset"""
def _clone(obj_id):
package_name = obj_id.get_identifier_namespace().split('.')[0]
obj_name = obj_id.get_identifier_namespace().split('.')[1].lower()
catalogs = {
... | need to clone both the enclosed object + the wrapping asset |
def breadcrumb_safe(context, label, viewname, *args, **kwargs):
"""
Same as breadcrumb but label is not escaped.
"""
append_breadcrumb(context, _(label), viewname, args, kwargs)
return '' | Same as breadcrumb but label is not escaped. |
def get_old_value(self, args, kwargs, default=None):
# type: (List[Any], Dict[str, Any], Any) -> Any
"""Returns the old value of the named argument without replacing it.
Returns ``default`` if the argument is not present.
"""
if self.arg_pos is not None and len(args) > self.arg_... | Returns the old value of the named argument without replacing it.
Returns ``default`` if the argument is not present. |
def copy_object(self, container, obj, metadata=None,
destination=None, **kwargs):
"""Copy object
:param container: container name (Container is equivalent to
Bucket term in Amazon).
:param obj: object name (Object is equivalent to
... | Copy object
:param container: container name (Container is equivalent to
Bucket term in Amazon).
:param obj: object name (Object is equivalent to
Key term in Amazon).
:param destination: The container and object name of the destination
... |
def parse_entry(self, row):
"""Parse an individual VCF entry and return a VCFEntry which contains information about
the call (such as alternative allele, zygosity, etc.)
"""
var_call = VCFEntry(self.individuals)
var_call.parse_entry(row)
return var_call | Parse an individual VCF entry and return a VCFEntry which contains information about
the call (such as alternative allele, zygosity, etc.) |
def _CreateZMQSocket(self):
"""Creates a ZeroMQ socket."""
logger.debug('Creating socket for {0:s}'.format(self.name))
if not self._zmq_context:
self._zmq_context = zmq.Context()
# The terminate and close threading events need to be created when the
# socket is opened. Threading events are u... | Creates a ZeroMQ socket. |
def _from_dict(cls, _dict):
"""Initialize a SyntaxResult object from a json dictionary."""
args = {}
if 'tokens' in _dict:
args['tokens'] = [
TokenResult._from_dict(x) for x in (_dict.get('tokens'))
]
if 'sentences' in _dict:
args['sent... | Initialize a SyntaxResult object from a json dictionary. |
def md5(self):
"""
MD5 of scene which will change when meshes or
transforms are changed
Returns
--------
hashed: str, MD5 hash of scene
"""
# start with transforms hash
hashes = [self.graph.md5()]
for g in self.geometry.values():
... | MD5 of scene which will change when meshes or
transforms are changed
Returns
--------
hashed: str, MD5 hash of scene |
async def read_data(self, stream_id: int) -> bytes:
"""Read data from the specified stream until it is closed by the remote
peer. If the stream is never ended, this never returns.
"""
frames = [f async for f in self.stream_frames(stream_id)]
return b''.join(frames) | Read data from the specified stream until it is closed by the remote
peer. If the stream is never ended, this never returns. |
def view_package_path(self, package: str) -> _PATH:
'''Print the path to the APK of the given.'''
if package not in self.view_packgets_list():
raise NoSuchPackageException(
f'There is no such package {package!r}.')
output, _ = self._execute(
'-s', self.dev... | Print the path to the APK of the given. |
def _common(ret, name, service_name, kwargs):
'''
Returns: tuple whose first element is a bool indicating success or failure
and the second element is either a ret dict for salt or an object
'''
if 'interface' not in kwargs and 'public_url' not in kwargs:
kwargs['interface'] = name
... | Returns: tuple whose first element is a bool indicating success or failure
and the second element is either a ret dict for salt or an object |
def _ReadParserPresetsFromFile(self):
"""Reads the parser presets from the presets.yaml file.
Raises:
BadConfigOption: if the parser presets file cannot be read.
"""
self._presets_file = os.path.join(
self._data_location, self._PRESETS_FILE_NAME)
if not os.path.isfile(self._presets_fi... | Reads the parser presets from the presets.yaml file.
Raises:
BadConfigOption: if the parser presets file cannot be read. |
def _list_gids():
'''
Return a list of gids in use
'''
output = __salt__['cmd.run'](
['dscacheutil', '-q', 'group'],
output_loglevel='quiet',
python_shell=False
)
ret = set()
for line in salt.utils.itertools.split(output, '\n'):
if line.startswith('gid:'):
... | Return a list of gids in use |
def list(self):
"""
List all VMware VMs
"""
try:
return (yield from self._vmware_manager.list_vms())
except VMwareError as e:
raise GNS3VMError("Could not list VMware VMs: {}".format(str(e))) | List all VMware VMs |
def filter_oauth_params(params):
"""Removes all non oauth parameters from a dict or a list of params."""
is_oauth = lambda kv: kv[0].startswith("oauth_")
if isinstance(params, dict):
return list(filter(is_oauth, list(params.items())))
else:
return list(filter(is_oauth, params)) | Removes all non oauth parameters from a dict or a list of params. |
def get_csv_next_event_start(location, event_buffer):
""" determin the event start and end of *any* valid event """
start = -1
end = -1
event_start = event_buffer.find("\n", location + 1)
event_end = event_buffer.find('"\n', event_start + 1)
while (event_end > 0):
parts = event_buffer... | determin the event start and end of *any* valid event |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.