text_prompt stringlengths 100 17.7k ⌀ | code_prompt stringlengths 7 9.86k ⌀ |
|---|---|
<SYSTEM_TASK:>
method performs logging into log file and the freerun_entry
<END_TASK>
<USER_TASK:>
Description:
def _log_message(self, level, freerun_entry, msg):
""" method performs logging into log file and the freerun_entry """ |
self.logger.log(level, msg)
assert isinstance(freerun_entry, FreerunProcessEntry)
event_log = freerun_entry.event_log
if len(event_log) > MAX_NUMBER_OF_EVENTS:
del event_log[-1]
event_log.insert(0, msg)
self.freerun_process_dao.update(freerun_entry) |
<SYSTEM_TASK:>
method that takes care of processing unit_of_work records in
<END_TASK>
<USER_TASK:>
Description:
def _process_terminal_state(self, freerun_entry, uow, flow_request=None):
""" method that takes care of processing unit_of_work records in
STATE_PROCESSED, STATE_NOOP, STATE_INVALID, STAT... |
msg = 'UOW for {0} found in state {1}.'.format(freerun_entry.schedulable_name, uow.state)
self._log_message(INFO, freerun_entry, msg)
self.insert_and_publish_uow(freerun_entry, flow_request, reset_uow=True) |
<SYSTEM_TASK:>
method main duty - is to _avoid_ publishing another unit_of_work, if previous was not yet processed
<END_TASK>
<USER_TASK:>
Description:
def manage_schedulable(self, freerun_entry, flow_request=None):
""" method main duty - is to _avoid_ publishing another unit_of_work, if previous was not yet pr... |
assert isinstance(freerun_entry, FreerunProcessEntry)
uow = None
if freerun_entry.related_unit_of_work:
uow = self.uow_dao.get_one(freerun_entry.related_unit_of_work)
try:
if uow is None:
self._process_state_embryo(freerun_entry, flow_request)
... |
<SYSTEM_TASK:>
fine-tuned data engine. MongoDB legacy
<END_TASK>
<USER_TASK:>
Description:
def _run_custom_data_engine(self, start_id_obj, end_id_obj, start_timeperiod, end_timeperiod):
""" fine-tuned data engine. MongoDB legacy """ |
collection_name = context.process_context[self.process_name].source
iteration = 0
while True:
cursor = self.ds.cursor_fine(collection_name,
start_id_obj,
end_id_obj,
... |
<SYSTEM_TASK:>
regular data engine
<END_TASK>
<USER_TASK:>
Description:
def _run_data_engine(self, start_timeperiod, end_timeperiod):
""" regular data engine """ |
collection_name = context.process_context[self.process_name].source
cursor = self.ds.cursor_batch(collection_name,
start_timeperiod,
end_timeperiod)
for document in cursor:
self._process_single_document(docu... |
<SYSTEM_TASK:>
Build a request body object.
<END_TASK>
<USER_TASK:>
Description:
def build_request_body(type, id, attributes=None, relationships=None):
"""Build a request body object.
A body JSON object is used for any of the ``update`` or ``create``
methods on :class:`Resource` subclasses. In normal lib... |
result = {
"data": {
"type": type
}
}
data = result['data']
if attributes is not None:
data['attributes'] = attributes
if relationships is not None:
data['relationships'] = relationships
if id is not None:
data['id'] = id
return result |
<SYSTEM_TASK:>
Build a relationship list.
<END_TASK>
<USER_TASK:>
Description:
def build_request_relationship(type, ids):
"""Build a relationship list.
A relationship list is used to update relationships between two
resources. Setting sensors on a label, for example, uses this
function to construct the... |
if ids is None:
return {
'data': None
}
elif isinstance(ids, str):
return {
'data': {'id': ids, 'type': type}
}
else:
return {
"data": [{"id": id, "type": type} for id in ids]
} |
<SYSTEM_TASK:>
Augment request parameters with includes.
<END_TASK>
<USER_TASK:>
Description:
def build_request_include(include, params):
"""Augment request parameters with includes.
When one or all resources are requested an additional set of
resources can be requested as part of the request. This functio... |
params = params or OrderedDict()
if include is not None:
params['include'] = ','.join([cls._resource_type() for cls in include])
return params |
<SYSTEM_TASK:>
Retrieve a single resource.
<END_TASK>
<USER_TASK:>
Description:
def find(cls, session, resource_id, include=None):
"""Retrieve a single resource.
This should only be called from sub-classes.
Args:
session(Session): The session to find the resource in
r... |
url = session._build_url(cls._resource_path(), resource_id)
params = build_request_include(include, None)
process = cls._mk_one(session, include=include)
return session.get(url, CB.json(200, process), params=params) |
<SYSTEM_TASK:>
Get filtered resources of the given resource class.
<END_TASK>
<USER_TASK:>
Description:
def where(cls, session, include=None, metadata=None, filter=None):
"""Get filtered resources of the given resource class.
This should be called on sub-classes only.
The include argument allo... |
url = session._build_url(cls._resource_path())
params = build_request_include(include, None)
if metadata is not None:
params['filter[metadata]'] = to_json(metadata)
process = cls._mk_many(session, include=include, filter=filter)
return session.get(url, CB.json(200, p... |
<SYSTEM_TASK:>
Create a resource of the resource.
<END_TASK>
<USER_TASK:>
Description:
def create(cls, session, attributes=None, relationships=None):
"""Create a resource of the resource.
This should only be called from sub-classes
Args:
session(Session): The session to create the r... |
resource_type = cls._resource_type()
resource_path = cls._resource_path()
url = session._build_url(resource_path)
json = build_request_body(resource_type, None,
attributes=attributes,
relationships=relationships)
... |
<SYSTEM_TASK:>
Get the a singleton API resource.
<END_TASK>
<USER_TASK:>
Description:
def singleton(cls, session, include=None):
"""Get the a singleton API resource.
Some Helium API resources are singletons. The authorized user
and organization for a given API key are examples of this.
... |
params = build_request_include(include, None)
url = session._build_url(cls._resource_path())
process = cls._mk_one(session, singleton=True, include=include)
return session.get(url, CB.json(200, process), params=params) |
<SYSTEM_TASK:>
Update this resource.
<END_TASK>
<USER_TASK:>
Description:
def update(self, attributes=None):
"""Update this resource.
Not all aspects of a resource can be updated. If the server
rejects updates an error will be thrown.
Keyword Arguments:
attributes(dict): Att... |
resource_type = self._resource_type()
resource_path = self._resource_path()
session = self._session
singleton = self.is_singleton()
id = None if singleton else self.id
url = session._build_url(resource_path, id)
attributes = build_request_body(resource_type, self... |
<SYSTEM_TASK:>
Delete the resource.
<END_TASK>
<USER_TASK:>
Description:
def delete(self):
"""Delete the resource.
Returns:
True if the delete is successful. Will throw an error if
other errors occur
""" |
session = self._session
url = session._build_url(self._resource_path(), self.id)
return session.delete(url, CB.boolean(204)) |
<SYSTEM_TASK:>
Changes file mode permissions.
<END_TASK>
<USER_TASK:>
Description:
def chmod(path, mode=None, user=None, group=None, other=None, recursive=False):
"""Changes file mode permissions.
>>> if chmod('/tmp/one', 0755):
... print('OK')
OK
NOTE: The precending ``0`` is required w... |
successful = True
mode = _ops_mode(mode)
if user is not None:
mode.user = user
if group is not None:
mode.group = group
if other is not None:
mode.other = other
if recursive:
for p in find(path, no_peek=True):
successful = _chmod(p, mode) and successf... |
<SYSTEM_TASK:>
Create a directory at the specified path. By default this function
<END_TASK>
<USER_TASK:>
Description:
def mkdir(path, recursive=True):
"""Create a directory at the specified path. By default this function
recursively creates the path.
>>> if mkdir('/tmp/one/two'):
... print('OK... |
if os.path.exists(path):
return True
try:
if recursive:
os.makedirs(path)
else:
os.mkdir(path)
except OSError as error:
log.error('mkdir: execute failed: %s (%s)' % (path, error))
return False
return True |
<SYSTEM_TASK:>
Convert string variables to a specified type.
<END_TASK>
<USER_TASK:>
Description:
def normalize(value, default=None, type=None, raise_exception=False):
"""Convert string variables to a specified type.
>>> normalize('true', type='boolean')
True
>>> normalize('11', type='number')
... |
NUMBER_RE = re.compile('^[-+]?(([0-9]+\.?[0-9]*)|([0-9]*\.?[0-9]+))$')
if type is None and default is None:
type = unicode_type
elif type is None:
type = type_(default)
if type in str_types:
if value is not None:
if isinstance(value, unicode_type):
re... |
<SYSTEM_TASK:>
Delete a specified file or directory. This function does not recursively
<END_TASK>
<USER_TASK:>
Description:
def rm(path, recursive=False):
"""Delete a specified file or directory. This function does not recursively
delete by default.
>>> if rm('/tmp/build', recursive=True):
... ... |
try:
if recursive:
if os.path.isfile(path):
os.remove(path)
else:
shutil.rmtree(path)
else:
if os.path.isfile(path):
os.remove(path)
else:
os.rmdir(path)
except OSError as error:
... |
<SYSTEM_TASK:>
Ensure a MongoDB index on a particular field name
<END_TASK>
<USER_TASK:>
Description:
def simple_ensure_index(request, database_name, collection_name):
"""Ensure a MongoDB index on a particular field name""" |
name = "Ensure a MongoDB index on a particular field name"
if request.method == 'POST':
form = EnsureIndexForm(request.POST)
if form.is_valid():
result = form.save(database_name, collection_name)
messages.success(request,
_("Index for %s cr... |
<SYSTEM_TASK:>
Create a New Mongo Database by adding a single document.
<END_TASK>
<USER_TASK:>
Description:
def create_new_database(request):
"""Create a New Mongo Database by adding a single document.""" |
name = "Create a New MongoDB Database"
if request.method == 'POST':
form = CreateDatabaseForm(request.POST)
if form.is_valid():
result = form.save()
if "error" in result:
messages.error(
request, "The database creation operation fail... |
<SYSTEM_TASK:>
wraps method with verification for is_request_valid
<END_TASK>
<USER_TASK:>
Description:
def valid_action_request(method):
""" wraps method with verification for is_request_valid""" |
@functools.wraps(method)
def _wrapper(self, *args, **kwargs):
assert isinstance(self, BaseRequestHandler)
if not self.is_request_valid:
return self.reply_bad_request()
try:
return method(self, *args, **kwargs)
except UserWarning as e:
return... |
<SYSTEM_TASK:>
makes sure the response' document has all leaf-fields converted to string
<END_TASK>
<USER_TASK:>
Description:
def safe_json_response(method):
""" makes sure the response' document has all leaf-fields converted to string """ |
def _safe_document(document):
""" function modifies the document in place
it iterates over the json document and stringify all non-string types
:return: modified document """
assert isinstance(document, dict), 'Error: provided document is not of DICT type: {0}' \
... |
<SYSTEM_TASK:>
Authentificate user and store token
<END_TASK>
<USER_TASK:>
Description:
def _auth(self, username, password) :
""" Authentificate user and store token """ |
self.user_credentials = self.call('auth', {'username': username, 'password': password})
if 'error' in self.user_credentials:
raise T411Exception('Error while fetching authentication token: %s'\
% self.user_credentials['error'])
# Create or update user fi... |
<SYSTEM_TASK:>
method iterates over each reprocessing queues and re-submits UOW whose waiting time has expired
<END_TASK>
<USER_TASK:>
Description:
def flush(self, ignore_priority=False):
""" method iterates over each reprocessing queues and re-submits UOW whose waiting time has expired """ |
for process_name, q in self.reprocess_uows.items():
self._flush_queue(q, ignore_priority) |
<SYSTEM_TASK:>
method iterates over the reprocessing queue and synchronizes state of every UOW with the DB
<END_TASK>
<USER_TASK:>
Description:
def validate(self):
""" method iterates over the reprocessing queue and synchronizes state of every UOW with the DB
should it change via the MX to STATE_CAN... |
for process_name, q in self.reprocess_uows.items():
if not q:
continue
invalid_entries = list()
for entry in q.queue:
assert isinstance(entry, PriorityEntry)
uow = self.uow_dao.get_one(entry.entry.db_id)
if uow... |
<SYSTEM_TASK:>
method iterates over the reprocessing queue for the given process
<END_TASK>
<USER_TASK:>
Description:
def flush_one(self, process_name, ignore_priority=False):
""" method iterates over the reprocessing queue for the given process
and re-submits UOW whose waiting time has expired """ |
q = self.reprocess_uows[process_name]
self._flush_queue(q, ignore_priority) |
<SYSTEM_TASK:>
return trees assigned to given MX Page
<END_TASK>
<USER_TASK:>
Description:
def mx_page_trees(self, mx_page):
""" return trees assigned to given MX Page """ |
resp = dict()
for tree_name, tree in self.scheduler.timetable.trees.items():
if tree.mx_page == mx_page:
rest_tree = self._get_tree_details(tree_name)
resp[tree.tree_name] = rest_tree.document
return resp |
<SYSTEM_TASK:>
Compute 2D coordinates of the piece.
<END_TASK>
<USER_TASK:>
Description:
def compute_coordinates(self):
""" Compute 2D coordinates of the piece. """ |
self._x, self._y = self.board.index_to_coordinates(self.index) |
<SYSTEM_TASK:>
All horizontal squares from the piece's point of view.
<END_TASK>
<USER_TASK:>
Description:
def horizontals(self):
""" All horizontal squares from the piece's point of view.
Returns a list of relative movements up to the board's bound.
""" |
horizontal_shifts = set(izip_longest(map(
lambda i: i - self.x, range(self.board.length)), [], fillvalue=0))
horizontal_shifts.discard((0, 0))
return horizontal_shifts |
<SYSTEM_TASK:>
All vertical squares from the piece's point of view.
<END_TASK>
<USER_TASK:>
Description:
def verticals(self):
""" All vertical squares from the piece's point of view.
Returns a list of relative movements up to the board's bound.
""" |
vertical_shifts = set(izip_longest([], map(
lambda i: i - self.y, range(self.board.height)), fillvalue=0))
vertical_shifts.discard((0, 0))
return vertical_shifts |
<SYSTEM_TASK:>
All diagonal squares from the piece's point of view.
<END_TASK>
<USER_TASK:>
Description:
def diagonals(self):
""" All diagonal squares from the piece's point of view.
Returns a list of relative movements up to the board's bound.
""" |
left_top_shifts = map(lambda i: (-(i + 1), -(i + 1)), range(min(
self.left_distance, self.top_distance)))
left_bottom_shifts = map(lambda i: (-(i + 1), +(i + 1)), range(min(
self.left_distance, self.bottom_distance)))
right_top_shifts = map(lambda i: (+(i + 1), -(i + 1))... |
<SYSTEM_TASK:>
Return the cached territory occupied by the piece.
<END_TASK>
<USER_TASK:>
Description:
def territory(self):
""" Return the cached territory occupied by the piece. """ |
cache_key = (
self.board.length, self.board.height, self.uid, self.index)
if cache_key not in self.territory_cache:
vector = self.compute_territory()
self.territory_cache[cache_key] = vector
else:
vector = self.territory_cache[cache_key]
r... |
<SYSTEM_TASK:>
Compute territory reachable by the piece from its current position.
<END_TASK>
<USER_TASK:>
Description:
def compute_territory(self):
""" Compute territory reachable by the piece from its current position.
Returns a list of boolean flags of squares indexed linearly, for which
a T... |
# Initialize the square occupancy vector of the board.
vector = self.board.new_vector()
# Mark current position as reachable.
vector[self.index] = True
# List all places reacheable by the piece from its current position.
for x_shift, y_shift in self.movements:
... |
<SYSTEM_TASK:>
Empty board, remove all pieces and reset internal states.
<END_TASK>
<USER_TASK:>
Description:
def reset(self):
""" Empty board, remove all pieces and reset internal states. """ |
# Store positionned pieces on the board.
self.pieces = set()
# Squares on the board already occupied by a piece.
self.occupancy = self.new_vector()
# Territory susceptible to attacke, i.e. squares reachable by at least
# a piece.
self.exposed_territory = self.n... |
<SYSTEM_TASK:>
Generator producing all 2D positions of all squares.
<END_TASK>
<USER_TASK:>
Description:
def positions(self):
""" Generator producing all 2D positions of all squares. """ |
for y in range(self.height):
for x in range(self.length):
yield x, y |
<SYSTEM_TASK:>
Check that a linear index of a square is within board's bounds.
<END_TASK>
<USER_TASK:>
Description:
def validate_index(self, index):
""" Check that a linear index of a square is within board's bounds. """ |
if index < 0 or index >= self.size:
raise ForbiddenIndex("Linear index {} not in {}x{} board.".format(
index, self.length, self.height)) |
<SYSTEM_TASK:>
Check if the piece lie within the board.
<END_TASK>
<USER_TASK:>
Description:
def validate_coordinates(self, x, y):
""" Check if the piece lie within the board. """ |
if not(0 <= x < self.length and 0 <= y < self.height):
raise ForbiddenCoordinates(
"x={}, y={} outside of {}x{} board.".format(
x, y, self.length, self.height)) |
<SYSTEM_TASK:>
Return a linear index from a set of 2D coordinates.
<END_TASK>
<USER_TASK:>
Description:
def coordinates_to_index(self, x, y, x_shift=0, y_shift=0):
""" Return a linear index from a set of 2D coordinates.
Optionnal vertical and horizontal shifts might be applied.
""" |
target_x = x + x_shift
target_y = y + y_shift
self.validate_coordinates(target_x, target_y)
index = (target_y * self.length) + target_x
return index |
<SYSTEM_TASK:>
Add a piece to the board at the provided linear position.
<END_TASK>
<USER_TASK:>
Description:
def add(self, piece_uid, index):
""" Add a piece to the board at the provided linear position. """ |
# Square already occupied by another piece.
if self.occupancy[index]:
raise OccupiedPosition
# Square reachable by another piece.
if self.exposed_territory[index]:
raise VulnerablePosition
# Create a new instance of the piece.
klass = PIECE_CLAS... |
<SYSTEM_TASK:>
Return piece placed at the provided coordinates.
<END_TASK>
<USER_TASK:>
Description:
def get(self, x, y):
""" Return piece placed at the provided coordinates. """ |
for piece in self.pieces:
if (piece.x, piece.y) == (x, y):
return piece |
<SYSTEM_TASK:>
Returns descriptive information about this cruddy handler and the
<END_TASK>
<USER_TASK:>
Description:
def describe(self, **kwargs):
"""
Returns descriptive information about this cruddy handler and the
methods supported by it.
""" |
response = self._new_response()
description = {
'cruddy_version': __version__,
'table_name': self.table_name,
'supported_operations': copy.copy(self.supported_ops),
'prototype': copy.deepcopy(self.prototype),
'operations': {}
}
... |
<SYSTEM_TASK:>
Cruddy provides a limited but useful interface to search GSI indexes in
<END_TASK>
<USER_TASK:>
Description:
def search(self, query, **kwargs):
"""
Cruddy provides a limited but useful interface to search GSI indexes in
DynamoDB with the following limitations (hopefully some of th... |
response = self._new_response()
if self._check_supported_op('search', response):
if '=' not in query:
response.status = 'error'
response.error_type = 'InvalidQuery'
msg = 'Only the = operation is supported'
response.error_messa... |
<SYSTEM_TASK:>
Returns a list of items in the database. Encrypted attributes are not
<END_TASK>
<USER_TASK:>
Description:
def list(self, **kwargs):
"""
Returns a list of items in the database. Encrypted attributes are not
decrypted when listing items.
""" |
response = self._new_response()
if self._check_supported_op('list', response):
self._call_ddb_method(self.table.scan, {}, response)
if response.status == 'success':
response.data = self._replace_decimals(
response.raw_response['Items'])
... |
<SYSTEM_TASK:>
Creates a new item. You pass in an item containing initial values.
<END_TASK>
<USER_TASK:>
Description:
def create(self, item, **kwargs):
"""
Creates a new item. You pass in an item containing initial values.
Any attribute names defined in ``prototype`` that are missing from the... |
response = self._new_response()
if self._prototype_handler.check(item, 'create', response):
self._encrypt(item)
params = {'Item': item}
self._call_ddb_method(self.table.put_item,
params, response)
if response.status == 's... |
<SYSTEM_TASK:>
Updates the item based on the current values of the dictionary passed
<END_TASK>
<USER_TASK:>
Description:
def update(self, item, encrypt=True, **kwargs):
"""
Updates the item based on the current values of the dictionary passed
in.
""" |
response = self._new_response()
if self._check_supported_op('update', response):
if self._prototype_handler.check(item, 'update', response):
if encrypt:
self._encrypt(item)
params = {'Item': item}
self._call_ddb_method(self... |
<SYSTEM_TASK:>
Atomically increments a counter attribute in the item identified by
<END_TASK>
<USER_TASK:>
Description:
def increment_counter(self, id, counter_name, increment=1,
id_name='id', **kwargs):
"""
Atomically increments a counter attribute in the item identified by
... |
response = self._new_response()
if self._check_supported_op('increment_counter', response):
params = {
'Key': {id_name: id},
'UpdateExpression': 'set #ctr = #ctr + :val',
'ExpressionAttributeNames': {"#ctr": counter_name},
'Exp... |
<SYSTEM_TASK:>
Deletes the item corresponding to ``id``.
<END_TASK>
<USER_TASK:>
Description:
def delete(self, id, id_name='id', **kwargs):
"""
Deletes the item corresponding to ``id``.
""" |
response = self._new_response()
if self._check_supported_op('delete', response):
params = {'Key': {id_name: id}}
self._call_ddb_method(self.table.delete_item, params, response)
response.data = 'true'
response.prepare()
return response |
<SYSTEM_TASK:>
Perform a search and delete all items that match.
<END_TASK>
<USER_TASK:>
Description:
def bulk_delete(self, query, **kwargs):
"""
Perform a search and delete all items that match.
""" |
response = self._new_response()
if self._check_supported_op('search', response):
n = 0
pe = 'id'
response = self.search(query, projection_expression=pe, **kwargs)
while response.status == 'success' and response.data:
for item in response.d... |
<SYSTEM_TASK:>
In addition to the methods described above, cruddy also provides a
<END_TASK>
<USER_TASK:>
Description:
def handler(self, operation=None, **kwargs):
"""
In addition to the methods described above, cruddy also provides a
generic handler interface. This is mainly useful when you wa... |
response = self._new_response()
if operation is None:
response.status = 'error'
response.error_type = 'MissingOperation'
response.error_message = 'You must pass an operation'
return response
operation = operation.lower()
self._check_suppor... |
<SYSTEM_TASK:>
Creates a new Netconf request based on the last received or if
<END_TASK>
<USER_TASK:>
Description:
def get_lldp_neighbors_request(last_ifindex, rbridge_id):
""" Creates a new Netconf request based on the last received or if
rbridge_id is specifed
ifindex when the hasMore flag is ... |
request_lldp = ET.Element(
'get-lldp-neighbor-detail',
xmlns="urn:brocade.com:mgmt:brocade-lldp-ext"
)
if rbridge_id is not None:
rbridge_el = ET.SubElement(request_lldp, "rbridge-id")
rbridge_el.text = rbridge_id
elif last_ifindex != '':... |
<SYSTEM_TASK:>
Gets a 201 response with the specified data.
<END_TASK>
<USER_TASK:>
Description:
def created(self, data, schema=None, envelope=None):
"""
Gets a 201 response with the specified data.
:param data: The content value.
:param schema: The schema to serialize the data.
... |
data = marshal(data, schema, envelope)
return self.__make_response((data, 201)) |
<SYSTEM_TASK:>
Gets a 200 response with the specified data.
<END_TASK>
<USER_TASK:>
Description:
def ok(self, data, schema=None, envelope=None):
"""
Gets a 200 response with the specified data.
:param data: The content value.
:param schema: The schema to serialize the data.
:par... |
data = marshal(data, schema, envelope)
return self.__make_response(data) |
<SYSTEM_TASK:>
A decorator that sets a list of authenticators for a function.
<END_TASK>
<USER_TASK:>
Description:
def authenticators(self, auths):
"""
A decorator that sets a list of authenticators for a function.
:param auths: The list of authenticator instances or classes.
:return: A... |
if not isinstance(auths, (list, tuple)):
auths = [auths]
instances = []
for auth in auths:
if isclass(auth):
instances.append(auth())
else:
instances.append(auth)
def decorator(func):
func.authenticators... |
<SYSTEM_TASK:>
A decorator that sets a list of permissions for a function.
<END_TASK>
<USER_TASK:>
Description:
def permissions(self, perms):
"""
A decorator that sets a list of permissions for a function.
:param perms: The list of permission instances or classes.
:return: A function
... |
if not isinstance(perms, (list, tuple)):
perms = [perms]
instances = []
for perm in perms:
if isclass(perm):
instances.append(perm())
else:
instances.append(perm)
def decorator(func):
func.permissions = ... |
<SYSTEM_TASK:>
A decorator that converts the request body into a function parameter based on the specified schema.
<END_TASK>
<USER_TASK:>
Description:
def from_body(self, param_name, schema):
"""
A decorator that converts the request body into a function parameter based on the specified schema.
... |
schema = schema() if isclass(schema) else schema
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
kwargs[param_name] = self.__parse_body(schema)
return func(*args, **kwargs)
return wrapper
return deco... |
<SYSTEM_TASK:>
A decorator that converts a request cookie into a function parameter based on the specified field.
<END_TASK>
<USER_TASK:>
Description:
def from_cookie(self, param_name, field):
"""
A decorator that converts a request cookie into a function parameter based on the specified field.
... |
return self.__from_source(param_name, field, lambda: request.cookies, 'cookie') |
<SYSTEM_TASK:>
A decorator that converts a request form into a function parameter based on the specified field.
<END_TASK>
<USER_TASK:>
Description:
def from_form(self, param_name, field):
"""
A decorator that converts a request form into a function parameter based on the specified field.
:para... |
return self.__from_source(param_name, field, lambda: request.form, 'form') |
<SYSTEM_TASK:>
A decorator that converts a request header into a function parameter based on the specified field.
<END_TASK>
<USER_TASK:>
Description:
def from_header(self, param_name, field):
"""
A decorator that converts a request header into a function parameter based on the specified field.
... |
return self.__from_source(param_name, field, lambda: request.headers, 'header') |
<SYSTEM_TASK:>
A decorator that converts a query string into a function parameter based on the specified field.
<END_TASK>
<USER_TASK:>
Description:
def from_query(self, param_name, field):
"""
A decorator that converts a query string into a function parameter based on the specified field.
:par... |
return self.__from_source(param_name, field, lambda: request.args, 'query') |
<SYSTEM_TASK:>
A decorator that apply marshalling to the return values of your methods.
<END_TASK>
<USER_TASK:>
Description:
def marshal_with(self, schema, envelope=None):
"""
A decorator that apply marshalling to the return values of your methods.
:param schema: The schema class to be used to ... |
# schema is pre instantiated to avoid instantiate it
# on every request
schema_is_class = isclass(schema)
schema_cache = schema() if schema_is_class else schema
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
da... |
<SYSTEM_TASK:>
A decorator that allows to change the trace emitter.
<END_TASK>
<USER_TASK:>
Description:
def trace_emit(self):
"""
A decorator that allows to change the trace emitter.
By default Python logging is used to emit the trace data.
""" |
def decorator(f):
self.tracer.emitter = f
return f
return decorator |
<SYSTEM_TASK:>
Creates a Flask response object from the specified data.
<END_TASK>
<USER_TASK:>
Description:
def __make_response(self, data, default_renderer=None):
"""
Creates a Flask response object from the specified data.
The appropriated encoder is taken based on the request header Accept.
... |
status = headers = None
if isinstance(data, tuple):
data, status, headers = unpack(data)
if data is None:
data = self.__app.response_class(status=204)
elif not isinstance(data, self.__app.response_class):
renderer, mimetype = self.content_negotiatio... |
<SYSTEM_TASK:>
cruddy is a CLI interface to the cruddy handler. It can be used in one
<END_TASK>
<USER_TASK:>
Description:
def cli(ctx, profile, region, lambda_fn, config, debug):
"""
cruddy is a CLI interface to the cruddy handler. It can be used in one
of two ways.
First, you can pass in a ``--conf... |
ctx.obj = CLIHandler(profile, region, lambda_fn, config, debug) |
<SYSTEM_TASK:>
Increment a counter attribute atomically
<END_TASK>
<USER_TASK:>
Description:
def increment(handler, increment, item_id, counter_name):
"""Increment a counter attribute atomically""" |
data = {'operation': 'increment_counter',
'id': item_id,
'counter_name': counter_name,
'increment': increment}
handler.invoke(data) |
<SYSTEM_TASK:>
Returns a Markdown document that describes this handler and
<END_TASK>
<USER_TASK:>
Description:
def help(handler):
"""
Returns a Markdown document that describes this handler and
it's operations.
""" |
data = {'operation': 'describe'}
response = handler.invoke(data, raw=True)
description = response.data
lines = []
lines.append('# {}'.format(handler.lambda_fn))
lines.append('## Handler Info')
lines.append('**Cruddy version**: {}'.format(
description['cruddy_version']))
lines.ap... |
<SYSTEM_TASK:>
Swap the byte-ordering in a packet with N=4 bytes per word
<END_TASK>
<USER_TASK:>
Description:
def byteswap(data, word_size=4):
""" Swap the byte-ordering in a packet with N=4 bytes per word
""" |
return reduce(lambda x,y: x+''.join(reversed(y)), chunks(data, word_size), '') |
<SYSTEM_TASK:>
Set VCS Virtual IP.
<END_TASK>
<USER_TASK:>
Description:
def vcs_vip(self, **kwargs):
"""Set VCS Virtual IP.
Args:
vip (str): IPv4/IPv6 Virtual IP Address.
rbridge_id (str): rbridge-id for device. Only required when type is
`ve`.
delete... |
get_config = kwargs.pop('get', False)
delete = kwargs.pop('delete', False)
callback = kwargs.pop('callback', self._callback)
method_class = self._vcs
if not get_config:
vip = str(kwargs.pop('vip'))
ipaddress = ip_interface(unicode(vip))
vcs_... |
<SYSTEM_TASK:>
Get BGP neighbors configured on a device.
<END_TASK>
<USER_TASK:>
Description:
def get_bgp_neighbors(self, **kwargs):
"""Get BGP neighbors configured on a device.
Args:
rbridge_id (str): The rbridge ID of the device on which BGP will be
configured in a VCS fab... |
callback = kwargs.pop('callback', self._callback)
neighbor_args = dict(router_bgp_neighbor_address='',
remote_as='',
vrf_name=kwargs.pop('vrf', 'default'),
rbridge_id=kwargs.pop('rbridge_id', '1'))
neighbor... |
<SYSTEM_TASK:>
Set BGP multihop property for a neighbor.
<END_TASK>
<USER_TASK:>
Description:
def multihop(self, **kwargs):
"""Set BGP multihop property for a neighbor.
Args:
vrf (str): The VRF for this BGP process.
rbridge_id (str): The rbridge ID of the device on which BGP wil... |
callback = kwargs.pop('callback', self._callback)
ip_addr = ip_interface(unicode(kwargs.pop('neighbor')))
config = self._multihop_xml(neighbor=ip_addr,
count=kwargs.pop('count'),
rbridge_id=kwargs.pop('rbridge_id', '1'),
... |
<SYSTEM_TASK:>
Set BGP update source property for a neighbor.
<END_TASK>
<USER_TASK:>
Description:
def update_source(self, **kwargs):
"""Set BGP update source property for a neighbor.
This method currently only supports loopback interfaces.
Args:
vrf (str): The VRF for this BGP pro... |
callback = kwargs.pop('callback', self._callback)
ip_addr = ip_interface(unicode(kwargs.pop('neighbor')))
config = self._update_source_xml(neighbor=ip_addr,
int_type=kwargs.pop('int_type'),
int_name=kwargs.pop('in... |
<SYSTEM_TASK:>
Encodes a Python datetime.datetime object as an ECMA-262 compliant
<END_TASK>
<USER_TASK:>
Description:
def encode_datetime(o):
""" Encodes a Python datetime.datetime object as an ECMA-262 compliant
datetime string.""" |
r = o.isoformat()
if o.microsecond:
r = r[:23] + r[26:]
if r.endswith('+00:00'):
r = r[:-6] + 'Z'
return r |
<SYSTEM_TASK:>
Encodes a Python datetime.time object as an ECMA-262 compliant
<END_TASK>
<USER_TASK:>
Description:
def encode_time(o):
""" Encodes a Python datetime.time object as an ECMA-262 compliant
time string.""" |
r = o.isoformat()
if o.microsecond:
r = r[:12]
if r.endswith('+00:00'):
r = r[:-6] + 'Z'
return r |
<SYSTEM_TASK:>
Colorize text with hex code.
<END_TASK>
<USER_TASK:>
Description:
def colorize(text, color, background=False):
"""
Colorize text with hex code.
:param text: the text you want to paint
:param color: a hex color or rgb color
:param background: decide to colorize background
::
... |
if color in _styles:
c = Color(text)
c.styles = [_styles.index(color) + 1]
return c
c = Color(text)
if background:
c.bgcolor = _color2ansi(color)
else:
c.fgcolor = _color2ansi(color)
return c |
<SYSTEM_TASK:>
Checks if the given rule matches with any filter added.
<END_TASK>
<USER_TASK:>
Description:
def match(self, rule):
"""
Checks if the given rule matches with any filter added.
:param rule: The Flask rule to be matched.
:return: True if there is a filter that matches.
... |
if len(self.filters) == 0:
return True
for filter in self.filters:
if filter.match(rule):
return True
return False |
<SYSTEM_TASK:>
Collects the data from the given parameters and emit it.
<END_TASK>
<USER_TASK:>
Description:
def trace(self, request, response, error, latency):
"""
Collects the data from the given parameters and emit it.
:param request: The Flask request.
:param response: The Flask res... |
data = self.__collect_trace_data(request, response, error, latency)
self.inspector(data)
self.emitter(data) |
<SYSTEM_TASK:>
Writes the given tracing data to Python Logging.
<END_TASK>
<USER_TASK:>
Description:
def __default_emit_trace(self, data):
"""
Writes the given tracing data to Python Logging.
:param data: The tracing data to be written.
""" |
message = format_trace_data(data)
self.io.logger.info(message) |
<SYSTEM_TASK:>
Checks if the given rule matches with the filter.
<END_TASK>
<USER_TASK:>
Description:
def match(self, rule):
"""
Checks if the given rule matches with the filter.
:param rule: The Flask rule to be matched.
:return: True if the filter matches.
""" |
if self.methods:
for method in self.methods:
if method in rule.methods:
return True
if self.endpoints:
for endpoint in self.endpoints:
if endpoint == rule.endpoint:
return True
return False |
<SYSTEM_TASK:>
Add SNMP Community to NOS device.
<END_TASK>
<USER_TASK:>
Description:
def add_snmp_community(self, **kwargs):
"""
Add SNMP Community to NOS device.
Args:
community (str): Community string to be added to device.
callback (function): A function executed upo... |
community = kwargs.pop('community')
callback = kwargs.pop('callback', self._callback)
config = ET.Element('config')
snmp_server = ET.SubElement(config, 'snmp-server',
xmlns=("urn:brocade.com:mgmt:"
"brocade-... |
<SYSTEM_TASK:>
Add SNMP host to NOS device.
<END_TASK>
<USER_TASK:>
Description:
def add_snmp_host(self, **kwargs):
"""
Add SNMP host to NOS device.
Args:
host_info (tuple(str, str)): Tuple of host IP and port.
community (str): Community string to be added to device.
... |
host_info = kwargs.pop('host_info')
community = kwargs.pop('community')
callback = kwargs.pop('callback', self._callback)
config = ET.Element('config')
snmp_server = ET.SubElement(config, 'snmp-server',
xmlns=("urn:brocade.com:mgmt:"
... |
<SYSTEM_TASK:>
Compiles a SASS string
<END_TASK>
<USER_TASK:>
Description:
def compile_str(contents):
"""Compiles a SASS string
:param str contents: The SASS contents to compile
:returns: The compiled CSS
""" |
ctx = SASS_CLIB.sass_new_context()
ctx.contents.source_string = c_char_p(contents)
SASS_CLIB.compile(ctx)
if ctx.contents.error_status:
print(ctx.contents.error_message)
return ctx.contents.output_string or "" |
<SYSTEM_TASK:>
Loads the libsass library if it isn't already loaded.
<END_TASK>
<USER_TASK:>
Description:
def _load(self):
"""Loads the libsass library if it isn't already loaded.""" |
if self.clib is None:
root_path = os.path.normpath(os.path.join(os.path.dirname(os.path.realpath(__file__ )), '..'))
path1 = os.path.join(root_path, 'sass.so')
path2 = os.path.join(root_path, '..', 'sass.so')
if os.path.exists(path1):
self.clib =... |
<SYSTEM_TASK:>
Set gateway type
<END_TASK>
<USER_TASK:>
Description:
def hwvtep_set_overlaygw_type(self, **kwargs):
"""
Set gateway type
Args:
name (str): gateway-name
type (str): gateway-type
callback (function): A function executed upon completion of the
... |
name = kwargs.pop('name')
type = kwargs.pop('type')
ip_args = dict(name=name, gw_type=type)
method_name = 'overlay_gateway_gw_type'
method_class = self._brocade_tunnels
gw_attr = getattr(method_class, method_name)
config = gw_attr(**ip_args)
output = self... |
<SYSTEM_TASK:>
Add a range of rbridge-ids
<END_TASK>
<USER_TASK:>
Description:
def hwvtep_add_rbridgeid(self, **kwargs):
"""
Add a range of rbridge-ids
Args:
name (str): gateway-name
vlan (str): rbridge-ids range
callback (function): A function executed upon... |
name = kwargs.pop('name')
id = kwargs.pop('rb_range')
ip_args = dict(name=name, rb_add=id)
method_name = 'overlay_gateway_attach_rbridge_id_rb_add'
method_class = self._brocade_tunnels
gw_attr = getattr(method_class, method_name)
config = gw_attr(**ip_args)
... |
<SYSTEM_TASK:>
Add loopback interface to the overlay-gateway
<END_TASK>
<USER_TASK:>
Description:
def hwvtep_add_loopback_interface(self, **kwargs):
"""
Add loopback interface to the overlay-gateway
Args:
name (str): gateway-name
int_id (int): loopback inteface id
... |
name = kwargs.pop('name')
id = kwargs.pop('int_id')
ip_args = dict(name=name, loopback_id=id)
method_name = 'overlay_gateway_ip_interface_loopback_loopback_id'
method_class = self._brocade_tunnels
gw_attr = getattr(method_class, method_name)
config = gw_attr(**ip... |
<SYSTEM_TASK:>
Activate the hwvtep
<END_TASK>
<USER_TASK:>
Description:
def hwvtep_activate_hwvtep(self, **kwargs):
"""
Activate the hwvtep
Args:
name (str): overlay_gateway name
callback (function): A function executed upon completion of the
method.
... |
name = kwargs.pop('name')
name_args = dict(name=name)
method_name = 'overlay_gateway_activate'
method_class = self._brocade_tunnels
gw_attr = getattr(method_class, method_name)
config = gw_attr(**name_args)
output = self._callback(config)
return output |
<SYSTEM_TASK:>
Identifies exported VLANs in VXLAN gateway configurations.
<END_TASK>
<USER_TASK:>
Description:
def hwvtep_attach_vlan_vid(self, **kwargs):
"""
Identifies exported VLANs in VXLAN gateway configurations.
Args:
name (str): overlay_gateway name
vlan(str): vl... |
name = kwargs.pop('name')
mac = kwargs.pop('mac')
vlan = kwargs.pop('vlan')
name_args = dict(name=name, vid=vlan, mac=mac)
method_name = 'overlay_gateway_attach_vlan_mac'
method_class = self._brocade_tunnels
gw_attr = getattr(method_class, method_name)
co... |
<SYSTEM_TASK:>
Format the message of the logger.
<END_TASK>
<USER_TASK:>
Description:
def message(self, level, *args):
"""
Format the message of the logger.
You can rewrite this method to format your own message::
class MyLogger(Logger):
def message(self, level, *a... |
msg = ' '.join((str(o) for o in args))
if level not in ('start', 'end', 'debug', 'info', 'warn', 'error'):
return msg
return '%s: %s' % (level, msg) |
<SYSTEM_TASK:>
Make it the verbose log.
<END_TASK>
<USER_TASK:>
Description:
def verbose(self):
"""
Make it the verbose log.
A verbose log can be only shown when user want to see more logs.
It works as::
log.verbose.warn('this is a verbose warn')
log.verbose.inf... |
log = copy.copy(self)
log._is_verbose = True
return log |
<SYSTEM_TASK:>
Start a nested log.
<END_TASK>
<USER_TASK:>
Description:
def start(self, *args):
"""
Start a nested log.
""" |
if self._is_verbose:
# verbose log has no start method
return self
self.writeln('start', *args)
self._indent += 1
return self |
<SYSTEM_TASK:>
End a nested log.
<END_TASK>
<USER_TASK:>
Description:
def end(self, *args):
"""
End a nested log.
""" |
if self._is_verbose:
# verbose log has no end method
return self
if not args:
self._indent -= 1
return self
self.writeln('end', *args)
self._indent -= 1
return self |
<SYSTEM_TASK:>
A generic method to call any operation supported by the Lambda handler
<END_TASK>
<USER_TASK:>
Description:
def call_operation(self, operation, **kwargs):
"""
A generic method to call any operation supported by the Lambda handler
""" |
data = {'operation': operation}
data.update(kwargs)
return self.invoke(data) |
<SYSTEM_TASK:>
After receiving a datagram, generate the deferreds and add myself to it.
<END_TASK>
<USER_TASK:>
Description:
def datagramReceived(self, datagram, address):
"""
After receiving a datagram, generate the deferreds and add myself to it.
""" |
def write(result):
print "Writing %r" % result
self.transport.write(result, address)
d = self.d()
#d.addCallbacks(write, log.err)
d.addCallback(write) # errors are silently ignored!
d.callback(datagram) |
<SYSTEM_TASK:>
After receiving the data, generate the deferreds and add myself to it.
<END_TASK>
<USER_TASK:>
Description:
def dataReceived(self, data):
"""
After receiving the data, generate the deferreds and add myself to it.
""" |
def write(result):
print "Writing %r" % result
self.transport.write(result)
d = self.d()
d.addCallback(write) # errors are silently ignored!
d.callback(data) |
<SYSTEM_TASK:>
Configure an unnumbered interface.
<END_TASK>
<USER_TASK:>
Description:
def ip_unnumbered(self, **kwargs):
"""Configure an unnumbered interface.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet etc).
name (str): Name o... |
kwargs['ip_donor_interface_name'] = kwargs.pop('donor_name')
kwargs['ip_donor_interface_type'] = kwargs.pop('donor_type')
kwargs['delete'] = kwargs.pop('delete', False)
callback = kwargs.pop('callback', self._callback)
valid_int_types = ['gigabitethernet', 'tengigabitethernet',
... |
<SYSTEM_TASK:>
Return the `ip unnumbered` donor name XML.
<END_TASK>
<USER_TASK:>
Description:
def _ip_unnumbered_name(self, **kwargs):
"""Return the `ip unnumbered` donor name XML.
You should not use this method.
You probably want `Interface.ip_unnumbered`.
Args:
int_type ... |
method_name = 'interface_%s_ip_ip_config_unnumbered_ip_donor_'\
'interface_name' % kwargs['int_type']
ip_unnumbered_name = getattr(self._interface, method_name)
config = ip_unnumbered_name(**kwargs)
if kwargs['delete']:
tag = 'ip-donor-interface-name'
... |
<SYSTEM_TASK:>
Return the `ip unnumbered` donor type XML.
<END_TASK>
<USER_TASK:>
Description:
def _ip_unnumbered_type(self, **kwargs):
"""Return the `ip unnumbered` donor type XML.
You should not use this method.
You probably want `Interface.ip_unnumbered`.
Args:
int_type ... |
method_name = 'interface_%s_ip_ip_config_unnumbered_ip_donor_'\
'interface_type' % kwargs['int_type']
ip_unnumbered_type = getattr(self._interface, method_name)
config = ip_unnumbered_type(**kwargs)
if kwargs['delete']:
tag = 'ip-donor-interface-type'
... |
<SYSTEM_TASK:>
Get and merge the `ip unnumbered` config from an interface.
<END_TASK>
<USER_TASK:>
Description:
def _get_ip_unnumbered(self, unnumbered_type, unnumbered_name):
"""Get and merge the `ip unnumbered` config from an interface.
You should not use this method.
You probably want `Inter... |
unnumbered_type = self._callback(unnumbered_type, handler='get_config')
unnumbered_name = self._callback(unnumbered_name, handler='get_config')
unnumbered_type = pynos.utilities.return_xml(str(unnumbered_type))
unnumbered_name = pynos.utilities.return_xml(str(unnumbered_name))
r... |
<SYSTEM_TASK:>
Configure an anycast MAC address.
<END_TASK>
<USER_TASK:>
Description:
def anycast_mac(self, **kwargs):
"""Configure an anycast MAC address.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet etc).
mac (str): MAC addres... |
callback = kwargs.pop('callback', self._callback)
anycast_mac = getattr(self._rbridge, 'rbridge_id_ip_static_ag_ip_'
'config_anycast_gateway_mac_ip_anycast_'
'gateway_mac')
config = anycast_mac(rbridge_id=kwargs.pop('rbridge_id', '1'),... |
<SYSTEM_TASK:>
Configure BFD for Interface.
<END_TASK>
<USER_TASK:>
Description:
def bfd(self, **kwargs):
"""Configure BFD for Interface.
Args:
name (str): name of the interface to configure (230/0/1 etc)
int_type (str): interface type (gigabitethernet etc)
tx (str):... |
int_type = str(kwargs.pop('int_type').lower())
kwargs['name'] = str(kwargs.pop('name'))
kwargs['min_tx'] = kwargs.pop('tx')
kwargs['min_rx'] = kwargs.pop('rx')
kwargs['delete'] = kwargs.pop('delete', False)
callback = kwargs.pop('callback', self._callback)
valid_... |
<SYSTEM_TASK:>
Enable conversational arp learning on VDX switches
<END_TASK>
<USER_TASK:>
Description:
def conversational_arp(self, **kwargs):
"""Enable conversational arp learning on VDX switches
Args:
rbridge_id (str): rbridge-id for device.
get (bool): Get config instead of e... |
rbridge_id = kwargs.pop('rbridge_id', '1')
callback = kwargs.pop('callback', self._callback)
arp_config = getattr(self._rbridge,
'rbridge_id_host_table_aging_mode_conversational')
arp_args = dict(rbridge_id=rbridge_id)
config = arp_config(**arp_arg... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.