text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_version(addon_dir, manifest, odoo_version_override=None, git_post_version=True): """ Get addon version information from an addon directory """
version = manifest.get('version') if not version: warn("No version in manifest in %s" % addon_dir) version = '0.0.0' if not odoo_version_override: if len(version.split('.')) < 5: raise DistutilsSetupError("Version in manifest must have at least " ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_install_requires_odoo_addon(addon_dir, no_depends=[], depends_override={}, external_dependencies_override={}, odoo_version_override=None): """ Get the li...
manifest = read_manifest(addon_dir) _, _, odoo_version_info = _get_version(addon_dir, manifest, odoo_version_override, git_post_version=False) return _get_install_requires(odoo_v...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_install_requires_odoo_addons(addons_dir, depends_override={}, external_dependencies_override={}, odoo_version_override=None): """ Get the list of require...
addon_dirs = [] addons = os.listdir(addons_dir) for addon in addons: addon_dir = os.path.join(addons_dir, addon) if is_installable_addon(addon_dir): addon_dirs.append(addon_dir) install_requires = set() for addon_dir in addon_dirs: r = get_install_requires_odoo_a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_declarative_base(self, metadata=None): """Override parent function with alchy's"""
return make_declarative_base(self.session, Model=self.Model, metadata=metadata)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prep_doc(self, doc_obj): """ This method Validates, gets the Python value, checks unique indexes, gets the db value, and then returns the prepared doc dict o...
doc = doc_obj._data.copy() for key, prop in list(doc_obj._base_properties.items()): prop.validate(doc.get(key), key) raw_value = prop.get_python_value(doc.get(key)) if prop.unique: self.check_unique(doc_obj, key, raw_value) value = prop.ge...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def apply_zappa_settings(zappa_obj, zappa_settings, environment): '''Load Zappa settings, set defaults if needed, and apply to the Zappa object''' settings_all = json.load(zappa_settings) settings = settings_all[environment] # load defaults for missing options for key,value in DEFAULT_SETTINGS.ite...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deploy(environment, zappa_settings): """ Package, create and deploy to Lambda."""
print(("Deploying " + environment)) zappa, settings, lambda_name, zip_path = \ _package(environment, zappa_settings) s3_bucket_name = settings['s3_bucket'] try: # Load your AWS credentials from ~/.aws/credentials zappa.load_credentials() # Make sure the necessary IAM...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(environment, zappa_settings): """ Update an existing deployment."""
print(("Updating " + environment)) # Package dependencies, and the source code into a zip zappa, settings, lambda_name, zip_path = \ _package(environment, zappa_settings) s3_bucket_name = settings['s3_bucket'] try: # Load your AWS credentials from ~/.aws/credentials zapp...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lambda_handler(event, context, settings_name="zappa_settings"): """ An AWS Lambda function which parses specific API Gateway input into a WSGI request, feeds...
# Loading settings from a python module settings = importlib.import_module(settings_name) # The flask-app module app_module = importlib.import_module(settings.APP_MODULE) # The flask-app app = getattr(app_module, settings.APP_OBJECT) app.config.from_object('zappa_settings') app.wsgi_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_context_data(self, **kwargs): """Get the context for this view. Also adds the *page_template* variable in the context. If the *page_template* is not give...
queryset = kwargs.pop('object_list') page_template = kwargs.pop('page_template', None) context_object_name = self.get_context_object_name(queryset) context = {'object_list': queryset, 'view': self} context.update(kwargs) if context_object_name is not None: c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean_var(text): """Turn text into a valid python classname or variable"""
text = re_invalid_var.sub('', text) text = re_invalid_start.sub('', text) return text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def full_tasktrace(self): """ List of all failed tasks caused by this and all previous errors. Returns: List[Task] """
if self.prev_error: return self.prev_error.tasktrace + self.tasktrace else: return self.tasktrace
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dist_sq(self, other=None): """ For fast length comparison """
v = self - other if other else self return sum(map(lambda a: a * a, v))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def yaw_pitch(self): """ Calculate the yaw and pitch of this vector """
if not self: return YawPitch(0, 0) ground_distance = math.sqrt(self.x ** 2 + self.z ** 2) if ground_distance: alpha1 = -math.asin(self.x / ground_distance) / math.pi * 180 alpha2 = math.acos(self.z / ground_distance) / math.pi * 180 if alpha2 > 90...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_slot_check(wanted): """ Creates and returns a function that takes a slot and checks if it matches the wanted item. Args: wanted: function(Slot) or Slot ...
if isinstance(wanted, types.FunctionType): return wanted # just forward the slot check function if isinstance(wanted, int): item, meta = wanted, None elif isinstance(wanted, Slot): item, meta = wanted.item_id, wanted.damage # TODO compare NBT elif isinstance(wanted, (Item, Bl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _make_window(window_dict): """ Creates a new class for that window and registers it at this module. """
cls_name = '%sWindow' % camel_case(str(window_dict['name'])) bases = (Window,) attrs = { '__module__': sys.modules[__name__], 'name': str(window_dict['name']), 'inv_type': str(window_dict['id']), 'inv_data': window_dict, } # creates function-local index and size var...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_dict(self): """ Formats the slot for network packing. """
data = {'id': self.item_id} if self.item_id != constants.INV_ITEMID_EMPTY: data['damage'] = self.damage data['amount'] = self.amount if self.nbt is not None: data['enchants'] = self.nbt return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def on_success(self, inv_plugin, emit_set_slot): """ Called when the click was successful and should be applied to the inventory. Args: inv_plugin (InventoryPlug...
self.dirty = set() self.apply(inv_plugin) for changed_slot in self.dirty: emit_set_slot(changed_slot)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authenticate(self): """ Generate an access token using an username and password. Any existing client token is invalidated if not provided. Returns: dict: Res...
endpoint = '/authenticate' payload = { 'agent': { 'name': 'Minecraft', 'version': self.ygg_version, }, 'username': self.username, 'password': self.password, 'clientToken': self.client_token, } r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate(self): """ Check if an access token is valid Returns: dict: Empty or error dict """
endpoint = '/validate' payload = dict(accessToken=self.access_token) rep = self._ygg_req(endpoint, payload) return not bool(rep)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def total_stored(self, wanted, slots=None): """ Calculates the total number of items of that type in the current window or given slot range. Args: wanted: functi...
if slots is None: slots = self.window.slots wanted = make_slot_check(wanted) return sum(slot.amount for slot in slots if wanted(slot))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_slot(self, wanted, slots=None): """ Searches the given slots or, if not given, active hotbar slot, hotbar, inventory, open window in this order. Args: w...
for slot in self.find_slots(wanted, slots): return slot return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_slots(self, wanted, slots=None): """ Yields all slots containing the item. Searches the given slots or, if not given, active hotbar slot, hotbar, invent...
if slots is None: slots = self.inv_slots_preferred + self.window.window_slots wanted = make_slot_check(wanted) for slot in slots: if wanted(slot): yield slot
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def click_slot(self, slot, right=False): """ Left-click or right-click the slot. Args: slot (Slot): The clicked slot. Can be ``Slot`` instance or integer. Set t...
if isinstance(slot, int): slot = self.window.slots[slot] button = constants.INV_BUTTON_RIGHT \ if right else constants.INV_BUTTON_LEFT return self.send_click(windows.SingleClick(slot, button))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def drop_slot(self, slot=None, drop_stack=False): """ Drop one or all items of the slot. Does not wait for confirmation from the server. If you want that, use a ...
if slot is None: if self.cursor_slot.is_empty: slot = self.active_slot else: slot = self.cursor_slot elif isinstance(slot, int): # also allow slot nr slot = self.window.slots[slot] if slot == self.cursor_slot: # dr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inv_slots_preferred(self): """ List of all available inventory slots in the preferred search order. Does not include the additional slots from the open windo...
slots = [self.active_slot] slots.extend(slot for slot in self.window.hotbar_slots if slot != self.active_slot) slots.extend(self.window.inventory_slots) return slots
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_block_entity_data(self, pos_or_x, y=None, z=None): """ Access block entity data. Returns: BlockEntityData subclass instance or None if no block entity da...
if None not in (y, z): # x y z supplied pos_or_x = pos_or_x, y, z coord_tuple = tuple(int(floor(c)) for c in pos_or_x) return self.block_entities.get(coord_tuple, None)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_block_entity_data(self, pos_or_x, y=None, z=None, data=None): """ Update block entity data. Returns: Old data if block entity data was already stored for...
if None not in (y, z): # x y z supplied pos_or_x = pos_or_x, y, z coord_tuple = tuple(int(floor(c)) for c in pos_or_x) old_data = self.block_entities.get(coord_tuple, None) self.block_entities[coord_tuple] = data return old_data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_vlq(self, segment): """ Parse a string of VLQ-encoded data. Returns: a list of integers. """
values = [] cur, shift = 0, 0 for c in segment: val = B64[ord(c)] # Each character is 6 bits: # 5 of value and the high bit is the continuation. val, cont = val & 0b11111, val >> 5 cur += val << shift shift += 5 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decode(self, source): """Decode a source map object into a SourceMapIndex. The index is keyed on (dst_line, dst_column) for lookups, and a per row index is k...
# According to spec (https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.h7yy76c5il9v) # A SouceMap may be prepended with ")]}'" to cause a Javascript error. # If the file starts with that string, ignore the entire first line. if source[:4] == ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def discover(source): "Given a JavaScript file, find the sourceMappingURL line" source = source.splitlines() # Source maps are only going to exist at either the top or bottom of the document. # Technically, there isn't anything indicating *where* it should exist, so we # are generous and assume it's...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean(): """Remove build, dist, egg-info garbage."""
d = ['build', 'dist', 'scikits.audiolab.egg-info', HTML_DESTDIR, PDF_DESTDIR] for i in d: paver.path.path(i).rmtree() (paver.path.path('docs') / options.sphinx.builddir).rmtree()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_attendees(self, attendees, required=True): """ Adds new attendees to the event. *attendees* can be a list of email addresses or :class:`ExchangeEventAtte...
new_attendees = self._build_resource_dictionary(attendees, required=required) for email in new_attendees: self._attendees[email] = new_attendees[email] self._dirty_attributes.add(u'attendees')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_attendees(self, attendees): """ Removes attendees from the event. *attendees* can be a list of email addresses or :class:`ExchangeEventAttendee` objec...
attendees_to_delete = self._build_resource_dictionary(attendees) for email in attendees_to_delete.keys(): if email in self._attendees: del self._attendees[email] self._dirty_attributes.add(u'attendees')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_resources(self, resources): """ Adds new resources to the event. *resources* can be a list of email addresses or :class:`ExchangeEventAttendee` objects. ...
new_resources = self._build_resource_dictionary(resources) for key in new_resources: self._resources[key] = new_resources[key] self._dirty_attributes.add(u'resources')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_resources(self, resources): """ Removes resources from the event. *resources* can be a list of email addresses or :class:`ExchangeEventAttendee` objec...
resources_to_delete = self._build_resource_dictionary(resources) for email in resources_to_delete.keys(): if email in self._resources: del self._resources[email] self._dirty_attributes.add(u'resources')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate(self): """ Validates that all required fields are present """
if not self.start: raise ValueError("Event has no start date") if not self.end: raise ValueError("Event has no end date") if self.end < self.start: raise ValueError("Start date is after end date") if self.reminder_minutes_before_start and not isinstance(self.reminder_minutes_before...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def info_factory(name, libnames, headers, frameworks=None, section=None, classname=None): """Create a system_info class. Parameters name : str name of the librar...
if not classname: classname = '%s_info' % name if not section: section = name if not frameworks: framesworks = [] class _ret(system_info): def __init__(self): system_info.__init__(self) def library_extensions(self): return system_info.li...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_all_details(self): """ This function will execute all the event lookups for known events. This is intended for use when you want to have a completely po...
log.debug(u"Loading all details") if self.count > 0: # Now, empty out the events to prevent duplicates! del(self.events[:]) # Send the SOAP request with the list of exchange ID values. log.debug(u"Requesting all event details for events: {event_list}".format(event_list=str(self.event_i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def seek(self, offset, whence=0, mode='rw'): """similar to python seek function, taking only in account audio data. :Parameters: offset : int the number of frame...
try: st = self._sndfile.seek(offset, whence, mode) except IOError, e: raise PyaudioIOError(str(e)) return st
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_frames(self, nframes, dtype=np.float64): """Read nframes frames of the file. :Parameters: nframes : int number of frames to read. dtype : numpy dtype dt...
return self._sndfile.read_frames(nframes, dtype)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_frames(self, input, nframes = -1): """write data to file. :Parameters: input : ndarray array containing data to write. nframes : int number of frames t...
if nframes == -1: if input.ndim == 1: nframes = input.size elif input.ndim == 2: nframes = input.shape[0] else: raise ValueError("Input has to be rank 1 (mono) or rank 2 "\ "(multi-channels)") ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_field(field_uri): """ Helper function to request deletion of a field. This is necessary when you want to overwrite values instead of appending. <t:Del...
root = T.DeleteItemField( T.FieldURI(FieldURI=field_uri) ) return root
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_occurrence(exchange_id, instance_index, format=u"Default"): """ Requests one or more calendar items from the store matching the master & index. exchange_...
root = M.GetItem( M.ItemShape( T.BaseShape(format) ), M.ItemIds() ) items_node = root.xpath("//m:ItemIds", namespaces=NAMESPACES)[0] for index in instance_index: items_node.append(T.OccurrenceItemId(RecurringMasterId=exchange_id, InstanceIndex=str(index))) return root
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_property_node(node_to_insert, field_uri): """ Helper function - generates a SetItemField which tells Exchange you want to overwrite the contents of a ...
root = T.SetItemField( T.FieldURI(FieldURI=field_uri), T.CalendarItem(node_to_insert) ) return root
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _validate_example(rh, method, example_type): """Validates example against schema :returns: Formatted example if example exists and validates, otherwise None ...
example = getattr(method, example_type + "_example") schema = getattr(method, example_type + "_schema") if example is None: return None try: validate(example, schema) except ValidationError as e: raise ValidationError( "{}_example for {}.{} could not be validat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_rh_methods(rh): """Yield all HTTP methods in ``rh`` that are decorated with schema.validate"""
for k, v in vars(rh).items(): if all([ k in HTTP_METHODS, is_method(v), hasattr(v, "input_schema") ]): yield (k, v)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _escape_markdown_literals(string): """Escape any markdown literals in ``string`` by prepending with \\ :type string: str :rtype: str """
literals = list("\\`*_{}[]()<>#+-.!:|") escape = lambda c: '\\' + c if c in literals else c return "".join(map(escape, string))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _cleandoc(doc): """Remove uniform indents from ``doc`` lines that are not empty :returns: Cleaned ``doc`` """
indent_length = lambda s: len(s) - len(s.lstrip(" ")) not_empty = lambda s: s != "" lines = doc.split("\n") indent = min(map(indent_length, filter(not_empty, lines))) return "\n".join(s[indent:] for s in lines)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_api_docs(routes): """ Generates GitHub Markdown formatted API documentation using provided schemas in RequestHandler methods and their docstrings. :param...
routes = map(_get_tuple_from_route, routes) documentation = [] for url, rh, methods in sorted(routes, key=lambda a: a[0]): if issubclass(rh, APIHandler): documentation.append(_get_route_doc(url, rh, methods)) documentation = ( "**This documentation is automatically generate...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def error(self, message, data=None, code=None): """An error occurred in processing the request, i.e. an exception was thrown. :type data: A JSON-serializable obj...
result = {'status': 'error', 'message': message} if data: result['data'] = data if code: result['code'] = code self.write(result) self.finish()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def input_schema_clean(input_, input_schema): """ Updates schema default values with input data. :param input_: Input data :type input_: dict :param input_schema...
if input_schema.get('type') == 'object': try: defaults = get_object_defaults(input_schema) except NoObjectDefaults: pass else: return deep_update(defaults, input_) return input_
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate(input_schema=None, output_schema=None, input_example=None, output_example=None, validator_cls=None, format_checker=None, on_empty_404=False, use_defa...
@container def _validate(rh_method): """Decorator for RequestHandler schema validation This decorator: - Validates request body against input schema of the method - Calls the ``rh_method`` and gets output from it - Validates output against output schema of ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(filename): """Read and return `filename` in root dir of project and return string"""
return codecs.open(os.path.join(__DIR__, filename), 'r').read()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deep_update(source, overrides): """Update a nested dictionary or similar mapping. Modify ``source`` in place. :type source: collections.Mapping :type overrid...
for key, value in overrides.items(): if isinstance(value, collections.Mapping) and value: returned = deep_update(source.get(key, {}), value) source[key] = returned else: source[key] = overrides[key] return source
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_handler_subclass(cls, classnames=("ViewHandler", "APIHandler")): """Determines if ``cls`` is indeed a subclass of ``classnames``"""
if isinstance(cls, list): return any(is_handler_subclass(c) for c in cls) elif isinstance(cls, type): return any(c.__name__ in classnames for c in inspect.getmro(cls)) else: raise TypeError( "Unexpected type `{}` for class `{}`".format( type(cls), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_error(self, status_code, **kwargs): """Override of RequestHandler.write_error Calls ``error()`` or ``fail()`` from JSendMixin depending on which except...
def get_exc_message(exception): return exception.log_message if \ hasattr(exception, "log_message") else str(exception) self.clear() self.set_status(status_code) # Any APIError exceptions raised will result in a JSend fail written # back with the lo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gen_submodule_names(package): """Walk package and yield names of all submodules :type package: package :param package: The package to get submodule names of ...
for importer, modname, ispkg in pkgutil.walk_packages( path=package.__path__, prefix=package.__name__ + '.', onerror=lambda x: None): yield modname
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_module_routes(module_name, custom_routes=None, exclusions=None, arg_pattern=r'(?P<{}>[a-zA-Z0-9_\-]+)'): """Create and return routes for module_name Rout...
def has_method(module, cls_name, method_name): return all([ method_name in vars(getattr(module, cls_name)), is_method(reduce(getattr, [module, cls_name, method_name])) ]) def yield_args(module, cls_name, method_name): """Get signature of ``module.cls_name.method...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def coroutine(func, replace_callback=True): """Tornado-JSON compatible wrapper for ``tornado.gen.coroutine`` Annotates original argspec.args of ``func`` as attri...
# gen.coroutine in tornado 3.x.x and 5.x.x have a different signature than 4.x.x if TORNADO_MAJOR != 4: wrapper = gen.coroutine(func) else: wrapper = gen.coroutine(func, replace_callback) wrapper.__argspec_args = inspect.getargspec(func).args return wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(): """ Entry point for gns3-converter """
arg_parse = setup_argparse() args = arg_parse.parse_args() if not args.quiet: print('GNS3 Topology Converter') if args.debug: logging_level = logging.DEBUG else: logging_level = logging.WARNING logging.basicConfig(level=logging_level, format=LO...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup_argparse(): """ Setup the argparse argument parser :return: instance of argparse :rtype: ArgumentParser """
parser = argparse.ArgumentParser( description='Convert old ini-style GNS3 topologies (<=0.8.7) to ' 'the newer version 1+ JSON format') parser.add_argument('--version', action='version', version='%(prog)s ' + __version__) parser.ad...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_conversion(topology_def, topology_name, output_dir=None, debug=False, quiet=False): """ Convert the topology :param dict topology_def: Dict containing top...
# Create a new instance of the the Converter gns3_conv = Converter(topology_def['file'], debug) # Read the old topology old_top = gns3_conv.read_topology() new_top = JSONTopology() # Process the sections (topology) = gns3_conv.process_topology(old_top) # Generate the nodes new_top...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_snapshots(topology): """ Return the paths of any snapshot topologies :param str topology: topology file :return: list of dicts containing snapshot topolo...
snapshots = [] snap_dir = os.path.join(topology_dirname(topology), 'snapshots') if os.path.exists(snap_dir): snaps = os.listdir(snap_dir) for directory in snaps: snap_top = os.path.join(snap_dir, directory, 'topology.net') if os.path.exists(snap_top): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def name(topology_file, topology_name=None): """ Calculate the name to save the converted topology as using either either a specified name or the directory name ...
if topology_name is not None: logging.debug('topology name supplied') topo_name = topology_name else: logging.debug('topology name not supplied') topo_name = os.path.basename(topology_dirname(topology_file)) return topo_name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def snapshot_name(topo_name): """ Get the snapshot name :param str topo_name: topology file location. The name is taken from the directory containing the topolog...
topo_name = os.path.basename(topology_dirname(topo_name)) snap_re = re.compile('^topology_(.+)(_snapshot_)(\d{6}_\d{6})$') result = snap_re.search(topo_name) if result is not None: snap_name = result.group(1) + '_' + result.group(3) else: raise ConvertError('Unable to get snapshot ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(output_dir, converter, json_topology, snapshot, quiet): """ Save the converted topology :param str output_dir: Output Directory :param Converter convert...
try: old_topology_dir = topology_dirname(converter.topology) if output_dir: output_dir = os.path.abspath(output_dir) else: output_dir = os.getcwd() topology_name = json_topology.name topology_files_dir = os.path.join(output_dir, topology_name + '-fi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy_configs(configs, source, target): """ Copy dynamips configs to converted topology :param configs: Configs to copy :param str source: Source topology dir...
config_err = False if len(configs) > 0: config_dir = os.path.join(target, 'dynamips', 'configs') os.makedirs(config_dir) for config in configs: old_config_file = os.path.join(source, config['old']) new_config_file = os.path.join(config_dir, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy_vpcs_configs(source, target): """ Copy any VPCS configs to the converted topology :param str source: Source topology directory :param str target: Target...
# Prepare a list of files to copy vpcs_files = glob.glob(os.path.join(source, 'configs', '*.vpc')) vpcs_hist = os.path.join(source, 'configs', 'vpcs.hist') vpcs_config_path = os.path.join(target, 'vpcs', 'multi-host') if os.path.isfile(vpcs_hist): vpcs_files.append(vpcs_hist) # Create t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy_topology_image(source, target): """ Copy any images of the topology to the converted topology :param str source: Source topology directory :param str ta...
files = glob.glob(os.path.join(source, '*.png')) for file in files: shutil.copy(file, target)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy_images(images, source, target): """ Copy images to converted topology :param images: Images to copy :param source: Old Topology Directory :param target:...
image_err = False if len(images) > 0: images_dir = os.path.join(target, 'images') os.makedirs(images_dir) for image in images: if os.path.isabs(image): old_image_file = image else: old_image_file = os.path.join(source, image) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_vbox_dirs(max_vbox_id, output_dir, topology_name): """ Create VirtualBox working directories if required :param int max_vbox_id: Number of directories t...
if max_vbox_id is not None: for i in range(1, max_vbox_id + 1): vbox_dir = os.path.join(output_dir, topology_name + '-files', 'vbox', 'vm-%s' % i) os.makedirs(vbox_dir)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_qemu_dirs(max_qemu_id, output_dir, topology_name): """ Create Qemu VM working directories if required :param int max_qemu_id: Number of directories to c...
if max_qemu_id is not None: for i in range(1, max_qemu_id + 1): qemu_dir = os.path.join(output_dir, topology_name + '-files', 'qemu', 'vm-%s' % i) os.makedirs(qemu_dir)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_wic(self, old_wic, wic): """ Convert the old style WIC slot to a new style WIC slot and add the WIC to the node properties :param str old_wic: Old WIC sl...
new_wic = 'wic' + old_wic[-1] self.node['properties'][new_wic] = wic
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_slot_ports(self, slot): """ Add the ports to be added for a adapter card :param str slot: Slot name """
slot_nb = int(slot[4]) # slot_adapter = None # if slot in self.node['properties']: # slot_adapter = self.node['properties'][slot] # elif self.device_info['model'] == 'c7200': # if self.device_info['npe'] == 'npe-g2': # slot_adapter = 'C7200-IO-GE-...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_info_from_hv(self): """ Add the information we need from the old hypervisor section """
# Router Image if 'image' in self.hypervisor: self.node['properties']['image'] = \ os.path.basename(self.hypervisor['image']) # IDLE-PC if 'idlepc' in self.hypervisor: self.node['properties']['idlepc'] = self.hypervisor['idlepc'] # Router ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_device_items(self, item, device): """ Add the various items from the device to the node :param str item: item key :param dict device: dictionary containi...
if item in ('aux', 'console'): self.node['properties'][item] = device[item] elif item.startswith('slot'): # if self.device_info['model'] == 'c7200': # if item != 'slot0': # self.node['properties'][item] = device[item] # else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_to_virtualbox(self): """ Add additional parameters that were in the VBoxDevice section or not present """
# VirtualBox Image if 'vmname' not in self.node['properties']: self.node['properties']['vmname'] = \ self.hypervisor['VBoxDevice']['image'] # Number of adapters if 'adapters' not in self.node['properties']: self.node['properties']['adapters'] = \ ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_to_qemu(self): """ Add additional parameters to a QemuVM Device that were present in its global conf section """
device = self.device_info['ext_conf'] node_prop = self.node['properties'] hv_device = self.hypervisor[device] # QEMU HDD Images if 'hda_disk_image' not in node_prop: if 'image' in hv_device: node_prop['hda_disk_image'] = hv_device['image'] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_vm_ethernet_ports(self): """ Add ethernet ports to Virtualbox and Qemu nodes """
for i in range(self.node['properties']['adapters']): port = {'id': self.port_id, 'name': 'Ethernet%s' % i, 'port_number': i} self.node['ports'].append(port) self.port_id += 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_qemu_symbol(self): """ Set the appropriate symbol for QEMU Devices """
valid_devices = {'ASA': 'asa', 'PIX': 'PIX_firewall', 'JUNOS': 'router', 'IDS': 'ids'} if self.device_info['from'] in valid_devices \ and 'default_symbol' not in self.node \ and 'hover_symbol' not in self.node: self.set_symbol(valid_d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_symbol(self, symbol): """ Set a symbol for a device :param str symbol: Symbol to use """
if symbol == 'EtherSwitch router': symbol = 'multilayer_switch' elif symbol == 'Host': symbol = 'computer' normal = ':/symbols/%s.normal.svg' % symbol selected = ':/symbols/%s.selected.svg' % symbol self.node['default_symbol'] = normal self.node...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_ethsw_port(self, port_num, port_def): """ Split and create the port entry for an Ethernet Switch :param port_num: port number :type port_num: str or int...
# Port String - access 1 SW2 1 # 0: type 1: vlan 2: destination device 3: destination port port_def = port_def.split(' ') if len(port_def) == 4: destination = {'device': port_def[2], 'port': port_def[3]} else: destination = {'de...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_mb_ports(self): """ Add the default ports to add to a router """
model = self.device_info['model'] chassis = self.device_info['chassis'] num_ports = MODEL_MATRIX[model][chassis]['ports'] ports = [] if num_ports > 0: port_type = MODEL_MATRIX[model][chassis]['type'] # Create the ports dict for i in range(nu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_link(self, src_id, src_port, src_port_name, destination): """ Add a link item for processing later :param int src_id: Source node ID :param int src_port...
if destination['device'] == 'NIO': destination['port'] = destination['port'].lower() link = {'source_node_id': src_id, 'source_port_id': src_port, 'source_port_name': src_port_name, 'source_dev': self.node['properties']['name'], ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_description(self): """ Set the node description """
if self.device_info['type'] == 'Router': self.node['description'] = '%s %s' % (self.device_info['type'], self.device_info['model']) else: self.node['description'] = self.device_info['desc']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_type(self): """ Set the node type """
if self.device_info['type'] == 'Router': self.node['type'] = self.device_info['model'].upper() else: self.node['type'] = self.device_info['type']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_device_links(self): """ Calculate a router or VirtualBox link """
for connection in self.interfaces: int_type = connection['from'][0] int_name = connection['from'].replace(int_type, PORT_TYPES[int_type.upper()]) # Get the source port id src_port = None for port in se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_cloud_connection(self): """ Add the ports and nios for a cloud connection :return: None on success or RuntimeError on error """
# Connection String - SW1:1:nio_gen_eth:eth0 # 0: Destination device 1: Destination port # 2: NIO 3: NIO Destination self.node['properties']['nios'] = [] if self.connections is None: return None else: self.connections = self.connections.split(' ')...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_mappings(self): """ Process the mappings for a Frame Relay switch. Removes duplicates and adds the mappings to the node properties """
for mapping_a in self.mappings: for mapping_b in self.mappings: if mapping_a['source'] == mapping_b['dest']: self.mappings.remove(mapping_b) break self.node['properties']['mappings'] = {} mappings = self.node['properties']['ma...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fix_path(path): """ Fix windows path's. Linux path's will remain unaltered :param str path: The path to be fixed :return: The fixed path :rtype: str """
if '\\' in path: path = path.replace('\\', '/') path = os.path.normpath(path) return path
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_topology(self): """ Read the ini-style topology file using ConfigObj :return config: Topology parsed by :py:mod:`ConfigObj` :rtype: ConfigObj """
configspec = resource_stream(__name__, 'configspec') try: handle = open(self._topology) handle.close() try: config = ConfigObj(self._topology, configspec=configspec, raise_errors=Tr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_topology(self, old_top): """ Processes the sections returned by get_instances :param ConfigObj old_top: old topology as processed by :py:meth:`read_t...
sections = self.get_sections(old_top) topo = LegacyTopology(sections, old_top) for instance in sorted(sections): if instance.startswith('vbox') or instance.startswith('qemu'): if instance.startswith('qemu') and \ 'qemupath' in old_top[instan...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_links(self, nodes): """ Generate a list of links :param list nodes: A list of nodes from :py:meth:`generate_nodes` :return: list of links :rtype: li...
new_links = [] for link in self.links: # Expand port name if required if INTERFACE_RE.search(link['dest_port'])\ or VBQ_INT_RE.search(link['dest_port']): int_type = link['dest_port'][0] dest_port = link['dest_port'].replace( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def device_id_from_name(device_name, nodes): """ Get the device ID when given a device name :param str device_name: device name :param list nodes: list of nodes ...
device_id = None for node in nodes: if device_name == node['properties']['name']: device_id = node['id'] break return device_id
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def port_id_from_name(port_name, device_id, nodes): """ Get the port ID when given a port name :param str port_name: port name :param str device_id: device ID :p...
port_id = None for node in nodes: if device_id == node['id']: for port in node['ports']: if port_name == port['name']: port_id = port['id'] break break return port_id
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_destination_to_id(destination_node, destination_port, nodes): """ Convert a destination to device and port ID :param str destination_node: Destinatio...
device_id = None device_name = None port_id = None if destination_node != 'NIO': for node in nodes: if destination_node == node['properties']['name']: device_id = node['id'] device_name = destination_node ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_node_name_from_id(node_id, nodes): """ Get the name of a node when given the node_id :param int node_id: The ID of a node :param list nodes: list of node...
node_name = '' for node in nodes: if node['id'] == node_id: node_name = node['properties']['name'] break return node_name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_port_name_from_id(node_id, port_id, nodes): """ Get the name of a port for a given node and port ID :param int node_id: node ID :param int port_id: port ...
port_name = '' for node in nodes: if node['id'] == node_id: for port in node['ports']: if port['id'] == port_id: port_name = port['name'] break return port_name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_node_connection(self, link, nodes): """ Add a connection to a node :param dict link: link definition :param list nodes: list of nodes from :py:meth:`gene...
# Description src_desc = 'connected to %s on port %s' % \ (self.get_node_name_from_id(link['destination_node_id'], nodes), self.get_port_name_from_id(link['destination_node_id'], ...