Instruction:
Implement a Python 3 function for
checking if to_value is a valid transition from from_value. Returns True if it is a valid transition.

Response:
def is_valid_transition(cls, from_value, to_value):
        """ Will check if to_value is a valid transition from from_value. Returns true if it is a valid transition.
        :param from_value: Start transition point
        :param to_value: End transition point
        :type from_value: int
        :type to_value: int
        :return: Success flag
        :rtype: bool
        """
        try:
            return from_value == to_value or from_value in cls.transition_origins(to_value)
        except KeyError:
            return False


Instruction:
Make a summary of the following Python 3 code
def _setup_validation(self, sender, **kwargs):
        att_name = self.get_attname()
        private_att_name = '_enum_%s' % att_name
        enum = self.enum

        def set_enum(self, new_value):
            if hasattr(self, private_att_name):
                # Fetch previous value from private enum attribute.
                old_value = getattr(self, private_att_name)
            else:
                # First setattr no previous value on instance.
                old_value = new_value
            # Update private enum attribute with new value
            setattr(self, private_att_name, new_value)
            self.__dict__[att_name] = new_value
            # Run validation for new value.
            validators.validate_valid_transition(enum, old_value, new_value)

        def get_enum(self):
            return getattr(self, private_att_name)

        def delete_enum(self):
            self.__dict__[att_name] = None
            return setattr(self, private_att_name, None)

        if not sender._meta.abstract:
            setattr(sender, att_name, property(get_enum, set_enum, delete_enum))

Response: Setup validation for the current value of the attribute.


Instruction:
Can you tell what is the following Python 3 function doing
def validate_valid_transition(enum, from_value, to_value):
    validate_available_choice(enum, to_value)
    if hasattr(enum, '_transitions') and not enum.is_valid_transition(from_value, to_value):
        message = _(six.text_type('{enum} can not go from "{from_value}" to "{to_value}"'))
        raise InvalidStatusOperationError(message.format(
            enum=enum.__name__,
            from_value=enum.name(from_value),
            to_value=enum.name(to_value) or to_value
        ))

Response: Validate that from_value is a valid transition from to_value.


Instruction:
Given the following Python 3 function, write the documentation
def validate_available_choice(enum, to_value):
    if to_value is None:
        return

    if type(to_value) is not int:
        try:
            to_value = int(to_value)
        except ValueError:
            message_str = "'{value}' cannot be converted to int"
            message = _(six.text_type(message_str))
            raise InvalidStatusOperationError(message.format(value=to_value))

    if to_value not in list(dict(enum.choices()).keys()):
        message = _(six.text_type('Select a valid choice. {value} is not one of the available choices.'))
        raise InvalidStatusOperationError(message.format(value=to_value))

Response: Validate that to_value is defined as a value in enum.


Instruction:
How would you implement a function in Python 3 that
gets a diff between running config and a proposed file.

Response:
def _get_diff(self, cp_file):
        """Get a diff between running config and a proposed file."""
        diff = []
        self._create_sot_file()
        diff_out = self.device.show(
            'show diff rollback-patch file {0} file {1}'.format(
                'sot_file', self.replace_file.split('/')[-1]), raw_text=True)
        try:
            diff_out = diff_out.split(
                '#Generating Rollback Patch')[1].replace(
                    'Rollback Patch is Empty', '').strip()
            for line in diff_out.splitlines():
                if line:
                    if line[0].strip() != '!':
                        diff.append(line.rstrip(' '))
        except (AttributeError, KeyError):
            raise ReplaceConfigException(
                'Could not calculate diff. It\'s possible the given file doesn\'t exist.')
        return '\n'.join(diff)


Instruction:
Create a Python 3 function to
save the current running config to the given file.

Response:
def _save_config(self, filename):
        """Save the current running config to the given file."""
        self.device.show('checkpoint file {}'.format(filename), raw_text=True)


Instruction:
Write a Python 3 script to
open the connection wit the device.

Response:
def open(self):
        """Open the connection wit the device."""
        try:
            self.device.open()
        except ConnectTimeoutError as cte:
            raise ConnectionException(cte.message)
        self.device.timeout = self.timeout
        self.device._conn._session.transport.set_keepalive(self.keepalive)
        if hasattr(self.device, "cu"):
            # make sure to remove the cu attr from previous session
            # ValueError: requested attribute name cu already exists
            del self.device.cu
        self.device.bind(cu=Config)
        if self.config_lock:
            self._lock()


Instruction:
Write a Python 3 script to
lock the config DB.

Response:
def _lock(self):
        """Lock the config DB."""
        if not self.locked:
            self.device.cu.lock()
            self.locked = True


Instruction:
Write a Python 3 script to
unlock the config DB.

Response:
def _unlock(self):
        """Unlock the config DB."""
        if self.locked:
            self.device.cu.unlock()
            self.locked = False


Instruction:
Can you generate a brief explanation for the following Python 3 code
def compare_config(self):
        diff = self.device.cu.diff()

        if diff is None:
            return ''
        else:
            return diff.strip()

Response: Compare candidate config with running.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def discard_config(self):
        self.device.cu.rollback(rb_id=0)
        if not self.config_lock:
            self._unlock()

Response: Discard changes from the device.


Instruction:
Explain what the following Python 3 code does
def get_facts(self):
        output = self.device.facts

        uptime = self.device.uptime or -1

        interfaces = junos_views.junos_iface_table(self.device)
        interfaces.get()
        interface_list = interfaces.keys()

        return {
            'vendor': u'Juniper',
            'model': py23_compat.text_type(output['model']),
            'serial_number': py23_compat.text_type(output['serialnumber']),
            'os_version': py23_compat.text_type(output['version']),
            'hostname': py23_compat.text_type(output['hostname']),
            'fqdn': py23_compat.text_type(output['fqdn']),
            'uptime': uptime,
            'interface_list': interface_list
        }

Response: Return the facts of the device.


Instruction:
Write a Python 3 script for
returning the details of all the interfaces in the device.

Response:
def get_interfaces(self):
        """Return interfaces details."""
        result = {}

        interfaces = junos_views.junos_iface_table(self.device)
        interfaces.get()

        # convert all the tuples to our pre-defined dict structure
        for iface in interfaces.keys():
            result[iface] = {
                'is_up': interfaces[iface]['is_up'],
                'is_enabled': interfaces[iface]['is_enabled'],
                'description': (interfaces[iface]['description'] or u''),
                'last_flapped': float((interfaces[iface]['last_flapped'] or -1)),
                'mac_address': napalm_base.helpers.convert(
                    napalm_base.helpers.mac,
                    interfaces[iface]['mac_address'],
                    py23_compat.text_type(interfaces[iface]['mac_address'])),
                'speed': -1
            }
            # result[iface]['last_flapped'] = float(result[iface]['last_flapped'])

            match = re.search(r'(\d+)(\w*)', interfaces[iface]['speed'] or u'')
            if match is None:
                continue
            speed_value = napalm_base.helpers.convert(int, match.group(1), -1)
            if speed_value == -1:
                continue
            speed_unit = match.group(2)
            if speed_unit.lower() == 'gbps':
                speed_value *= 1000
            result[iface]['speed'] = speed_value

        return result


Instruction:
How would you code a function in Python 3 to
function to derive the address family from a junos routing table name.

Response:
def _get_address_family(table):
        """
        Function to derive address family from a junos table name.

        :params table: The name of the routing table
        :returns: address family
        """
        address_family_mapping = {
            'inet': 'ipv4',
            'inet6': 'ipv6',
            'inetflow': 'flow'
        }
        family = table.split('.')[-2]
        try:
            address_family = address_family_mapping[family]
        except KeyError:
            address_family = family
        return address_family


Instruction:
Here you have a function in Python 3, explain what it does
def get_bgp_neighbors(self):
        bgp_neighbor_data = {}
        default_neighbor_details = {
            'local_as': 0,
            'remote_as': 0,
            'remote_id': '',
            'is_up': False,
            'is_enabled': False,
            'description': '',
            'uptime': 0,
            'address_family': {}
        }
        keys = default_neighbor_details.keys()

        uptime_table = junos_views.junos_bgp_uptime_table(self.device)
        bgp_neighbors_table = junos_views.junos_bgp_table(self.device)

        uptime_table_lookup = {}

        def _get_uptime_table(instance):
            if instance not in uptime_table_lookup:
                uptime_table_lookup[instance] = uptime_table.get(instance=instance).items()
            return uptime_table_lookup[instance]

        def _get_bgp_neighbors_core(neighbor_data, instance=None, uptime_table_items=None):
            '''
            Make sure to execute a simple request whenever using
            junos > 13. This is a helper used to avoid code redundancy
            and reuse the function also when iterating through the list
            BGP neighbors under a specific routing instance,
            also when the device is capable to return the routing
            instance name at the BGP neighbor level.
            '''
            for bgp_neighbor in neighbor_data:
                peer_ip = napalm_base.helpers.ip(bgp_neighbor[0].split('+')[0])
                neighbor_details = deepcopy(default_neighbor_details)
                neighbor_details.update(
                    {elem[0]: elem[1] for elem in bgp_neighbor[1] if elem[1] is not None}
                )
                if not instance:
                    # not instance, means newer Junos version,
                    # as we request everything in a single request
                    peer_fwd_rti = neighbor_details.pop('peer_fwd_rti')
                    instance = peer_fwd_rti
                else:
                    # instance is explicitly requests,
                    # thus it's an old Junos, so we retrieve the BGP neighbors
                    # under a certain routing instance
                    peer_fwd_rti = neighbor_details.pop('peer_fwd_rti', '')
                instance_name = 'global' if instance == 'master' else instance
                if instance_name not in bgp_neighbor_data:
                    bgp_neighbor_data[instance_name] = {}
                if 'router_id' not in bgp_neighbor_data[instance_name]:
                    # we only need to set this once
                    bgp_neighbor_data[instance_name]['router_id'] = \
                        py23_compat.text_type(neighbor_details.get('local_id', ''))
                peer = {
                    key: self._parse_value(value)
                    for key, value in neighbor_details.items()
                    if key in keys
                }
                peer['local_as'] = napalm_base.helpers.as_number(peer['local_as'])
                peer['remote_as'] = napalm_base.helpers.as_number(peer['remote_as'])
                peer['address_family'] = self._parse_route_stats(neighbor_details)
                if 'peers' not in bgp_neighbor_data[instance_name]:
                    bgp_neighbor_data[instance_name]['peers'] = {}
                bgp_neighbor_data[instance_name]['peers'][peer_ip] = peer
                if not uptime_table_items:
                    uptime_table_items = _get_uptime_table(instance)
                for neighbor, uptime in uptime_table_items:
                    if neighbor not in bgp_neighbor_data[instance_name]['peers']:
                        bgp_neighbor_data[instance_name]['peers'][neighbor] = {}
                    bgp_neighbor_data[instance_name]['peers'][neighbor]['uptime'] = uptime[0][1]

        # Commenting out the following sections, till Junos
        #   will provide a way to identify the routing instance name
        #   from the details of the BGP neighbor
        #   currently, there are Junos 15 version having a field called `peer_fwd_rti`
        #   but unfortunately, this is not consistent.
        # Junos 17 might have this fixed, but this needs to be revisited later.
        # In the definition below, `old_junos` means a version that does not provide
        #   the forwarding RTI information.
        #
        # old_junos = napalm_base.helpers.convert(
        #     int, self.device.facts.get('version', '0.0').split('.')[0], 0) < 15

        # if old_junos:
        instances = junos_views.junos_route_instance_table(self.device).get()
        for instance, instance_data in instances.items():
            if instance.startswith('__'):
                # junos internal instances
                continue
            bgp_neighbor_data[instance] = {'peers': {}}
            instance_neighbors = bgp_neighbors_table.get(instance=instance).items()
            uptime_table_items = uptime_table.get(instance=instance).items()
            _get_bgp_neighbors_core(instance_neighbors,
                                    instance=instance,
                                    uptime_table_items=uptime_table_items)
        # If the OS provides the `peer_fwd_rti` or any way to identify the
        #   rotuing instance name (see above), the performances of this getter
        #   can be significantly improved, as we won't execute one request
        #   for each an every RT.
        # However, this improvement would only be beneficial for multi-VRF envs.
        #
        # else:
        #     instance_neighbors = bgp_neighbors_table.get().items()
        #     _get_bgp_neighbors_core(instance_neighbors)
        bgp_tmp_dict = {}
        for k, v in bgp_neighbor_data.items():
            if bgp_neighbor_data[k]['peers']:
                bgp_tmp_dict[k] = v
        return bgp_tmp_dict

