output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Search a rule for a rule tag or name value value
Can you generate the documentation for the following Python 3 function def search_rule(self, search): result = self.make_request( resource='search_rule', params={'filter': search}) if result: results = [] for data in result: typeof...
As a Python code composer, you craft elegant and concise scripts.
This method returns a list of RuleCounter objects for the given engine and duration.
Make a summary of the following Python 3 code def rule_counters(self, engine, duration_type='one_week', duration=0, start_time=0): """ .. versionadded:: 0.5.6 Obtain rule counters for this policy. Requires SMC >= 6.2 Rule counters can be obtained for a given poli...
As a Python code composer, you craft elegant and concise scripts.
Create a new VPN - level policy based VPN - level entry.
Can you generate a brief explanation for the following Python 3 code def create(cls, name, nat=False, mobile_vpn_toplogy_mode=None, vpn_profile=None): """ Create a new policy based VPN :param name: name of vpn policy :param bool nat: whether to apply NAT to the VPN (defau...
You are a Python code analyst, evaluating scripts for potential improvements.
Enable or disable NAT on this policy.
Given the following Python 3 function, write the documentation def enable_disable_nat(self): if self.nat: self.data['nat'] = False else: self.data['nat'] = True
As a Python code analyst, you investigate and solve complex coding mysteries
def add_mobile_gateway(self, gateway): """ Add a mobile VPN gateway to this policy VPN. Example of adding or removing a mobile VPN gateway:: policy_vpn = PolicyVPN('myvpn') policy_vpn.open() policy_vpn.add_mobile_vpn_gateway(ExternalGateway('extgw3')...
Can you create a Python 3 function that adds a mobile VPN gateway to this policy VPN.
You are a Python code generator, capable of creating scripts from specifications.
Adds an internal gateway to VPN policy using the href of the engine internal gateway.
Make a summary of the following Python 3 code def add_internal_gateway_to_vpn(internal_gateway_href, vpn_policy, vpn_role='central'): """ Add an internal gateway (managed engine node) to a VPN policy based on the internal gateway href. :param str inte...
As a Python code translator, you convert algorithms and pseudocode into Python.
def enable_disable(self): """ Enable or disable the tunnel link between endpoints. :raises UpdateElementFailed: failed with reason :return: None """ if self.enabled: self.update(enabled=False) else: self.update(enabled=True)
Create a Python 3 function for enabling or disable the tunnel link between endpoints.
As a Python code translator, you convert algorithms and pseudocode into Python.
def prepare_blacklist(src, dst, duration=3600, src_port1=None, src_port2=None, src_proto='predefined_tcp', dst_port1=None, dst_port2=None, dst_proto='predefined_tcp'): """ Create a blacklist entry. A blacklist can be added directly from...
Create a Python 3 function to prepare a blacklist entry for the given source and destination.
You are a Python code generator, capable of creating scripts from specifications.
def add_element(self, element): """ Element can be href or type :py:class:`smc.base.model.Element` :: >>> from smc.elements.other import Category >>> category = Category('foo') >>> category.add_element(Host('kali')) :param str,Element element: elemen...
How would you implement a function in Python 3 that adds an element to the tag.
You are a Python code analyst, evaluating scripts for potential improvements.
def add_category_tag(self, tags, append_lists=True): """ Add this category to a category tag (group). This provides drop down filters in the SMC UI by category tag. :param list tags: category tag by name :param bool append_lists: append to existing tags or overwrite ...
Implement a function in Python 3 to add this category to a category tag.
As a Python code analyst, you investigate and solve complex coding mysteries
Removes a category from this Category Tag.
Can you tell what is the following Python 3 function doing def remove_category(self, categories): categories = element_resolver(categories) diff = [category for category in self.data['category_child_ref'] if category not in categories] self.update(category_child_ref=diff)
As a python code expert, you are capable of creating scripts from specifications.
Add a new entry to the blacklist.
Make a summary of the following Python 3 code def add_entry(self, src, dst, duration=3600, src_port1=None, src_port2=None, src_proto='predefined_tcp', dst_port1=None, dst_port2=None, dst_proto='predefined_tcp'): """ Create a blacklist entry. ...
As a Python code composer, you craft elegant and concise scripts.
def update_or_create(cls, append_lists=True, with_status=False, remove_members=False, **kwargs): """ Update or create group entries. If the group exists, the members will be updated. Set append_lists=True to add new members to the list, or False to reset the list...
Create a Python 3 function to update or create a group entry.
As a python code expert, you are capable of creating scripts from specifications.
Create the TCP Service group with the given name and members.
Explain what the following Python 3 code does def create(cls, name, members=None, comment=None): element = [] if members is None else element_resolver(members) json = {'name': name, 'element': element, 'comment': comment} return ElementCreator(cls, json)
As a Python code composer, you craft elegant and concise scripts.
def generate(self, start_time=0, end_time=0, senders=None, wait_for_finish=False, timeout=5, **kw): # @ReservedAssignment """ Generate the report and optionally wait for results. You can optionally add filters to the report by providing the senders argument as a list of typ...
Implement a function in Python 3 to generate the report and optionally wait for results.
You are a Python code architect, reviewing and designing scalable and efficient code
Creates a report design based on an existing template.
Explain what the following Python 3 code does def create_design(self, name): result = self.make_request( CreateElementFailed, resource='create_design', raw_result=True, method='create', params={'name': name}) return ReportDesign( ...
As a Python code composer, you craft elegant and concise scripts.
def export_pdf(self, filename): """ Export the report in PDF format. Specify a path for which to save the file, including the trailing filename. :param str filename: path including filename :return: None """ self.make_request( raw_result=True,...
Write a Python 3 script for exporting the report in PDF format.
As a python code expert, you are capable of creating scripts from specifications.
def export_text(self, filename=None): """ Export in text format. Optionally provide a filename to save to. :param str filename: path including filename (optional) :return: None """ result = self.make_request( resource='export', par...
How would you code a function in Python 3 to export the current neccessary entry in text format. Optionally provide a filename to save to.
As a Python code translator, you convert algorithms and pseudocode into Python.
def create_ipsec_tunnel(cls, name, local_endpoint, remote_endpoint, preshared_key=None, monitoring_group=None, vpn_profile=None, mtu=0, pmtu_discovery=True, ttl=0, enabled=True, comment=None): """ The VPN tunnel type neg...
Write a Python 3 script for creating a new VPN tunnel based on routing.
You are a Python code analyst, evaluating scripts for potential improvements.
def create_gre_tunnel_mode(cls, name, local_endpoint, remote_endpoint, policy_vpn, mtu=0, pmtu_discovery=True, ttl=0, enabled=True, comment=None): """ Create a GRE based tunnel mode route VPN. Tunnel mode GRE wraps the GRE tunnel in an IPSEC tu...
Create a Python 3 function to create a GRE based tunnel mode route VPN.
You are a Python code generator, capable of creating scripts from specifications.
def create_gre_tunnel_no_encryption(cls, name, local_endpoint, remote_endpoint, mtu=0, pmtu_discovery=True, ttl=0, enabled=True, comment=None): """ Create a GRE Tunnel with no encryption. See `create_gre_tunnel_mode` for constructor description...
How would you implement a function in Python 3 that creates a GRE Tunnel with no encryption.
You are a Python code generator, capable of creating scripts from specifications.
Sets the preshared key for this VPN.
Explain what the following Python 3 code does def set_preshared_key(self, new_key): if self.data.get('preshared_key'): self.update(preshared_key=new_key)
As a Python code translator, you convert algorithms and pseudocode into Python.
def endpoint(self): """ Endpoint is used to specify which interface is enabled for VPN. This is the InternalEndpoint property of the InternalGateway. :return: internal endpoint where VPN is enabled :rtype: InternalEndpoint,ExternalGateway """ if s...
Write a Python 3 script to return the internal endpoint and external gateway that is used to specify which interface is enabled for VPN.
As a python code expert, you are capable of creating scripts from specifications.
Create the GRE tunnel endpoint.
Make a summary of the following Python 3 code def create_gre_tunnel_endpoint(cls, endpoint=None, tunnel_interface=None, remote_address=None): """ Create the GRE tunnel mode or no encryption mode endpoint. If the GRE tunnel mode endpoint is an SMC managed device...
You are a Python code generator, capable of creating scripts from specifications.
def create_gre_transport_endpoint(cls, endpoint, tunnel_interface=None): """ Create the GRE transport mode endpoint. If the GRE transport mode endpoint is an SMC managed device, both an endpoint and a tunnel interface is required. If the GRE endpoint is an externally managed devi...
How would you implement a function in Python 3 that creates a GRE transport mode endpoint.
As a python code expert, you are capable of creating scripts from specifications.
def create_ipsec_endpoint(cls, gateway, tunnel_interface=None): """ Create the VPN tunnel endpoint. If the VPN tunnel endpoint is an SMC managed device, both a gateway and a tunnel interface is required. If the VPN endpoint is an externally managed device, only a gateway is r...
Create a Python 3 function to create the VPN tunnel endpoint.
You are a Python code generator, capable of creating scripts from specifications.
def set_auth_request(self, interface_id, address=None): """ Set the authentication request field for the specified engine. """ self.interface.set_auth_request(interface_id, address) self._engine.update()
How would you code a function in Python 3 to set the authentication request field for the specified interface_id.
You are a Python code architect, reviewing and designing scalable and efficient code
def set_primary_heartbeat(self, interface_id): """ Set this interface as the primary heartbeat for this engine. This will 'unset' the current primary heartbeat and move to specified interface_id. Clusters and Master NGFW Engines only. :param str,int interface_id...
How would you code a function in Python 3 to set this interface as the primary heartbeat for this master NGFW Engines only.
As a Python code analyst, you investigate and solve complex coding mysteries
def set_backup_heartbeat(self, interface_id): """ Set this interface as the backup heartbeat interface. Clusters and Master NGFW Engines only. :param str,int interface_id: interface as backup :raises InterfaceNotFound: specified interface is not found :raises Upd...
Can you implement a function in Python 3 that sets this interface as the backup heartbeat interface.
You are a Python code analyst, evaluating scripts for potential improvements.
def set_primary_mgt(self, interface_id, auth_request=None, address=None): """ Specifies the Primary Control IP address for Management Server contact. For single FW and cluster FW's, this will enable 'Outgoing', 'Auth Request' and the 'Primary Control' interface. F...
How would you implement a function in Python 3 that sets the primary management for a specific interface.
You are a Python code generator, capable of creating scripts from specifications.
Set the specified interface as a backup management interface.
Can you tell what is the following Python 3 function doing def set_backup_mgt(self, interface_id): self.interface.set_unset(interface_id, 'backup_mgt') self._engine.update()
You are a Python code analyst, evaluating scripts for potential improvements.
Sets the outgoing address for the specified interface.
How would you explain what the following Python 3 function does def set_outgoing(self, interface_id): self.interface.set_unset(interface_id, 'outgoing') self._engine.update()
As a python code expert, you are capable of creating scripts from specifications.
Enables DSCP marking and throttling on the interface.
Here you have a function in Python 3, explain what it does def dscp_marking_and_throttling(self, qos_policy): self._interface.data.update(qos_limit=-1, qos_mode='dscp', qos_policy_ref=qos_policy.href)
You are a Python code generator, capable of creating scripts from specifications.
def delete(self): """ Override delete in parent class, this will also delete the routing configuration referencing this interface. :: engine = Engine('vm') interface = engine.interface.get(2) interface.delete() """ super(Interface, sel...
Write a Python 3 function for deleting the related object from the cache.
You are a Python code architect, reviewing and designing scalable and efficient code
Update this interface s information back to SMC.
Make a summary of the following Python 3 code def update(self, *args, **kw): super(Interface, self).update(*args, **kw) self._engine._del_cache() return self
As a Python code analyst, you investigate and solve complex coding mysteries
def addresses(self): """ Return 3-tuple with (address, network, nicid) :return: address related information of interface as 3-tuple list :rtype: list """ addresses = [] for i in self.all_interfaces: if isinstance(i, VlanInterface): for...
Create a Python 3 function for returning 3 - tuple with ( address network nicid )
You are a Python code architect, reviewing and designing scalable and efficient code
Flatten out all top level interfaces and only return sub interfaces.
Here you have a function in Python 3, explain what it does def sub_interfaces(self): interfaces = self.all_interfaces sub_interfaces = [] for interface in interfaces: if isinstance(interface, VlanInterface): if interface.has_interfaces: for subaddr...
As a Python code composer, you craft elegant and concise scripts.
Get the boolean value for the attribute specified from the the sub interface.
Can you generate the documentation for the following Python 3 function def get_boolean(self, name): for interface in self.all_interfaces: if isinstance(interface, VlanInterface): if any(vlan for vlan in interface.interfaces if getattr(vlan, name)): ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def delete_invalid_route(self): """ Delete any invalid routes for this interface. An invalid route is a left over when an interface is changed to a different network. :return: None """ try: routing = self._engine.routing.get(self.interface_id) ...
Can you write a function in Python 3 where it deletes any invalid routes for this interface.
You are a Python code analyst, evaluating scripts for potential improvements.
Reset the interface by removing all assigned addresses and VLANs.
Can you generate a brief explanation for the following Python 3 code def reset_interface(self): self.data['interfaces'] = [] if self.typeof != 'tunnel_interface': self.data['vlanInterfaces'] = [] self.update() self.delete_invalid_route()
As a Python code composer, you craft elegant and concise scripts.
def change_interface_id(self, interface_id): """ Change the interface ID for this interface. This can be used on any interface type. If the interface is an Inline interface, you must provide the ``interface_id`` in format '1-2' to define both interfaces in the pair. The change is...
Write a Python 3 function for changing the interface ID for this interface. This method is used to change the interface ID for both CVI and NDI interfaces.
As a python code expert, you are capable of creating scripts from specifications.
def _update_interface(self, other_interface): """ Update the physical interface base settings with another interface. Only set updated if a value has changed. You must also call `update` on the interface if modifications are made. This is called from other interfaces (i.e. Physic...
Write a Python 3 function that can update the physical interface base settings with the values in another_interface.
You are a Python code architect, reviewing and designing scalable and efficient code
Update an existing interface by comparing values between two interfaces.
Given the following Python 3 function, write the documentation def update_interface(self, other_interface, ignore_mgmt=True): base_updated = self._update_interface(other_interface) mgmt = ('auth_request', 'backup_heartbeat', 'backup_mgt', 'primary_mgt', 'primary_heartbeat', 'outgoin...
You are a Python code analyst, evaluating scripts for potential improvements.
def _add_interface(self, interface_id, **kw): """ Create a tunnel interface. Kw argument list is as follows """ base_interface = ElementCache() base_interface.update( interface_id=str(interface_id), interfaces=[]) if 'zone_ref' in kw: ...
Can you implement a function in Python 3 that adds an interface to the tunnel interface cache.
You are a Python code analyst, evaluating scripts for potential improvements.
def ndi_interfaces(self): """ Return a formatted dict list of NDI interfaces on this engine. This will ignore CVI or any inline or layer 2 interface types. This can be used to identify to indicate available IP addresses for a given interface which can be used to run services suc...
Can you implement a function in Python 3 that returns a formatted list of NDI interfaces on this engine.
As a Python code analyst, you investigate and solve complex coding mysteries
Change the VLAN ID for a single or inline VLAN or inline VLAN.
Make a summary of the following Python 3 code def change_vlan_id(self, original, new): vlan = self.vlan_interface.get_vlan(original) newvlan = str(new).split('-') splitted = vlan.interface_id.split('.') vlan.interface_id = '{}.{}'.format(splitted[0], newvlan[0]) for interface in ...
You are a Python code generator, capable of creating scripts from specifications.
def enable_aggregate_mode(self, mode, interfaces): """ Enable Aggregate (LAGG) mode on this interface. Possible LAGG types are 'ha' and 'lb' (load balancing). For HA, only one secondary interface ID is required. For load balancing mode, up to 7 additional are supported (8 max...
How would you code a function in Python 3 to enable aggregate mode on this LAGG entry.
As a Python code analyst, you investigate and solve complex coding mysteries
def static_arp_entry(self, ipaddress, macaddress, arp_type='static', netmask=32): """ Add an arp entry to this physical interface. :: interface = engine.physical_interface.get(0) interface.static_arp_entry( ipaddress='23.23.23.23', arp_typ...
Can you implement a function in Python 3 that adds an entry to the static ARP table.
You are a Python code generator, capable of creating scripts from specifications.
def _add_interface(self, interface_id, mgt=None, **kw): """ Add the Cluster interface. If adding a cluster interface to an existing node, retrieve the existing interface and call this method. Use the supported format for defining an interface. """ _kw = copy.deepcopy(kw) ...
Write a Python 3 function that can add the Cluster interface to the internal data structure.
As a Python code composer, you craft elegant and concise scripts.
Delete this Vlan interface from the parent interface.
Can you tell what is the following Python 3 function doing def delete(self): if self in self._parent.vlan_interface: self._parent.data['vlanInterfaces'] = [ v for v in self._parent.vlan_interface if v != self] self.update() for route in self._p...
As a python code expert, you are capable of creating scripts from specifications.
Change the VLAN id for this interface.
Given the following Python 3 function, write the documentation def change_vlan_id(self, vlan_id): intf_id, _ = self.interface_id.split('.') self.interface_id = '{}.{}'.format(intf_id, vlan_id) for interface in self.interfaces: interface.change_vlan_id(vlan_id) self.update()
You are a Python code architect, reviewing and designing scalable and efficient code
def get(self, *args, **kwargs): """ Get from the interface collection. It is more accurate to use kwargs to specify an attribute of the sub interface to retrieve rather than using an index value. If retrieving using an index, the collection will first check vlan interfaces and st...
Write a Python 3 function for getting from the interface collection.
As a Python code analyst, you investigate and solve complex coding mysteries
Get the VLAN from this PhysicalInterface.
Make a summary of the following Python 3 code def get_vlan(self, *args, **kwargs): if args: kwargs = {'vlan_id': str(args[0])} key, value = kwargs.popitem() for vlan in self: if getattr(vlan, key, None) == value: return vlan raise InterfaceNotFound...
You are a Python code architect, reviewing and designing scalable and efficient code
def get(self, *args, **kwargs): """ Get the sub interfaces for this VlanInterface >>> itf = engine.interface.get(3) >>> list(itf.vlan_interface) [Layer3PhysicalInterfaceVlan(name=VLAN 3.3), Layer3PhysicalInterfaceVlan(name=VLAN 3.5), Layer3Physica...
Can you write a function in Python 3 where it gets the sub interfaces for this VlanInterface
You are a Python code generator, capable of creating scripts from specifications.
def find_mgmt_interface(self, mgmt): """ Find the management interface specified and return either the string representation of the interface_id. Valid options: primary_mgt, backup_mgt, primary_heartbeat, backup_heartbeat, outgoing, auth_request :ret...
How would you code a function in Python 3 to find the management interface specified and return either the string representation of the interface_id.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get(self, interface_id): """ Get the interface from engine json :param str interface_id: interface ID to find :raises InterfaceNotFound: Cannot find interface """ # From within engine, skips nested iterators for this find # Make sure were dealing with...
Write a Python 3 function that can get the interface from engine json
As a python code expert, you are capable of creating scripts from specifications.
Set attribute to True and unset the same attribute for all other CVI interfaces.
Can you generate the documentation for the following Python 3 function def set_unset(self, interface_id, attribute, address=None): interface = self.get(interface_id) if interface_id is not None else None if address is not None: target_network = None sub_interface = interface.all_...
You are a Python code architect, reviewing and designing scalable and efficient code
Set auth request on a NDI interface.
Here you have a function in Python 3, explain what it does def set_auth_request(self, interface_id, address=None): for engine_type in ['master', 'layer2', 'ips']: if engine_type in self.engine.type: return interface = self.get(interface_id) if 'cluster' in se...
As a python code expert, you are capable of creating scripts from specifications.
Return the ASN number represented by the given string as a dotted string.
Here you have a function in Python 3, explain what it does def as_dotted(dotted_str): #max_asn = 4294967295 (65535 * 65535) if '.' not in dotted_str: return dotted_str max_byte = 65535 left, right = map(int, dotted_str.split('.')) if left > max_byte or right > max_byte: raise ValueEr...
As a Python code analyst, you investigate and solve complex coding mysteries
def update_antispoofing(self, networks=None): """ Pass a list of networks to update antispoofing networks with. You can clear networks by providing an empty list. If networks are provided but already exist, no update is made. :param list networks: networks, groups or hos...
Write a Python 3 script for updating the antispoofing list with the given networks.
You are a Python code generator, capable of creating scripts from specifications.
def enable(self, autonomous_system, announced_networks, router_id=None, bgp_profile=None): """ Enable BGP on this engine. On master engine, enable BGP on the virtual firewall. When adding networks to `announced_networks`, the element types can be of type :class:`smc.elemen...
Implement a Python 3 function for enabling BGP on this engine.
As a python code expert, you are capable of creating scripts from specifications.
Update the configuration of the current object based on the given kwargs.
Here you have a function in Python 3, explain what it does def update_configuration(self, **kwargs): updated = False if 'announced_networks' in kwargs: kwargs.update(announced_ne_setting=kwargs.pop('announced_networks')) if 'bgp_profile' in kwargs: kwargs.update(bgp_profi...
As a Python code translator, you convert algorithms and pseudocode into Python.
Show all announced networks for the BGP configuration.
Given the following Python 3 function, write the documentation def announced_networks(self): return [(Element.from_href(ne.get('announced_ne_ref')), Element.from_href(ne.get('announced_rm_ref'))) for ne in self.data.get('announced_ne_setting')]
As a python code expert, you are capable of creating scripts from specifications.
def create(cls, name, as_number, comment=None): """ Create an AS to be applied on the engine BGP configuration. An AS is a required parameter when creating an ExternalBGPPeer. You can also provide an AS number using an 'asdot' syntax:: AutonomousSystem.create(name='m...
How would you implement a function in Python 3 that creates an AutonomousSystem with the specified name and AS number.
You are a Python code architect, reviewing and designing scalable and efficient code
Create a custom BGP profile with specific attributes.
Can you generate the documentation for the following Python 3 function def create(cls, name, port=179, external_distance=20, internal_distance=200, local_distance=200, subnet_distance=None): """ Create a custom BGP Profile :param str name: name of profile :param int port:...
As a Python code analyst, you investigate and solve complex coding mysteries
Create an external BGP Peer.
Can you generate a brief explanation for the following Python 3 code def create(cls, name, neighbor_as, neighbor_ip, neighbor_port=179, comment=None): """ Create an external BGP Peer. :param str name: name of peer :param str,AutonomousSystem neighbor_as_ref: AutonomousSy...
You are a Python code generator, capable of creating scripts from specifications.
Creates a new BGP PEERing configuration.
Given the following Python 3 function, write the documentation def create(cls, name, connection_profile_ref=None, md5_password=None, local_as_option='not_set', max_prefix_option='not_enabled', send_community='no', connected_check='disabled', orf_option='disabled', ...
You are a Python code generator, capable of creating scripts from specifications.
Create a new BGP Connection Profile.
Make a summary of the following Python 3 code def create(cls, name, md5_password=None, connect_retry=120, session_hold_timer=180, session_keep_alive=60): """ Create a new BGP Connection Profile. :param str name: name of profile :param str md5_password: optional md5 passwo...
As a python code expert, you are capable of creating scripts from specifications.
Enable specific permissions on this role.
Explain what the following Python 3 code does def enable(self, values): for value in values: if value in self.data: self.data[value] = True
You are a Python code generator, capable of creating scripts from specifications.
def disable(self, values): """ Disable specific permissions on this role. Use :py:attr:`~permissions` to view valid permission settings and current value/s. Change is committed immediately. :param list values: list of values by allowed types :return: None ...
Create a Python 3 function for disabling specific permissions on this role.
You are a Python code generator, capable of creating scripts from specifications.
def permissions(self): """ Return valid permissions and setting for this role. Permissions are returned as a list of dict items, {permission: state}. State for the permission is either True or False. Use :meth:`~enable` and :meth:`~disable` to toggle role settings. ...
Write a Python 3 script for returning valid permissions and setting for this role.
You are a Python code architect, reviewing and designing scalable and efficient code
def _extract_ports(port_string): """ Return a dict for translated_value based on a string or int value. Value could be 80, or '80' or '80-90'. Will be returned as {'min_port': 80, 'max_port': 80} or {'min_port': 80, 'max_port': 90} :rtype: dict """ _ports = str(port_s...
Create a Python 3 function to extract the port range from a string or int .
As a Python code composer, you craft elegant and concise scripts.
This method updates the original value of the source or destination field of a NAT rule.
How would you explain what the following Python 3 function does def _update_nat_field(self, source_or_dest): original_value = source_or_dest.all_as_href() if original_value: nat_element = None if 'src' in source_or_dest.typeof and self.static_src_nat.has_nat: nat_...
As a Python code composer, you craft elegant and concise scripts.
Update this object s fields with the given NATValue.
Make a summary of the following Python 3 code def _update_field(self, natvalue): updated = False if natvalue.element and natvalue.element != self.element: self.update(element=natvalue.element) self.pop('ip_descriptor', None) updated = True elif natvalue.ip_des...
As a Python code analyst, you investigate and solve complex coding mysteries
def update_field(self, element_or_ip_address=None, start_port=None, end_port=None, **kw): """ Update the source NAT translation on this rule. You must call `save` or `update` on the rule to make this modification. To update the source target for this NAT rule, update ...
Create a Python 3 function for updating the source field for this rule.
As a Python code analyst, you investigate and solve complex coding mysteries
def translated_value(self): """ The translated value for this NAT type. If this rule does not have a NAT value defined, this will return None. :return: NATValue or None :rtype: NATValue """ if self.typeof in self: return NATValue(self....
Create a Python 3 function for returning the translated value for this rule.
You are a Python code architect, reviewing and designing scalable and efficient code
def update_field(self, element_or_ip_address=None, original_port=None, translated_port=None, **kw): """ Update the destination NAT translation on this rule. You must call `save` or `update` on the rule to make this modification. The destination field in the NAT rule determin...
Write a Python 3 script for updating the field of the destination field in the rule.
As a Python code analyst, you investigate and solve complex coding mysteries
Creates a new NAT rule in the national domain.
How would you explain what the following Python 3 function does def create(self, name, sources=None, destinations=None, services=None, dynamic_src_nat=None, dynamic_src_nat_ports=(1024, 65535), static_src_nat=None, static_dst_nat=None, static_dst_nat_ports=None, is_disabled=...
You are a Python code generator, capable of creating scripts from specifications.
Implementation of httplib2 s Http. request.
Can you tell what is the following Python 3 function doing def request(self, uri, method='GET', body=None, headers=None, **kwargs): """Implementation of httplib2's Http.request.""" _credential_refresh_attempt = kwargs.pop( '_credential_refresh_attempt', 0) # Make a ...
As a Python code composer, you craft elegant and concise scripts.
Connect to an MQTT broker.
Can you tell what is the following Python 3 function doing def connect(self, broker, port=1883, client_id="", clean_session=True): logger.info('Connecting to %s at port %s' % (broker, port)) self._connected = False self._unexpected_disconnect = False self._mqttc = mqtt.Client(client_id, ...
As a Python code composer, you craft elegant and concise scripts.
Publish a message to a topic with specified qos and retain flag.
Can you generate a brief explanation for the following Python 3 code def publish(self, topic, message=None, qos=0, retain=False): logger.info('Publish topic: %s, message: %s, qos: %s, retain: %s' % (topic, message, qos, retain)) self._mid = -1 self._mqttc.on_publish = self._on_publis...
You are a Python code architect, reviewing and designing scalable and efficient code
Subscribe to a topic and return a list of message payloads received within the specified time.
How would you explain what the following Python 3 function does def subscribe(self, topic, qos, timeout=1, limit=1): seconds = convert_time(timeout) self._messages[topic] = [] limit = int(limit) self._subscribed = False logger.info('Subscribing to topic: %s' % topic) sel...
As a Python code translator, you convert algorithms and pseudocode into Python.
Listen to a topic and return a list of message payloads received within the specified time.
Make a summary of the following Python 3 code def listen(self, topic, timeout=1, limit=1): if not self._subscribed: logger.warn('Cannot listen when not subscribed to a topic') return [] if topic not in self._messages: logger.warn('Cannot listen when not subscribed to...
As a Python code translator, you convert algorithms and pseudocode into Python.
def subscribe_and_validate(self, topic, qos, payload, timeout=1): """ Subscribe to a topic and validate that the specified payload is received within timeout. It is required that a connection has been established using `Connect` keyword. The payload can be specified as a python regular e...
Write a Python 3 function that can subscribe to a topic and validate that the specified payload is received within the specified timeout.
As a python code expert, you are capable of creating scripts from specifications.
Unsubscribe from a topic.
Explain what the following Python 3 code does def unsubscribe(self, topic): try: tmp = self._mqttc except AttributeError: logger.info('No MQTT Client instance found so nothing to unsubscribe from.') return if self._background_mqttc: logger.info('C...
You are a Python code analyst, evaluating scripts for potential improvements.
def disconnect(self): """ Disconnect from MQTT Broker. Example: | Disconnect | """ try: tmp = self._mqttc except AttributeError: logger.info('No MQTT Client instance found so nothing to disconnect from.') return self._disconn...
Write a Python 3 function for disconnecting from the broker.
As a Python code analyst, you investigate and solve complex coding mysteries
def publish_single(self, topic, payload=None, qos=0, retain=False, hostname="localhost", port=1883, client_id="", keepalive=60, will=None, auth=None, tls=None, protocol=mqtt.MQTTv31): """ Publish a single message and disconnect. This keyword uses the [http://eclipse.org/paho/cli...
Create a Python 3 function to publish a single message and disconnect.
As a python code expert, you are capable of creating scripts from specifications.
Publish multiple messages and disconnect.
Here you have a function in Python 3, explain what it does def publish_multiple(self, msgs, hostname="localhost", port=1883, client_id="", keepalive=60, will=None, auth=None, tls=None, protocol=mqtt.MQTTv31): """ Publish multiple messages and disconnect. This keyword uses the [h...
As a Python code composer, you craft elegant and concise scripts.
def user_to_request(handler): '''Add user to request if user logged in''' @wraps(handler) async def decorator(*args): request = _get_request(args) request[cfg.REQUEST_USER_KEY] = await get_cur_user(request) return await handler(*args) return decorator
Write a Python 3 script to add user to request if user logged in
As a python code expert, you are capable of creating scripts from specifications.
Add a synonym to the list of synonyms.
Here you have a function in Python 3, explain what it does def add_synonym(self, other): self.synonyms.extend(other.synonyms) other.synonyms = self.synonyms
You are a Python code analyst, evaluating scripts for potential improvements.
Return a SQL query that only returns one row.
Given the following Python 3 function, write the documentation def find_one_sql(table, filter, fields=None): ''' >>> find_one_sql('tbl', {'foo': 10, 'bar': 'baz'}) ('SELECT * FROM tbl WHERE bar=$1 AND foo=$2', ['baz', 10]) >>> find_one_sql('tbl', {'id': 10}, fields=['foo', 'bar']) ('SELECT foo, bar ...
As a python code expert, you are capable of creating scripts from specifications.
Insert data into the specified table.
Explain what the following Python 3 code does def insert_sql(table, data, returning='id'): ''' >>> insert_sql('tbl', {'foo': 'bar', 'id': 1}) ('INSERT INTO tbl (foo, id) VALUES ($1, $2) RETURNING id', ['bar', 1]) >>> insert_sql('tbl', {'foo': 'bar', 'id': 1}, returning=None) ('INSERT INTO tbl (foo,...
As a python code expert, you are capable of creating scripts from specifications.
>>> update_sql - Updates the table with the given filter and updates
Make a summary of the following Python 3 code def update_sql(table, filter, updates): ''' >>> update_sql('tbl', {'foo': 'a', 'bar': 1}, {'bar': 2, 'baz': 'b'}) ('UPDATE tbl SET bar=$1, baz=$2 WHERE bar=$3 AND foo=$4', [2, 'b', 1, 'a']) ''' where_keys, where_vals = _split_dict(filter) up_keys, up...
You are a Python code generator, capable of creating scripts from specifications.
>>> delete_sql - Delete a table from the database with a filter
How would you explain what the following Python 3 function does def delete_sql(table, filter): ''' >>> delete_sql('tbl', {'foo': 10, 'bar': 'baz'}) ('DELETE FROM tbl WHERE bar=$1 AND foo=$2', ['baz', 10]) ''' keys, values = _split_dict(filter) where = _pairs(keys) sql = 'DELETE FROM {} WHERE...
You are a Python code architect, reviewing and designing scalable and efficient code
def _split_dict(dic): '''Split dict into sorted keys and values >>> _split_dict({'b': 2, 'a': 1}) (['a', 'b'], [1, 2]) ''' keys = sorted(dic.keys()) return keys, [dic[k] for k in keys]
Write a Python 3 function that can split dict into sorted keys and values >>>
As a Python code composer, you craft elegant and concise scripts.
def play(seed=None): """Turn the Python prompt into an Adventure game. With optional the `seed` argument the caller can supply an integer to start the Python random number generator at a known state. """ global _game from .game import Game from .prompt import install_words _game = Ga...
Can you write a function in Python 3 where it turns the Python prompt into an Adventure game.
As a Python code composer, you craft elegant and concise scripts.
def write(self, more): """Append the Unicode representation of `s` to our output.""" if more: self.output += str(more).upper() self.output += '\n'
How would you implement a function in Python 3 that appends the Unicode representation of s to our output.
You are a Python code analyst, evaluating scripts for potential improvements.
def yesno(self, s, yesno_callback, casual=False): """Ask a question and prepare to receive a yes-or-no answer.""" self.write(s) self.yesno_callback = yesno_callback self.yesno_casual = casual
Implement a Python 3 function for asking a question and prepare to receive a yes - or - no answer.
As a Python code composer, you craft elegant and concise scripts.
def start2(self, yes): """Display instructions if the user wants them.""" if yes: self.write_message(1) self.hints[3].used = True self.lamp_turns = 1000 self.oldloc2 = self.oldloc = self.loc = self.rooms[1] self.dwarves = [ Dwarf(self.rooms[n]) for n ...
How would you implement a function in Python 3 that displays instructions if the user wants them.
As a python code expert, you are capable of creating scripts from specifications.
Parse and act upon the command in the list of strings words.
Explain what the following Python 3 code does def do_command(self, words): self.output = '' self._do_command(words) return self.output
As a python code expert, you are capable of creating scripts from specifications.