_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q260500 | Stash.list | validation | def list(self,
key_name=None,
max_suggestions=100,
cutoff=0.5,
locked_only=False,
key_type=None):
"""Return a list of all keys.
"""
self._assert_valid_stash()
key_list = [k for k in self._storage.list()
if k['name'] != 'stored_passphrase' and
(k.get('lock') if locked_only else True)]
if key_type:
# To maintain backward compatibility with keys without a type.
| python | {
"resource": ""
} |
q260501 | Stash.delete | validation | def delete(self, key_name):
"""Delete a key if it exists.
"""
self._assert_valid_stash()
if key_name == 'stored_passphrase':
raise GhostError(
'`stored_passphrase` is a reserved ghost key name '
'which cannot be deleted')
# TODO: Optimize. We get from the storage twice here for no reason
if not self.get(key_name):
raise GhostError('Key `{0}` not found'.format(key_name))
key = self._storage.get(key_name)
if key.get('lock'):
raise GhostError(
'Key `{0}` is locked and | python | {
"resource": ""
} |
q260502 | Stash.purge | validation | def purge(self, force=False, key_type=None):
"""Purge the stash from all keys
"""
self._assert_valid_stash()
if not force:
raise GhostError(
"The `force` flag must be provided to perform a stash purge. "
"I mean, you don't really want to just delete everything "
"without precautionary measures eh?")
audit(
| python | {
"resource": ""
} |
q260503 | Stash.export | validation | def export(self, output_path=None, decrypt=False):
"""Export all keys in the stash to a list or a file
"""
self._assert_valid_stash()
all_keys = []
for key in self.list():
# We `dict` this as a precaution as tinydb returns
# a tinydb.database.Element instead of a dictionary | python | {
"resource": ""
} |
q260504 | Stash.load | validation | def load(self, origin_passphrase, keys=None, key_file=None):
"""Import keys to the stash from either a list of keys or a file
`keys` is a list of dictionaries created by `self.export`
`stash_path` is a path to a file created by `self.export`
"""
# TODO: Handle keys not dict or key_file not json
self._assert_valid_stash()
# Check if both or none are provided (ahh, the mighty xor)
if not (bool(keys) ^ bool(key_file)):
raise GhostError(
'You must either provide a path to an exported stash file '
'or a list of key dicts to import')
if key_file:
with open(key_file) as stash_file:
keys = json.loads(stash_file.read())
# If the passphrases are the same, there's no reason to decrypt
# and re-encrypt. We can simply pass the value.
decrypt = origin_passphrase != self.passphrase
if decrypt:
# TODO: The fact that we need to create a stub stash just to
# decrypt | python | {
"resource": ""
} |
q260505 | Stash._encrypt | validation | def _encrypt(self, value):
"""Turn a json serializable value into an jsonified, encrypted,
hexa string.
"""
value = json.dumps(value)
| python | {
"resource": ""
} |
q260506 | Stash._decrypt | validation | def _decrypt(self, hexified_value):
"""The exact opposite of _encrypt
"""
encrypted_value = binascii.unhexlify(hexified_value)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
| python | {
"resource": ""
} |
q260507 | TinyDBStorage.get | validation | def get(self, key_name):
"""Return a dictionary consisting of the key itself
e.g.
{u'created_at': u'2016-10-10 08:31:53',
u'description': None,
u'metadata': None,
u'modified_at': u'2016-10-10 08:31:53',
u'name': u'aws',
u'uid': u'459f12c0-f341-413e-9d7e-7410f912fb74',
| python | {
"resource": ""
} |
q260508 | TinyDBStorage.delete | validation | def delete(self, key_name):
"""Delete the key and return true if the key was deleted, else false
"""
| python | {
"resource": ""
} |
q260509 | SQLAlchemyStorage._construct_key | validation | def _construct_key(self, values):
"""Return a dictionary representing a key from a list of columns
and a tuple of values
"""
key = {}
for column, value in | python | {
"resource": ""
} |
q260510 | ConsulStorage.put | validation | def put(self, key):
"""Put and return the only unique identifier possible, its url
"""
| python | {
"resource": ""
} |
q260511 | VaultStorage.put | validation | def put(self, key):
"""Put and return the only unique identifier possible, its path
"""
| python | {
"resource": ""
} |
q260512 | ElasticsearchStorage.init | validation | def init(self):
"""Create an Elasticsearch index if necessary
"""
# ignore 400 (IndexAlreadyExistsException) when creating an index
| python | {
"resource": ""
} |
q260513 | S3Storage.init | validation | def init(self):
"""Create a bucket.
"""
try:
self.client.create_bucket(
Bucket=self.db_path,
CreateBucketConfiguration=self.bucket_configuration)
except botocore.exceptions.ClientError as e:
| python | {
"resource": ""
} |
q260514 | terminal | validation | def terminal(port=default_port(), baud='9600'):
"""Launch minterm from pyserial"""
testargs = ['nodemcu-uploader', port, | python | {
"resource": ""
} |
q260515 | Uploader.__set_baudrate | validation | def __set_baudrate(self, baud):
"""setting baudrate if supported"""
log.info('Changing communication to %s baud', baud)
self.__writeln(UART_SETUP.format(baud=baud))
# Wait for the string to be sent before switching baud
time.sleep(0.1)
| python | {
"resource": ""
} |
q260516 | Uploader.set_timeout | validation | def set_timeout(self, timeout):
"""Set the timeout for the communication with the | python | {
"resource": ""
} |
q260517 | Uploader.__clear_buffers | validation | def __clear_buffers(self):
"""Clears the input and output buffers"""
try:
self._port.reset_input_buffer()
self._port.reset_output_buffer()
| python | {
"resource": ""
} |
q260518 | Uploader.__expect | validation | 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 is fast enough
if self._port.timeout != MINIMAL_TIMEOUT:
self._port.timeout = MINIMAL_TIMEOUT
end = time.time() + timeout
# Finish as soon as either exp matches or we run out of time (work like dump, but faster on success)
data = ''
while not data.endswith(exp) and time.time() <= end:
| python | {
"resource": ""
} |
q260519 | Uploader.__write | validation | 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)
| python | {
"resource": ""
} |
q260520 | Uploader.__exchange | validation | def __exchange(self, output, timeout=None):
"""Write output to the port and wait for response"""
self.__writeln(output)
| python | {
"resource": ""
} |
q260521 | Uploader.close | validation | 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()
| python | {
"resource": ""
} |
q260522 | Uploader.prepare | validation | 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('function:') == -1:
break
else:
log.info('Preparation already done. Not adding functions again.')
return True
functions = RECV_LUA + '\n' + SEND_LUA
data = functions.format(baud=self._port.baudrate)
##change any \r\n to just \n and split on that
lines = data.replace('\r', '').split('\n')
#remove some unneccesary spaces to conserve some bytes
| python | {
"resource": ""
} |
q260523 | Uploader.download_file | validation | 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 Exception('Unexpected error downloading file')
#tell device we are ready to receive
self.__write('C')
#we should get a NUL terminated filename to start with
sent_filename = self.__expect(NUL).strip()
log.info('receiveing ' + sent_filename)
#ACK to start download
| python | {
"resource": ""
} |
q260524 | Uploader.read_file | validation | 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 contain folder, so create it if needed.
log.info(destination)
if not os.path.exists(os.path.dirname(destination)):
| python | {
"resource": ""
} |
q260525 | Uploader.write_file | validation | 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("recv()")
res = self.__expect('C> ')
if not res.endswith('C> '):
log.error('Error waiting for esp "%s"', res)
raise CommunicationTimeout('Error waiting for device to start receiving', res)
log.debug('sending destination filename "%s"', destination)
self.__write(destination + '\x00', True)
if not self.__got_ack():
log.error('did not ack destination filename')
raise NoAckException('Device did not ACK destination filename')
content = from_file(path)
log.debug('sending %d bytes in %s', len(content), filename)
pos = 0
chunk_size = 128
while pos < len(content):
rest = len(content) - pos
if rest > chunk_size:
| python | {
"resource": ""
} |
q260526 | Uploader.verify_file | validation | 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':
data = self.download_file(destination)
if content != data:
log.error('Raw verification failed.')
raise VerificationError('Verification failed.')
else:
log.info('Verification successful. Contents are identical.')
elif verify == 'sha1':
#Calculate SHA1 on remote file. Extract just hash from result
data = self.__exchange('shafile("'+destination+'")').splitlines()[1]
log.info('Remote SHA1: %s', data)
| python | {
"resource": ""
} |
q260527 | Uploader.exec_file | validation | 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')
| python | {
"resource": ""
} |
q260528 | Uploader.__got_ack | validation | def __got_ack(self):
"""Returns true if ACK is received"""
log.debug('waiting for ack')
res = self._port.read(1)
| python | {
"resource": ""
} |
q260529 | Uploader.write_lines | validation | def write_lines(self, data):
"""write lines, one by one, separated by \n to device"""
| python | {
"resource": ""
} |
q260530 | Uploader.__write_chunk | validation | 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)
| python | {
"resource": ""
} |
q260531 | Uploader.__read_chunk | validation | 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.timeout = MINIMAL_TIMEOUT
end = time.time() + timeout_before
while len(buf) < 130 and time.time() <= end:
buf = buf + self._port.read()
if buf[0] != BLOCK_START or len(buf) < 130:
| python | {
"resource": ""
} |
q260532 | Uploader.file_list | validation | 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] | python | {
"resource": ""
} |
q260533 | Uploader.file_do | validation | def file_do(self, filename):
"""Execute a file on the device using 'do'"""
| python | {
"resource": ""
} |
q260534 | Uploader.file_format | validation | def file_format(self):
"""Formats device filesystem"""
log.info('Formating, can take minutes depending on flash size...')
res = self.__exchange('file.format()', timeout=300)
| python | {
"resource": ""
} |
q260535 | Uploader.file_print | validation | def file_print(self, filename):
"""Prints a file on the device to console"""
log.info('Printing ' + filename)
| python | {
"resource": ""
} |
q260536 | Uploader.node_heap | validation | def node_heap(self):
"""Show device heap size"""
log.info('Heap')
| python | {
"resource": ""
} |
q260537 | Uploader.file_compile | validation | def file_compile(self, path):
"""Compiles a file specified by path on the device"""
log.info('Compile '+path)
cmd = 'node.compile("%s")' % path
| python | {
"resource": ""
} |
q260538 | Uploader.file_remove | validation | def file_remove(self, path):
"""Removes a file on the device"""
log.info('Remove '+path)
cmd = 'file.remove("%s")' % path
| python | {
"resource": ""
} |
q260539 | Uploader.backup | validation | def backup(self, path):
"""Backup all files from the device"""
log.info('Backing up in '+path)
# List file to backup | python | {
"resource": ""
} |
q260540 | operation_upload | validation | 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):
if do_compile:
uploader.file_remove(os.path.splitext(dst)[0]+'.lc')
uploader.write_file(filename, dst, verify)
| python | {
"resource": ""
} |
q260541 | operation_download | validation | 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 zip(sources, destinations):
| python | {
"resource": ""
} |
q260542 | operation_list | validation | def operation_list(uploader):
"""List file on target"""
files = uploader.file_list() | python | {
"resource": ""
} |
q260543 | display | validation | 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.display(GPAuthWidget(content))
elif isinstance(content, gp.GPTask):
| python | {
"resource": ""
} |
q260544 | from_timestamp | validation | def from_timestamp(ts):
"""
Convert a numeric timestamp to a timezone-aware datetime.
A client may override this function | python | {
"resource": ""
} |
q260545 | DelayedCommand.at_time | validation | def at_time(cls, at, target):
"""
Construct a DelayedCommand to come due at `at`, where `at` may be
a datetime or | python | {
"resource": ""
} |
q260546 | PeriodicCommand._localize | validation | def _localize(dt):
"""
Rely on pytz.localize to ensure new result honors DST.
"""
try:
tz = dt.tzinfo
| python | {
"resource": ""
} |
q260547 | PeriodicCommandFixedDelay.daily_at | validation | 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
| python | {
"resource": ""
} |
q260548 | strftime | validation | 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_time, tuple)):
t = datetime.datetime(*t[:6])
assert isinstance(t, (datetime.datetime, datetime.time, datetime.date))
try:
year = t.year
if year < 1900:
t = t.replace(year=1900)
except AttributeError:
year = 1900
subs = | python | {
"resource": ""
} |
q260549 | strptime | validation | 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 | python | {
"resource": ""
} |
q260550 | get_nearest_year_for_day | validation | 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 > | python | {
"resource": ""
} |
q260551 | get_period_seconds | validation | 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):
...
ValueError: period not in (second, minute, hour, day, month, year)
"""
if isinstance(period, six.string_types):
try:
name = 'seconds_per_' + period.lower()
result = globals()[name]
except KeyError:
| python | {
"resource": ""
} |
q260552 | divide_timedelta_float | validation | 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 | python | {
"resource": ""
} |
q260553 | parse_timedelta | validation | 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)
>>> parse_timedelta('47.32 days, 20 minutes, 15.4 milliseconds')
datetime.timedelta(days=47, seconds=28848, microseconds=15400) | python | {
"resource": ""
} |
q260554 | divide_timedelta | validation | 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 | python | {
"resource": ""
} |
q260555 | date_range | validation | 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
True
>>> datetime.datetime(2005,12,22) in my_range
True
| python | {
"resource": ""
} |
q260556 | DatetimeConstructor.construct_datetime | validation | 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:
result = result.replace(tzinfo=kwargs.pop('tzinfo'))
except KeyError:
pass
if kwargs: | python | {
"resource": ""
} |
q260557 | API.get | validation | 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
)
else:
full_query = query
if self.debug:
logging.getLogger().info(query)
# Get the response from Overpass
r = self._get_from_overpass(full_query)
content_type = r.headers.get("content-type")
if self.debug:
print(content_type)
if content_type == "text/csv":
result = []
reader = csv.reader(StringIO(r.text), delimiter="\t")
for row in reader:
result.append(row)
return result
elif content_type in ("text/xml", "application/xml", "application/osm3s+xml"):
return r.text
elif content_type == "application/json":
response = json.loads(r.text)
if not build:
return response
| python | {
"resource": ""
} |
q260558 | get_ports_count | validation | 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 for
a port as listed in the RESOURCE_ATTRIBUTE_MAP object
in neutron/api/v2/attributes.py. Values in this dictionary
are an iterable containing values that will be used for an exact
match comparison for that value. Each result returned by this
function will have matched one of the values for each key in
| python | {
"resource": ""
} |
q260559 | QuarkIpam._allocate_from_v6_subnet | validation | 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 assignment as a
first time allocation utilizing the MAC address of the VIF. Because
we recycle MACs, we will eventually attempt to recreate a previously
generated v6 address. Instead of failing, we've opted to handle
reallocating that address in this method.
This should provide a performance boost over attempting to check
each and every subnet in the existing reallocate logic, as we'd
have to iterate over each and every subnet returned
"""
LOG.info("Attempting to allocate a v6 address - [{0}]".format(
utils.pretty_kwargs(network_id=net_id, subnet=subnet,
port_id=port_id, ip_address=ip_address)))
if ip_address:
LOG.info("IP %s explicitly requested, deferring to standard "
"allocation" % ip_address)
return self._allocate_from_subnet(context, net_id=net_id,
subnet=subnet, port_id=port_id,
reuse_after=reuse_after,
ip_address=ip_address, **kwargs)
else:
mac = kwargs.get("mac_address")
if mac:
mac = kwargs["mac_address"].get("address")
if subnet and subnet["ip_policy"]:
ip_policy_cidrs = subnet["ip_policy"].get_cidrs_ip_set()
else:
ip_policy_cidrs = netaddr.IPSet([])
for tries, ip_address in enumerate(
generate_v6(mac, port_id, subnet["cidr"])):
LOG.info("Attempt {0} of {1}".format(
tries + 1, CONF.QUARK.v6_allocation_attempts))
if tries > CONF.QUARK.v6_allocation_attempts - 1:
LOG.info("Exceeded v6 allocation attempts, bailing")
raise ip_address_failure(net_id)
| python | {
"resource": ""
} |
q260560 | _create_flip | validation | 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 port>": {"port": <quark.db.models.Port>,
"fixed_ip": "<fixed ip address>"}}
:return: None
"""
if port_fixed_ips:
context.session.begin()
try:
ports = [val['port'] for val in port_fixed_ips.values()]
flip = db_api.port_associate_ip(context, ports, flip,
port_fixed_ips.keys())
for port_id in port_fixed_ips:
fixed_ip = port_fixed_ips[port_id]['fixed_ip']
flip = db_api.floating_ip_associate_fixed_ip(context, flip,
| python | {
"resource": ""
} |
q260561 | create_floatingip | validation | 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 populated.
:returns: Dictionary containing details for the new floating IP. If values
are declared in the fields parameter, then only those keys will be
present.
"""
LOG.info('create_floatingip %s for tenant %s and body %s' %
(id, context.tenant_id, content))
network_id = content.get('floating_network_id')
# TODO(blogan): Since the extension logic will reject any requests without
# floating_network_id, is this still needed?
if not network_id:
raise n_exc.BadRequest(resource='floating_ip',
| python | {
"resource": ""
} |
q260562 | update_floatingip | validation | 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'
as listed in the RESOURCE_ATTRIBUTE_MAP object in
neutron/api/v2/attributes.py.
:returns: Dictionary containing details for the new floating IP. If values
are declared in the fields parameter, then only those keys will be
present.
"""
LOG.info('update_floatingip %s for tenant %s and body %s' %
(id, context.tenant_id, | python | {
"resource": ""
} |
q260563 | delete_floatingip | validation | def delete_floatingip(context, id):
"""deallocate a floating IP.
:param context: neutron api request context.
:param id: id of the floating ip
"""
| python | {
"resource": ""
} |
q260564 | get_floatingip | validation | 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 in neutron/api/v2/attributes.py. Only these fields
will be returned.
| python | {
"resource": ""
} |
q260565 | get_floatingips | validation | 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 listed in the RESOURCE_ATTRIBUTE_MAP object
in neutron/api/v2/attributes.py. Values in this dictionary
are an iterable containing values that will be used for an exact
match comparison for that value. Each result returned by this
function will have matched one of the values for each key in
filters.
:param fields: a list of strings that are valid keys in a
floating IP dictionary as listed in the RESOURCE_ATTRIBUTE_MAP
object in | python | {
"resource": ""
} |
q260566 | get_floatingips_count | validation | 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. Values in this dictionary
are an iterable containing values that will be used for an exact
match comparison for that value. Each result returned by this
function will have matched one of the values for each key in
filters.
:returns: The number of floating IPs that are accessible to the tenant who
submits the request (as indicated by the tenant id of the context)
as well as any filters.
NOTE: this | python | {
"resource": ""
} |
q260567 | create_scalingip | validation | 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 populated.
:returns: Dictionary containing details for the new scaling IP. If values
are declared in the fields parameter, then only those keys will be
present.
"""
LOG.info('create_scalingip for tenant %s and body %s',
context.tenant_id, content)
network_id = content.get('scaling_network_id')
ip_address = content.get('scaling_ip_address')
requested_ports = content.get('ports', [])
network = _get_network(context, network_id)
port_fixed_ips = {}
for req_port in requested_ports:
| python | {
"resource": ""
} |
q260568 | update_scalingip | validation | 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 listed in the RESOURCE_ATTRIBUTE_MAP object in
| python | {
"resource": ""
} |
q260569 | delete_scalingip | validation | def delete_scalingip(context, id):
"""Deallocate a scaling IP.
:param context: neutron api request context.
:param id: id of the scaling ip
"""
| python | {
"resource": ""
} |
q260570 | get_scalingip | validation | 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 neutron/api/v2/attributes.py. Only these fields
will be returned.
| python | {
"resource": ""
} |
q260571 | get_scalingips | validation | 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 in the RESOURCE_ATTRIBUTE_MAP object
in neutron/api/v2/attributes.py. Values in this dictionary
are an iterable containing values that will be used for an exact
match comparison for that value. Each result returned by this
function will have matched one of the values for each key in
filters.
:param fields: a list of strings that are valid keys in a
scaling IP dictionary as listed in the RESOURCE_ATTRIBUTE_MAP
object | python | {
"resource": ""
} |
q260572 | is_isonet_vif | validation | 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.
"""
| python | {
"resource": ""
} |
q260573 | partition_vifs | validation | 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 that have not been ack'd and the VIF
is already tagged
Action: Do not tag the VIF, do apply flows
Removed - Groups do NOT exist in Redis but the VIF is tagged
Action: Untag the VIF, apply default flows
Self-Heal - Groups are ack'd in Redis but the VIF is untagged. We treat
this case as if it were an "added" group.
Action: Tag the VIF and apply flows
NOOP - The VIF is not tagged and there are no matching groups in Redis.
This is our implicit category
Action: Do nothing
"""
added = []
updated = []
removed = []
for vif in interfaces:
# Quark should not action on isonet vifs in regions that use FLIP
if ('floating_ip' in CONF.QUARK.environment_capabilities and
is_isonet_vif(vif)):
| python | {
"resource": ""
} |
q260574 | get_groups_to_ack | validation | 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 update occurred during
the window that the xapi_client.update_interfaces was executing.
Return a list of vifs whose security group rules have not changed.
"""
security_groups_changed = []
# Compare current security group rules with initial rules.
for vif in groups_to_ack:
initial_state = init_sg_states[vif][sg_cli.SECURITY_GROUP_HASH_ATTR]
current_state = curr_sg_states[vif][sg_cli.SECURITY_GROUP_HASH_ATTR]
bad_match_msg = ('security group rules were changed for vif "%s" while'
' executing xapi_client.update_interfaces.'
' Will not ack rule.' % vif)
# If lists are different lengths, they're automatically different.
if len(initial_state) != len(current_state):
security_groups_changed.append(vif)
LOG.info(bad_match_msg)
elif len(initial_state) | python | {
"resource": ""
} |
q260575 | run | validation | 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_client = sg_cli.SecurityGroupsClient()
xapi_client = xapi.XapiClient()
interfaces = set()
while True:
try:
interfaces = xapi_client.get_interfaces()
except Exception:
LOG.exception("Unable to get instances/interfaces from xapi")
_sleep()
continue
try:
sg_states = groups_client.get_security_group_states(interfaces)
new_sg, updated_sg, removed_sg = partition_vifs(xapi_client,
| python | {
"resource": ""
} |
q260576 | QuarkQuotaDriver.delete_tenant_quota | validation | 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.
"""
| python | {
"resource": ""
} |
q260577 | _validate_subnet_cidr | validation | 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.cfg.CONF.allow_overlapping_ips:
return
try:
new_subnet_ipset = netaddr.IPSet([new_subnet_cidr])
except TypeError:
LOG.exception("Invalid or missing cidr: %s" % new_subnet_cidr)
raise n_exc.BadRequest(resource="subnet",
msg="Invalid or missing cidr")
filters = {
'network_id': network_id,
| python | {
"resource": ""
} |
q260578 | get_subnet | validation | 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 neutron/api/v2/attributes.py. Only these fields
will be returned.
"""
LOG.info("get_subnet %s for tenant %s with fields %s" %
| python | {
"resource": ""
} |
q260579 | get_subnets | validation | 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.
: param context: neutron api request context
: param filters: a dictionary with keys that are valid keys for
a subnet as listed in the RESOURCE_ATTRIBUTE_MAP object
in neutron/api/v2/attributes.py. Values in this dictiontary
are an iterable containing values that will be used for an exact
match comparison for that value. Each result returned by this
| python | {
"resource": ""
} |
q260580 | get_subnets_count | validation | 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 keys for
a network as listed in the RESOURCE_ATTRIBUTE_MAP object
in neutron/api/v2/attributes.py. Values in this dictiontary
are an iterable containing values that will be used for an exact
match comparison for that value. Each result returned by this
function will have matched one of the values for each | python | {
"resource": ""
} |
q260581 | delete_subnet | validation | def delete_subnet(context, id):
"""Delete a subnet.
: param context: neutron api request context
: param id: UUID representing the subnet to delete.
"""
LOG.info("delete_subnet %s for tenant %s" % (id, context.tenant_id))
with context.session.begin():
subnet = db_api.subnet_find(context, id=id, scope=db_api.ONE)
if not subnet:
raise n_exc.SubnetNotFound(subnet_id=id)
if not context.is_admin:
if STRATEGY.is_provider_network(subnet.network_id):
if subnet.tenant_id == context.tenant_id:
# A tenant can't delete subnets on | python | {
"resource": ""
} |
q260582 | _perform_async_update_rule | validation | def _perform_async_update_rule(context, id, db_sg_group, rule_id, action):
"""Updates a SG rule async and return the job information.
Only happens if the security group has associated ports. If the async
connection fails the update continues (legacy mode).
"""
rpc_reply = None
sg_rpc = sg_rpc_api.QuarkSGAsyncProcessClient()
ports = db_api.sg_gather_associated_ports(context, db_sg_group)
if len(ports) > 0:
rpc_reply = sg_rpc.start_update(context, | python | {
"resource": ""
} |
q260583 | update_security_group_rule | validation | def update_security_group_rule(context, id, security_group_rule):
'''Updates a rule and updates the ports'''
LOG.info("update_security_group_rule for tenant %s" %
(context.tenant_id))
new_rule = security_group_rule["security_group_rule"]
# Only allow updatable fields
new_rule = _filter_update_security_group_rule(new_rule)
with context.session.begin():
rule = db_api.security_group_rule_find(context, id=id,
scope=db_api.ONE)
if not rule:
raise | python | {
"resource": ""
} |
q260584 | JSONStrategy.get_public_net_id | validation | def get_public_net_id(self):
"""Returns the public net id"""
for id, net_params in | python | {
"resource": ""
} |
q260585 | opt_args_decorator | validation | def opt_args_decorator(func):
"""A decorator to be used on another decorator
This is done to allow separate handling on the basis of argument values
"""
@wraps(func)
def wrapped_dec(*args, **kwargs):
if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):
# actual decorated function
| python | {
"resource": ""
} |
q260586 | Plugin._fix_missing_tenant_id | validation | def _fix_missing_tenant_id(self, context, body, key):
"""Will add the tenant_id to the context from body.
It is assumed that the body must have a tenant_id because neutron
core could never have gotten here otherwise.
"""
if not body:
raise n_exc.BadRequest(resource=key,
msg="Body malformed")
resource = body.get(key)
if not resource:
raise n_exc.BadRequest(resource=key,
| python | {
"resource": ""
} |
q260587 | AllocationPools._validate_allocation_pools | validation | def _validate_allocation_pools(self):
"""Validate IP allocation pools.
Verify start and end address for each allocation pool are valid,
ie: constituted by valid and appropriately ordered IP addresses.
Also, verify pools do not overlap among themselves.
Finally, verify that each range fall within the subnet's CIDR.
"""
ip_pools = self._alloc_pools
subnet_cidr = self._subnet_cidr
LOG.debug(_("Performing IP validity checks on allocation pools"))
ip_sets = []
for ip_pool in ip_pools:
try:
start_ip = netaddr.IPAddress(ip_pool['start'])
end_ip = netaddr.IPAddress(ip_pool['end'])
except netaddr.AddrFormatError:
LOG.info(_("Found invalid IP address in pool: "
"%(start)s - %(end)s:"),
{'start': ip_pool['start'],
'end': ip_pool['end']})
raise n_exc_ext.InvalidAllocationPool(pool=ip_pool)
if (start_ip.version != self._subnet_cidr.version or
end_ip.version != self._subnet_cidr.version):
LOG.info(_("Specified IP addresses do not match "
"the subnet IP version"))
raise n_exc_ext.InvalidAllocationPool(pool=ip_pool)
if end_ip < start_ip:
LOG.info(_("Start IP (%(start)s) is greater than end IP "
"(%(end)s)"),
{'start': ip_pool['start'], 'end': ip_pool['end']})
raise n_exc_ext.InvalidAllocationPool(pool=ip_pool)
if (start_ip < self._subnet_first_ip or
end_ip > self._subnet_last_ip):
LOG.info(_("Found pool larger than subnet "
"CIDR:%(start)s - %(end)s"),
{'start': ip_pool['start'],
'end': ip_pool['end']})
raise n_exc_ext.OutOfBoundsAllocationPool(
| python | {
"resource": ""
} |
q260588 | add_job_to_context | validation | def add_job_to_context(context, job_id):
"""Adds job to neutron context for use later."""
db_job = db_api.async_transaction_find(
| python | {
"resource": ""
} |
q260589 | create_job | validation | def create_job(context, body):
"""Creates a job with support for subjobs.
If parent_id is not in the body:
* the job is considered a parent job
* it will have a NULL transaction id
* its transaction id == its id
* all subjobs will use its transaction id as theirs
Else:
* the job is a sub job
* the parent id is the id passed in
* the transaction id is the root of the job tree
"""
LOG.info("create_job for tenant %s" % context.tenant_id)
if not context.is_admin:
raise n_exc.NotAuthorized()
job = body.get('job')
if 'parent_id' in job:
parent_id = job['parent_id']
if not parent_id:
raise q_exc.JobNotFound(job_id=parent_id)
parent_job = db_api.async_transaction_find(
| python | {
"resource": ""
} |
q260590 | NVPDriver._lswitch_select_open | validation | def _lswitch_select_open(self, context, switches=None, **kwargs):
"""Selects an open lswitch for a network.
Note that it does not select the most full switch, but merely one with
ports available.
"""
| python | {
"resource": ""
} |
q260591 | NVPDriver._add_default_tz_bindings | validation | def _add_default_tz_bindings(self, context, switch, network_id):
"""Configure any additional default transport zone bindings."""
default_tz = CONF.NVP.default_tz
# If there is no default tz specified it's pointless to try
# and add any additional default tz bindings.
if not default_tz:
LOG.warn("additional_default_tz_types specified, "
"but no default_tz. Skipping "
"_add_default_tz_bindings().")
return
# This should never be called without a neutron network uuid,
# we require it to bind some segment allocations.
| python | {
"resource": ""
} |
q260592 | NVPDriver._remove_default_tz_bindings | validation | def _remove_default_tz_bindings(self, context, network_id):
"""Deconfigure any additional default transport zone bindings."""
default_tz = CONF.NVP.default_tz
if not default_tz:
LOG.warn("additional_default_tz_types specified, "
"but no default_tz. Skipping "
"_remove_default_tz_bindings().")
return
if not network_id:
LOG.warn("neutron network_id not specified, skipping "
"_remove_default_tz_bindings()")
| python | {
"resource": ""
} |
q260593 | NVPDriver.get_lswitch_ids_for_network | validation | def get_lswitch_ids_for_network(self, context, network_id):
"""Public interface for fetching lswitch ids for a given network.
NOTE(morgabra) This is here because calling private methods
from outside the class feels wrong, and we need to be able to
fetch lswitch ids for use in | python | {
"resource": ""
} |
q260594 | QuarkAsyncServer._load_worker_plugin_with_module | validation | def _load_worker_plugin_with_module(self, module, version):
"""Instantiates worker plugins that have requsite properties.
The required properties are:
* must have PLUGIN_EP entrypoint registered (or it wouldn't be in the
list)
* must have class attribute versions (list) of supported RPC versions
* must subclass QuarkAsyncPluginBase
"""
classes = inspect.getmembers(module, inspect.isclass)
| python | {
"resource": ""
} |
q260595 | QuarkAsyncServer._discover_via_entrypoints | validation | def _discover_via_entrypoints(self):
"""Looks for modules with amtching entry points."""
emgr | python | {
"resource": ""
} |
q260596 | QuarkAsyncServer.start_api_and_rpc_workers | validation | def start_api_and_rpc_workers(self):
"""Initializes eventlet and starts wait for workers to exit.
Spawns the workers | python | {
"resource": ""
} |
q260597 | BaseSegmentAllocation._chunks | validation | def _chunks(self, iterable, chunk_size):
"""Chunks data into chunk with size<=chunk_size."""
iterator = iter(iterable)
chunk = list(itertools.islice(iterator, 0, chunk_size))
| python | {
"resource": ""
} |
q260598 | BaseSegmentAllocation._check_collisions | validation | def _check_collisions(self, new_range, existing_ranges):
"""Check for overlapping ranges."""
def _contains(num, r1):
return (num >= r1[0] and
num <= r1[1])
def _is_overlap(r1, r2):
return (_contains(r1[0], r2) or
_contains(r1[1], r2) or
_contains(r2[0], r1) or
| python | {
"resource": ""
} |
q260599 | BaseSegmentAllocation._try_allocate | validation | def _try_allocate(self, context, segment_id, network_id):
"""Find a deallocated network segment id and reallocate it.
NOTE(morgabra) This locks the segment table, but only the rows
in use by the segment, which is pretty handy if we ever have
more than 1 segment or segment type.
"""
LOG.info("Attempting to allocate segment for network %s "
"segment_id %s segment_type %s"
% (network_id, segment_id, self.segment_type))
filter_dict = {
"segment_id": segment_id,
"segment_type": self.segment_type,
"do_not_use": False
}
available_ranges = db_api.segment_allocation_range_find(
context, scope=db_api.ALL, **filter_dict)
available_range_ids = [r["id"] for r in available_ranges]
try:
with context.session.begin(subtransactions=True):
# Search for any deallocated segment ids for the
# given segment.
filter_dict = {
"deallocated": True,
"segment_id": segment_id,
"segment_type": self.segment_type,
"segment_allocation_range_ids": available_range_ids
}
# NOTE(morgabra) We select 100 deallocated segment ids from
# the table here, and then choose 1 randomly. This is to help
# alleviate the case where an uncaught exception might leave
# an allocation active on a remote service but we do not have
# a record of it locally. If we *do* end up choosing a
# conflicted id, the caller should simply allocate another one
# and mark them all as reserved. If a single object has
# multiple reservations on the same segment, they will not be
# deallocated, and the operator must resolve the conficts
# manually.
allocations = | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.