Response: Return BGP neighbors details.


Instruction:
Here you have a function in Python 3, explain what it does
def get_lldp_neighbors(self):
        lldp = junos_views.junos_lldp_table(self.device)
        try:
            lldp.get()
        except RpcError as rpcerr:
            # this assumes the library runs in an environment
            # able to handle logs
            # otherwise, the user just won't see this happening
            log.error('Unable to retrieve the LLDP neighbors information:')
            log.error(rpcerr.message)
            return {}
        result = lldp.items()

        neighbors = {}
        for neigh in result:
            if neigh[0] not in neighbors.keys():
                neighbors[neigh[0]] = []
            neighbors[neigh[0]].append({x[0]: py23_compat.text_type(x[1]) for x in neigh[1]})

        return neighbors

Response: Return LLDP neighbors details.


Instruction:
Write a Python 3 script for
detailing view of the LLDP neighbors.

Response:
def get_lldp_neighbors_detail(self, interface=''):
        """Detailed view of the LLDP neighbors."""
        lldp_neighbors = {}

        lldp_table = junos_views.junos_lldp_neighbors_detail_table(self.device)
        try:
            lldp_table.get()
        except RpcError as rpcerr:
            # this assumes the library runs in an environment
            # able to handle logs
            # otherwise, the user just won't see this happening
            log.error('Unable to retrieve the LLDP neighbors information:')
            log.error(rpcerr.message)
            return {}
        interfaces = lldp_table.get().keys()

        # get lldp neighbor by interface rpc for EX Series, QFX Series, J Series
        # and SRX Series is get-lldp-interface-neighbors-information,
        # and rpc for M, MX, and T Series is get-lldp-interface-neighbors
        # ref1: https://apps.juniper.net/xmlapi/operTags.jsp  (Junos 13.1 and later)
        # ref2: https://www.juniper.net/documentation/en_US/junos12.3/information-products/topic-collections/junos-xml-ref-oper/index.html  (Junos 12.3) # noqa
        lldp_table.GET_RPC = 'get-lldp-interface-neighbors'
        if self.device.facts.get('personality') not in ('MX', 'M', 'T'):
            lldp_table.GET_RPC = 'get-lldp-interface-neighbors-information'

        for interface in interfaces:
            if self.device.facts.get('personality') not in ('MX', 'M', 'T'):
                lldp_table.get(interface_name=interface)
            else:
                lldp_table.get(interface_device=interface)
            for item in lldp_table:
                if interface not in lldp_neighbors.keys():
                    lldp_neighbors[interface] = []
                lldp_neighbors[interface].append({
                    'parent_interface': item.parent_interface,
                    'remote_port': item.remote_port,
                    'remote_chassis_id': napalm_base.helpers.convert(
                        napalm_base.helpers.mac, item.remote_chassis_id, item.remote_chassis_id),
                    'remote_port_description': napalm_base.helpers.convert(
                        py23_compat.text_type, item.remote_port_description),
                    'remote_system_name': item.remote_system_name,
                    'remote_system_description': item.remote_system_description,
                    'remote_system_capab': item.remote_system_capab,
                    'remote_system_enable_capab': item.remote_system_enable_capab
                })

        return lldp_neighbors


Instruction:
Make a summary of the following Python 3 code
def get_arp_table(self):
        # could use ArpTable
        # from jnpr.junos.op.phyport import ArpTable
        # and simply use it
        # but
        # we need:
        #   - filters
        #   - group by VLAN ID
        #   - hostname & TTE fields as well

        arp_table = []

        arp_table_raw = junos_views.junos_arp_table(self.device)
        arp_table_raw.get()
        arp_table_items = arp_table_raw.items()

        for arp_table_entry in arp_table_items:
            arp_entry = {
                elem[0]: elem[1] for elem in arp_table_entry[1]
            }
            arp_entry['mac'] = napalm_base.helpers.mac(arp_entry.get('mac'))
            arp_entry['ip'] = napalm_base.helpers.ip(arp_entry.get('ip'))
            arp_table.append(arp_entry)

        return arp_table

Response: Return the ARP table.


Instruction:
Create a Python 3 function to
return the NTP peers configured on the device.

Response:
def get_ntp_peers(self):
        """Return the NTP peers configured on the device."""
        ntp_table = junos_views.junos_ntp_peers_config_table(self.device)
        ntp_table.get()

        ntp_peers = ntp_table.items()

        if not ntp_peers:
            return {}

        return {napalm_base.helpers.ip(peer[0]): {} for peer in ntp_peers}


Instruction:
Write a Python 3 script to
return the NTP servers configured on the device.

Response:
def get_ntp_servers(self):
        """Return the NTP servers configured on the device."""
        ntp_table = junos_views.junos_ntp_servers_config_table(self.device)
        ntp_table.get()

        ntp_servers = ntp_table.items()

        if not ntp_servers:
            return {}

        return {napalm_base.helpers.ip(server[0]): {} for server in ntp_servers}


Instruction:
Create a Python 3 function to
return NTP stats (associations).

Response:
def get_ntp_stats(self):
        """Return NTP stats (associations)."""
        # NTP Peers does not have XML RPC defined
        # thus we need to retrieve raw text and parse...
        # :(

        ntp_stats = []

        REGEX = (
            '^\s?(\+|\*|x|-)?([a-zA-Z0-9\.+-:]+)'
            '\s+([a-zA-Z0-9\.]+)\s+([0-9]{1,2})'
            '\s+(-|u)\s+([0-9h-]+)\s+([0-9]+)'
            '\s+([0-9]+)\s+([0-9\.]+)\s+([0-9\.-]+)'
            '\s+([0-9\.]+)\s?$'
        )

        ntp_assoc_output = self.device.cli('show ntp associations no-resolve')
        ntp_assoc_output_lines = ntp_assoc_output.splitlines()

        for ntp_assoc_output_line in ntp_assoc_output_lines[3:]:  # except last line
            line_search = re.search(REGEX, ntp_assoc_output_line, re.I)
            if not line_search:
                continue  # pattern not found
            line_groups = line_search.groups()
            try:
                ntp_stats.append({
                    'remote': napalm_base.helpers.ip(line_groups[1]),
                    'synchronized': (line_groups[0] == '*'),
                    'referenceid': py23_compat.text_type(line_groups[2]),
                    'stratum': int(line_groups[3]),
                    'type': py23_compat.text_type(line_groups[4]),
                    'when': py23_compat.text_type(line_groups[5]),
                    'hostpoll': int(line_groups[6]),
                    'reachability': int(line_groups[7]),
                    'delay': float(line_groups[8]),
                    'offset': float(line_groups[9]),
                    'jitter': float(line_groups[10])
                })
            except Exception:
                continue  # jump to next line

        return ntp_stats


Instruction:
Can you write a function in Python 3 where it
returns the MAC address table.

Response:
def get_mac_address_table(self):
        """Return the MAC address table."""
        mac_address_table = []

        if self.device.facts.get('personality', '') in ['SWITCH']:  # for EX & QFX devices
            if self.device.facts.get('switch_style', '') in ['VLAN_L2NG']:  # for L2NG devices
                mac_table = junos_views.junos_mac_address_table_switch_l2ng(self.device)
            else:
                mac_table = junos_views.junos_mac_address_table_switch(self.device)
        else:
            mac_table = junos_views.junos_mac_address_table(self.device)

        mac_table.get()
        mac_table_items = mac_table.items()

        default_values = {
            'mac': u'',
            'interface': u'',
            'vlan': 0,
            'static': False,
            'active': True,
            'moves': 0,
            'last_move': 0.0
        }

        for mac_table_entry in mac_table_items:
            mac_entry = default_values.copy()
            mac_entry.update(
                {elem[0]: elem[1] for elem in mac_table_entry[1]}
            )
            mac = mac_entry.get('mac')

            # JUNOS returns '*' for Type = Flood
            if mac == '*':
                continue

            mac_entry['mac'] = napalm_base.helpers.mac(mac)
            mac_address_table.append(mac_entry)

        return mac_address_table


Instruction:
Here you have a function in Python 3, explain what it does
def get_probes_config(self):
        probes = {}

        probes_table = junos_views.junos_rpm_probes_config_table(self.device)
        probes_table.get()
        probes_table_items = probes_table.items()

        for probe_test in probes_table_items:
            test_name = py23_compat.text_type(probe_test[0])
            test_details = {
                p[0]: p[1] for p in probe_test[1]
            }
            probe_name = napalm_base.helpers.convert(
                py23_compat.text_type, test_details.pop('probe_name'))
            target = napalm_base.helpers.convert(
                py23_compat.text_type, test_details.pop('target', ''))
            test_interval = napalm_base.helpers.convert(int, test_details.pop('test_interval', '0'))
            probe_count = napalm_base.helpers.convert(int, test_details.pop('probe_count', '0'))
            probe_type = napalm_base.helpers.convert(
                py23_compat.text_type, test_details.pop('probe_type', ''))
            source = napalm_base.helpers.convert(
                py23_compat.text_type, test_details.pop('source_address', ''))
            if probe_name not in probes.keys():
                probes[probe_name] = {}
            probes[probe_name][test_name] = {
                'probe_type': probe_type,
                'target': target,
                'source': source,
                'probe_count': probe_count,
                'test_interval': test_interval
            }

        return probes

