INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
will wait for exp to be returned from nodemcu or timeout | def __expect(self, exp='> ', timeout=None):
"""will wait for exp to be returned from nodemcu or timeout"""
timeout_before = self._port.timeout
timeout = timeout or self._timeout
#do NOT set timeout on Windows
if SYSTEM != 'Windows':
# Checking for new data every 100us... |
write data on the nodemcu port. If binary is True the debug log will show the intended output as hex otherwise as string | def __write(self, output, binary=False):
"""write data on the nodemcu port. If 'binary' is True the debug log
will show the intended output as hex, otherwise as string"""
if not binary:
log.debug('write: %s', output)
else:
log.debug('write binary: %s', hexify(outp... |
Write output to the port and wait for response | def __exchange(self, output, timeout=None):
"""Write output to the port and wait for response"""
self.__writeln(output)
self._port.flush()
return self.__expect(timeout=timeout or self._timeout) |
restores the nodemcu to default baudrate and then closes the port | def close(self):
"""restores the nodemcu to default baudrate and then closes the port"""
try:
if self.baud != self.start_baud:
self.__set_baudrate(self.start_baud)
self._port.flush()
self.__clear_buffers()
except serial.serialutil.SerialExcepti... |
This uploads the protocol functions nessecary to do binary chunked transfer | def prepare(self):
"""
This uploads the protocol functions nessecary to do binary
chunked transfer
"""
log.info('Preparing esp for transfer.')
for func in LUA_FUNCTIONS:
detected = self.__exchange('print({0})'.format(func))
if detected.find('funct... |
Download a file from device to local filesystem | def download_file(self, filename):
"""Download a file from device to local filesystem"""
res = self.__exchange('send("{filename}")'.format(filename=filename))
if ('unexpected' in res) or ('stdin' in res):
log.error('Unexpected error downloading file: %s', res)
raise Excep... |
reading data from device into local file | def read_file(self, filename, destination=''):
"""reading data from device into local file"""
if not destination:
destination = filename
log.info('Transferring %s to %s', filename, destination)
data = self.download_file(filename)
# Just in case, the filename may cont... |
sends a file to the device using the transfer protocol | def write_file(self, path, destination='', verify='none'):
"""sends a file to the device using the transfer protocol"""
filename = os.path.basename(path)
if not destination:
destination = filename
log.info('Transferring %s as %s', path, destination)
self.__writeln("r... |
Tries to verify if path has same checksum as destination. Valid options for verify is raw sha1 or none | def verify_file(self, path, destination, verify='none'):
"""Tries to verify if path has same checksum as destination.
Valid options for verify is 'raw', 'sha1' or 'none'
"""
content = from_file(path)
log.info('Verifying using %s...' % verify)
if verify == 'raw':
... |
execute the lines in the local file path | def exec_file(self, path):
"""execute the lines in the local file 'path'"""
filename = os.path.basename(path)
log.info('Execute %s', filename)
content = from_file(path).replace('\r', '').split('\n')
res = '> '
for line in content:
line = line.rstrip('\n')
... |
Returns true if ACK is received | def __got_ack(self):
"""Returns true if ACK is received"""
log.debug('waiting for ack')
res = self._port.read(1)
log.debug('ack read %s', hexify(res))
return res == ACK |
write lines one by one separated by \ n to device | def write_lines(self, data):
"""write lines, one by one, separated by \n to device"""
lines = data.replace('\r', '').split('\n')
for line in lines:
self.__exchange(line) |
formats and sends a chunk of data to the device according to transfer protocol | def __write_chunk(self, chunk):
"""formats and sends a chunk of data to the device according
to transfer protocol"""
log.debug('writing %d bytes chunk', len(chunk))
data = BLOCK_START + chr(len(chunk)) + chunk
if len(chunk) < 128:
padding = 128 - len(chunk)
... |
Read a chunk of data | def __read_chunk(self, buf):
"""Read a chunk of data"""
log.debug('reading chunk')
timeout_before = self._port.timeout
if SYSTEM != 'Windows':
# Checking for new data every 100us is fast enough
if self._port.timeout != MINIMAL_TIMEOUT:
self._port.t... |
list files on the device | def file_list(self):
"""list files on the device"""
log.info('Listing files')
res = self.__exchange(LIST_FILES)
res = res.split('\r\n')
# skip first and last lines
res = res[1:-1]
files = []
for line in res:
files.append(line.split('\t'))
... |
Execute a file on the device using do | def file_do(self, filename):
"""Execute a file on the device using 'do'"""
log.info('Executing '+filename)
res = self.__exchange('dofile("'+filename+'")')
log.info(res)
return res |
Formats device filesystem | def file_format(self):
"""Formats device filesystem"""
log.info('Formating, can take minutes depending on flash size...')
res = self.__exchange('file.format()', timeout=300)
if 'format done' not in res:
log.error(res)
else:
log.info(res)
return res |
Prints a file on the device to console | def file_print(self, filename):
"""Prints a file on the device to console"""
log.info('Printing ' + filename)
res = self.__exchange(PRINT_FILE.format(filename=filename))
log.info(res)
return res |
Show device heap size | def node_heap(self):
"""Show device heap size"""
log.info('Heap')
res = self.__exchange('print(node.heap())')
log.info(res)
return int(res.split('\r\n')[1]) |
Restarts device | def node_restart(self):
"""Restarts device"""
log.info('Restart')
res = self.__exchange('node.restart()')
log.info(res)
return res |
Compiles a file specified by path on the device | def file_compile(self, path):
"""Compiles a file specified by path on the device"""
log.info('Compile '+path)
cmd = 'node.compile("%s")' % path
res = self.__exchange(cmd)
log.info(res)
return res |
Removes a file on the device | def file_remove(self, path):
"""Removes a file on the device"""
log.info('Remove '+path)
cmd = 'file.remove("%s")' % path
res = self.__exchange(cmd)
log.info(res)
return res |
Backup all files from the device | def backup(self, path):
"""Backup all files from the device"""
log.info('Backing up in '+path)
# List file to backup
files = self.file_list()
# then download each of then
self.prepare()
for f in files:
self.read_file(f[0], os.path.join(path, f[0])) |
Split each of the sources in the array on: First part will be source second will be destination. Modifies the the original array to contain only sources and returns an array of destinations. | def destination_from_source(sources, use_glob=True):
"""
Split each of the sources in the array on ':'
First part will be source, second will be destination.
Modifies the the original array to contain only sources
and returns an array of destinations.
"""
destinations = []
newsources = [... |
The upload operation | def operation_upload(uploader, sources, verify, do_compile, do_file, do_restart):
"""The upload operation"""
sources, destinations = destination_from_source(sources)
if len(destinations) == len(sources):
if uploader.prepare():
for filename, dst in zip(sources, destinations):
... |
The download operation | def operation_download(uploader, sources):
"""The download operation"""
sources, destinations = destination_from_source(sources, False)
print('sources', sources)
print('destinations', destinations)
if len(destinations) == len(sources):
if uploader.prepare():
for filename, dst in ... |
List file on target | def operation_list(uploader):
"""List file on target"""
files = uploader.file_list()
for f in files:
log.info("{file:30s} {size}".format(file=f[0], size=f[1])) |
File operations | def operation_file(uploader, cmd, filename=''):
"""File operations"""
if cmd == 'list':
operation_list(uploader)
if cmd == 'do':
for path in filename:
uploader.file_do(path)
elif cmd == 'format':
uploader.file_format()
elif cmd == 'remove':
for path in fil... |
Main function for cli | def main_func():
"""Main function for cli"""
parser = argparse.ArgumentParser(
description='NodeMCU Lua file uploader',
prog='nodemcu-uploader'
)
parser.add_argument(
'--verbose',
help='verbose output',
action='store_true',
default=False)
parser.... |
Display a widget text or other media in a notebook without the need to import IPython at the top level. | def display(content):
"""
Display a widget, text or other media in a notebook without the need to import IPython at the top level.
Also handles wrapping GenePattern Python Library content in widgets.
:param content:
:return:
"""
if isinstance(content, gp.GPServer):
IPython.display.d... |
Register a new GenePattern server session for the provided server username and password. Return the session.: param server:: param username:: param password:: return: | def register(self, server, username, password):
"""
Register a new GenePattern server session for the provided
server, username and password. Return the session.
:param server:
:param username:
:param password:
:return:
"""
# Create the session
... |
Returns a registered GPServer object with a matching GenePattern server url or index Returns None if no matching result was found: param server:: return: | def get(self, server):
"""
Returns a registered GPServer object with a matching GenePattern server url or index
Returns None if no matching result was found
:param server:
:return:
"""
# Handle indexes
if isinstance(server, int):
if server >= ... |
Returns a registered GPServer object with a matching GenePattern server url Returns - 1 if no matching result was found: param server_url:: return: | def _get_index(self, server_url):
"""
Returns a registered GPServer object with a matching GenePattern server url
Returns -1 if no matching result was found
:param server_url:
:return:
"""
for i in range(len(self.sessions)):
session = self.sessions[i]
... |
Accept None or ∞ or datetime or numeric for target | def _accept(self, target):
"Accept None or ∞ or datetime or numeric for target"
if isinstance(target, datetime.timedelta):
target = target.total_seconds()
if target is None:
# treat None as infinite target
target = float('Inf')
return target |
Convert a numeric timestamp to a timezone - aware datetime. | def from_timestamp(ts):
"""
Convert a numeric timestamp to a timezone-aware datetime.
A client may override this function to change the default behavior,
such as to use local time or timezone-naïve times.
"""
return datetime.datetime.utcfromtimestamp(ts).replace(tzinfo=pytz.utc) |
Construct a DelayedCommand to come due at at where at may be a datetime or timestamp. | def at_time(cls, at, target):
"""
Construct a DelayedCommand to come due at `at`, where `at` may be
a datetime or timestamp.
"""
at = cls._from_timestamp(at)
cmd = cls.from_datetime(at)
cmd.delay = at - now()
cmd.target = target
return cmd |
Rely on pytz. localize to ensure new result honors DST. | def _localize(dt):
"""
Rely on pytz.localize to ensure new result honors DST.
"""
try:
tz = dt.tzinfo
return tz.localize(dt.replace(tzinfo=None))
except AttributeError:
return dt |
Schedule a command to run at a specific time each day. | def daily_at(cls, at, target):
"""
Schedule a command to run at a specific time each day.
"""
daily = datetime.timedelta(days=1)
# convert when to the next datetime matching this time
when = datetime.datetime.combine(datetime.date.today(), at)
if when < now():
... |
A class to replace the strftime in datetime package or time module. Identical to strftime behavior in those modules except supports any year. Also supports datetime. datetime times. Also supports milliseconds using %s Also supports microseconds using %u | def strftime(fmt, t):
"""A class to replace the strftime in datetime package or time module.
Identical to strftime behavior in those modules except supports any
year.
Also supports datetime.datetime times.
Also supports milliseconds using %s
Also supports microseconds using %u"""
if isinstance(t, (time.struct_ti... |
A function to replace strptime in the time module. Should behave identically to the strptime function except it returns a datetime. datetime object instead of a time. struct_time object. Also takes an optional tzinfo parameter which is a time zone info object. | def strptime(s, fmt, tzinfo=None):
"""
A function to replace strptime in the time module. Should behave
identically to the strptime function except it returns a datetime.datetime
object instead of a time.struct_time object.
Also takes an optional tzinfo parameter which is a time zone info object.
"""
res = time... |
Find the time which is the specified date/ time truncated to the time delta relative to the start date/ time. By default the start time is midnight of the same day as the specified date/ time. | def datetime_mod(dt, period, start=None):
"""
Find the time which is the specified date/time truncated to the time delta
relative to the start date/time.
By default, the start time is midnight of the same day as the specified
date/time.
>>> datetime_mod(datetime.datetime(2004, 1, 2, 3),
... datetime.timedel... |
Find the nearest even period for the specified date/ time. | def datetime_round(dt, period, start=None):
"""
Find the nearest even period for the specified date/time.
>>> datetime_round(datetime.datetime(2004, 11, 13, 8, 11, 13),
... datetime.timedelta(hours = 1))
datetime.datetime(2004, 11, 13, 8, 0)
>>> datetime_round(datetime.datetime(2004, 11, 13, 8, 31, 13),
...... |
Returns the nearest year to now inferred from a Julian date. | def get_nearest_year_for_day(day):
"""
Returns the nearest year to now inferred from a Julian date.
"""
now = time.gmtime()
result = now.tm_year
# if the day is far greater than today, it must be from last year
if day - now.tm_yday > 365 // 2:
result -= 1
# if the day is far less than today, it must be for ne... |
Gregorian Date is defined as a year and a julian day ( 1 - based index into the days of the year ). | def gregorian_date(year, julian_day):
"""
Gregorian Date is defined as a year and a julian day (1-based
index into the days of the year).
>>> gregorian_date(2007, 15)
datetime.date(2007, 1, 15)
"""
result = datetime.date(year, 1, 1)
result += datetime.timedelta(days=julian_day - 1)
return result |
return the number of seconds in the specified period | def get_period_seconds(period):
"""
return the number of seconds in the specified period
>>> get_period_seconds('day')
86400
>>> get_period_seconds(86400)
86400
>>> get_period_seconds(datetime.timedelta(hours=24))
86400
>>> get_period_seconds('day + os.system("rm -Rf *")')
Traceback (most recent call last):
... |
For a given period ( e. g. month day or some numeric interval such as 3600 ( in secs )) return the format string that can be used with strftime to format that time to specify the times across that interval but no more detailed. For example | def get_date_format_string(period):
"""
For a given period (e.g. 'month', 'day', or some numeric interval
such as 3600 (in secs)), return the format string that can be
used with strftime to format that time to specify the times
across that interval, but no more detailed.
For example,
>>> get_date_format_string(... |
Divide a timedelta by a float value | def divide_timedelta_float(td, divisor):
"""
Divide a timedelta by a float value
>>> one_day = datetime.timedelta(days=1)
>>> half_day = datetime.timedelta(days=.5)
>>> divide_timedelta_float(one_day, 2.0) == half_day
True
>>> divide_timedelta_float(one_day, 2) == half_day
True
"""
# td is comprised of days,... |
A utility function to prompt for a rate ( a string in units per unit time ) and return that same rate for various time periods. | def calculate_prorated_values():
"""
A utility function to prompt for a rate (a string in units per
unit time), and return that same rate for various time periods.
"""
rate = six.moves.input("Enter the rate (3/hour, 50/month)> ")
res = re.match(r'(?P<value>[\d.]+)/(?P<period>\w+)$', rate).groupdict()
value = flo... |
Take a string representing a span of time and parse it to a time delta. Accepts any string of comma - separated numbers each with a unit indicator. | def parse_timedelta(str):
"""
Take a string representing a span of time and parse it to a time delta.
Accepts any string of comma-separated numbers each with a unit indicator.
>>> parse_timedelta('1 day')
datetime.timedelta(days=1)
>>> parse_timedelta('1 day, 30 seconds')
datetime.timedelta(days=1, seconds=30)... |
Get the ratio of two timedeltas | def divide_timedelta(td1, td2):
"""
Get the ratio of two timedeltas
>>> one_day = datetime.timedelta(days=1)
>>> one_hour = datetime.timedelta(hours=1)
>>> divide_timedelta(one_hour, one_day) == 1 / 24
True
"""
try:
return td1 / td2
except TypeError:
# Python 3.2 gets division
# http://bugs.python.org/i... |
Much like the built - in function range but works with dates | def date_range(start=None, stop=None, step=None):
"""
Much like the built-in function range, but works with dates
>>> range_items = date_range(
... datetime.datetime(2005,12,21),
... datetime.datetime(2005,12,25),
... )
>>> my_range = tuple(range_items)
>>> datetime.datetime(2005,12,21) in my_range
Tr... |
Construct a datetime. datetime from a number of different time types found in python and pythonwin | def construct_datetime(cls, *args, **kwargs):
"""Construct a datetime.datetime from a number of different time
types found in python and pythonwin"""
if len(args) == 1:
arg = args[0]
method = cls.__get_dt_constructor(
type(arg).__module__,
type(arg).__name__,
)
result = method(arg)
try:
... |
__common_triplet ( input_string consonants vowels ) - > string | def __common_triplet(input_string, consonants, vowels):
"""__common_triplet(input_string, consonants, vowels) -> string"""
output = consonants
while len(output) < 3:
try:
output += vowels.pop(0)
except IndexError:
# If there are less wovels than needed to fill the tr... |
__consonants_and_vowels ( input_string ) - > ( string list ) | def __consonants_and_vowels(input_string):
"""__consonants_and_vowels(input_string) -> (string, list)
Get the consonants as a string and the vowels as a list.
"""
input_string = input_string.upper().replace(' ', '')
consonants = [ char for char in input_string if char in __CONSONANTS ]
vowels ... |
__surname_triplet ( input_string ) - > string | def __surname_triplet(input_string):
"""__surname_triplet(input_string) -> string"""
consonants, vowels = __consonants_and_vowels(input_string)
return __common_triplet(input_string, consonants, vowels) |
__name_triplet ( input_string ) - > string | def __name_triplet(input_string):
"""__name_triplet(input_string) -> string"""
if input_string == '':
# highly unlikely: no first name, like for instance some Indian persons
# with only one name on the passport
# pylint: disable=W0511
return 'XXX'
consonants, vowels = __con... |
control_code ( input_string ) - > int | def control_code(input_string):
"""``control_code(input_string) -> int``
Computes the control code for the given input_string string. The expected
input_string is the first 15 characters of a fiscal code.
eg: control_code('RCCMNL83S18D969') -> 'H'
"""
assert len(input_string) == 15
# buil... |
build ( surname name birthday sex municipality ) - > string | def build(surname, name, birthday, sex, municipality):
"""``build(surname, name, birthday, sex, municipality) -> string``
Computes the fiscal code for the given person data.
eg: build('Rocca', 'Emanuele', datetime.datetime(1983, 11, 18), 'M', 'D969')
-> RCCMNL83S18D969H
"""
# RCCMNL
... |
get_birthday ( code ) - > string | def get_birthday(code):
"""``get_birthday(code) -> string``
Birthday of the person whose fiscal code is 'code', in the format DD-MM-YY.
Unfortunately it's not possible to guess the four digit birth year, given
that the Italian fiscal code uses only the last two digits (1983 -> 83).
Therefore, thi... |
Pass in an Overpass query in Overpass QL. | def get(self, query, responseformat="geojson", verbosity="body", build=True):
"""Pass in an Overpass query in Overpass QL."""
# Construct full Overpass query
if build:
full_query = self._construct_ql_query(
query, responseformat=responseformat, verbosity=verbosity
... |
Arguments: - self: - text: | def parse(self, text):
"""
Arguments:
- `self`:
- `text`:
"""
results = list()
for oneline in text.split('\n'):
self._tagger.stdin.write(oneline+'\n')
while True:
r = self._tagger.stdout.readline()[:-1]
... |
Create a port | def create_port(context, port):
"""Create a port
Create a port which is a connection point of a device (e.g., a VM
NIC) to attach to a L2 Neutron network.
: param context: neutron api request context
: param port: dictionary describing the port, with keys
as listed in the RESOURCE_ATTRIBUTE... |
Update values of a port. | def update_port(context, id, port):
"""Update values of a port.
: param context: neutron api request context
: param id: UUID representing the port to update.
: param port: dictionary with keys indicating fields to update.
valid keys are those that have a value of True for 'allow_put'
a... |
Retrieve a port. | def get_port(context, id, fields=None):
"""Retrieve a port.
: param context: neutron api request context
: param id: UUID representing the port to fetch.
: param fields: a list of strings that are valid keys in a
port dictionary as listed in the RESOURCE_ATTRIBUTE_MAP
object in neutron/... |
Retrieve a list of ports. | def get_ports(context, limit=None, sorts=['id'], marker=None,
page_reverse=False, filters=None, fields=None):
"""Retrieve a list of ports.
The contents of the list depends on the identity of the user
making the request (as indicated by the context) as well as any
filters.
: param cont... |
Return the number of ports. | def get_ports_count(context, filters=None):
"""Return the number of ports.
The result depends on the identity of the user making the request
(as indicated by the context) as well as any filters.
: param context: neutron api request context
: param filters: a dictionary with keys that are valid keys... |
Delete a port. | def delete_port(context, id):
"""Delete a port.
: param context: neutron api request context
: param id: UUID representing the port to delete.
"""
LOG.info("delete_port %s for tenant %s" % (id, context.tenant_id))
port = db_api.port_find(context, id=id, scope=db_api.ONE)
if not port:
... |
Returns Ext Resources. | def get_resources(cls):
"""Returns Ext Resources."""
plugin = directory.get_plugin()
controller = SegmentAllocationRangesController(plugin)
return [extensions.ResourceExtension(
Segment_allocation_ranges.get_alias(),
controller)] |
Returns Ext Resources. | def get_resources(cls):
"""Returns Ext Resources."""
plugin = directory.get_plugin()
controller = IPAvailabilityController(plugin)
return [extensions.ResourceExtension(Ip_availability.get_alias(),
controller)] |
This attempts to allocate v6 addresses as per RFC2462 and RFC3041. | def _allocate_from_v6_subnet(self, context, net_id, subnet,
port_id, reuse_after, ip_address=None,
**kwargs):
"""This attempts to allocate v6 addresses as per RFC2462 and RFC3041.
To accomodate this, we effectively treat all v6 assignmen... |
Associates the flip with ports and creates it with the flip driver | def _create_flip(context, flip, port_fixed_ips):
"""Associates the flip with ports and creates it with the flip driver
:param context: neutron api request context.
:param flip: quark.db.models.IPAddress object representing a floating IP
:param port_fixed_ips: dictionary of the structure:
{"<id of p... |
Update a flip based IPAddress | def _update_flip(context, flip_id, ip_type, requested_ports):
"""Update a flip based IPAddress
:param context: neutron api request context.
:param flip_id: id of the flip or scip
:param ip_type: ip_types.FLOATING | ip_types.SCALING
:param requested_ports: dictionary of the structure:
{"port_id"... |
Allocate or reallocate a floating IP. | def create_floatingip(context, content):
"""Allocate or reallocate a floating IP.
:param context: neutron api request context.
:param content: dictionary describing the floating ip, with keys
as listed in the RESOURCE_ATTRIBUTE_MAP object in
neutron/api/v2/attributes.py. All keys will be p... |
Update an existing floating IP. | def update_floatingip(context, id, content):
"""Update an existing floating IP.
:param context: neutron api request context.
:param id: id of the floating ip
:param content: dictionary with keys indicating fields to update.
valid keys are those that have a value of True for 'allow_put'
... |
deallocate a floating IP. | def delete_floatingip(context, id):
"""deallocate a floating IP.
:param context: neutron api request context.
:param id: id of the floating ip
"""
LOG.info('delete_floatingip %s for tenant %s' % (id, context.tenant_id))
_delete_flip(context, id, ip_types.FLOATING) |
Retrieve a floating IP. | def get_floatingip(context, id, fields=None):
"""Retrieve a floating IP.
:param context: neutron api request context.
:param id: The UUID of the floating IP.
:param fields: a list of strings that are valid keys in a
floating IP dictionary as listed in the RESOURCE_ATTRIBUTE_MAP
object i... |
Retrieve a list of floating ips. | def get_floatingips(context, filters=None, fields=None, sorts=['id'],
limit=None, marker=None, page_reverse=False):
"""Retrieve a list of floating ips.
:param context: neutron api request context.
:param filters: a dictionary with keys that are valid keys for
a floating ip as li... |
Return the number of floating IPs. | def get_floatingips_count(context, filters=None):
"""Return the number of floating IPs.
:param context: neutron api request context
:param filters: a dictionary with keys that are valid keys for
a floating IP as listed in the RESOURCE_ATTRIBUTE_MAP object
in neutron/api/v2/attributes.py. V... |
Allocate or reallocate a scaling IP. | def create_scalingip(context, content):
"""Allocate or reallocate a scaling IP.
:param context: neutron api request context.
:param content: dictionary describing the scaling ip, with keys
as listed in the RESOURCE_ATTRIBUTE_MAP object in
neutron/api/v2/attributes.py. All keys will be popu... |
Update an existing scaling IP. | def update_scalingip(context, id, content):
"""Update an existing scaling IP.
:param context: neutron api request context.
:param id: id of the scaling ip
:param content: dictionary with keys indicating fields to update.
valid keys are those that have a value of True for 'allow_put'
as ... |
Deallocate a scaling IP. | def delete_scalingip(context, id):
"""Deallocate a scaling IP.
:param context: neutron api request context.
:param id: id of the scaling ip
"""
LOG.info('delete_scalingip %s for tenant %s' % (id, context.tenant_id))
_delete_flip(context, id, ip_types.SCALING) |
Retrieve a scaling IP. | def get_scalingip(context, id, fields=None):
"""Retrieve a scaling IP.
:param context: neutron api request context.
:param id: The UUID of the scaling IP.
:param fields: a list of strings that are valid keys in a
scaling IP dictionary as listed in the RESOURCE_ATTRIBUTE_MAP
object in ne... |
Retrieve a list of scaling ips. | def get_scalingips(context, filters=None, fields=None, sorts=['id'],
limit=None, marker=None, page_reverse=False):
"""Retrieve a list of scaling ips.
:param context: neutron api request context.
:param filters: a dictionary with keys that are valid keys for
a scaling ip as listed... |
Due to NCP - 1592 ensure that address_type cannot change after update. | def update_ip_address(context, id, ip_address):
"""Due to NCP-1592 ensure that address_type cannot change after update."""
LOG.info("update_ip_address %s for tenant %s" % (id, context.tenant_id))
ports = []
if 'ip_address' not in ip_address:
raise n_exc.BadRequest(resource="ip_addresses",
... |
Delete an ip address. | def delete_ip_address(context, id):
"""Delete an ip address.
: param context: neutron api request context
: param id: UUID representing the ip address to delete.
"""
LOG.info("delete_ip_address %s for tenant %s" % (id, context.tenant_id))
with context.session.begin():
ip_address = db_ap... |
Retrieve a list of ports. | def get_ports_for_ip_address(context, ip_id, limit=None, sorts=['id'],
marker=None, page_reverse=False, filters=None,
fields=None):
"""Retrieve a list of ports.
The contents of the list depends on the identity of the user
making the request (as indi... |
Retrieve a port. | def get_port_for_ip_address(context, ip_id, id, fields=None):
"""Retrieve a port.
: param context: neutron api request context
: param id: UUID representing the port to fetch.
: param fields: a list of strings that are valid keys in a
port dictionary as listed in the RESOURCE_ATTRIBUTE_MAP
... |
Update values of a port. | def update_port_for_ip_address(context, ip_id, id, port):
"""Update values of a port.
: param context: neutron api request context
: param ip_id: UUID representing the ip associated with port to update
: param id: UUID representing the port to update.
: param port: dictionary with keys indicating f... |
Determine if a vif is on isonet | def is_isonet_vif(vif):
"""Determine if a vif is on isonet
Returns True if a vif belongs to an isolated network by checking
for a nicira interface id.
"""
nicira_iface_id = vif.record.get('other_config').get('nicira-iface-id')
if nicira_iface_id:
return True
return False |
Splits VIFs into three explicit categories and one implicit | def partition_vifs(xapi_client, interfaces, security_group_states):
"""Splits VIFs into three explicit categories and one implicit
Added - Groups exist in Redis that have not been ack'd and the VIF
is not tagged.
Action: Tag the VIF and apply flows
Updated - Groups exist in Redis th... |
Compares initial security group rules with current sg rules. | def get_groups_to_ack(groups_to_ack, init_sg_states, curr_sg_states):
"""Compares initial security group rules with current sg rules.
Given the groups that were successfully returned from
xapi_client.update_interfaces call, compare initial and current
security group rules to determine if an upd... |
Fetches changes and applies them to VIFs periodically | def run():
"""Fetches changes and applies them to VIFs periodically
Process as of RM11449:
* Get all groups from redis
* Fetch ALL VIFs from Xen
* Walk ALL VIFs and partition them into added, updated and removed
* Walk the final "modified" VIFs list and apply flows to each
"""
groups_cl... |
Delete the quota entries for a given tenant_id. | def delete_tenant_quota(context, tenant_id):
"""Delete the quota entries for a given tenant_id.
Atfer deletion, this tenant will use default quota values in conf.
"""
tenant_quotas = context.session.query(Quota)
tenant_quotas = tenant_quotas.filter_by(tenant_id=tenant_id)
... |
Returns Ext Resources. | def get_resources(cls):
"""Returns Ext Resources."""
ip_controller = IpAddressesController(
directory.get_plugin())
ip_port_controller = IpAddressPortController(
directory.get_plugin())
resources = []
resources.append(extensions.ResourceExtension(
... |
Validate the CIDR for a subnet. | def _validate_subnet_cidr(context, network_id, new_subnet_cidr):
"""Validate the CIDR for a subnet.
Verifies the specified CIDR does not overlap with the ones defined
for the other subnets specified for this network, or with any other
CIDR if overlapping IPs are disabled.
"""
if neutron_cfg.cf... |
Create a subnet. | def create_subnet(context, subnet):
"""Create a subnet.
Create a subnet which represents a range of IP addresses
that can be allocated to devices
: param context: neutron api request context
: param subnet: dictionary describing the subnet, with keys
as listed in the RESOURCE_ATTRIBUTE_MAP... |
Update values of a subnet. | def update_subnet(context, id, subnet):
"""Update values of a subnet.
: param context: neutron api request context
: param id: UUID representing the subnet to update.
: param subnet: dictionary with keys indicating fields to update.
valid keys are those that have a value of True for 'allow_put'... |
Retrieve a subnet. | def get_subnet(context, id, fields=None):
"""Retrieve a subnet.
: param context: neutron api request context
: param id: UUID representing the subnet to fetch.
: param fields: a list of strings that are valid keys in a
subnet dictionary as listed in the RESOURCE_ATTRIBUTE_MAP
object in ... |
Retrieve a list of subnets. | def get_subnets(context, limit=None, page_reverse=False, sorts=['id'],
marker=None, filters=None, fields=None):
"""Retrieve a list of subnets.
The contents of the list depends on the identity of the user
making the request (as indicated by the context) as well as any
filters.
: para... |
Return the number of subnets. | def get_subnets_count(context, filters=None):
"""Return the number of subnets.
The result depends on the identity of the user making the request
(as indicated by the context) as well as any filters.
: param context: neutron api request context
: param filters: a dictionary with keys that are valid ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.