text stringlengths 81 112k |
|---|
Return a generator function which yields every time the user presses
return.
def press_enter(multiple=False, silent=False):
"""Return a generator function which yields every time the user presses
return."""
def f():
try:
while True:
if silent:
yi... |
Listen for a 'ping' broadcast message from an unbooted SpiNNaker board.
Unbooted SpiNNaker boards send out a UDP broadcast message every 4-ish
seconds on port 54321. This function listens for such messages and reports
the IP address that it came from.
Parameters
----------
timeout : float
... |
Remove any files we may have uploaded from the cache.
def clear_cache(m, files_processed):
"""Remove any files we may have uploaded from the cache. """
for what, reason, url, path in files_processed:
cp = m.doc.downloader.cache_path(url)
if m.cache.exists(cp):
m.cache.remove(cp) |
Fill categoricals with 'NA', possibly creating a new category,
and fill other NaNa with blanks
def fill_categorical_na(df, nan_cat='NA'):
"""Fill categoricals with 'NA', possibly creating a new category,
and fill other NaNa with blanks """
for col in df.columns[df.isna().any()].tolist():
if df... |
gets the unique ip addresses of the executors of the current application
This uses the REST API of the status web UI on the driver (http://spark.apache.org/docs/latest/monitoring.html)
:param sc: Spark context
:return: set of ip addresses
def executor_ips(sc):
""" gets the unique ip addresses of ... |
Returns a new Spark Context (sc) object with added properties set
:param sc: current SparkContext if None will create a new one
:param app_name: name of new spark app
:param master: url to master, if None will get from current sc
:param wait: when to return after asking for a new sc (or max of tim... |
Decorator function for functions that handle spark context.
If a function changes sc we might lose it if an error occurs in the function.
In the event of an error this decorator will log the error but return sc.
:param func: function to decorate
:return: decorated function
def fallback(func):
... |
Decorator for functions so they could get as input a thunder.Images / thunder.Series object,
while they are expecting an rdd. Also will return the data from rdd to the appropriate type
Assumes only one input object of type Images/Series, and up to one output object of type RDD
:param func: function to ... |
balanced_repartition(data, partitions)
Reparations an RDD making sure data is evenly distributed across partitions
for Spark version < 2.1 (see: https://issues.apache.org/jira/browse/SPARK-17817)
or < 2.3 when #partitions is power of 2 (see: https://issues.apache.org/jira/browse/SPARK-21782)
:para... |
Regroup an rdd using a new key added that is 0 ... number of groups - 1
:param rdd: input rdd as a (k,v) pairs
:param groups: number of groups to concatenate to
:param check_first: check if first value is a key value pair.
:return: a new rdd in the form of (groupNum, list of (k, v) in that group) ... |
Saves an rdd by grouping all the records of each partition as one pickle file
:param rdd: rdd to save
:param path: where to save
:param batch_size: batch size to pass to spark saveAsPickleFile
:param overwrite: if directory exist whether to overwrite
def save_rdd_as_pickle(rdd, path, batch_size=1... |
Loads an rdd that was saved as one pickle file per partition
:param sc: Spark Context
:param path: directory to load from
:param min_partitions: minimum number of partitions. If None will be sc.defaultParallelism
:param return_type: what to return:
'rdd' - RDD
'images' - Thunder ... |
Return a geopandas dataframe
def geo(self):
"""Return a geopandas dataframe"""
import geopandas as gpd
from shapely.geometry.polygon import BaseGeometry
from shapely.wkt import loads
gdf = gpd.GeoDataFrame(self)
first = next(gdf.iterrows())[1].geometry
if isin... |
Yield rows like a partition does, with a header first, then rows.
def rows(self):
"""Yield rows like a partition does, with a header first, then rows. """
yield [self.index.name] + list(self.columns)
for t in self.itertuples():
yield list(t) |
Check whether the node_set properties match the given model type definition
def _matches_node_set_props(type_info, node_set_props):
"""
Check whether the node_set properties match the given model type definition
"""
matches = None
for key in node_set_props:
ns_val = node_set_props[key]
... |
Return a NeuroMLDocument with (most of) the contents of the Sonata model
def get_neuroml_from_sonata(sonata_filename, id, generate_lems = True, format='xml'):
"""
Return a NeuroMLDocument with (most of) the contents of the Sonata model
"""
from neuroml.hdf5.NetworkBuilder import NetworkBuilder
... |
Search the strings in a config file for a substitutable value, e.g.
"morphologies_dir": "$COMPONENT_DIR/morphologies",
def subs(self, path):
"""
Search the strings in a config file for a substitutable value, e.g.
"morphologies_dir": "$COMPONENT_DIR/morphologies",
"... |
Main method to parse the Sonata files and call the appropriate methods
in the handler
def parse(self, handler):
"""
Main method to parse the Sonata files and call the appropriate methods
in the handler
"""
################################################################... |
Based on cell & synapse properties found, create the corresponding NeuroML components
def add_neuroml_components(self, nml_doc):
"""
Based on cell & synapse properties found, create the corresponding NeuroML components
"""
is_nest = False
print_v("Adding NeuroML cel... |
Generate a LEMS file to use in simulations of the NeuroML file
def generate_lems_file(self, nml_file_name, nml_doc):
"""
Generate a LEMS file to use in simulations of the NeuroML file
"""
#pp.pprint(self.simulation_config)
#pp.pprint(self.pop_comp_info)
#pp.... |
Clip input geometry to SRS bounds of given TilePyramid.
If geometry passes the antimeridian, it will be split up in a multipart
geometry and shifted to within the SRS boundaries.
Note: geometry SRS must be the TilePyramid SRS!
- geometry: any shapely geometry
- pyramid: a TilePyramid object
- ... |
Extend bounds to be aligned with union of tile bboxes.
- bounds: (left, bottom, right, top)
- tile_pyramid: a TilePyramid object
- zoom: target zoom level
- pixelbuffer: apply pixelbuffer
def snap_bounds(bounds=None, tile_pyramid=None, zoom=None, pixelbuffer=0):
"""
Extend bounds to be aligned... |
Verify that shape corresponds to bounds apect ratio.
def _verify_shape_bounds(shape, bounds):
"""Verify that shape corresponds to bounds apect ratio."""
if not isinstance(shape, (tuple, list)) or len(shape) != 2:
raise TypeError(
"shape must be a tuple or list with two elements: %s" % str(s... |
Return all tiles from tilepyramid intersecting with tile.
def _tile_intersecting_tilepyramid(tile, tp):
"""Return all tiles from tilepyramid intersecting with tile."""
if tile.tp.grid != tp.grid:
raise ValueError("Tile and TilePyramid source grids must be the same.")
tile_metatiling = tile.tile_pyr... |
Return also Tiles if bounds cross the antimeridian.
def _global_tiles_from_bounds(tp, bounds, zoom):
"""Return also Tiles if bounds cross the antimeridian."""
seen = set()
# clip to tilepyramid top and bottom bounds
left, right = bounds.left, bounds.right
top = tp.top if bounds.top > tp.top else b... |
Return all tiles intersecting with bounds.
def _tiles_from_cleaned_bounds(tp, bounds, zoom):
"""Return all tiles intersecting with bounds."""
lb = _tile_from_xy(tp, bounds.left, bounds.bottom, zoom, on_edge_use="rt")
rt = _tile_from_xy(tp, bounds.right, bounds.top, zoom, on_edge_use="lb")
for tile_id i... |
The `mp open` command will open a resource with the system application, such as Excel or OpenOffice
def open_args(subparsers):
"""
The `mp open` command will open a resource with the system application, such as Excel or OpenOffice
"""
parser = subparsers.add_parser(
'open',
help='open ... |
A memoized wrapper around :py:func:`rig.geometry.concentric_hexagons`
which memoizes the coordinates and stores them as a tuple. Note that the
caller must manually offset the coordinates as required.
This wrapper is used to avoid the need to repeatedly call
:py:func:`rig.geometry.concentric_hexagons` f... |
Produce a shortest path tree for a given net using NER.
This is the kernel of the NER algorithm.
Parameters
----------
source : (x, y)
The coordinate of the source vertex.
destinations : iterable([(x, y), ...])
The coordinates of destination vertices.
width : int
Width ... |
Copy a RoutingTree (containing nothing but RoutingTrees), disconnecting
nodes which are not connected in the machine.
Note that if a dead chip is part of the input RoutingTree, no corresponding
node will be included in the copy. The assumption behind this is that the
only reason a tree would visit a de... |
Use A* to find a path from any of the sources to the sink.
Note that the heuristic means that the search will proceed towards
heuristic_source without any concern for any other sources. This means that
the algorithm may miss a very close neighbour in order to pursue its goal
of reaching heuristic_sourc... |
Quickly determine if a route uses any dead links.
Parameters
----------
root : :py:class:`~rig.place_and_route.routing_tree.RoutingTree`
The root of the RoutingTree which contains nothing but RoutingTrees
(i.e. no vertices and links).
machine : :py:class:`~rig.place_and_route.Machine`
... |
Modify a RoutingTree to route-around dead links in a Machine.
Uses A* to reconnect disconnected branches of the tree (due to dead links
in the machine).
Parameters
----------
root : :py:class:`~rig.place_and_route.routing_tree.RoutingTree`
The root of the RoutingTree which contains nothing... |
Routing algorithm based on Neighbour Exploring Routing (NER).
Algorithm refrence: J. Navaridas et al. SpiNNaker: Enhanced multicast
routing, Parallel Computing (2014).
http://dx.doi.org/10.1016/j.parco.2015.01.002
This algorithm attempts to use NER to generate routing trees for all nets
and routes... |
Given a string return true if it matches the supplied list of
patterns.
Parameters
----------
string : str
The string to be matched.
patterns : None or [pattern, ...]
The series of regular expressions to attempt to match.
def match(string, patterns):
"""Given a string return tr... |
Scan a SpiNNaker system's cores filtering by the specified features.
Generates
-------
(x, y, core, state, runtime_exception, application, app_id)
def get_process_list(mc, x_=None, y_=None, p_=None,
app_ids=None, applications=None, states=None):
"""Scan a SpiNNaker system's cores ... |
Build a :py:class:`~rig.place_and_route.Machine` object from a
:py:class:`~rig.machine_control.machine_controller.SystemInfo` object.
.. note::
Links are tested by sending a 'PEEK' command down the link which
checks to see if the remote device responds correctly. If the link
is dead, no... |
Yield a minimal set of
:py:class:`~rig.place_and_route.constraints.ReserveResourceConstraint`
objects which reserve the specified set of cores.
Parameters
----------
core_resource : resource type
The type of resource representing cores.
cores : [int, ...]
The core numbers to res... |
Return a set of place-and-route
:py:class:`~rig.place_and_route.constraints.ReserveResourceConstraint`
which reserve any cores that that are already in use.
The returned list of
:py:class:`~rig.place_and_route.constraints.ReserveResourceConstraint`\ s
reserves all cores not in an Idle state (i.e. n... |
Build a mapping from application to a list of cores where the
application is used.
This utility function assumes that each vertex is associated with a
specific application.
Parameters
----------
vertices_applications : {vertex: application, ...}
Applications are represented by the path... |
**DEPRECATED** Convert a set of RoutingTrees into a per-chip set of
routing tables.
.. warning::
This method has been deprecated in favour of
:py:meth:`rig.routing_table.routing_tree_to_tables` and
:py:meth:`rig.routing_table.minimise`.
E.g. most applications should use somethi... |
Register the Sentry integration.
Exceptions making jobs fail are sent to Sentry.
:param raven_client: configured Raven client used to sent errors to Sentry
:param namespace: optionally only register the Sentry integration for a
particular Spinach :class:`Engine`
:param send_retries: whether... |
Add a resources entry, downloading the intuiting the file, replacing entries with
the same reference
def add_resource(mt_file, ref, cache):
"""Add a resources entry, downloading the intuiting the file, replacing entries with
the same reference"""
if isinstance(mt_file, MetapackDoc):
doc = mt_f... |
Return Tile boundaries.
- pixelbuffer: tile buffer in pixels
def bounds(self, pixelbuffer=0):
"""
Return Tile boundaries.
- pixelbuffer: tile buffer in pixels
"""
left = self._left
bottom = self._bottom
right = self._right
top = self._top
... |
Return an Affine object of tile.
- pixelbuffer: tile buffer in pixels
def affine(self, pixelbuffer=0):
"""
Return an Affine object of tile.
- pixelbuffer: tile buffer in pixels
"""
return Affine(
self.pixel_x_size,
0,
self.bounds(pix... |
Return a tuple of tile height and width.
- pixelbuffer: tile buffer in pixels
def shape(self, pixelbuffer=0):
"""
Return a tuple of tile height and width.
- pixelbuffer: tile buffer in pixels
"""
# apply pixelbuffers
height = self._base_shape.height + 2 * pixel... |
Return True if tile is available in tile pyramid.
def is_valid(self):
"""Return True if tile is available in tile pyramid."""
if not all([
isinstance(self.zoom, int),
self.zoom >= 0,
isinstance(self.row, int),
self.row >= 0,
isinstance(self.co... |
Return tile from previous zoom level.
def get_parent(self):
"""Return tile from previous zoom level."""
return None if self.zoom == 0 else self.tile_pyramid.tile(
self.zoom - 1, self.row // 2, self.col // 2
) |
Return tiles from next zoom level.
def get_children(self):
"""Return tiles from next zoom level."""
next_zoom = self.zoom + 1
return [
self.tile_pyramid.tile(
next_zoom,
self.row * 2 + row_offset,
self.col * 2 + col_offset
... |
Return tile neighbors.
Tile neighbors are unique, i.e. in some edge cases, where both the left
and right neighbor wrapped around the antimeridian is the same. Also,
neighbors ouside the northern and southern TilePyramid boundaries are
excluded, because they are invalid.
-------... |
Add a new field to the BitField.
If any existing fields' values are set, the newly created field will
become a child of those fields. This means that this field will exist
only when the parent fields' values are set as they are currently.
Parameters
----------
identifie... |
Generate an integer whose bits are set according to the values of
fields in this bit field. All other bits are set to zero.
Parameters
----------
tag : str
Optionally specifies that the value should only include fields with
the specified tag.
field : str
... |
Get the mask for all fields which exist in the current bit field.
Parameters
----------
tag : str
Optionally specifies that the mask should only include fields with
the specified tag.
field : str
Optionally specifies that the mask should only include ... |
For internal use only. Returns an OrderedDict of {identifier: field}
representing fields which match the supplied field/tag.
Parameters
----------
tag : str
Optionally specifies that the mask should only include fields with
the specified tag.
field : str
... |
Get the set of tags for a given field.
.. note::
The named field must be accessible given the current set of values
defined.
Parameters
----------
field : str
The field whose tag should be read.
Returns
-------
set([tag, ...]... |
Get the location and length of a field within the bitfield.
.. note::
The named field must be accessible given the current set of values
defined.
Parameters
----------
field : str
The field of interest.
Returns
-------
locati... |
Assign a position & length to any fields which do not have one.
Users should typically call this method after all field values have
been assigned, otherwise fields may be fixed at an inadequate size.
def assign_fields(self):
"""Assign a position & length to any fields which do not have one.
... |
For internal use only. Assign lengths & positions to a subset of all
potential fields with the supplied field_values.
This method will check for any assigned bits of all potential fields
but will only assign those fields whose identifiers are provided.
Parameters
----------
... |
For internal use only. Assign a length and position to a field
which may have either one of these values missing.
Parameters
----------
assigned_bits : int
A bit mask of bits already in use by other fields
identifier : str
The identifier of the field to ... |
Remove the geography from the files, since it isn't particularly useful in Excel
def _load_resources(self):
"""Remove the geography from the files, since it isn't particularly useful in Excel"""
for t in self.doc.find('Root.Table'):
for c in t.find('Table.Column'):
if c.get... |
Convert a bucket policy to a dict mapping principal/prefix names to 'R' or 'W'
def user_policy_to_dict(doc):
"""Convert a bucket policy to a dict mapping principal/prefix names to 'R' or 'W' """
import json
if not isinstance(doc, dict):
doc = json.loads(doc)
d = {}
def get_statement(nam... |
Return the statemtns in a bucket policy as a dict of dicts
def make_bucket_policy_statements(bucket):
"""Return the statemtns in a bucket policy as a dict of dicts"""
import yaml
from os.path import dirname, join, abspath
import copy
import metatab
with open(join(dirname(abspath(metatab.__file... |
Create a bucket policy document from a permissions dict.
The dictionary d maps (user, prefix) to 'R' or 'W'.
:param bucket_name:
:param d:
:return:
def bucket_dict_to_policy(args, bucket_name, d):
"""
Create a bucket policy document from a permissions dict.
The dictionary d maps (user, p... |
Produce a dictionary of read, write permissions for an existing bucket policy document
def bucket_policy_to_dict(policy):
"""Produce a dictionary of read, write permissions for an existing bucket policy document"""
import json
if not isinstance(policy, dict):
policy = json.loads(policy)
state... |
Return the local Account for a user name, by fetching User and looking up
the arn.
def get_iam_account(l, args, user_name):
"""Return the local Account for a user name, by fetching User and looking up
the arn. """
iam = get_resource(args, 'iam')
user = iam.User(user_name)
user.load()
retu... |
Wrapper for computeSVD that will normalize and handle a Thunder Images object
:param data: Thunder Images object
:param k: number of components to keep
:param getComponents: will return the components if true, otherwise will return None
:returns: projections, components, s
def getSVD(data, k, getComp... |
Convert a duration in seconds into a human friendly string.
def human_duration(duration_seconds: float) -> str:
"""Convert a duration in seconds into a human friendly string."""
if duration_seconds < 0.001:
return '0 ms'
if duration_seconds < 1:
return '{} ms'.format(int(duration_seconds * ... |
Call a function and retry it on failure.
def call_with_retry(func: Callable, exceptions, max_retries: int,
logger: Logger, *args, **kwargs):
"""Call a function and retry it on failure."""
attempt = 0
while True:
try:
return func(*args, **kwargs)
except except... |
Calculate a delay to retry using an exponential backoff algorithm.
It is an exponential backoff with random jitter to prevent failures
from being retried at the same time. It is a good fit for most
applications.
:arg attempt: the number of attempts made
:arg cap: maximum delay, defaults to 20 minu... |
Handle SIGTERM like a normal SIGINT (KeyboardInterrupt).
By default Docker sends a SIGTERM for stopping containers, giving them
time to terminate before getting killed. If a process does not catch this
signal and does nothing, it just gets killed.
Handling SIGTERM like SIGINT allows to gracefully term... |
Return a function to convert a floating point value to a fixed point
value.
For example, a function to convert a float to a signed fractional
representation with 8 bits overall and 4 fractional bits (S3.4) can be
constructed and used with::
>>> s34 = float_to_fp(signed=True, n_bits=8, n_frac=4... |
**DEPRECATED** Return a function to convert a floating point value to a
fixed point value.
.. warning::
This function is deprecated in favour of :py:meth:`~.float_to_fp`.
For example, a function to convert a float to a signed fractional
representation with 8 bits overall and 4 fractional bits ... |
**DEPRECATED** Return a function to convert a fixed point value to a
floating point value.
.. warning::
This function is deprecated in favour of :py:meth:`~.fp_to_float`.
For example, a function to convert from signed fractional representations
with 8 bits overall and 4 fractional representati... |
Get reference metadata file path.
def get_metadata_path(name):
"""Get reference metadata file path."""
return pkg_resources.resource_filename('voobly', os.path.join(METADATA_PATH, '{}.json'.format(name))) |
Save cookies to a file.
def _save_cookies(requests_cookiejar, filename):
"""Save cookies to a file."""
with open(filename, 'wb') as handle:
pickle.dump(requests_cookiejar, handle) |
Make a request to API endpoint.
def _make_request(session, url, argument=None, params=None, raw=False):
"""Make a request to API endpoint."""
if not params:
params = {}
params['key'] = session.auth.key
try:
if argument:
request_url = '{}{}{}{}'.format(session.auth.base_url, ... |
Make a request to URL.
def make_scrape_request(session, url, mode='get', data=None):
"""Make a request to URL."""
try:
html = session.request(mode, url, data=data)
except RequestException:
raise VooblyError('failed to connect')
if SCRAPE_FETCH_ERROR in html.text:
raise VooblyErr... |
Get ladder.
def get_ladder(session, ladder_id, user_id=None, user_ids=None, start=0, limit=LADDER_RESULT_LIMIT):
"""Get ladder."""
params = {
'start': start,
'limit': limit
}
if isinstance(ladder_id, str):
ladder_id = lookup_ladder_id(ladder_id)
if limit > LADDER_RESULT_LIMI... |
Get lobbies for a game.
def get_lobbies(session, game_id):
"""Get lobbies for a game."""
if isinstance(game_id, str):
game_id = lookup_game_id(game_id)
lobbies = _make_request(session, LOBBY_URL, game_id)
for lobby in lobbies:
# pylint: disable=len-as-condition
if len(lobby['lad... |
Get user.
def get_user(session, user_id):
"""Get user."""
try:
user_id = int(user_id)
except ValueError:
user_id = find_user(session, user_id)
resp = _make_request(session, USER_URL, user_id)
if not resp:
raise VooblyError('user id not found')
return resp[0] |
Find user by name - returns user ID.
def find_user(session, username):
"""Find user by name - returns user ID."""
resp = _make_request(session, FIND_USER_URL, username)
if not resp:
raise VooblyError('user not found')
try:
return int(resp[0]['uid'])
except ValueError:
raise ... |
Find multiple users by name.
def find_users(session, *usernames):
"""Find multiple users by name."""
user_string = ','.join(usernames)
return _make_request(session, FIND_USERS_URL, user_string) |
Get all possible user info by name.
def user(session, uid, ladder_ids=None):
"""Get all possible user info by name."""
data = get_user(session, uid)
resp = dict(data)
if not ladder_ids:
return resp
resp['ladders'] = {}
for ladder_id in ladder_ids:
if isinstance(ladder_id, str):
... |
Get a list of ladder IDs.
def ladders(session, game_id):
"""Get a list of ladder IDs."""
if isinstance(game_id, str):
game_id = lookup_game_id(game_id)
lobbies = get_lobbies(session, game_id)
ladder_ids = set()
for lobby in lobbies:
ladder_ids |= set(lobby['ladders'])
return lis... |
Re-authenticate if session expired.
def authenticated(function):
"""Re-authenticate if session expired."""
def wrapped(session, *args, **kwargs):
"""Wrap function."""
try:
return function(session, *args, **kwargs)
except VooblyError:
with session.cache_disabled()... |
Get recent matches by clan.
def get_clan_matches(session, subdomain, clan_id, from_timestamp=None, limit=None):
"""Get recent matches by clan."""
return get_recent_matches(session, 'https://{}.voobly.com/{}/{}/0'.format(
subdomain, TEAM_MATCHES_URL, clan_id), from_timestamp, limit) |
Get recent matches by user.
def get_user_matches(session, user_id, from_timestamp=None, limit=None):
"""Get recent matches by user."""
return get_recent_matches(session, '{}{}/{}/Matches/games/matches/user/{}/0'.format(
session.auth.base_url, PROFILE_URL, user_id, user_id), from_timestamp, limit) |
Get recently played user matches.
def get_recent_matches(session, init_url, from_timestamp, limit):
"""Get recently played user matches."""
if not from_timestamp:
from_timestamp = datetime.datetime.now() - datetime.timedelta(days=1)
matches = []
page_id = 0
done = False
while not done a... |
Get recently played ladder matches.
def get_ladder_matches(session, ladder_id, from_timestamp=None, limit=LADDER_MATCH_LIMIT):
"""Get recently played ladder matches."""
if not from_timestamp:
from_timestamp = datetime.datetime.now() - datetime.timedelta(days=1)
matches = []
page_id = 0
done... |
Get match metadata.
def get_match(session, match_id):
"""Get match metadata."""
url = '{}{}/{}'.format(session.auth.base_url, MATCH_URL, match_id)
parsed = make_scrape_request(session, url)
game = parsed.find('h3').text
if game != GAME_AOC:
raise ValueError('not an aoc match')
date_play... |
Download and extract a recorded game.
def download_rec(session, rec_url, target_path):
"""Download and extract a recorded game."""
try:
resp = session.get(session.auth.base_url + rec_url)
except RequestException:
raise VooblyError('failed to connect for download')
try:
downloade... |
Login to Voobly.
def login(session):
"""Login to Voobly."""
if not session.auth.username or not session.auth.password:
raise VooblyError('must supply username and password')
_LOGGER.info("logging in (no valid cookie found)")
session.cookies.clear()
try:
session.get(session.auth.base... |
Get Voobly API session.
def get_session(key=None, username=None, password=None, cache=True,
cache_expiry=datetime.timedelta(days=7), cookie_path=COOKIE_PATH, backend='memory',
version=VERSION_GLOBAL):
"""Get Voobly API session."""
class VooblyAuth(AuthBase): # pylint: disable=t... |
The entry point for the Hyper-V Neutron Agent.
def main():
"""The entry point for the Hyper-V Neutron Agent."""
neutron_config.register_agent_state_opts_helper(CONF)
common_config.init(sys.argv[1:])
neutron_config.setup_logging()
hyperv_agent = HyperVNeutronAgent()
# Start everything.
LOG... |
Setup the layer two agent.
def _setup(self):
"""Setup the layer two agent."""
super(HyperVNeutronAgent, self)._setup()
self._sg_plugin_rpc = sg_rpc.SecurityGroupServerRpcApi(topics.PLUGIN)
self._sec_groups_agent = HyperVSecurityAgent(self._context,
... |
Setup the QOS extension if it is required.
def _setup_qos_extension(self):
"""Setup the QOS extension if it is required."""
if not CONF.AGENT.enable_qos_extension:
return
self._qos_ext = qos_extension.QosAgentExtension()
self._qos_ext.consume_api(self)
self._qos_ext.... |
Provision the network with the received information.
def _provision_network(self, port_id, net_uuid, network_type,
physical_network, segmentation_id):
"""Provision the network with the received information."""
LOG.info("Provisioning network %s", net_uuid)
vswitch_nam... |
Bind the port to the recived network.
def _port_bound(self, port_id, network_id, network_type, physical_network,
segmentation_id, port_security_enabled, set_port_sriov):
"""Bind the port to the recived network."""
super(HyperVNeutronAgent, self)._port_bound(
port_id, net... |
Process the information regarding the available ports.
def _work(self):
"""Process the information regarding the available ports."""
super(HyperVNeutronAgent, self)._work()
if self._nvgre_enabled:
self._nvgre_ops.refresh_nvgre_records()
self._port_enable_control_metrics() |
Run a limited number of magics from scripts, without IPython
def run_cell_magic(self, magic_name, line, cell):
"""Run a limited number of magics from scripts, without IPython"""
if magic_name == 'bash':
self.shebang("bash", cell)
elif magic_name == 'metatab':
self.mm.me... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.