Response: Return the configuration of the RPM probes.


Instruction:
Can you implement a function in Python 3 that
returns the results of the RPM probes.

Response:
def get_probes_results(self):
        """Return the results of the RPM probes."""
        probes_results = {}

        probes_results_table = junos_views.junos_rpm_probes_results_table(self.device)
        probes_results_table.get()
        probes_results_items = probes_results_table.items()

        for probe_result in probes_results_items:
            probe_name = py23_compat.text_type(probe_result[0])
            test_results = {
                p[0]: p[1] for p in probe_result[1]
            }
            test_results['last_test_loss'] = napalm_base.helpers.convert(
                int, test_results.pop('last_test_loss'), 0)
            for test_param_name, test_param_value in test_results.items():
                if isinstance(test_param_value, float):
                    test_results[test_param_name] = test_param_value * 1e-3
                    # convert from useconds to mseconds
            test_name = test_results.pop('test_name', '')
            source = test_results.get('source', u'')
            if source is None:
                test_results['source'] = u''
            if probe_name not in probes_results.keys():
                probes_results[probe_name] = {}
            probes_results[probe_name][test_name] = test_results

        return probes_results


Instruction:
Can you generate the documentation for the following Python 3 function
def traceroute(self,
                   destination,
                   source=C.TRACEROUTE_SOURCE,
                   ttl=C.TRACEROUTE_TTL,
                   timeout=C.TRACEROUTE_TIMEOUT,
                   vrf=C.TRACEROUTE_VRF):
        """Execute traceroute and return results."""
        traceroute_result = {}

        # calling form RPC does not work properly :(
        # but defined junos_route_instance_table just in case

        source_str = ''
        maxttl_str = ''
        wait_str = ''
        vrf_str = ''

        if source:
            source_str = ' source {source}'.format(source=source)
        if ttl:
            maxttl_str = ' ttl {ttl}'.format(ttl=ttl)
        if timeout:
            wait_str = ' wait {timeout}'.format(timeout=timeout)
        if vrf:
            vrf_str = ' routing-instance {vrf}'.format(vrf=vrf)

        traceroute_command = 'traceroute {destination}{source}{maxttl}{wait}{vrf}'.format(
            destination=destination,
            source=source_str,
            maxttl=maxttl_str,
            wait=wait_str,
            vrf=vrf_str
        )

        traceroute_rpc = E('command', traceroute_command)
        rpc_reply = self.device._conn.rpc(traceroute_rpc)._NCElement__doc
        # make direct RPC call via NETCONF
        traceroute_results = rpc_reply.find('.//traceroute-results')

        traceroute_failure = napalm_base.helpers.find_txt(
            traceroute_results, 'traceroute-failure', '')
        error_message = napalm_base.helpers.find_txt(
            traceroute_results, 'rpc-error/error-message', '')

        if traceroute_failure and error_message:
            return {'error': '{}: {}'.format(traceroute_failure, error_message)}

        traceroute_result['success'] = {}
        for hop in traceroute_results.findall('hop'):
            ttl_value = napalm_base.helpers.convert(
                int, napalm_base.helpers.find_txt(hop, 'ttl-value'), 1)
            if ttl_value not in traceroute_result['success']:
                traceroute_result['success'][ttl_value] = {'probes': {}}
            for probe in hop.findall('probe-result'):
                probe_index = napalm_base.helpers.convert(
                    int, napalm_base.helpers.find_txt(probe, 'probe-index'), 0)
                ip_address = napalm_base.helpers.convert(
                    napalm_base.helpers.ip, napalm_base.helpers.find_txt(probe, 'ip-address'), '*')
                host_name = py23_compat.text_type(
                    napalm_base.helpers.find_txt(probe, 'host-name', '*'))
                rtt = napalm_base.helpers.convert(
                    float, napalm_base.helpers.find_txt(probe, 'rtt'), 0) * 1e-3  # ms
                traceroute_result['success'][ttl_value]['probes'][probe_index] = {
                    'ip_address': ip_address,
                    'host_name': host_name,
                    'rtt': rtt
                }

        return traceroute_result

Response: Execute a traceroute and return the result.


Instruction:
Write a Python 3 function that can
parse a single entry from show interfaces output.

Response:
def parse_intf_section(interface):
    """Parse a single entry from show interfaces output.

    Different cases:
    mgmt0 is up
    admin state is up

    Ethernet2/1 is up
    admin state is up, Dedicated Interface

    Vlan1 is down (Administratively down), line protocol is down, autostate enabled

    Ethernet154/1/48 is up (with no 'admin state')
    """
    interface = interface.strip()
    re_protocol = r"^(?P<intf_name>\S+?)\s+is\s+(?P<status>.+?)" \
                  r",\s+line\s+protocol\s+is\s+(?P<protocol>\S+).*$"
    re_intf_name_state = r"^(?P<intf_name>\S+) is (?P<intf_state>\S+).*"
    re_is_enabled_1 = r"^admin state is (?P<is_enabled>\S+)$"
    re_is_enabled_2 = r"^admin state is (?P<is_enabled>\S+), "
    re_is_enabled_3 = r"^.* is down.*Administratively down.*$"
    re_mac = r"^\s+Hardware.*address:\s+(?P<mac_address>\S+) "
    re_speed = r"^\s+MTU .*, BW (?P<speed>\S+) (?P<speed_unit>\S+), "
    re_description = r"^\s+Description:\s+(?P<description>.*)$"

    # Check for 'protocol is ' lines
    match = re.search(re_protocol, interface, flags=re.M)
    if match:
        intf_name = match.group('intf_name')
        status = match.group('status')
        protocol = match.group('protocol')

        if 'admin' in status.lower():
            is_enabled = False
        else:
            is_enabled = True
        is_up = bool('up' in protocol)

    else:
        # More standard is up, next line admin state is lines
        match = re.search(re_intf_name_state, interface)
        intf_name = match.group('intf_name')
        intf_state = match.group('intf_state').strip()
        is_up = True if intf_state == 'up' else False

        admin_state_present = re.search("admin state is", interface)
        if admin_state_present:
            # Parse cases where 'admin state' string exists
            for x_pattern in [re_is_enabled_1, re_is_enabled_2]:
                match = re.search(x_pattern, interface, flags=re.M)
                if match:
                    is_enabled = match.group('is_enabled').strip()
                    is_enabled = True if is_enabled == 'up' else False
                    break
            else:
                msg = "Error parsing intf, 'admin state' never detected:\n\n{}".format(interface)
                raise ValueError(msg)
        else:
            # No 'admin state' should be 'is up' or 'is down' strings
            # If interface is up; it is enabled
            is_enabled = True
            if not is_up:
                match = re.search(re_is_enabled_3, interface, flags=re.M)
                if match:
                    is_enabled = False

    match = re.search(re_mac, interface, flags=re.M)
    if match:
        mac_address = match.group('mac_address')
        mac_address = napalm_base.helpers.mac(mac_address)
    else:
        mac_address = ""

    match = re.search(re_speed, interface, flags=re.M)
    speed = int(match.group('speed'))
    speed_unit = match.group('speed_unit')
    # This was alway in Kbit (in the data I saw)
    if speed_unit != "Kbit":
        msg = "Unexpected speed unit in show interfaces parsing:\n\n{}".format(interface)
        raise ValueError(msg)
    speed = int(round(speed / 1000.0))

    description = ''
    match = re.search(re_description, interface, flags=re.M)
    if match:
        description = match.group('description')

    return {
             intf_name: {
                    'description': description,
                    'is_enabled': is_enabled,
                    'is_up': is_up,
                    'last_flapped': -1.0,
                    'mac_address': mac_address,
                    'speed': speed}
           }


Instruction:
Explain what the following Python 3 code does
def _get_diff(self):
        diff = []
        self._create_sot_file()
        command = ('show diff rollback-patch file {0} file {1}'.format(
                   'sot_file', self.replace_file.split('/')[-1]))
        diff_out = self.device.send_command(command)
        try:
            diff_out = diff_out.split(
                '#Generating Rollback Patch')[1].replace(
                    'Rollback Patch is Empty', '').strip()
            for line in diff_out.splitlines():
                if line:
                    if line[0].strip() != '!' and line[0].strip() != '.':
                        diff.append(line.rstrip(' '))
        except (AttributeError, KeyError):
            raise ReplaceConfigException(
                'Could not calculate diff. It\'s possible the given file doesn\'t exist.')
        return '\n'.join(diff)

Response: Get a diff between running config and a proposed file.


Instruction:
Make a summary of the following Python 3 code
def _save_to_checkpoint(self, filename):
        command = 'checkpoint file {}'.format(filename)
        self.device.send_command(command)

Response: Save the current running config to the given file.


Instruction:
Write a Python 3 script to
return a set of facts from the devices.

Response:
def get_facts(self):
        """Return a set of facts from the devices."""
        # default values.
        vendor = u'Cisco'
        uptime = -1
        serial_number, fqdn, os_version, hostname, domain_name = ('',) * 5

        # obtain output from device
        show_ver = self.device.send_command('show version')
        show_hosts = self.device.send_command('show hosts')
        show_int_status = self.device.send_command('show interface status')
        show_hostname = self.device.send_command('show hostname')

        # uptime/serial_number/IOS version
        for line in show_ver.splitlines():
            if ' uptime is ' in line:
                _, uptime_str = line.split(' uptime is ')
                uptime = self.parse_uptime(uptime_str)

            if 'Processor Board ID' in line:
                _, serial_number = line.split("Processor Board ID ")
                serial_number = serial_number.strip()

            if 'system: ' in line:
                line = line.strip()
                os_version = line.split()[2]
                os_version = os_version.strip()

            if 'cisco' in line and 'Chassis' in line:
                _, model = line.split()[:2]
                model = model.strip()

        hostname = show_hostname.strip()

        # Determine domain_name and fqdn
        for line in show_hosts.splitlines():
            if 'Default domain' in line:
                _, domain_name = re.split(r".*Default domain.*is ", line)
                domain_name = domain_name.strip()
                break
        if hostname.count(".") >= 2:
            fqdn = hostname
        elif domain_name:
            fqdn = '{}.{}'.format(hostname, domain_name)

        # interface_list filter
        interface_list = []
        show_int_status = show_int_status.strip()
        for line in show_int_status.splitlines():
            if line.startswith(' ') or line.startswith('-') or line.startswith('Port '):
                continue
            interface = line.split()[0]
            interface_list.append(interface)

        return {
            'uptime': int(uptime),
            'vendor': vendor,
            'os_version': py23_compat.text_type(os_version),
            'serial_number': py23_compat.text_type(serial_number),
            'model': py23_compat.text_type(model),
            'hostname': py23_compat.text_type(hostname),
            'fqdn': fqdn,
            'interface_list': interface_list
        }


Instruction:
Write a Python 3 script for
getting arp table information.

Response:
def get_arp_table(self):
        """
        Get arp table information.

        Return a list of dictionaries having the following set of keys:
            * interface (string)
            * mac (string)
            * ip (string)
            * age (float)

        For example::
            [
                {
                    'interface' : 'MgmtEth0/RSP0/CPU0/0',
                    'mac'       : '5c:5e:ab:da:3c:f0',
                    'ip'        : '172.17.17.1',
                    'age'       : 12.0
                },
                {
                    'interface': 'MgmtEth0/RSP0/CPU0/0',
                    'mac'       : '66:0e:94:96:e0:ff',
                    'ip'        : '172.17.17.2',
                    'age'       : 14.0
                }
            ]
        """
        arp_table = []

        command = 'show ip arp vrf default | exc INCOMPLETE'
        output = self.device.send_command(command)

        separator = r"^Address\s+Age.*Interface.*$"
        arp_list = re.split(separator, output, flags=re.M)
        if len(arp_list) != 2:
            raise ValueError("Error processing arp table output:\n\n{}".format(output))

        arp_entries = arp_list[1].strip()
        for line in arp_entries.splitlines():
            if len(line.split()) == 4:
                address, age, mac, interface = line.split()
            else:
                raise ValueError("Unexpected output from: {}".format(line.split()))

            if age == '-':
                age = -1.0
            elif ':' not in age:
                # Cisco sometimes returns a sub second arp time 0.411797
                try:
                    age = float(age)
                except ValueError:
                    age = -1.0
            else:
                age = convert_hhmmss(age)
                age = float(age)
            age = round(age, 1)

            # Validate we matched correctly
            if not re.search(RE_IPADDR, address):
                raise ValueError("Invalid IP Address detected: {}".format(address))
            if not re.search(RE_MAC, mac):
                raise ValueError("Invalid MAC Address detected: {}".format(mac))
            entry = {
                'interface': interface,
                'mac': napalm_base.helpers.mac(mac),
                'ip': address,
                'age': age
            }
            arp_table.append(entry)
        return arp_table


Instruction:
How would you explain what the following Python 3 function does
def get(self, request, format=None):
        tokens = Token.objects.filter(user=request.user)
        for token in tokens:
            token.delete()
        content = {'success': _('User logged out.')}
        return Response(content, status=status.HTTP_200_OK)

Response: Remove all auth tokens owned by request. user.


Instruction:
How would you implement a function in Python 3 that
sets attributes to values so can access via dot notation.

Response:
def _set_attrs_to_values(self, response={}):
        """
        Set attributes to dictionary values so can access via dot notation.
        """
        for key in response.keys():
            setattr(self, key, response[key])


Instruction:
Write a Python 3 function for
adding a custom filter nl2br to jinja2 Replaces all newline to <BR >

Response:
def add_custom_nl2br_filters(self, app):
        """Add a custom filter nl2br to jinja2
         Replaces all newline to

        """
        _paragraph_re = re.compile(r'(?:\r\n|\r|\n){3,}')

        @app.template_filter()
        @evalcontextfilter
        def nl2br(eval_ctx, value):
            result = '\n\n'.join('%s' % p.replace('\n', '
\n')
                                 for p in _paragraph_re.split(value))
            return result


Instruction:
Write a Python 3 script for
adding flask route to automatic documentation for automatic documentation.

Response:
def doc(self, groups=None, set_location=True, **properties):
        """Add flask route to autodoc for automatic documentation

        Any route decorated with this method will be added to the list of
        routes to be documented by the generate() or html() methods.

        By default, the route is added to the 'all' group.
        By specifying group or groups argument, the route can be added to one
        or multiple other groups as well, besides the 'all' group.

        If set_location is True, the location of the function will be stored.
        NOTE: this assumes that the decorator is placed just before the
        function (in the normal way).

        Custom parameters may also be passed in beyond groups, if they are
        named something not already in the dict descibed in the docstring for
        the generare() function, they will be added to the route's properties,
        which can be accessed from the template.

        If a parameter is passed in with a name that is already in the dict, but
        not of a reserved name, the passed parameter overrides that dict value.
        """
        def decorator(f):
            # Get previous group list (if any)
            if f in self.func_groups:
                groupset = self.func_groups[f]
            else:
                groupset = set()

            # Set group[s]
            if type(groups) is list:
                groupset.update(groups)
            elif type(groups) is str:
                groupset.add(groups)
            groupset.add('all')
            self.func_groups[f] = groupset
            self.func_props[f] = properties

            # Set location
            if set_location:
                caller_frame = inspect.stack()[1]
                self.func_locations[f] = {
                        'filename': caller_frame[1],
                        'line':     caller_frame[2],
                        }

            return f
        return decorator


Instruction:
Can you tell what is the following Python 3 function doing
def generate(self, groups='all', sort=None):
        groups_to_generate = list()
        if type(groups) is list:
            groups_to_generate = groups
        elif type(groups) is str:
            groups_to_generate.append(groups)

        links = []
        for rule in current_app.url_map.iter_rules():

            if rule.endpoint == 'static':
                continue

            func = current_app.view_functions[rule.endpoint]
            arguments = rule.arguments if rule.arguments else ['None']
            func_groups = self.func_groups[func]
            func_props = self.func_props[func] if func in self.func_props \
                else {}
            location = self.func_locations.get(func, None)

            if func_groups.intersection(groups_to_generate):
                props = dict(
                    methods=rule.methods,
                    rule="%s" % rule,
                    endpoint=rule.endpoint,
                    docstring=func.__doc__,
                    args=arguments,
                    defaults=rule.defaults,
                    location=location,
                )
                for p in func_props:
                    if p not in self.immutable_props:
                        props[p] = func_props[p]
                links.append(props)
        if sort:
            return sort(links)
        else:
            return sorted(links, key=itemgetter('rule'))

Response: Generate a list of routes that are defined by the current application.


Instruction:
Can you tell what is the following Python 3 function doing
def html(self, groups='all', template=None, **context):
        context['autodoc'] = context['autodoc'] if 'autodoc' in context \
            else self.generate(groups=groups)
        context['defaults'] = context['defaults'] if 'defaults' in context \
            else self.default_props
        if template:
            return render_template(template, **context)
        else:
            filename = os.path.join(
                os.path.dirname(__file__),
                'templates',
                'autodoc_default.html'
            )
            with open(filename) as file:
                content = file.read()
                with current_app.app_context():
                    return render_template_string(content, **context)

Response: Returns an html string of the routes specified by the doc method.


Instruction:
Implement a function in Python 3 to
return True if OK to continue with close or quit or whatever

Response:
def unsaved_files_dialog(
            self, all_files=False, with_cancel=True, with_discard=True):
        """Return true if OK to continue with close or quit or whatever"""
        for image in self.images:
            if image.metadata.changed() and (all_files or image.selected):
                break
        else:
            return True
        dialog = QtWidgets.QMessageBox()
        dialog.setWindowTitle(self.tr('Photini: unsaved data'))
        dialog.setText(self.tr('
Some images have unsaved metadata.
'))
        dialog.setInformativeText(self.tr('Do you want to save your changes?'))
        dialog.setIcon(QtWidgets.QMessageBox.Warning)
        buttons = QtWidgets.QMessageBox.Save
        if with_cancel:
            buttons |= QtWidgets.QMessageBox.Cancel
        if with_discard:
            buttons |= QtWidgets.QMessageBox.Discard
        dialog.setStandardButtons(buttons)
        dialog.setDefaultButton(QtWidgets.QMessageBox.Save)
        result = dialog.exec_()
        if result == QtWidgets.QMessageBox.Save:
            self._save_files()
            return True
        return result == QtWidgets.QMessageBox.Discard


Instruction:
Can you tell what is the following Python 3 function doing
def from_ISO_8601(cls, date_string, time_string, tz_string):
        # parse tz_string
        if tz_string:
            tz_offset = (int(tz_string[1:3]) * 60) + int(tz_string[3:])
            if tz_string[0] == '-':
                tz_offset = -tz_offset
        else:
            tz_offset = None
        if time_string == '000000':
            # assume no time information
            time_string = ''
            tz_offset = None
        datetime_string = date_string + time_string[:13]
        precision = min((len(datetime_string) - 2) // 2, 7)
        if precision <= 0:
            return None
        fmt = ''.join(('%Y', '%m', '%d', '%H', '%M', '%S', '.%f')[:precision])
        return cls(
            (datetime.strptime(datetime_string, fmt), precision, tz_offset))

Response: Sufficiently general ISO 8601 parser.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def post_post():
    authorid = request.form.get('authorid', None)
    Post(request.form['title'],
         request.form['content'],
         users[authorid])
    return redirect("/posts")

Response: Create a new post.


Instruction:
How would you implement a function in Python 3 that
finds another node by XPath originating at the current node.

Response:
def xpath(self, xpath):
    """ Finds another node by XPath originating at the current node. """
    return [self.get_node_factory().create(node_id)
            for node_id in self._get_xpath_ids(xpath).split(",")
            if node_id]


Instruction:
Can you generate the documentation for the following Python 3 function
def css(self, css):
    return [self.get_node_factory().create(node_id)
            for node_id in self._get_css_ids(css).split(",")
            if node_id]

Response: Finds another node by a CSS selector relative to the current node.


Instruction:
How would you code a function in Python 3 to
return the value of a boolean HTML attribute like checked or disabled.

Response:
def get_bool_attr(self, name):
    """ Returns the value of a boolean HTML attribute like `checked` or `disabled`
    """
    val = self.get_attr(name)
    return val is not None and val.lower() in ("true", name)


Instruction:
Implement a function in Python 3 to
set the value of an attribute.

Response:
def set_attr(self, name, value):
    """ Sets the value of an attribute. """
    self.exec_script("node.setAttribute(%s, %s)" % (repr(name), repr(value)))


Instruction:
Write a Python 3 script to
return the node s value.

Response:
def value(self):
    """ Returns the node's value. """
    if self.is_multi_select():
      return [opt.value()
              for opt in self.xpath(".//option")
              if opt["selected"]]
    else:
      return self._invoke("value")


Instruction:
Can you generate a brief explanation for the following Python 3 code
def set_header(self, key, value):
    self.conn.issue_command("Header", _normalize_header(key), value)

Response: Sets a HTTP header for future requests.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def headers(self):
    headers = self.conn.issue_command("Headers")
    res = []
    for header in headers.split("\r"):
      key, value = header.split(": ", 1)
      for line in value.split("\n"):
        res.append((_normalize_header(key), line))
    return res

Response: Returns a list of the last HTTP response headers.


Instruction:
Write a Python 3 script to
evaluate a piece of Javascript in the current page and returns its value.

Response:
def eval_script(self, expr):
    """ Evaluates a piece of Javascript in the context of the current page and
    returns its value. """
    ret = self.conn.issue_command("Evaluate", expr)
    return json.loads("[%s]" % ret)[0]


Instruction:
Here you have a function in Python 3, explain what it does
def render(self, path, width = 1024, height = 1024):
    self.conn.issue_command("Render", path, width, height)

Response: Renders the current page to a PNG file.


Instruction:
Can you create a Python 3 function that
returns a list of all cookies in cookie string format.

Response:
def cookies(self):
    """ Returns a list of all cookies in cookie string format. """
    return [line.strip()
            for line in self.conn.issue_command("GetCookies").split("\n")
            if line.strip()]


Instruction:
Write a Python 3 function that can
set a custom attribute for our Webkit instance.

Response:
def set_attribute(self, attr, value = True):
    """ Sets a custom attribute for our Webkit instance. Possible attributes are:

      * ``auto_load_images``
      * ``dns_prefetch_enabled``
      * ``plugins_enabled``
      * ``private_browsing_enabled``
      * ``javascript_can_open_windows``
      * ``javascript_can_access_clipboard``
      * ``offline_storage_database_enabled``
      * ``offline_web_application_cache_enabled``
      * ``local_storage_enabled``
      * ``local_storage_database_enabled``
      * ``local_content_can_access_remote_urls``
      * ``local_content_can_access_file_urls``
      * ``accelerated_compositing_enabled``
      * ``site_specific_quirks_enabled``

    For all those options, ``value`` must be a boolean. You can find more
    information about these options `in the QT docs
    <http://developer.qt.nokia.com/doc/qt-4.8/qwebsettings.html#WebAttribute-enum>`_.
    """
    value = "true" if value else "false"
    self.conn.issue_command("SetAttribute",
                            self._normalize_attr(attr),
                            value)


Instruction:
Can you create a Python 3 function that
sets custom HTML in our Webkit session and allows to specify a fake URL.

Response:
def set_html(self, html, url = None):
    """ Sets custom HTML in our Webkit session and allows to specify a fake URL.
    Scripts and CSS is dynamically fetched as if the HTML had been loaded from
    the given URL. """
    if url:
      self.conn.issue_command('SetHtml', html, url)
    else:
      self.conn.issue_command('SetHtml', html)


Instruction:
Write a Python 3 function for
setting a custom HTTP proxy to use for future requests.

Response:
def set_proxy(self, host     = "localhost",
                      port     = 0,
                      user     = "",
                      password = ""):
    """ Sets a custom HTTP proxy to use for future requests. """
    self.conn.issue_command("SetProxy", host, port, user, password)


Instruction:
Can you write a function in Python 3 where it
returns a new socket connection to this server.

Response:
def connect(self):
    """ Returns a new socket connection to this server. """
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect(("127.0.0.1", self._port))
    return sock


Instruction:
How would you implement a function in Python 3 that
consumes one line from the stream.

Response:
def read_line(self):
    """ Consume one line from the stream. """
    while True:
      newline_idx = self.buf.find(b"\n")
      if newline_idx >= 0:
        res = self.buf[:newline_idx]
        self.buf = self.buf[newline_idx + 1:]
        return res
      chunk = self.f.recv(4096)
      if not chunk:
        raise EndOfStreamError()
      self.buf += chunk


Instruction:
Can you generate the documentation for the following Python 3 function
def read(self, n):
    while len(self.buf) < n:
      chunk = self.f.recv(4096)
      if not chunk:
        raise EndOfStreamError()
      self.buf += chunk
    res, self.buf = self.buf[:n], self.buf[n:]
    return res

Response: Consume n characters from the stream.


Instruction:
Create a Python 3 function to
issue a command to the server.

Response:
def issue_command(self, cmd, *args):
    """ Sends and receives a message to/from the server """
    self._writeline(cmd)
    self._writeline(str(len(args)))
    for arg in args:
      arg = str(arg)
      self._writeline(str(len(arg)))
      self._sock.sendall(arg.encode("utf-8"))

    return self._read_response()


Instruction:
Can you create a Python 3 function that
reads a complete response packet from the server.

Response:
def _read_response(self):
    """ Reads a complete response packet from the server """
    result = self.buf.read_line().decode("utf-8")
    if not result:
      raise NoResponseError("No response received from server.")

    msg = self._read_message()
    if result != "ok":
      raise InvalidResponseError(msg)

    return msg


Instruction:
Can you tell what is the following Python 3 function doing
def _read_message(self):
    size = int(self.buf.read_line().decode("utf-8"))
    return self.buf.read(size).decode("utf-8")

Response: Reads a single message from the server


Instruction:
Can you create a Python 3 function that
gets updated property details for a given zpid

Response:
def get_updated_property_details(self, zpid):
        """
        GetUpdatedPropertyDetails API
        """
        url = 'http://www.zillow.com/webservice/GetUpdatedPropertyDetails.htm'

        params = {
            'zpid': zpid,
            'zws-id': self.api_key
        }
        return self.get_data(url, params)


Instruction:
How would you code a function in Python 3 to
fix the orientation of an image.

Response:
def fix_orientation(img, save_over=False):
    """
    `img` can be an Image instance or a path to an image file.
    `save_over` indicates if the original image file should be replaced by the new image.
    * Note: `save_over` is only valid if `img` is a file path.
    """
    path = None
    if not isinstance(img, Image.Image):
        path = img
        img = Image.open(path)
    elif save_over:
        raise ValueError("You can't use `save_over` when passing an Image instance.  Use a file path instead.")
    try:
        orientation = img._getexif()[EXIF_ORIENTATION_TAG]
    except (TypeError, AttributeError, KeyError):
        raise ValueError("Image file has no EXIF data.")
    if orientation in [3,6,8]:
        degrees = ORIENTATIONS[orientation][1]
        img = img.transpose(degrees)
        if save_over and path is not None:
            try:
                img.save(path, quality=95, optimize=1)
            except IOError:
                # Try again, without optimization (PIL can't optimize an image
                # larger than ImageFile.MAXBLOCK, which is 64k by default).
                # Setting ImageFile.MAXBLOCK should fix this....but who knows.
                img.save(path, quality=95)
        return (img, degrees)
    else:
        return (img, 0)


Instruction:
Implement a function in Python 3 to
add an error message and optional user message to the error list

Response:
def log_error(self, error, message, detail=None, strip=4):
        "Add an error message and optional user message to the error list"
        if message:
            msg = message + ": " + error
        else:
            msg = error

        tb = traceback.format_stack()
        if sys.version_info >= (3, 0):
            tb = tb[:-strip]
        else:
            tb = tb[strip:]

        self.errors.append({
            'message': msg,
            'traceback': tb,
            'detail': detail
        })


Instruction:
Create a Python 3 function to
check if two values are equal

Response:
def equal(self, a, b, message=None):
        "Check if two values are equal"
        if a != b:
            self.log_error("{} != {}".format(str(a), str(b)), message)
            return False
        return True


Instruction:
Can you write a function in Python 3 where it
checks if a value is not None

Response:
def is_not_none(self, a, message=None):
        "Check if a value is not None"
        if a is None:
            self.log_error("{} is None".format(str(a)), message)
            return False
        return True


Instruction:
Create a Python 3 function for
checking if a function raises an exception type

Response:
def raises(self, exception_type, function, *args, **kwargs):
        """
            Check if a function raises a specified exception type,
            *args and **kwargs are forwarded to the function
        """
        try:
            result = function(*args, **kwargs)
            self.log_error("{} did not throw exception {}".format(
                function.__name__,
                exception_type.__name__
            ), None)
            return result
        except Exception as e:
            if type(e) != exception_type:
                self.log_error("{} did raise {}: {}".format(
                    function.__name__,
                    type(e).__name__, e
                ), None)


Instruction:
How would you code a function in Python 3 to
check if a function does not raise an exception

Response:
def does_not_raise(self, function, *args, **kwargs):
        """
            Check if a function does not raise an exception,
            *args and **kwargs are forwarded to the function
        """
        try:
            return function(*args, **kwargs)
        except Exception as e:
            self.log_error("{} did raise {}: {}".format(
                function.__name__,
                type(e).__name__, e
            ), None)


Instruction:
Implement a Python 3 function for
converting the raw R G B values to color temperature in degrees Kelvin.

Response:
def calculate_color_temperature(r, g, b):
    """Converts the raw R/G/B values to color temperature in degrees Kelvin."""
    # 1. Map RGB values to their XYZ counterparts.
    # Based on 6500K fluorescent, 3000K fluorescent
    # and 60W incandescent values for a wide range.
    # Note: Y = Illuminance or lux
    X = (-0.14282 * r) + (1.54924 * g) + (-0.95641 * b)
    Y = (-0.32466 * r) + (1.57837 * g) + (-0.73191 * b)
    Z = (-0.68202 * r) + (0.77073 * g) + ( 0.56332 * b)
    # Check for divide by 0 (total darkness) and return None.
    if (X + Y + Z) == 0:
        return None
    # 2. Calculate the chromaticity co-ordinates
    xc = (X) / (X + Y + Z)
    yc = (Y) / (X + Y + Z)
    # Check for divide by 0 again and return None.
    if (0.1858 - yc) == 0:
        return None
    # 3. Use McCamy's formula to determine the CCT
    n = (xc - 0.3320) / (0.1858 - yc)
    # Calculate the final CCT
    cct = (449.0 * (n ** 3.0)) + (3525.0 *(n ** 2.0)) + (6823.3 * n) + 5520.33
    return int(cct)


Instruction:
Make a summary of the following Python 3 code
def calculate_lux(r, g, b):
    illuminance = (-0.32466 * r) + (1.57837 * g) + (-0.73191 * b)
    return int(illuminance)

Response: Converts the raw R G B values to luminosity in lux.


Instruction:
Explain what the following Python 3 code does
def _write8(self, reg, value):
        self._device.write8(TCS34725_COMMAND_BIT | reg, value)

Response: Write an 8 - bit value to a register.


Instruction:
Write a Python 3 script to
disable the chip (power down).

Response:
def disable(self):
        """Disable the chip (power down)."""
        # Flip off the power on and enable bits.
        reg = self._readU8(TCS34725_ENABLE)
        reg &= ~(TCS34725_ENABLE_PON | TCS34725_ENABLE_AEN)
        self._write8(TCS34725_ENABLE, reg)


Instruction:
Create a Python 3 function for
setting the integration time for the TC34725.

Response:
def set_integration_time(self, integration_time):
        """Sets the integration time for the TC34725.  Provide one of these
        constants:
         - TCS34725_INTEGRATIONTIME_2_4MS  = 2.4ms - 1 cycle    - Max Count: 1024
         - TCS34725_INTEGRATIONTIME_24MS   = 24ms  - 10 cycles  - Max Count: 10240
         - TCS34725_INTEGRATIONTIME_50MS   = 50ms  - 20 cycles  - Max Count: 20480
         - TCS34725_INTEGRATIONTIME_101MS  = 101ms - 42 cycles  - Max Count: 43008
         - TCS34725_INTEGRATIONTIME_154MS  = 154ms - 64 cycles  - Max Count: 65535
         - TCS34725_INTEGRATIONTIME_700MS  = 700ms - 256 cycles - Max Count: 65535
        """
        self._integration_time = integration_time
        self._write8(TCS34725_ATIME, integration_time)


Instruction:
Make a summary of the following Python 3 code
def set_interrupt(self, enabled):
        enable_reg = self._readU8(TCS34725_ENABLE)
        if enabled:
            enable_reg |= TCS34725_ENABLE_AIEN
        else:
            enable_reg &= ~TCS34725_ENABLE_AIEN
        self._write8(TCS34725_ENABLE, enable_reg)
        time.sleep(1)

Response: Enable or disable interrupts by setting enabled to True or False.


Instruction:
Implement a Python 3 function for
setting the interrupt limits to provied unsigned 16 - bit threshold values.

Response:
def set_interrupt_limits(self, low, high):
        """Set the interrupt limits to provied unsigned 16-bit threshold values.
        """
        self._device.write8(0x04, low & 0xFF)
        self._device.write8(0x05, low >> 8)
        self._device.write8(0x06, high & 0xFF)
        self._device.write8(0x07, high >> 8)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def convert(json_input, build_direction="LEFT_TO_RIGHT", table_attributes=None):
    json_converter = JsonConverter(build_direction=build_direction, table_attributes=table_attributes)
    return json_converter.convert(json_input)

Response: Converts JSON object to HTML Table format.


Instruction:
Implement a Python 3 function for
converting a dictionary into HTML Table format.

Response:
def convert(self, json_input):
        """
        Converts JSON to HTML Table format.

        Parameters
        ----------
        json_input : dict
            JSON object to convert into HTML.

        Returns
        -------
        str
            String of converted HTML.
        """
        html_output = self._table_opening_tag
        if self._build_top_to_bottom:
            html_output += self._markup_header_row(json_input.keys())
            html_output += "
"
            for value in json_input.values():
                if isinstance(value, list):
                    # check if all keys in the list are identical
                    # and group all values under a common column
                    # heading if so, if not default to normal markup
                    html_output += self._maybe_club(value)
                else:
                    html_output += self._markup_table_cell(value)
            html_output += "
"
        else:
            for key, value in iter(json_input.items()):
                html_output += "
{:s}	".format(self._markup(key))
                if isinstance(value, list):
                    html_output += self._maybe_club(value)
                else:
                    html_output += self._markup_table_cell(value)
                html_output += "
"
        html_output += "
"
        return html_output


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _dict_to_html_attributes(d):
        if d is None:
            return ""

        return "".join(" {}=\"{}\"".format(key, value) for key, value in iter(d.items()))

Response: Converts a dictionary to a string of html attributes.


Instruction:
Here you have a function in Python 3, explain what it does
def _list_of_dicts_to_column_headers(list_of_dicts):

        if len(list_of_dicts) < 2 or not all(isinstance(item, dict) for item in list_of_dicts):
            return None

        column_headers = list_of_dicts[0].keys()
        for d in list_of_dicts[1:]:
            if len(d.keys()) != len(column_headers) or not all(header in d for header in column_headers):
                return None
        return column_headers

Response: Returns the list of column headers from a list of dicts.


Instruction:
Explain what the following Python 3 code does
def _maybe_club(self, list_of_dicts):
        column_headers = JsonConverter._list_of_dicts_to_column_headers(list_of_dicts)
        if column_headers is None:
            # common headers not found, return normal markup
            html_output = self._markup(list_of_dicts)
        else:
            html_output = self._table_opening_tag
            html_output += self._markup_header_row(column_headers)
            for list_entry in list_of_dicts:
                html_output += "
"
                html_output += "	".join(self._markup(list_entry[column_header]) for column_header in column_headers)
                html_output += "
"
            html_output += "
"

        return self._markup_table_cell(html_output)

Response: Given a list of dicts and a list of dicts return a HTML string that can be used to club the list of dicts.


Instruction:
Write a Python 3 function that can
update the voice notify.

Response:
def update_voice_notify(self, param, must=[APIKEY, TPL_ID, TPL_CONTENT]):
        '''修改语音通知模版

        注意：模板成功修改之后需要重新审核才能使用！同时提醒您如果修改了变量，务必重新测试，以免替换出错!
        参数：
        参数名    类型    是否必须    描述    示例
        apikey    String    是    用户唯一标识    9b11127a9701975c734b8aee81ee3526
        tpl_id    Long    是    模板id，64位长整形。指定id时返回id对应的模板。未指定时返回所有模板    9527
        tpl_content    String    是    模板id，64位长整形。指定id时返回id对应的模板。未指定时返回所有模板模板内容    您的验证码是#code#

        Args:
            param:
        Results:
            Result
        '''
        r = self.verify_param(param, must)
        if not r.is_succ():
            return r
        h = CommonResultHandler(lambda rsp: {VERSION_V2:rsp}[self.version()])
        return self.path('update_voice_notify.json').post(param, h, r)


Instruction:
Create a Python 3 function to
set code of the current object

Response:
def code(self, code=None, ret_r=False):
        '''
        Args:
            code: (Optional) set code
            ret_r: (Optional) force to return Result. Default value is False
        returns:
            response code(0-success, others-failure) or self
        '''
        if code or ret_r:
            self._code = code
            return self
        return self._code


Instruction:
Implement a Python 3 function for
getting a specific resource from the API.

Response:
def get(self, param=None, must=[APIKEY]):
        '''查账户信息

        参数名 类型 是否必须 描述 示例
        apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526

        Args:
            param: (Optional)
        Results:
            Result
        '''
        param = {} if param is None else param
        r = self.verify_param(param, must)
        if not r.is_succ():
            return r
        handle = CommonResultHandler(lambda rsp: {VERSION_V1:rsp.get(USER), VERSION_V2:rsp}[self.version()])
        return self.path('get.json').post(param, handle, r)


Instruction:
Can you create a Python 3 function that
initializes api by YunpianClient

Response:
def _init(self, clnt):
        '''initialize api by YunpianClient'''
        assert clnt, "clnt is None"
        self._clnt = clnt
        self._apikey = clnt.apikey()
        self._version = clnt.conf(YP_VERSION, defval=VERSION_V2)
        self._charset = clnt.conf(HTTP_CHARSET, defval=CHARSET_UTF8)
        self._name = self.__class__.__module__.split('.')[-1]


Instruction:
Can you generate the documentation for the following Python 3 function
def post(self, param, h, r):
        '''
        Args:
            param: request parameters
            h: ResultHandler
            r: YunpianApiResult
        '''
        try:
            rsp = self.client().post(self.uri(), param)
            # print(rsp)
            return self.result(rsp, h, r)
        except ValueError as err:
            return h.catch_exception(err, r)

Response: POST a new object to the resource.


Instruction:
How would you code a function in Python 3 to
verify that all keys in must are present in param

Response:
def verify_param(self, param, must=[], r=None):
        '''return Code.ARGUMENT_MISSING if every key in must not found in param'''
        if APIKEY not in param:
            param[APIKEY] = self.apikey()

        r = Result() if r is None else r
        for p in must:
            if p not in param:
                r.code(Code.ARGUMENT_MISSING).detail('missing-' + p)
                break

        return r


Instruction:
Make a summary of the following Python 3 code
def custom_conf(self, conf):
        '''custom apikey and http parameters'''
        if conf:
            for (key, val) in conf.items():
                self.__conf[key] = val
        return self

Response: custom apikey and http parameters


Instruction:
Can you create a Python 3 function that
returns special API by package s name

Response:
def api(self, name):
        '''return special API by package's name'''

        assert name, 'name is none'
        if flow.__name__ == name:
            api = flow.FlowApi()
        elif sign.__name__ == name:
            api = sign.SignApi()
        elif sms.__name__ == name:
            api = sms.SmsApi()
        elif tpl.__name__ == name:
            api = tpl.TplApi()
        elif user.__name__ == name:
            api = user.UserApi()
        elif voice.__name__ == name:
            api = voice.VoiceApi()

        assert api, "not found api-" + name

        api._init(self._clnt)
        return api


Instruction:
Create a Python 3 function to
return value in YunpianConf if key = None else return value in YunpianConf

Response:
def conf(self, key=None, defval=None):
        '''return YunpianConf if key=None, else return value in YunpianConf'''
        if key is None:
            return self._ypconf
        val = self._ypconf.conf(key)
        return defval if val is None else val


Instruction:
Can you implement a function in Python 3 that
posts data to url

Response:
def post(self, url, data, charset=CHARSET_UTF8, headers={}):
        '''response json text'''
        if 'Api-Lang' not in headers:
            headers['Api-Lang'] = 'python'
        if 'Content-Type' not in headers:
            headers['Content-Type'] = "application/x-www-form-urlencoded;charset=" + charset
        rsp = requests.post(url, data, headers=headers,
                            timeout=(int(self.conf(HTTP_CONN_TIMEOUT, '10')), int(self.conf(HTTP_SO_TIMEOUT, '30'))))
        return json.loads(rsp.text)


Instruction:
Given the following Python 3 function, write the documentation
def urlEncodeAndJoin(self, seq, sepr=','):
        '''sepr.join(urlencode(seq))
        Args:
            seq: string list to be urlencoded
            sepr: join seq with sepr
        Returns:
            str
        '''
        try:
            from urllib.parse import quote_plus as encode
            return sepr.join([encode(x, encoding=CHARSET_UTF8) for x in seq])
        except ImportError:
            from urllib import quote as encode
            return sepr.join([i for i in map(lambda x: encode(x), seq)])

Response: URL encode and join a list of strings


Instruction:
Make a summary of the following Python 3 code
def send(self, param, must=[APIKEY, MOBILE, CODE]):
        '''发语音验证码

        参数名 类型 是否必须 描述 示例
        apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
        mobile String 是 接收的手机号、固话（需加区号） 15205201314 01088880000
        code String 是 验证码，支持4~6位阿拉伯数字 1234
        encrypt String 否 加密方式 使用加密 tea (不再使用)
        _sign String 否 签名字段 参考使用加密 393d079e0a00912335adfe46f4a2e10f (不再使用)
        callback_url String 否 本条语音验证码状态报告推送地址 http://your_receive_url_address
        display_num String 否 透传号码，为保证全国范围的呼通率，云片会自动选择最佳的线路，透传的主叫号码也会相应变化。
        如需透传固定号码则需要单独注册报备，为了确保号码真实有效，客服将要求您使用报备的号码拨打一次客服电话

        Args:
            param:
        Results:
            Result
        '''
        r = self.verify_param(param, must)
        if not r.is_succ():
            return r
        h = CommonResultHandler(lambda rsp: {VERSION_V1:rsp.get(RESULT), VERSION_V2:rsp}[self.version()])
        return self.path('send.json').post(param, h, r)

Response: send a message to the server


Instruction:
Given the following Python 3 function, write the documentation
def single_send(self, param, must=[APIKEY, MOBILE, TEXT]):
        '''单条发送

        参数名 类型 是否必须 描述 示例
        apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
        mobile String 是
        接收的手机号；仅支持单号码发送；国际号码需包含国际地区前缀号码，格式必须是"+"号开头("+"号需要urlencode处理，否则会出现格式错误)，国际号码不以"+"开头将被认为是中国地区的号码
        （针对国际短信，mobile参数会自动格式化到E.164格式，可能会造成传入mobile参数跟后续的状态报告中的号码不一致。E.164格式说明，参见：
        https://en.wikipedia.org/wiki/E.164） 国内号码：15205201314
        国际号码：urlencode("+93701234567");
        text String 是 短信内容 【云片网】您的验证码是1234
        extend String 否 扩展号。默认不开放，如有需要请联系客服申请 001
        uid String 否 该条短信在您业务系统内的ID，比如订单号或者短信发送记录的流水号。填写后发送状态返回值内将包含这个ID
        默认不开放，如有需要请联系客服申请 10001
        callback_url String 否
        本条短信状态报告推送地址。短信发送后将向这个地址推送短信发送报告。"后台-系统设置-数据推送与获取”可以做批量设置。如果后台已经设置地址的情况下，单次请求内也包含此参数，将以请求内的推送地址为准。
        http://your_receive_url_address

        Args:
            param:
        Results:
            Result
        '''
        r = self.verify_param(param, must)
        if not r.is_succ():
            return r
        h = CommonResultHandler(lambda rsp: {VERSION_V2:rsp}[self.version()])
        return self.path('single_send.json').post(param, h, r)

Response: sends a single request to the server


Instruction:
Can you generate the documentation for the following Python 3 function
def pull_reply(self, param=None, must=[APIKEY]):
        '''获取回复短信

        参数名 类型 是否必须 描述 示例
        apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
        page_size Integer 否 每页个数，最大100个，默认20个 20

        Args:
            param:
        Results:
            Result
        '''
        param = {} if param is None else param
        r = self.verify_param(param, must)
        if not r.is_succ():
            return r
        h = CommonResultHandler(lambda rsp: {VERSION_V1:rsp[SMS_REPLY] if SMS_REPLY in rsp else None, VERSION_V2:rsp}[self.version()])
        return self.path('pull_reply.json').post(param, h, r)

Response: pull reply from a user


Instruction:
Create a Python 3 function to
get reply from a user.

Response:
def get_reply(self, param, must=[APIKEY, START_TIME, END_TIME, PAGE_NUM, PAGE_SIZE]):
        '''查回复的短信

        参数名 类型 是否必须 描述 示例
        apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
        start_time String 是 短信回复开始时间 2013-08-11 00:00:00
        end_time String 是 短信回复结束时间 2013-08-12 00:00:00
        page_num Integer 是 页码，默认值为1 1
        page_size Integer 是 每页个数，最大100个 20
        mobile String 否 填写时只查该手机号的回复，不填时查所有的回复 15205201314
        return_fields 否 返回字段（暂未开放
        sort_fields 否 排序字段（暂未开放） 默认按提交时间降序

        Args:
            param:
        Results:
            Result
        '''
        r = self.verify_param(param, must)
        if not r.is_succ():
            return r
        h = CommonResultHandler(lambda rsp: {VERSION_V1:rsp[SMS_REPLY] if SMS_REPLY in rsp else None, VERSION_V2:rsp}[self.version()])
        return self.path('get_reply.json').post(param, h, r)


Instruction:
Can you generate the documentation for the following Python 3 function
def get_record(self, param, must=[APIKEY, START_TIME, END_TIME]):
        '''查短信发送记录

        参数名 类型 是否必须 描述 示例
        apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
        mobile String 否 需要查询的手机号 15205201314
        start_time String 是 短信发送开始时间 2013-08-11 00:00:00
        end_time String 是 短信发送结束时间 2013-08-12 00:00:00
        page_num Integer 否 页码，默认值为1 1
        page_size Integer 否 每页个数，最大100个 20

        Args:
            param:
        Results:
            Result
        '''
        r = self.verify_param(param, must)
        if not r.is_succ():
            return r
        h = CommonResultHandler(lambda rsp: {VERSION_V1:rsp[SMS] if SMS in rsp else None, VERSION_V2:rsp}[self.version()])
        return self.path('get_record.json').post(param, h, r)

Response: Get a record from a user s account.


Instruction:
Implement a Python 3 function for
counting the number of items in a resource.

Response:
def count(self, param, must=[APIKEY, START_TIME, END_TIME]):
        '''统计短信条数

        参数名 类型 是否必须 描述 示例
        apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
        start_time String 是 短信发送开始时间 2013-08-11 00:00:00
        end_time String 是 短信发送结束时间 2013-08-12 00:00:00
        mobile String 否 需要查询的手机号 15205201314
        page_num Integer 否 页码，默认值为1 1
        page_size Integer 否 每页个数，最大100个 20

        Args:
            param:
        Results:
            Result
        '''
        r = self.verify_param(param, must)
        if not r.is_succ():
            return r
        h = CommonResultHandler(lambda rsp: int(rsp[TOTAL]) if TOTAL in rsp else 0)
        return self.path('count.json').post(param, h, r)


Instruction:
Given the following Python 3 function, write the documentation
def tpl_send(self, param, must=[APIKEY, MOBILE, TPL_ID, TPL_VALUE]):
        '''指定模板发送 only v1 deprecated

        参数名 类型 是否必须 描述 示例
        apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
        mobile String 是 接收的手机号 15205201314
        tpl_id Long 是 模板id 1
        tpl_value String 是 变量名和变量值对。请先对您的变量名和变量值分别进行urlencode再传递。使用参考：代码示例。
        注：变量名和变量值都不能为空 模板： 【#company#】您的验证码是#code#。 最终发送结果： 【云片网】您的验证码是1234。
        tplvalue=urlencode("#code#") + "=" + urlencode("1234") + "&" +
        urlencode("#company#") + "=" + urlencode("云片网"); 若您直接发送报文请求则使用下面这种形式
        tplvalue=urlencode(urlencode("#code#") + "=" + urlencode("1234") + "&" +
        urlencode("#company#") + "=" + urlencode("云片网"));
        extend String 否 扩展号。默认不开放，如有需要请联系客服申请 001
        uid String 否 用户自定义唯一id。最大长度不超过256的字符串。 默认不开放，如有需要请联系客服申请 10001

        Args:
            param:
        Results:
            Result
        '''
        r = self.verify_param(param, must)
        if not r.is_succ():
            return r
        h = CommonResultHandler(lambda rsp: {VERSION_V1:rsp.get(RESULT)}[self.version()])
        return self.path('tpl_send.json').post(param, h, r)

Response: sends a message to the TPL


Instruction:
Create a Python 3 function for
sending a single message to the server

Response:
def tpl_single_send(self, param, must=[APIKEY, MOBILE, TPL_ID, TPL_VALUE]):
        '''指定模板单发 only v2 deprecated

        参数名 类型 是否必须 描述 示例
        apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
        mobile String 是
        接收的手机号（针对国际短信，mobile参数会自动格式化到E.164格式，可能会造成传入mobile参数跟后续的状态报告中的号码不一致。E.164格式说明，参见：
        https://en.wikipedia.org/wiki/E.164） 15205201314
        tpl_id Long 是 模板id 1
        tpl_value String 是 变量名和变量值对。请先对您的变量名和变量值分别进行urlencode再传递。使用参考：代码示例。
        注：变量名和变量值都不能为空 模板： 【#company#】您的验证码是#code#。 最终发送结果： 【云片网】您的验证码是1234。
        tplvalue=urlencode("#code#") + "=" + urlencode("1234") + "&" +
        urlencode("#company#") + "=" + urlencode("云片网"); 若您直接发送报文请求则使用下面这种形式
        tplvalue=urlencode(urlencode("#code#") + "=" + urlencode("1234") + "&" +
        urlencode("#company#") + "=" + urlencode("云片网"));
        extend String 否 扩展号。默认不开放，如有需要请联系客服申请 001
        uid String 否 用户自定义唯一id。最大长度不超过256的字符串。 默认不开放，如有需要请联系客服申请 10001

        Args:
            param:
        Results:
            Result
        '''
        r = self.verify_param(param, must)
        if not r.is_succ():
            return r
        h = CommonResultHandler(lambda rsp: {VERSION_V2:rsp}[self.version()])
        return self.path('tpl_single_send.json').post(param, h, r)


Instruction:
Can you implement a function in Python 3 that
gets a specific package from the API.

Response:
def get_package(self, param=None, must=[APIKEY]):
        '''查询流量包

        参数名 类型 是否必须 描述 示例
        apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
        carrier String 否 运营商ID 传入该参数则获取指定运营商的流量包， 否则获取所有运营商的流量包 移动：10086 联通：10010 电信：10000

        Args:
            param:
        Results:
            Result
        '''
        param = {} if param is None else param
        r = self.verify_param(param, must)
        if not r.is_succ():
            return r
        h = CommonResultHandler(lambda rsp: {VERSION_V1:rsp[FLOW_PACKAGE] if FLOW_PACKAGE in rsp else None, VERSION_V2:rsp}[self.version()])
        return self.path('get_package.json').post(param, h, r)


Instruction:
How would you explain what the following Python 3 function does
def recharge(self, param, must=[APIKEY, MOBILE, SN]):
        '''充值流量

        参数名 类型 是否必须 描述 示例
        apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
        mobile String 是 接收的手机号（仅支持大陆号码） 15205201314
        sn String 是 流量包的唯一ID 点击查看 1008601
        callback_url String 否 本条流量充值的状态报告推送地址 http://your_receive_url_address
        encrypt String 否 加密方式 使用加密 tea (不再使用)
        _sign String 否 签名字段 参考使用加密 393d079e0a00912335adfe46f4a2e10f (不再使用)

        Args:
            param:
        Results:
            Result
        '''
        r = self.verify_param(param, must)
        if not r.is_succ():
            return r
        h = CommonResultHandler(lambda rsp: {VERSION_V1:rsp[RESULT] if RESULT in rsp else None, VERSION_V2:rsp}[self.version()])
        return self.path('recharge.json').post(param, h, r)

Response: recharge a user s log entry


Instruction:
Write a Python 3 script for
getting the status of a specific resource from the server.

Response:
def pull_status(self, param=None, must=[APIKEY]):
        '''获取状态报告

        参数名 是否必须 描述 示例
        apikey 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
        page_size 否 每页个数，最大100个，默认20个 20

        Args:
            param:
        Results:
            Result
        '''
        param = {} if param is None else param
        r = self.verify_param(param, must)
        if not r.is_succ():
            return r
        h = CommonResultHandler(lambda rsp: {VERSION_V1:rsp[FLOW_STATUS] if FLOW_STATUS in rsp else None, VERSION_V2:rsp}[self.version()])
        return self.path('pull_status.json').post(param, h, r)


Instruction:
Create a Python 3 function for
running a command and returns the return info.

Response:
def run_command(*args, raise_exception=True, cwd=None):
    '''
    Runs a command, piping all output to the DMP log.
    The args should be separate arguments so paths and subcommands can have spaces in them:

        ret = run_command('ls', '-l', '/Users/me/My Documents')
        print(ret.code)
        print(ret.stdout)
        print(ret.stderr)

    On Windows, the PATH is not followed.  This can be overcome with:

        import shutil
        run_command(shutil.which('program'), '-l', '/Users/me/My Documents')
    '''
    args = [ str(a) for a in args ]
    log.info('running %s', ' '.join(args))
    p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, cwd=cwd)
    stdout, stderr = p.communicate()
    returninfo = ReturnInfo(p.returncode, stdout.decode('utf8'), stderr.decode('utf8'))
    if stdout:
        log.info('%s', returninfo.stdout)
    if raise_exception and returninfo.code != 0:
        raise CommandError(' '.join(args), returninfo)
    return returninfo


Instruction:
Implement a Python 3 function for
retrieving a *Django * API template object for the given template name.

Response:
def get_template(self, template, def_name=None):
        '''Retrieve a *Django* API template object for the given template name, using the app_path and template_subdir
           settings in this object.  This method still uses the corresponding Mako template and engine, but it
           gives a Django API wrapper around it so you can use it the same as any Django template.

           If def_name is provided, template rendering will be limited to the named def/block (see Mako docs).

           This method corresponds to the Django templating system API.
           A Django exception is raised if the template is not found or cannot compile.
        '''
        try:
            # wrap the mako template in an adapter that gives the Django template API
            return MakoTemplateAdapter(self.get_mako_template(template), def_name)

        except (TopLevelLookupException, TemplateLookupException) as e: # Mako exception raised
            tdne = TemplateDoesNotExist('Template "%s" not found in search path: %s.' % (template, self.template_search_dirs))
            if settings.DEBUG:
                tdne.template_debug = get_template_debug(template, e)
            raise tdne from e

        except (CompileException, SyntaxException) as e: # Mako exception raised
            tse = TemplateSyntaxError('Template "%s" raised an error: %s' % (template, e))
            if settings.DEBUG:
                tse.template_debug = get_template_debug(template, e)
            raise tse from e


Instruction:
Write a Python 3 function for
retrieving the real Mako template object for the given template name without any wrapper.

Response:
def get_mako_template(self, template, force=False):
        '''Retrieve the real *Mako* template object for the given template name without any wrapper,
           using the app_path and template_subdir settings in this object.

           This method is an alternative to get_template().  Use it when you need the actual Mako template object.
           This method raises a Mako exception if the template is not found or cannot compile.

           If force is True, an empty Mako template will be created when the file does not exist.
           This option is used by the providers part of DMP and normally be left False.
        '''
        if template is None:
            raise TemplateLookupException('Template "%s" not found in search path: %s.' % (template, self.template_search_dirs))
        # get the template
        try:
            template_obj = self.tlookup.get_template(template)
        except TemplateLookupException:
            if not force:
                raise
            template_obj = Template('', filename=os.path.join(self.template_dir, template))

        # get the template
        return template_obj


Instruction:
Given the following Python 3 function, write the documentation
def app_resolver(app_name=None, pattern_kwargs=None, name=None):
    '''
    Registers the given app_name with DMP and adds convention-based
    url patterns for it.

    This function is meant to be called in a project's urls.py.
    '''
    urlconf = URLConf(app_name, pattern_kwargs)
    resolver = re_path(
        '^{}/?'.format(app_name) if app_name is not None else '',
        include(urlconf),
        name=urlconf.app_name,
    )
    # this next line is a workaround for Django's URLResolver class not having
    # a `name` attribute, which is expected in Django's technical_404.html.
    resolver.name = getattr(resolver, 'name', name or app_name)
    return resolver

Response: Returns a new URLResolver instance that can be used to resolve the given app_name with DMP.


Instruction:
Explain what the following Python 3 code does
def dmp_paths_for_app(app_name, pattern_kwargs=None, pretty_app_name=None):
    '''Utility function that creates the default patterns for an app'''
    dmp = apps.get_app_config('django_mako_plus')
    # Because these patterns are subpatterns within the app's resolver,
    # we don't include the /app/ in the pattern -- it's already been
    # handled by the app's resolver.
    #
    # Also note how the each pattern below defines the four kwargs--
    # either as 1) a regex named group or 2) in kwargs.
    return [
        # page.function/urlparams
        dmp_path(
            r'^(?P<dmp_page>[_a-zA-Z0-9\-]+)\.(?P<dmp_function>[_a-zA-Z0-9\.\-]+)/(?P<dmp_urlparams>.+?)/?$',
            merge_dicts({
                'dmp_app': app_name or dmp.options['DEFAULT_APP'],
            }, pattern_kwargs),
            'DMP /{}/page.function/urlparams'.format(pretty_app_name),
            app_name,
        ),

        # page.function
        dmp_path(
            r'^(?P<dmp_page>[_a-zA-Z0-9\-]+)\.(?P<dmp_function>[_a-zA-Z0-9\.\-]+)/?$',
            merge_dicts({
                'dmp_app': app_name or dmp.options['DEFAULT_APP'],
                'dmp_urlparams': '',
            }, pattern_kwargs),
            'DMP /{}/page.function'.format(pretty_app_name),
            app_name,
        ),

        # page/urlparams
        dmp_path(
            r'^(?P<dmp_page>[_a-zA-Z0-9\-]+)/(?P<dmp_urlparams>.+?)/?$',
            merge_dicts({
                'dmp_app': app_name or dmp.options['DEFAULT_APP'],
                'dmp_function': 'process_request',
            }, pattern_kwargs),
            'DMP /{}/page/urlparams'.format(pretty_app_name),
            app_name,
        ),

        # page
        dmp_path(
            r'^(?P<dmp_page>[_a-zA-Z0-9\-]+)/?$',
            merge_dicts({
                'dmp_app': app_name or dmp.options['DEFAULT_APP'],
                'dmp_function': 'process_request',
                'dmp_urlparams': '',
            }, pattern_kwargs),
            'DMP /{}/page'.format(pretty_app_name),
            app_name,
        ),

        # empty
        dmp_path(
            r'^$',
            merge_dicts({
                'dmp_app': app_name or dmp.options['DEFAULT_APP'],
                'dmp_function': 'process_request',
                'dmp_urlparams': '',
                'dmp_page': dmp.options['DEFAULT_PAGE'],
            }, pattern_kwargs),
            'DMP /{}'.format(pretty_app_name),
            app_name,
        ),
    ]

Response: Utility function that creates the default patterns for an app


Instruction:
Can you generate a brief explanation for the following Python 3 code
def dmp_path(regex, kwargs=None, name=None, app_name=None):
    '''
    Creates a DMP-style, convention-based pattern that resolves
    to various view functions based on the 'dmp_page' value.

    The following should exist as 1) regex named groups or
    2) items in the kwargs dict:
        dmp_app         Should resolve to a name in INSTALLED_APPS.
                        If missing, defaults to DEFAULT_APP.
        dmp_page        The page name, which should resolve to a module:
                        project_dir/{dmp_app}/views/{dmp_page}.py
                        If missing, defaults to DEFAULT_PAGE.
        dmp_function    The function name (or View class name) within the module.
                        If missing, defaults to 'process_request'
        dmp_urlparams   The urlparams string to parse.
                        If missing, defaults to ''.

    The reason for this convenience function is to be similar to
    Django functions like url(), re_path(), and path().
    '''
    return PagePattern(regex, kwargs, name, app_name)

Response: Creates a DMP - style convention - based pattern that resolves the URL of the current page.


Instruction:
Make a summary of the following Python 3 code
def alternate_syntax(local, using, **kwargs):
    '''
    A Mako filter that renders a block of text using a different template engine
    than Mako.  The named template engine must be listed in settings.TEMPLATES.

    The template context variables are available in the embedded template.
    Specify kwargs to add additional variables created within the template.

    This is a kludge that should be used sparingly. The `dmp_include` template tag
    is often a better option.

    The following examples assume you have installed the django_mustache template
    engine in settings.py:

        ## Simple expression in Mustache syntax:
        ${ '{{ name }}' | template_syntax(local, 'django_mustache') }

        ## Embedded Mustache code block:
        <%block filter="template_syntax(local, 'django_mustache')">
            {{#repo}}
                <b>{{name}}</b>
            {{/repo}}
            {{^repo}}
                No repos :(
            {{/repo}}
        </%block>

    Rendering Django or Jinja2 templates should be done with `django_syntax` and
    `jinja2_syntax` because it doesn't require the using parameter.
    '''
    # get the request (the MakoTemplateAdapter above places this in the context)
    request = local.context['request'] if isinstance(local.context, RequestContext) else None
    # get the current Mako template object so we can attach the compiled string for later use
    # Mako caches and automatically recreates this if the file changes
    mako_template = local.template
    if not hasattr(mako_template, '__compiled_template_syntax'):
        mako_template.__compiled_template_syntax = {}

    # create a closure so we can still get to context and using (Mako filters take exactly one parameter: the string to filter)
    def wrap(template_st):
        # get the template object, or create and cache it
        try:
            template = mako_template.__compiled_template_syntax[template_st]
        except KeyError:
            engine = engines[using]
            template = engine.from_string(template_st)
            # using full string, even if long, as the key doesn't really affect performance of python's hash (see http://stackoverflow.com/questions/28150047/efficiency-of-long-str-keys-in-python-dictionary)
            mako_template.__compiled_template_syntax[template_st] = template

        # create a copy the context and add any kwargs to it
        dcontext = dict(local.context)
        dcontext.update(kwargs)

        # print a debug statement to the log
        log.debug('rendering embedded expression or block using %s template engine', using)

        # render the template with the context
        return template.render(context=dcontext, request=request)

    # return the embedded function
    return wrap

Response: A filter that renders a block of text using a different template engine than Mako.


Instruction:
How would you explain what the following Python 3 function does
def get_view_function(module_name, function_name, fallback_app=None, fallback_template=None, verify_decorator=True):
    '''
    Retrieves a view function from the cache, finding it if the first time.
    Raises ViewDoesNotExist if not found.  This is called by resolver.py.
    '''
    # first check the cache (without doing locks)
    key = ( module_name, function_name )
    try:
        return CACHED_VIEW_FUNCTIONS[key]
    except KeyError:
        with rlock:
            # try again now that we're locked
            try:
                return CACHED_VIEW_FUNCTIONS[key]
            except KeyError:
                # if we get here, we need to load the view function
                func = find_view_function(module_name, function_name, fallback_app, fallback_template, verify_decorator)
                # cache in production mode
                if not settings.DEBUG:
                    CACHED_VIEW_FUNCTIONS[key] = func
                return func

    # the code should never be able to get here
    raise Exception("Django-Mako-Plus error: get_view_function() should not have been able to get to this point.  Please notify the owner of the DMP project.  Thanks.")

Response: Returns a view function from the cache if the first time. Raises ViewDoesNotExist if not found.