Instruction:
Write a Python 3 script for
submitting a function to the pool.

Response:
def submit(self, func, *args, **kwargs):
        """Submit a function to the pool, `self.submit(function,arg1,arg2,arg3=3)`"""

        with self._shutdown_lock:
            if self._shutdown:
                raise RuntimeError("cannot schedule new futures after shutdown")
            callback = kwargs.pop("callback", self.default_callback)
            future = NewFuture(
                self._timeout,
                args,
                kwargs,
                callback=callback,
                catch_exception=self.catch_exception,
            )
            w = _WorkItem(future, func, args, kwargs)
            self._work_queue.put(w)
            self._adjust_thread_count()
            self._all_futures.add(future)
            return future


Instruction:
Implement a function in Python 3 to
submit a function to the pool.

Response:
def submit(self, func, *args, **kwargs):
        """Submit a function to the pool, `self.submit(function,arg1,arg2,arg3=3)`"""

        with self._shutdown_lock:
            if PY3 and self._broken:
                raise BrokenProcessPool(
                    "A child process terminated "
                    "abruptly, the process pool is not usable anymore"
                )
            if self._shutdown_thread:
                raise RuntimeError("cannot schedule new futures after shutdown")
            callback = kwargs.pop("callback", self.default_callback)
            future = NewFuture(
                self._timeout,
                args,
                kwargs,
                callback=callback,
                catch_exception=self.catch_exception,
            )
            w = _WorkItem(future, func, args, kwargs)
            self._pending_work_items[self._queue_count] = w
            self._work_ids.put(self._queue_count)
            self._queue_count += 1
            self._result_queue.put(None)
            self._start_queue_management_thread()
            if PY2:
                self._adjust_process_count()
            self._all_futures.add(future)
            return future


Instruction:
Implement a function in Python 3 to
invoke all the callbacks that have been set for this instance.

Response:
def _invoke_callbacks(self):
        """Record the task_end_time & task_cost_time, set result for self._callback_result."""
        self.task_end_time = time.time()
        self.task_cost_time = self.task_end_time - self.task_start_time
        with self._condition:
            for callback in self._done_callbacks:
                try:
                    result = callback(self)
                    if callback in self._user_callbacks:
                        self._callback_result = result
                except Exception as e:
                    Config.main_logger.error("exception calling callback for %s" % e)
            self._condition.notify_all()


Instruction:
Implement a Python 3 function for
blocking the main thead until the future finish return the future. callback_result.

Response:
def callback_result(self):
        """Block the main thead until future finish, return the future.callback_result."""
        if self._state in [PENDING, RUNNING]:
            self.x
        if self._user_callbacks:
            return self._callback_result
        else:
            return self.x


Instruction:
Can you implement a function in Python 3 that
blocks the main thead until the future finish return the future. result method.

Response:
def x(self):
        """Block the main thead until future finish, return the future.result()."""
        with self._condition:
            result = None
            if not self.done():
                self._condition.wait(self._timeout)
            if not self.done():
                # timeout
                self.set_exception(TimeoutError())
            if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
                # cancelled
                result = CancelledError()
            elif self._state == FINISHED:
                # finished
                if self._exception:
                    result = self._exception
                else:
                    result = self._result
            if isinstance(result, Exception):
                if self.catch_exception:
                    result = FailureException(result)
                    return result
                else:
                    raise result
            return result


Instruction:
Write a Python 3 function that can
close session shutdown pool.

Response:
def close(self, wait=False):
        """Close session, shutdown pool."""
        self.session.close()
        self.pool.shutdown(wait=wait)


Instruction:
How would you explain what the following Python 3 function does
def request(self, method, url, callback=None, retry=0, **kwargs):
        return self.pool.submit(
            self._request,
            method=method,
            url=url,
            retry=retry,
            callback=callback or self.default_callback,
            **kwargs
        )

Response: Similar to requests. request but return as NewFuture.


Instruction:
Can you generate the documentation for the following Python 3 function
def get(self, url, params=None, callback=None, retry=0, **kwargs):
        kwargs.setdefault("allow_redirects", True)
        return self.request(
            "get", url=url, params=params, callback=callback, retry=retry, **kwargs
        )

Response: Similar to requests. get but return as NewFuture.


Instruction:
Here you have a function in Python 3, explain what it does
def post(self, url, data=None, json=None, callback=None, retry=0, **kwargs):
        return self.request(
            "post",
            url=url,
            data=data,
            json=json,
            callback=callback,
            retry=retry,
            **kwargs
        )

Response: Similar to requests. post but return as NewFuture.


Instruction:
Explain what the following Python 3 code does
def getLinkInfo(self, wanInterfaceId=1, timeout=1):
        namespace = Wan.getServiceType("getLinkInfo") + str(wanInterfaceId)
        uri = self.getControlURL(namespace)

        results = self.execute(uri, namespace, "GetInfo", timeout=timeout)

        return WanLinkInfo(results)

Response: Execute GetInfo action to get basic WAN link information s.


Instruction:
Can you generate the documentation for the following Python 3 function
def getLinkProperties(self, wanInterfaceId=1, timeout=1):
        namespace = Wan.getServiceType("getLinkProperties") + str(wanInterfaceId)
        uri = self.getControlURL(namespace)

        results = self.execute(uri, namespace, "GetCommonLinkProperties", timeout=timeout)

        return WanLinkProperties(results)

Response: Execute GetCommonLinkProperties action to get WAN link properties.


Instruction:
Write a Python 3 function for
executing GetInfo action to get basic ADSL information s.

Response:
def getADSLInfo(self, wanInterfaceId=1, timeout=1):
        """Execute GetInfo action to get basic ADSL information's.

        :param int wanInterfaceId: the id of the WAN device
        :param float timeout: the timeout to wait for the action to be executed
        :return: ADSL informations.
        :rtype: ADSLInfo
        """
        namespace = Wan.getServiceType("getADSLInfo") + str(wanInterfaceId)
        uri = self.getControlURL(namespace)

        results = self.execute(uri, namespace, "GetInfo", timeout=timeout)

        return ADSLInfo(results)


Instruction:
Can you tell what is the following Python 3 function doing
def getEthernetLinkStatus(self, wanInterfaceId=1, timeout=1):
        namespace = Wan.getServiceType("getEthernetLinkStatus") + str(wanInterfaceId)
        uri = self.getControlURL(namespace)

        results = self.execute(uri, namespace, "GetEthernetLinkStatus", timeout=timeout)

        return results["NewEthernetLinkStatus"]

Response: Execute GetEthernetLinkStatus action to get the status of the ethernet link.


Instruction:
Write a Python 3 script to
execute GetTotalBytesSent & GetTotalBytesReceived actions to get WAN statistics.

Response:
def getByteStatistic(self, wanInterfaceId=1, timeout=1):
        """Execute GetTotalBytesSent&GetTotalBytesReceived actions to get WAN statistics.

        :param int wanInterfaceId: the id of the WAN device
        :param float timeout: the timeout to wait for the action to be executed
        :return: a tuple of two values, total bytes sent and total bytes received
        :rtype: list[int]
        """
        namespace = Wan.getServiceType("getByteStatistic") + str(wanInterfaceId)
        uri = self.getControlURL(namespace)

        results = self.execute(uri, namespace, "GetTotalBytesSent", timeout=timeout)
        results2 = self.execute(uri, namespace, "GetTotalBytesReceived", timeout=timeout)

        return [int(results["NewTotalBytesSent"]),
                int(results2["NewTotalBytesReceived"])]


Instruction:
Write a Python 3 script for
executing GetInfo action to get WAN connection information s.

Response:
def getConnectionInfo(self, wanInterfaceId=1, timeout=1):
        """Execute GetInfo action to get WAN connection information's.

        :param int wanInterfaceId: the id of the WAN device
        :param float timeout: the timeout to wait for the action to be executed
        :return: WAN connection information's.
        :rtype: ConnectionInfo
        """
        namespace = Wan.getServiceType("getConnectionInfo") + str(wanInterfaceId)
        uri = self.getControlURL(namespace)

        results = self.execute(uri, namespace, "GetInfo", timeout=timeout)

        return ConnectionInfo(results)


Instruction:
How would you explain what the following Python 3 function does
def setEnable(self, status, wanInterfaceId=1, timeout=1):
        namespace = Wan.getServiceType("setEnable") + str(wanInterfaceId)
        uri = self.getControlURL(namespace)

        if status:
            setStatus = 1
        else:
            setStatus = 0

        self.execute(uri, namespace, "SetEnable", timeout=timeout, NewEnable=setStatus)

Response: Set enable status for a WAN interface.


Instruction:
Implement a Python 3 function for
requesting the connection to be established

Response:
def requestConnection(self, wanInterfaceId=1, timeout=1):
        """Request the connection to be established

        :param int wanInterfaceId: the id of the WAN interface
        :param float timeout: the timeout to wait for the action to be executed
        """
        namespace = Wan.getServiceType("requestConnection") + str(wanInterfaceId)
        uri = self.getControlURL(namespace)

        self.execute(uri, namespace, "RequestConnection", timeout=timeout)


Instruction:
Can you implement a function in Python 3 that
writes a config object to filename

Response:
def write_config(filename, config, mode="w"):
    '''use configparser to write a config object to filename
    '''
    with open(filename, mode) as filey:
        config.write(filey)
    return filename


Instruction:
Can you generate a brief explanation for the following Python 3 code
def generate_temporary_file(folder='/tmp', prefix='helpme', ext='json'):
    '''write a temporary file, in base directory with a particular extension.

       Parameters
       ==========
       folder: the base directory to write in.
       prefix: the prefix to use
       ext: the extension to use.

    '''
    tmp = next(tempfile._get_candidate_names())
    return '%s/%s.%s.%s' %(folder, prefix, tmp, ext)

Response: generate a temporary file in base directory with a particular extension


Instruction:
Implement a function in Python 3 to
copy a file from a source to its destination.

Response:
def copyfile(source, destination, force=True):
    '''copy a file from a source to its destination.
    '''
    if os.path.exists(destination) and force is True:
        os.remove(destination)
    shutil.copyfile(source, destination)
    return destination


Instruction:
Can you create a Python 3 function that
returns a full inventory with all the keys and values

Response:
def full_inventory(self):
        """
        Returns a full inventory
        Some additional work required to provide consistent and consumable
        output.
        Inventory output only contains values, no keys - Add the keys to
        the output so that it can be consumed more easily.
        """
        if self._full_inventory:
            return self._full_inventory

        resp, inventory = self.get('Inventory')

        keys = ['host_id', 'hostname', 'ip_address', 'chassis',
                'used_count', 'current_state', 'comment', 'distro',
                'rel', 'centos_version', 'architecture', 'node_pool',
                'console_port', 'flavor']

        real_inventory = dict()
        for host in inventory:
            real_inventory[host[1]] = dict()
            for key in keys:
                real_inventory[host[1]][key] = host[keys.index(key)]

        self._full_inventory = real_inventory

        return self._full_inventory


Instruction:
Write a Python 3 script to
get the self - inventory for the current API key.

Response:
def self_inventory(self):
        """
        Inventory output will only contain the server name and the session ID
        when a key is provided. Provide the same format as with the full
        inventory instead for consistency.
        """
        if self.api_key is None:
            return {}

        if self._self_inventory:
            return self._self_inventory

        resp, self_inventory = self.get('Inventory?key=%s' % self.api_key)
        real_self_inventory = dict()

        for host in self_inventory:
            real_self_inventory[host[0]] = self.full_inventory[host[0]]

        self._self_inventory = real_self_inventory

        return self._self_inventory


Instruction:
Can you implement a function in Python 3 that
filters an inventory to only return servers matching ssid

Response:
def _ssid_inventory(self, inventory, ssid):
        """
        Filters an inventory to only return servers matching ssid
        """
        matching_hosts = {}
        for host in inventory:
            if inventory[host]['comment'] == ssid:
                matching_hosts[host] = inventory[host]

        return matching_hosts


Instruction:
Can you tell what is the following Python 3 function doing
def inventory(self, all=False, ssid=None):
        if all or self.api_key is None:
            if ssid is not None:
                return self._ssid_inventory(self.full_inventory, ssid)
            else:
                return self.full_inventory
        else:
            if ssid is not None:
                return self._ssid_inventory(self.self_inventory, ssid)
            else:
                return self.self_inventory

Response: Returns a node inventory.


Instruction:
Given the following Python 3 function, write the documentation
def node_get(self, arch=None, ver=None, flavor=None, count=1,
                 retry_count=1, retry_interval=10):
        """
        Requests specified number of nodes with the provided parameters.

        :param arch: Server architecture (ex: x86_64)
        :param ver: CentOS version (ex: 7)
        :param count: Number of servers (ex: 2)
        :parma flavor: The flavor of machine to use (multi-arch only)
        :param retry_count: Number of times to retry in case of failure (ex: 5)
        :param retry_interval: Wait in seconds between each retry (ex: 30)
        :return: [ [ requested_hosts ], ssid ]
        """
        if self.api_key is None:
            raise exceptions.ApiKeyRequired

        args = "key=%s" % self.api_key
        if arch is not None:
            args += "&arch=%s" % arch
        if ver is not None:
            args += "&ver=%s" % ver
        if flavor is not None:
            args += "&flavor=%s" % flavor
        args += "&count=%s" % count

        resp, body = self.get('Node/get?%s' % args)
        if not body:
            for _ in range(retry_count):
                time.sleep(retry_interval)
                resp, body = self.get('Node/get?%s' % args)
                if body:
                    break

        if not body:
            raise exceptions.NoInventory

        # Get the hosts that were requested.
        # Note: We have to iterate over full inventory instead of just the
        # hosts we got back from the response because the reply contains the
        # fqdn of the host while the full inventory only contains a short name.
        requested_hosts = dict()
        for host in self.full_inventory:
            for full_host in body['hosts']:
                if host in full_host:
                    requested_hosts[host] = self.full_inventory[host]

        return requested_hosts, body['ssid']

Response: Get the hosts and ssid of the nodes with the provided parameters.


Instruction:
Create a Python 3 function for
releasing the servers for the specified ssid.

Response:
def node_done(self, ssid=None):
        """
        Release the servers for the specified ssid.
        The API doesn't provide any kind of output, try to be helpful by
        providing the list of servers to be released.

        :param ssid: ssid of the server pool
        :return: [ requested_hosts ]
        """
        if self.api_key is None:
            raise exceptions.ApiKeyRequired

        if ssid is None:
            raise exceptions.SsidRequired

        # There is no body replied in this call so at least get the hosts for
        # the specified ssid to return them.
        requested_hosts = dict()
        for host in self.self_inventory:
            if ssid == self.self_inventory[host]['comment']:
                requested_hosts[host] = self.full_inventory[host]

        args = "key={key}&ssid={ssid}".format(key=self.api_key, ssid=ssid)

        resp, body = self.get('Node/done?%s' % args)

        return requested_hosts


Instruction:
Can you create a Python 3 function that
updates Redis state for a feature flag.

Response:
def update_redis(project: str, environment: str, feature: str, state: str) \
        -> None:
    """
    Update redis state for a feature flag.

    :param project: LaunchDarkly project key.
    :param environment: LaunchDarkly environment key.
    :param feature: LaunchDarkly feature key.
    :param state: State for a feature flag.
    """
    try:
        hosts = RedisWrapper.connection_string_parser(
            os.environ.get('REDIS_HOSTS'))
    except RuntimeError as ex:
        LOG.error(ex)
        sys.exit(1)

    for host in hosts:
        LOG.info("connecting to %s:%s", host.host, host.port)
        try:
            if valid_state(state):
                new_state = state.lower()
                redis = RedisWrapper(
                    host.host,
                    host.port,
                    project,
                    environment
                )
                redis.update_flag_record(new_state, feature)
                create_file(project, environment, feature, new_state)
                LOG.info("%s was successfully updated.", feature)
            else:
                raise Exception('Invalid state: {0}, -s needs \
                    to be either on or off.'.format(state))
        except KeyError as ex:
            LOG.error("unable to update %s. Exception: %s",
                      host.host,
                      ex)
            sys.exit(1)


Instruction:
How would you implement a function in Python 3 that
executes command against the LaunchDarkly API.

Response:
def update_ld_api(project: str, environment: str, feature: str, state: str):
    """
    Execute command against the LaunchDarkly API.

    This command is generally not used directly, instead it is called as a
    part of running the ``playback()`` function.

    :param project: LaunchDarkly project key.
    :param environment: LaunchDarkly environment key.
    :param feature: LaunchDarkly feature key.
    :param state: State for a feature flag.
    """
    ld_api = LaunchDarklyApi(
        os.environ.get('LD_API_KEY'),
        project,
        environment
    )

    if valid_state(state):
        if state.lower() == 'off':
            new_state = False
        else:
            new_state = True
        ld_api.update_flag(new_state, feature)
    else:
        raise ValueError('Invalid state: {0}, -s needs to be either \
            on or off.'.format(state))


Instruction:
How would you implement a function in Python 3 that
generates Relay Proxy Configuration.

Response:
def generate_relay_config(project):
    """
    Generate Relay Proxy Configuration.

    Generate a ld-relay.conf file to quickly spin up a relay proxy.
    Right now this is mostly used for integration testing.

    :param project: LaunchDarkly project key
    """
    ld_api = LaunchDarklyApi(
        os.environ.get('LD_API_KEY'),
        project_key=project
    )
    config = ConfigGenerator()

    envs = ld_api.get_environments(project)
    config.generate_relay_config(envs)


Instruction:
Make a summary of the following Python 3 code
def dicomdir_info(dirpath, *args, **kwargs):
    dr = DicomReader(dirpath=dirpath, *args, **kwargs)
    info = dr.dicomdirectory.get_stats_of_series_in_dir()
    return info

Response: Get information about series in dir


Instruction:
Can you generate a brief explanation for the following Python 3 code
def is_dicom_dir(datapath):
    # Second tries open files
    # with dicom module.

    retval = False
    datapath = op.expanduser(datapath)
    for f in os.listdir(datapath):
        if f.endswith((".dcm", ".DCM")):
            retval = True
            return True
        # @todo not working and I dont know why
        try:
            pydicom.read_file(os.path.join(datapath, f))

            retval = True
        # except pydicom.errors.InvalidDicomError:
        #     logger.debug("Invalid Dicom while reading file " + str(f))
        except Exception as e:
            logger.warning("Unable to read dicom file " + str(f))
            logger.warning(e)
            # import traceback
            # traceback.print_exc()

        if retval:
            return True
    return False

Response: Check if in dir is one or more dicom files.


Instruction:
Can you write a function in Python 3 where it
functions generates list of files from specific directory

Response:
def files_in_dir(dirpath, wildcard="*", startpath=None):
    """
    Function generates list of files from specific dir

    files_in_dir(dirpath, wildcard="*.*", startpath=None)

    dirpath: required directory
    wilcard: mask for files
    startpath: start for relative path

    Example
    files_in_dir('medical/jatra-kiv','*.dcm', '~/data/')
    """

    import glob

    filelist = []

    if startpath is not None:
        completedirpath = os.path.join(startpath, dirpath)
    else:
        completedirpath = dirpath

    if os.path.exists(completedirpath):
        logger.info('completedirpath = ' + completedirpath)

    else:
        logger.error('Wrong path: ' + completedirpath)
        raise Exception('Wrong path : ' + completedirpath)

    for infile in glob.glob(os.path.join(completedirpath, wildcard)):
        filelist.append(infile)

    if len(filelist) == 0:
        logger.error('No required files in path: ' + completedirpath)
        raise Exception('No required file in path: ' + completedirpath)

    return filelist


Instruction:
Can you generate the documentation for the following Python 3 function
def get_slice_location(dcmdata, teil=None):
    slice_location = None
    if hasattr(dcmdata, 'SliceLocation'):
        # print(dcmdata.SliceLocation)
        # print(type(dcmdata.SliceLocation))
        try:
            slice_location = float(dcmdata.SliceLocation)
        except Exception as exc:
            logger.info("It is not possible to use SliceLocation")
            logger.debug(traceback.format_exc())
    if slice_location is None and hasattr(dcmdata, "SliceThickness") and teil is not None:
        logger.debug(
            "Estimating SliceLocation wiht image number and SliceThickness"
        )

        # from builtins import map
        i = list(map(int, re.findall('\d+', teil)))
        i = i[-1]
        try:
            slice_location = float(i * float(dcmdata.SliceThickness))
        except ValueError as e:
            print(type(dcmdata.SliceThickness))
            print(dcmdata.SliceThickness)
            logger.debug(traceback.format_exc())
            logger.debug("SliceThickness problem")

    if slice_location is None and hasattr(dcmdata, "ImagePositionPatient") and hasattr(dcmdata,
                                                                                "ImageOrientationPatient"):
        if dcmdata.ImageOrientationPatient == [1, 0, 0, 0, 1, 0]:
            slice_location = dcmdata.ImagePositionPatient[2]
        else:
            logger.warning("Unknown ImageOrientationPatient")
    if slice_location is None:
        logger.warning("Problem with slice location")

    return slice_location

Response: get location of the slice in a single object


Instruction:
Write a Python 3 function for
adding attribute to dict if it exists.

Response:
def attr_to_dict(obj, attr, dct):
    """
    Add attribute to dict if it exists.
    :param dct:
    :param obj: object
    :param attr: object attribute name
    :return:  dict
    """
    if hasattr(obj, attr):
        dct[attr] = getattr(obj, attr)
    return dct


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_series_number_by_guess_for_liver(dcmreader, counts, bins, qt_app=None):
    series_info = dcmreader.dicomdirectory.get_stats_of_series_in_dir()
    print(dcmreader.print_series_info(series_info))
    import pandas as pd
    df = pd.DataFrame(list(series_info.values()))

    #select CT
    df = df[df["Modality"].str.lower().str.contains("ct") == True]
    # select just venous
    df = df[df["SeriesDescription"].str.lower().str.contains("ven") == True]
    # remove saggittal
    df = df[df["SeriesDescription"].str.lower().str.contains("sag") == False]
    # remove cor
    df = df[df["SeriesDescription"].str.lower().str.contains("cor") == False]
    df["dst_to_200"] = np.abs(200 - df.Count)
    dfs = df.sort_values(by="dst_to_200", ascending=True)
    sn = list(dfs.SeriesNumber)[0]

    return sn

Response: Select the series number that is used for liver.


Instruction:
How would you implement a function in Python 3 that
functions make 3D data from dicom file slices.

Response:
def get_overlay(self):
        """
        Function make 3D data from dicom file slices. There are usualy
        more overlays in the data.
        """
        overlay = {}
        dcmlist = self.files_in_serie

        for i in range(len(dcmlist)):
            onefile = dcmlist[i]
            logger.info("reading '%s'" % onefile)
            data = self._read_file(onefile)

            if len(overlay) == 0:
                # first there is created dictionary with
                # avalible overlay indexes
                for i_overlay in range(0, 50):
                    try:
                        # overlay index
                        data2d = decode_overlay_slice(data, i_overlay)
                        # mport pdb; pdb.set_trace()
                        shp2 = data2d.shape
                        overlay[i_overlay] = np.zeros([len(dcmlist), shp2[0],
                                                       shp2[1]], dtype=np.int8)
                        overlay[i_overlay][-i - 1, :, :] = data2d

                    except Exception:
                        # exception is exceptetd. We are trying numbers 0-50
                        # logger.exception('Problem with overlay image number ' +
                        #               str(i_overlay))
                        pass

            else:
                for i_overlay in overlay.keys():
                    try:
                        data2d = decode_overlay_slice(data, i_overlay)
                        overlay[i_overlay][-i - 1, :, :] = data2d
                    except Exception:
                        logger.warning('Problem with overlay number ' +
                                       str(i_overlay))

        return overlay


Instruction:
Can you implement a function in Python 3 that
functions make 3D data from dicom files

Response:
def get_3Ddata(self, start=0, stop=None, step=1):
        """
        Function make 3D data from dicom file slices
        """
        data3d = []
        dcmlist = self.files_in_serie
        # print('stsp ', start, stop, step)

        # raw_max = None
        # raw_min = None
        # slope = None
        # inter = None

        # get shape 2d

        # sometimes there is render in series
        if len(self.files_in_serie) > 1:
            data = self._read_file(dcmlist[0])
            data2d1 = data.pixel_array
            data = self._read_file(dcmlist[1])
            data2d2 = data.pixel_array
            if (data2d1.shape[0] == data2d2.shape[0]) and (data2d1.shape[1] == data2d2.shape[1]):
                pass
            else:
                dcmlist.pop(0)

        if stop is None:
            stop = len(dcmlist)

        # printRescaleWarning = False
        for i in xrange(start, stop, step):
            onefile = dcmlist[i]
            data = self._read_file(onefile)
            new_data2d = data.pixel_array
            # new_data2d, slope, inter = dcmtools.get_pixel_array_from_pdcm(data)
            # mport pdb; pdb.set_trace()

            if len(data3d) == 0:
                shp2 = new_data2d.shape
                data3d = np.zeros([len(dcmlist), shp2[0], shp2[1]],
                                  dtype=new_data2d.dtype)
                slope, inter = dcmtools.get_slope_and_intercept_from_pdcm(data)

            # first readed slide is at the end

            if (data3d.shape[1] == new_data2d.shape[0]) and (data3d.shape[2] == new_data2d.shape[1]):
                data3d[-i - 1, :, :] = new_data2d
            else:
                msg = "Problem with shape " + \
                      "Data size: " + str(data3d.nbytes) + \
                      ', shape: ' + str(shp2) + 'x' + str(len(dcmlist)) + \
                      ' file ' + onefile
                logger.warning(msg)
                print(msg)

            logger.debug("Data size: " + str(data3d.nbytes)
                         + ', shape: ' + str(shp2) + 'x' + str(len(dcmlist))
                         + ' file ' + onefile)
        data3d = misc.use_economic_dtype(data3d, slope=slope, inter=inter)
        # if original_dtype == np.uint16 and data3d.dtype == np.int16:
        #     data3d = data3d.astype(np.int32)
            # or just force set slope=0.5, inter = 0
        # new_data2d = rescale_pixel_array(data2d, slope, inter)
        # if printRescaleWarning:
        #     print("Automatic Rescale with slope 0.5")
        #     logger.warning("Automatic Rescale with slope 0.5")
        # data3d = dcmtools.rescale_pixel_array(data3d, slope=slope, inter=inter)

        return data3d


Instruction:
How would you explain what the following Python 3 function does
def get_standard_dicomdir_info(self):
        dicomdir_filepath = os.path.join(self.dirpath, self.standard_dicomdir_filename)
        if not os.path.exists(dicomdir_filepath):
            self.create_standard_dicomdir()
        return self.read_standard_dicomdir_info()

Response: Read DICOMDIR crate if necessary.


Instruction:
Make a summary of the following Python 3 code
def get_metadata_new(self, series_number):
        # TODO implement simplier metadata function
        # automatic test is prepared

        files, files_with_info = self.get_sorted_series_files(series_number=series_number, return_files_with_info=True)
        metadata = {
            # 'voxelsize_mm': voxelsize_mm,
            # 'Modality': data1.Modality,
            # 'SeriesNumber': series_number,
            # 'SeriesDescription' = data1.SeriesDescription,
            # 'ImageComments' : data1.ImageComments,
            # "AcquisitionDate": metadata,
            # "StudyDate": metadata,
            # "StudyDescription": metadata,
            # "RequestedProcedureDescription", metadata
        }
        return metadata

Response:
Return series metadata.
        Output condatin information about voxelsize_mm, series_number and modality.
        If it is possible, the ImageComment, AcquisitionDate and few other dicom tags are also in output dict.
        :param series_number:
        :return: metadata dict with voxelsize_mm, SeriesNumber and other dicom tags


Instruction:
Write a Python 3 script for
getting metadata for a neighboorhoding slice.

Response:
def get_metaData(self, dcmlist, series_number):
        """
        Get metadata.
        Voxel size is obtained from PixelSpacing and difference of
        SliceLocation of two neighboorhoding slices (first have index ifile).
        Files in are used.
        """
        # if dcmlist is None:
        #     dcmlist = self.files_in_serie

        # number of slice where to extract metadata inforamtion
        ifile = 0
        if len(dcmlist) == 0:
            return {}

        logger.debug("Filename: " + dcmlist[ifile])
        data1 = self._read_file(dcmlist[ifile])
        try:
            # try to get difference from the beginning and also from the end
            voxeldepth = self._get_slice_location_difference(dcmlist, ifile)
            voxeldepth_end = self._get_slice_location_difference(dcmlist, -2)
            if voxeldepth != voxeldepth_end:
                logger.warning("Depth of slices is not the same in beginning and end of the sequence")
                voxeldepth_1 = self._get_slice_location_difference(dcmlist, 1)
                voxeldepth = np.median([voxeldepth, voxeldepth_end, voxeldepth_1])

            # head1, teil1 = os.path.split(dcmlist[ifile])
            # head2, teil2 = os.path.split(dcmlist[ifile + 1])
            #
            # data2 = self._read_file(dcmlist[ifile + 1])
            # loc1 = get_slice_location(data1, teil1)
            # loc2 = get_slice_location(data2, teil2)
            # voxeldepth = float(np.abs(loc1 - loc2))
        except Exception:
            logger.warning('Problem with voxel depth. Using SliceThickness')
            logger.debug(traceback.format_exc())
            # + ' SeriesNumber: ' + str(data1.SeriesNumber))

            try:
                voxeldepth = float(data1.SliceThickness)
            except Exception:
                logger.warning('Probem with SliceThicknes, setting zero. '
                               + traceback.format_exc())
                voxeldepth = 0

        try:
            pixelsize_mm = data1.PixelSpacing
        except:
            logger.warning('Problem with PixelSpacing. Using [1,1]')
            pixelsize_mm = [1, 1]
        voxelsize_mm = [
            voxeldepth,
            float(pixelsize_mm[0]),
            float(pixelsize_mm[1]),
        ]
        metadata = {'voxelsize_mm': voxelsize_mm,
                    'Modality': data1.Modality,
                    'SeriesNumber': series_number
                    }

        try:
            metadata['SeriesDescription'] = data1.SeriesDescription

        except:
            logger.info(
                'Problem with tag SeriesDescription, SeriesNumber: ' +
                str(data1.SeriesNumber))
        try:
            metadata['ImageComments'] = data1.ImageComments
        except:
            logger.info(
                'Problem with tag ImageComments')
            # , SeriesNumber: ' +
            # str(data1.SeriesNumber))
        try:
            metadata['Modality'] = data1.Modality
        except:
            logger.info(
                'Problem with tag Modality')
            # SeriesNumber: ' +
            #     str(data1.SeriesNumber))
        metadata = attr_to_dict(data1, "AcquisitionDate", metadata)
        metadata = attr_to_dict(data1, "StudyDate", metadata)
        metadata = attr_to_dict(data1, "StudyID", metadata)
        metadata = attr_to_dict(data1, "StudyDescription", metadata)
        metadata = attr_to_dict(data1, "RequestedProcedureDescription", metadata)
        metadata = attr_to_dict(data1, "PatientSex", metadata)
        metadata = attr_to_dict(data1, "PatientAge", metadata)
        metadata = attr_to_dict(data1, "PatientID", metadata)
        metadata = attr_to_dict(data1, "PatientName", metadata)
        # metadata = attr_to_dict(data1, "AcquisitionTime", metadata)

        metadata['dcmfilelist'] = dcmlist
        return metadata


Instruction:
Explain what the following Python 3 code does
def get_stats_of_series_in_dir(self, study_id=None):
        if study_id is not None:
            logger.error("study_id tag is not implemented yet")
            return
        import numpy as np
        dcmdir = self.files_with_info
        # get series number
        # vytvoření slovníku, kde je klíčem číslo série a hodnotou jsou všechny
        # informace z dicomdir
        series_info = {line['SeriesNumber']: line for line in dcmdir}

        # počítání velikosti série
        try:
            dcmdirseries = [line['SeriesNumber'] for line in dcmdir]

        except:
            logger.debug('Dicom tag SeriesNumber not found')
            series_info = {0: {'Count': 0}}
            return series_info
            # eturn [0],[0]

        bins, counts = np.unique(dcmdirseries, return_counts=True)

        # sestavení informace o velikosti série a slovníku

        for i in range(0, len(bins)):
            series_info[bins[i]]['Count'] = counts[i]

            # adding information from files
            lst = self.get_sorted_series_files(series_number=bins[i])
            metadata = self.get_metaData(dcmlist=lst, series_number=bins[i])
            # adding dictionary metadata to series_info dictionary
            series_info[bins[i]] = dict(
                list(series_info[bins[i]].items()) +
                list(metadata.items())
            )

        return series_info

Response: get series staticstics from dicomdir


Instruction:
Explain what the following Python 3 code does
def print_series_info(self, series_info, minimal_series_number=1):
        strinfo = ''
        if len(series_info) > minimal_series_number:
            for serie_number in series_info.keys():
                strl = get_one_serie_info(series_info, serie_number)
                strinfo = strinfo + strl + '\n'
                # rint strl

        return strinfo

Response: Print series_info from dcmdirstats


Instruction:
Write a Python 3 script to
prepare info from dicomdir file

Response:
def __prepare_info_from_dicomdir_file(self, writedicomdirfile=True):
        """
        Check if exists dicomdir file and load it or cerate it

        dcmdir = get_dir(dirpath)

        dcmdir: list with filenames, SeriesNumber and SliceLocation
        """
        createdcmdir = True

        dicomdirfile = os.path.join(self.dirpath, self.dicomdir_filename)
        ftype = 'pickle'
        # if exist dicomdir file and is in correct version, use it
        if os.path.exists(dicomdirfile):
            try:
                dcmdirplus = misc.obj_from_file(dicomdirfile, ftype)
                if dcmdirplus['version'] == __version__:
                    createdcmdir = False
                dcmdir = dcmdirplus['filesinfo']
            except Exception:
                logger.debug('Found dicomdir.pkl with wrong version')
                createdcmdir = True

        if createdcmdir or self.force_create_dicomdir:
            dcmdirplus = self._create_dicomdir_info()
            dcmdir = dcmdirplus['filesinfo']
            if (writedicomdirfile) and len(dcmdir) > 0:
                # obj_to_file(dcmdirplus, dicomdirfile, ftype)
                try:
                    misc.obj_to_file(dcmdirplus, dicomdirfile, ftype)
                except:
                    logger.warning('Cannot write dcmdir file')
                    traceback.print_exc()

                # bj_to_file(dcmdir, dcmdiryamlpath )

        dcmdir = dcmdirplus['filesinfo']
        self.dcmdirplus = dcmdirplus
        self.files_with_info = dcmdir
        return dcmdir


Instruction:
Explain what the following Python 3 code does
def series_in_dir(self):

        # none_count = 0
        countsd = {}
        # dcmdirseries = []
        for line in self.files_with_info:
            if "SeriesNumber" in line:
                sn = line['SeriesNumber']
            else:
                sn = None
            if sn in countsd:
                countsd[sn] += 1
            else:
                countsd[sn] = 1

        bins = list(countsd)
        counts = list(countsd.values())

        # try:
        #     dcmdirseries = [line['SeriesNumber'] for line in self.files_with_info]
        # except:
        #     return [0], [0]

        # bins, counts = np.unique(dcmdirseries, return_counts=True)
        # binslist = bins.tolist()

        # if None in binslist:
        #     if len(binslist) == 1:
        #         return [0], [0]
        #     else:
        #         logger.warning

        #  kvůli správným intervalům mezi biny je nutno jeden přidat na konce
        # mxb = np.max(bins)
        # if mxb is None:
        #     mxb = 1
        # else:
        #     mxb = mxb + 1
        #
        # binslist.append(mxb)
        # counts, binsvyhodit = np.histogram(dcmdirseries, bins=binslist)

        # return counts.tolist(), bins.tolist()
        return counts, bins

Response: return list of series names and counts of all files in dirpath


Instruction:
How would you explain what the following Python 3 function does
def get_sorted_series_files(self, startpath="", series_number=None, return_files_with_info=False,
                                sort_keys="SliceLocation", return_files=True, remove_doubled_slice_locations=True):
        """
        Function returns sorted list of dicom files. File paths are organized
        by SeriesUID, StudyUID and FrameUID

        :param startpath: path prefix. E.g. "~/data"
        :param series_number: ID of series used for filtering the data
        :param return_files_with_info: return more complex information about sorted files
        :param return_files: return simple list of sorted files
        :type sort_keys: One key or list of keys used for sorting method by the order of keys.

        """
        dcmdir = self.files_with_info[:]

        # select sublist with SeriesNumber
        if series_number is not None:
            dcmdir = [
                line for line in dcmdir if line['SeriesNumber'] == series_number
            ]
        dcmdir = sort_list_of_dicts(dcmdir, keys=sort_keys)

        logger.debug('SeriesNumber: ' + str(series_number))

        if remove_doubled_slice_locations:
            dcmdir = self._remove_doubled_slice_locations(dcmdir)

        filelist = []
        for onefile in dcmdir:
            filelist.append(os.path.join(startpath,
                                         self.dirpath, onefile['filename']))
            # head, tail = os.path.split(onefile['filename'])

        retval = []
        if return_files:
            retval.append(filelist)
        if return_files_with_info:
            retval.append(dcmdir)

        if len(retval) == 0:
            retval = None
        elif len(retval) == 1:
            retval = retval[0]
        else:
            retval = tuple(retval)

        return retval

Response: Function returns sorted list of dicom files.


Instruction:
Make a summary of the following Python 3 code
def _create_dicomdir_info(self):

        filelist = files_in_dir(self.dirpath)
        files = []
        metadataline = {}

        for filepath in filelist:
            head, teil = os.path.split(filepath)
            dcmdata = None
            if os.path.isdir(filepath):
                logger.debug("Subdirectory found in series dir is ignored: " + str(filepath))
                continue
            try:
                dcmdata = pydicom.read_file(filepath)

            except pydicom.errors.InvalidDicomError as e:
                # some files doesnt have DICM marker
                try:
                    dcmdata = pydicom.read_file(filepath, force=self.force_read)

                    # if e.[0].startswith("File is missing \\'DICM\\' marker. Use force=True to force reading")
                except Exception as e:
                    if teil != self.dicomdir_filename:
                        # print('Dicom read problem with file ' + filepath)
                        logger.info('Dicom read problem with file ' + filepath)
                        import traceback
                        logger.debug(traceback.format_exc())
            if hasattr(dcmdata, "DirectoryRecordSequence"):
                # file is DICOMDIR - metainfo about files in directory
                # we are not using this info
                dcmdata = None

            if dcmdata is not None:
                metadataline = _prepare_metadata_line(dcmdata, teil)
                files.append(metadataline)

        # if SliceLocation is None, it is sorted to the end
        # this is not necessary it can be deleted
        files.sort(key=lambda x: (x['SliceLocation'] is None, x["SliceLocation"]))

        dcmdirplus = {'version': __version__, 'filesinfo': files, }
        if "StudyDate" in metadataline:
            dcmdirplus["StudyDate"] = metadataline["StudyDate"]
        return dcmdirplus

Response: Function crates list of all files in dicom dir with all IDs


Instruction:
How would you code a function in Python 3 to
return one item from seq or None by default.

Response:
def get_one(seq, default=None, skip_string_iter=True):
    """
    Return one item from seq or None(by default).
    """
    if skip_string_iter and isinstance(seq, (str, unicode, bytes, bytearray)):
        return seq
    if not seq:
        return ''
    try:
        return next(iter(seq))
    except TypeError:
        # not hasattr __iter__/__getitem__
        return default


Instruction:
Implement a Python 3 function for
ensuring that the object is a list of the available cache entries.

Response:
def ensure_list(obj):
        """
        null obj -> return [];

        str, unicode, bytes, bytearray -> [obj];

        else -> list(obj)
        """
        if not obj:
            return []
        elif isinstance(obj, (str, unicode, bytes, bytearray)):
            return [obj]
        elif hasattr(obj, '__iter__') or hasattr(obj, '__getitem__'):
            return list(obj)
        else:
            return [obj]


Instruction:
Can you create a Python 3 function that
operates a python obj

Response:
def python_parser(self, obj, *args):
        """operate a python obj"""
        attr, args = args[0], args[1:]
        item = getattr(obj, attr)
        if callable(item):
            item = item(*args)
        return [item]


Instruction:
Here you have a function in Python 3, explain what it does
def html_parser(self, scode, *args):
        allow_method = ('text', 'html', 'xml')
        css_path, method = args
        assert method in allow_method or method.startswith(
            '@'), 'method allow: %s or @attr' % allow_method
        result = self.ensure_list(
            self._fromstring(scode,
                             parser=self._html_parser).cssselect(css_path))
        if method.startswith('@'):
            result = [item.get(method[1:]) for item in result]
        else:
            result = [
                self._tostring(
                    item, method=method, with_tail=0, encoding='unicode')
                for item in result
            ]
        return result

Response: parse a single HTML code into a list of items


Instruction:
Here you have a function in Python 3, explain what it does
def xml_parser(self, scode, *args):
        allow_method = ('text', 'html', 'xml')
        xpath_string, method = args
        assert method in allow_method, 'method allow: %s' % allow_method
        result = self.ensure_list(
            self._fromstring(scode,
                             parser=self._xml_parser).xpath(xpath_string))
        result = [
            self._tostring(
                item, method=method, with_tail=0, encoding='unicode')
            for item in result
        ]
        return result

Response: Parse the XML code.


Instruction:
Write a Python 3 function for
parsing the scode and return a list of objects.

Response:
def parse(self, scode, args_chain=None, join_with=None, default=''):
        """
        single arg:
            [one_to_many, parser_name, *args]
        args_chain:
            [['1-n', 're', 'search', '(<.*?>)', '\\1']]
            [['1-n', 'html', 'p', 'html'], ['n-n', 'html', 'p', 'text']]
        """
        assert args_chain and isinstance(
            args_chain, (list, tuple)
        ) and isinstance(args_chain[0], (list, tuple)), ValueError(
            'args_chain type should be list of list, like: [["1-n", "html", "p", "html"], ["n-n", "html", "p", "text"]].'
        )
        for arg in args_chain:
            # py2 not support * unpack
            one_to_many, parser_name, parse_args = (arg[0], arg[1], arg[2:])
            assert self._re.match(
                '^[1n]-[1n]$',
                one_to_many), 'one_to_many should be one of 1-1, 1-n, n-n, n-1'
            input_count, output_count = one_to_many.split('-')
            parser = self._choose_parser(parser_name)
            # input data to parse.
            if input_count == 'n':
                scode = list(map(lambda item: parser(item, *parse_args), scode))
            if input_count == '1':
                if parser not in (self.jsonpath_parser, self.objectpath_parser,
                                  self.python_parser):
                    # json may remain multi-items
                    scode = get_one(scode, default=default)
                scode = parser(scode, *parse_args)
            # ensure result match n or 1 after parsing.
            if parser in (self.objectpath_parser,):
                # objectpath not need
                continue
            if output_count == '1':
                # 1-1 or n-1
                scode = get_one(scode, default=default)
            elif input_count == 'n':
                # n-n
                scode = [get_one(i, default=default) for i in scode]
            else:
                # 1-n
                scode = list(scode)
        if join_with:
            scode = join_with.join(map(str, scode))
        return scode


Instruction:
Can you tell what is the following Python 3 function doing
def parse(self):
        # Build the HTML tree
        self.tree = self._build_tree(self.html_contents)

        # Parse the CSS contents
        self.stylesheet = self.parser.parse_stylesheet(self.css_contents)

        # Get the cleaned CSS contents
        self.cleaned_css = self._clean_css()

Response: Parses the CSS contents and returns the cleaned CSS as a string


Instruction:
Can you generate the documentation for the following Python 3 function
def rel_to_abs(self, base_url):
        self.cleaned_css = self.rel_to_abs_re.sub(
            lambda match: "url('%s')" % urljoin(
                base_url, match.group('path').strip('\'"')),
            self.cleaned_css)

Response:
Converts relative links from css contents to absolute links
           .


Instruction:
How would you code a function in Python 3 to
clean the CSS rules and contents of the tree and return the cleaned CSS

Response:
def _clean_css(self):
        """
        Returns the cleaned CSS

        :param stylesheet: The Stylesheet object to parse
        :type stylesheet: tinycss.css21.Stylesheet
        """
        # Init the cleaned CSS rules and contents string
        css_rules = []

        # For every rule in the CSS
        for rule in self.stylesheet.rules:

            try:
                # Clean the CSS rule
                cleaned_rule = self._clean_rule(rule)

                # Append the rule to matched CSS rules
                if cleaned_rule is not None:
                    css_rules.append(cleaned_rule)

            except:
                # On error, assume the rule matched the tree
                css_rules.append(rule)

        return self._build_css(css_rules)


Instruction:
Here you have a function in Python 3, explain what it does
def _token_list_matches_tree(self, token_list):
        try:
            parsed_selector = cssselect.parse(
                ''.join(token.as_css() for token in token_list))[0]

            return bool(
                self.tree.xpath(
                    self.xpath_translator.selector_to_xpath(parsed_selector)))
        except:
            # On error, assume the selector matches the tree
            return True

Response: Returns True if the token list matches the HTML tree


Instruction:
How would you implement a function in Python 3 that
converts a tinycss rule to a formatted CSS string

Response:
def _rule_as_string(self, rule):
        """
        Converts a tinycss rule to a formatted CSS string

        :param rule: The rule to format
        :type rule: tinycss Rule object
        :returns: The Rule as a CSS string
        :rtype: str
        """
        if isinstance(rule, RuleSet):
            # Simple CSS rule : a { color: red; }
            return '%s{%s}' % (
                self._selector_as_string(rule.selector),
                self._declarations_as_string(rule.declarations))

        elif isinstance(rule, ImportRule):
            # @import rule
            return "@import url('%s') %s;" % (
                rule.uri, ','.join(rule.media))

        elif isinstance(rule, FontFaceRule):
            # @font-face rule
            return "@font-face{%s}" % self._declarations_as_string(rule.declarations)

        elif isinstance(rule, MediaRule):
            # @media rule
            return "@media %s{%s}" % (
                ','.join(rule.media),
                ''.join(self._rule_as_string(r) for r in rule.rules))

        elif isinstance(rule, PageRule):
            # @page rule
            selector, pseudo = rule.selector

            return "@page%s%s{%s}" % (
                ' %s' % selector if selector else '',
                ' :%s' % pseudo if pseudo else '',
                self._declarations_as_string(rule.declarations))

        return ''


Instruction:
Create a Python 3 function to
return a selector as a CSS string for the selector

Response:
def _selector_as_string(self, selector):
        """
        Returns a selector as a CSS string

        :param selector: A list of tinycss Tokens
        :type selector: list
        :returns: The CSS string for the selector
        :rtype: str
        """
        return ','.join(
            ''.join(token.as_css() for token in strip_whitespace(token_list))
            for token_list in split_on_comma(selector))


Instruction:
Can you tell what is the following Python 3 function doing
def _declarations_as_string(self, declarations):
        return ''.join('%s:%s%s;' % (
            d.name,
            d.value.as_css(),
            ' !' + d.priority if d.priority else '') for d in declarations)

Response: Returns a list of declarations as a formatted CSS string for the keys in the list.


Instruction:
Create a Python 3 function to
generate a markdown list of a list of environment variables

Response:
def envars_to_markdown(envars, title = "Environment"):
    '''generate a markdown list of a list of environment variable tuples

       Parameters
       ==========
       title: A title for the section (defaults to "Environment"
       envars: a list of tuples for the environment, e.g.:

            [('TERM', 'xterm-256color'),
             ('SHELL', '/bin/bash'),
             ('USER', 'vanessa'),
             ('LD_LIBRARY_PATH', ':/usr/local/pulse')]

    '''
    markdown = ''
    if envars not in [None, '', []]:
        markdown += '\n## %s\n' % title
        for envar in envars:
            markdown += ' - **%s**: %s\n' %(envar[0], envar[1])
    return markdown


Instruction:
Here you have a function in Python 3, explain what it does
async def create_vm(self, preset_name: str, image: str, flavor: str, security_groups: List=None,
                        userdata: Dict=None, key_name: str=None, availability_zone: str=None,
                        subnets: List=None) -> Any:
        """
        Create (boot) a new server.

        :arg string preset_name: Name of vm group where vm is created.
        :arg string image: Image name.
        :arg string flavor: Flavor (or instance_type in AWS) name.
        :arg list security_groups: A list of security group names.
        :arg dict userdata: A dict of arbitrary key/value metadata to store in grains.
        :arg string key_name: (optional extension) name of previously created
                      keypair to inject into the instance.
        :arg string availability_zone: Name of the availability zone for instance
                                  placement.
        :arg string subnets: List of the subnets for instance placement.

        Returns Any vm_id.
        """

        raise NotImplementedError

Response: Create a new server.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_default_commands(self):
        commands = Application.get_default_commands(self)

        self.add(ConstantsCommand())
        self.add(LoaderCommand())
        self.add(PyStratumCommand())
        self.add(WrapperCommand())

        return commands

Response: Returns the default commands of this application.


Instruction:
Make a summary of the following Python 3 code
def discover(service="ssdp:all", timeout=1, retries=2, ipAddress="239.255.255.250", port=1900):

        socket.setdefaulttimeout(timeout)

        messages = []

        if isinstance(service, str):
            services = [service]
        elif isinstance(service, list):
            services = service

        for service in services:
            message = 'M-SEARCH * HTTP/1.1\r\nMX: 5\r\nMAN: "ssdp:discover"\r\nHOST: ' + \
                      ipAddress + ':' + str(port) + '\r\n'
            message += "ST: " + service + "\r\n\r\n"
            messages.append(message)

        responses = {}

        for _ in range(retries):

            # setup the socket
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)

            # noinspection PyAssignmentToLoopOrWithParameter
            for _ in range(2):

                # send the messages with different service types
                for message in messages:
                    # send message more often to make sure all devices will get it
                    sock.sendto(message.encode('utf-8'), (ipAddress, port))

            while True:
                try:
                    # read the message until timeout
                    data = sock.recv(1024)
                except socket.timeout:
                    break
                else:
                    # no time out, read the response data and create response object
                    response = DiscoveryResponse(data)
                    # filter duplicated responses
                    responses[response.location] = response

        # return a list of all responses
        return list(responses.values())

Response: Discover UPnP devices in the local network.


Instruction:
Can you tell what is the following Python 3 function doing
def discoverParticularHost(host, service="ssdp:all", deviceDefinitionURL=None, timeout=1, retries=2,
                               ipAddress="239.255.255.250", port=1900, proxies=None):
        """Discover a particular host and find the best response.

        This tries to find the most specific discovery result for the given host. Only the discovery result contains
        the URL to the XML tree which initializes the device definition. If an URL is already known it should be
        provided to avoid additional latency for a broader first device discovery.
        This method also do some magic to find the best result for the given host as UPnP devices behave sometimes
        strangely. This call is costly the result if any should be cached.

        :param str host: the host to find
        :param service: the service type or list of service types if known to search for
        :type service: str or list[str]
        :param str deviceDefinitionURL: if provided it is used to skip a first device discovery
        :param float timeout: the time to wait for each retry
        :param int retries: the amount of times how often the device is tried to discover
        :param str ipAddress: the multicast ip address to discover devices
        :param int port: the port to discover devices
        :param str proxies: proxy definition as defined here:
            `Proxy definition <http://docs.python-requests.org/en/latest/user/advanced/#proxies>`_
        :return: If the device have been found the response is returned otherwise None
        :rtype: DiscoveryResponse
        :raises ValueError: if problems with reading or parsing the xml device definition occurs
        :raises requests.exceptions.ConnectionError: when the device definitions can not be downloaded
        :raises requests.exceptions.ConnectTimeout: when download time out

        Example:
          ::

            proxies = {"http": "http://localhost:8888"}
            result = discoverParticularHost("192.168.0.1", proxies=proxies)
            if result is not None:
                print("Host: " + result.locationHost + " Port: " + result.locationPort + " Device definitions: " + \\
                    result.location)

        .. seealso::

            :class:`~simpletr64.DiscoveryResponse`, :meth:`~simpletr64.Discover.discover`
        """

        # get all IP addresses for the given host
        ipResults = socket.getaddrinfo(host, 80)

        if len(ipResults) == 0:
            return None

        ipAddresses = []

        # remember all ip addresses for the given host
        for ipAdrTupple in ipResults:
            ipAddresses.append(ipAdrTupple[4][0])

        bestPick = None
        services = []

        if deviceDefinitionURL is None:
            # no xml definition given, so lets search for one

            # search for all devices first
            discoverResults = Discover.discover(service=service, timeout=timeout, retries=retries,
                                                ipAddress=ipAddress, port=port)

            for result in discoverResults:
                if result.locationHost in ipAddresses:
                    # now we found a result for that host, pick the best service type if multiple results for the host
                    # are found
                    if Discover.rateServiceTypeInResult(result) > Discover.rateServiceTypeInResult(bestPick):
                        bestPick = result

                    # remember all services
                    if result.service not in services:
                        services.append(result.service)

            if bestPick is None:
                return None
        else:
            # create response with given parameter
            bestPick = DiscoveryResponse.create(deviceDefinitionURL, service=service)

        # some routers do not advice their TR64 capabilities but their UPnp which is only a subset of actions.
        # Try to find out if the given XML definition path will give us a better service type.
        # load xml definition

        # some devices response differently without a User-Agent
        headers = {"User-Agent": "Mozilla/5.0; SimpleTR64-3"}

        request = requests.get(bestPick.location, proxies=proxies, headers=headers, timeout=float(timeout))

        if request.status_code != 200:
            errorStr = DeviceTR64._extractErrorString(request)
            raise ValueError('Could not get CPE definitions for "' + bestPick.location + '": ' +
                             str(request.status_code) + ' - ' + request.reason + " -- " + errorStr)

        # parse xml
        try:
            root = ET.fromstring(request.text.encode('utf-8'))
        except Exception as e:
            raise ValueError("Could not parse CPE definitions for '" + bestPick.location + "': " + str(e))

        # find the first deviceType in the document tree
        for element in root.getiterator():
            # check if element tag name ends on deviceType, skip XML namespace
            if element.tag.lower().endswith("devicetype"):

                serviceFound = element.text

                # remember the service found if it does not exist yet
                if serviceFound not in services:
                    services.append(serviceFound)

                # create a specific service just to check if we found it already
                serviceFound = serviceFound.replace("schemas-upnp-org", "dslforum-org")

                # test if we already have the best service type then we dont need to do an other discovery request
                if serviceFound == bestPick.service:
                    return bestPick

                for service in services:
                    # we search for the specific device tyoe version as of specified in TR64 protocol.
                    # some devices returns different results depending on the given service type, so lets be
                    # very specific
                    specificService = service.replace("schemas-upnp-org", "dslforum-org")

                    if specificService not in services:
                        services.append(specificService)

                # we do an other discovery request with more specific service/device type
                discoverResultsSpecific = Discover.discover(service=services, timeout=float(timeout), retries=retries,
                                                            ipAddress=ipAddress, port=port)

                # iterate through all results to find the most specific one
                evenBetterPick = None

                for specificResult in discoverResultsSpecific:
                    if specificResult.locationHost in ipAddresses:
                        if Discover.rateServiceTypeInResult(specificResult) > \
                                Discover.rateServiceTypeInResult(evenBetterPick):
                            evenBetterPick = specificResult

                if evenBetterPick is not None:
                    # best we could find
                    return evenBetterPick

                # we found first deviceType tag in the XML structure, no need to go further
                break

        if deviceDefinitionURL is not None:
            # we created our own response, so no result found
            return None

        # we found only an unspecific result, return it anyway
        return bestPick

Response: Discover a particular host and find the most specific response.


Instruction:
Write a Python 3 function for
rating the service type in a result.

Response:
def rateServiceTypeInResult(discoveryResponse):
        """Gives a quality rating for a given service type in a result, higher is better.

        Several UpnP devices reply to a discovery request with multiple responses with different service type
        announcements. To find the most specific one we need to be able rate the service types against each other.
        Usually this is an internal method and just exported for convenience reasons.

        :param DiscoveryResponse discoveryResponse: the response to rate
        :return: a rating of the quality of the given service type
        :rtype: int
        """
        if discoveryResponse is None:
            return 0

        serviceType = discoveryResponse.service

        if serviceType.startswith("urn:dslforum-org:device"):
            return 11
        if serviceType.startswith("urn:dslforum-org:service"):
            return 10
        if serviceType.startswith("urn:dslforum-org:"):
            return 9
        if serviceType.startswith("urn:schemas-upnp-org:device"):
            return 8
        if serviceType.startswith("urn:schemas-upnp-org:service"):
            return 7
        if serviceType.startswith("urn:schemas-upnp-org:"):
            return 6
        if serviceType.startswith("urn:schemas-"):  # other schemas, schema-any-com for example
            return 5
        if serviceType.startswith("urn:"):
            return 4
        if serviceType.startswith("upnp:rootdevice"):
            return 3
        if serviceType.startswith("uuid:"):  # no service, just the uuid given
            return 2
        return 1


Instruction:
How would you implement a function in Python 3 that
downloads the image from the url and return the name of the downloaded file

Response:
def download(self, url,
                   file_name,
                   headers=None,
                   show_progress=True):

    '''stream to a temporary file, rename on successful completion

        Parameters
        ==========
        file_name: the file name to stream to
        url: the url to stream from
        headers: additional headers to add
        force: If the final image exists, don't overwrite

    '''

    fd, tmp_file = tempfile.mkstemp(prefix=("%s.tmp." % file_name))
    os.close(fd)

    # Should we verify the request?
    verify = self._verify()

    # Check here if exists
    if requests.head(url, verify=verify).status_code in [200, 401]:
        response = self.stream(url, headers=headers, stream_to=tmp_file)

        if isinstance(response, HTTPError):
            bot.error("Error downloading %s, exiting." %url)
            sys.exit(1)
        shutil.move(tmp_file, file_name)
    else:
        bot.error("Invalid url or permissions %s" %url)
    return file_name


Instruction:
How would you code a function in Python 3 to
stream the response to a file.

Response:
def stream_response(self, response, stream_to=None):
    '''
       stream response is one level higher up than stream, starting with a
       response object and then performing the stream without making the
       requests.get. The expectation is that the request was successful
       (status code 20*).

       Parameters
       ==========
       response: a response that is ready to be iterated over to download in
                 streamed chunks
       stream_to: the file to stream to

    '''

    if response.status_code == 200:

        # Keep user updated with Progress Bar
        content_size = None
        if 'Content-Length' in response.headers:
            progress = 0
            content_size = int(response.headers['Content-Length'])
            bot.show_progress(progress, content_size, length=35)

        chunk_size = 1 << 20
        with open(stream_to, 'wb') as filey:
            for chunk in response.iter_content(chunk_size=chunk_size):
                filey.write(chunk)
                if content_size is not None:
                    progress+=chunk_size
                    bot.show_progress(iteration=progress,
                                      total=content_size,
                                      length=35,
                                      carriage_return=False)

        # Newline to finish download
        sys.stdout.write('\n')

        return stream_to

    bot.error("Problem with stream, response %s" %(response.status_code))
    sys.exit(1)


Instruction:
Can you write a function in Python 3 where it
returns the SCDP URL for a given service type and namespace. If no SCDP URL is given the default value is returned.

Response:
def getSCDPURL(self, serviceType, default=None):
        """Returns the SCDP (Service Control Protocol Document) URL for a given service type.

        When the device definitions have been loaded with :meth:`~simpletr64.DeviceTR64.loadDeviceDefinitions` this
        method returns for a given service type/namespace the associated URL to the SCDP. If the device definitions
        have not been loaded a default value can be given which gets returned instead. The SCDP specifies all the
        interaction functionality a device provides.

        :param serviceType: the service type to look up for
        :param default: the default return value in case the service type is not found and device definitions are not
            loaded
        :type default: str or None
        :return: the URL/URI
        :rtype: str or None
        :raises ValueError: if the device did load device definitions and the service type is not known.

        .. seealso::

            :meth:`~simpletr64.DeviceTR64.loadDeviceDefinitions`
        """
        if serviceType in self.__deviceServiceDefinitions.keys():
            return self.__deviceServiceDefinitions[serviceType]["scpdURL"]

        # check if definitions have been loaded, then dont return the default
        if self.__deviceXMLInitialized:
            raise ValueError("Device do not support given serviceType: " + serviceType)

        return default


Instruction:
Make a summary of the following Python 3 code
def getControlURL(self, serviceType, default=None):
        if serviceType in self.__deviceServiceDefinitions.keys():
            return self.__deviceServiceDefinitions[serviceType]["controlURL"]

        # check if definitions have been loaded, then dont return the default
        if self.__deviceXMLInitialized:
            raise ValueError("Device do not support given serviceType: " + serviceType)

        return default

Response: Returns the control URL for a given service type and namespace.


Instruction:
Can you create a Python 3 function that
returns the event URL for a given service type and namespace. If no event URL is given the associated event URL is returned. If no event URL is given the associated event URL is returned.

Response:
def getEventSubURL(self, serviceType, default=None):
        """Returns the event URL for a given service type.

        When the device definitions have been loaded with :meth:`~simpletr64.DeviceTR64.loadDeviceDefinitions` this
        method returns for a given service type/namespace the associated event URL. If the device definitions have
        not been loaded a default value can be given which gets returned instead.

        :param serviceType: the service type to look up for
        :param default: the default return value in case the service type is not found and device definitions are not
            loaded
        :type default: str or None
        :return: the URL/URI
        :rtype: str or None
        :raises ValueError: if the device did load device definitions and the service type is not known.

        .. seealso::

            :meth:`~simpletr64.DeviceTR64.loadDeviceDefinitions`
        """
        if serviceType in self.__deviceServiceDefinitions.keys():
            return self.__deviceServiceDefinitions[serviceType]["eventSubURL"]

        # check if definitions have been loaded, then dont return the default
        if self.__deviceXMLInitialized:
            raise ValueError("Device do not support given serviceType: " + serviceType)

        return default


Instruction:
Can you tell what is the following Python 3 function doing
def execute(self, uri, namespace, action, timeout=2, **kwargs):

        if not uri:
            raise ValueError("No action URI has been defined.")

        if not namespace:
            raise ValueError("No namespace has been defined.")

        if not action:
            raise ValueError("No action has been defined.")

        # soap headers
        header = {'Content-Type': 'text/xml; charset="UTF-8"',
                  'Soapaction': '"' + namespace + "#" + action + '"'}

        # build SOAP body
        body = '''<?xml version="1.0" encoding="UTF-8"?>
<s:Envelope
    s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
    xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <s:Header/>
    <s:Body>\n'''

        body += "        <u:" + action + ' xmlns="' + namespace + '">\n'

        arguments = {}

        for key in kwargs.keys():
            body += "            <" + key + ">" + str(kwargs[key]) + "</" + key + ">\n"
            arguments[key] = str(kwargs[key])

        body += "        </u:" + action + ">\n"
        body += '''</s:Body>
</s:Envelope>'''

        # setup proxies
        proxies = {}
        if self.__httpsProxy:
            proxies = {"https": self.__httpsProxy}

        if self.__httpProxy:
            proxies = {"http": self.__httpProxy}

        # setup authentication
        auth = None
        if self.__password:
            auth = HTTPDigestAuth(self.__username, self.__password)

        # build the URL
        location = self.__protocol + "://" + self.__hostname + ":" + str(self.port) + uri

        # Post http request
        request = requests.post(location, data=body, headers=header, auth=auth, proxies=proxies, timeout=float(timeout),
                               verify=self.__verify)

        if request.status_code != 200:
            errorStr = DeviceTR64._extractErrorString(request)
            raise ValueError('Could not execute "' + action + str(arguments) + '": ' + str(request.status_code) +
                             ' - ' + request.reason + " -- " + errorStr)

        # parse XML return
        try:
            root = ET.fromstring(request.text.encode('utf-8'))
        except Exception as e:
            raise ValueError("Can not parse results for the action: " + str(e))

        # iterate in the XML structure to get the action result
        actionNode = root[0][0]

        # we need to remove XML namespace for the action node
        namespaceLength = len(namespace) + 2  # add braces
        tag = actionNode.tag[namespaceLength:]

        if tag != (action + "Response"):
            raise ValueError('Soap result structure is wrong, expected action "' + action +
                             'Response" got "' + tag + '".')

        # pack all the received results
        results = {}

        for resultNode in actionNode:
            results[resultNode.tag] = resultNode.text

        return results

Response: Executes an action on a device and returns the results of the action.


Instruction:
Write a Python 3 function for
extracting an error string from a failed UPnP call.

Response:
def _extractErrorString(request):
        """Extract error string from a failed UPnP call.

        :param request: the failed request result
        :type request: requests.Response
        :return: an extracted error text or empty str
        :rtype: str
        """
        errorStr = ""

        tag = None

        # noinspection PyBroadException
        try:
            # parse XML return
            root = ET.fromstring(request.text.encode('utf-8'))
            tag = root[0][0]
        except:
            # return an empty string as we can not parse the structure
            return errorStr

        for element in tag.getiterator():
            tagName = element.tag.lower()

            if tagName.endswith("string"):
                errorStr += element.text + " "
            elif tagName.endswith("description"):
                errorStr += element.text + " "

        return errorStr


Instruction:
Can you generate a brief explanation for the following Python 3 code
def setupTR64Device(self, deviceType):

        if deviceType.lower() != "fritz.box":
            raise ValueError("Unknown device type given.")

        self.__deviceServiceDefinitions = {}
        self.__deviceXMLInitialized = False

        # Fritz.box setup
        self.deviceServiceDefinitions["urn:dslforum-org:service:DeviceConfig:1"] = {
            "controlURL": "/upnp/control/deviceconfig"}
        self.deviceServiceDefinitions["urn:dslforum-org:service:ManagementServer:1"] = {
            "controlURL": "/upnp/control/mgmsrv"}
        self.deviceServiceDefinitions["urn:dslforum-org:service:LANConfigSecurity:1"] = {
            "controlURL": "/upnp/control/lanconfigsecurity"}
        self.deviceServiceDefinitions["urn:dslforum-org:service:Time:1"] = {"controlURL": "/upnp/control/time"}
        self.deviceServiceDefinitions["urn:dslforum-org:service:LANHostConfigManagement:1"] = {
            "controlURL": "/upnp/control/lanhostconfigmgm"}
        self.deviceServiceDefinitions["urn:dslforum-org:service:UserInterface:1"] = {
            "controlURL": "/upnp/control/userif"}
        self.deviceServiceDefinitions["urn:dslforum-org:service:DeviceInfo:1"] = {
            "controlURL": "/upnp/control/deviceinfo"}
        self.deviceServiceDefinitions["urn:dslforum-org:service:X_AVM-DE_TAM:1"] = {"controlURL": "/upnp/control/x_tam"}
        self.deviceServiceDefinitions["urn:dslforum-org:service:X_AVM-DE_MyFritz:1"] = {
            "controlURL": "/upnp/control/x_myfritz"}
        self.deviceServiceDefinitions["urn:dslforum-org:service:X_AVM-DE_RemoteAccess:1"] = {
            "controlURL": "/upnp/control/x_remote"}
        self.deviceServiceDefinitions["urn:dslforum-org:service:WLANConfiguration:1"] = {
            "controlURL": "/upnp/control/wlanconfig1"}
        self.deviceServiceDefinitions["urn:dslforum-org:service:WLANConfiguration:3"] = {
            "controlURL": "/upnp/control/wlanconfig3"}
        self.deviceServiceDefinitions["urn:dslforum-org:service:WLANConfiguration:2"] = {
            "controlURL": "/upnp/control/wlanconfig2"}
        self.deviceServiceDefinitions["urn:dslforum-org:service:X_AVM-DE_WebDAVClient:1"] = {
            "controlURL": "/upnp/control/x_webdav"}
        self.deviceServiceDefinitions["urn:dslforum-org:service:WANDSLLinkConfig:1"] = {
            "controlURL": "/upnp/control/wandsllinkconfig1"}
        self.deviceServiceDefinitions["urn:dslforum-org:service:Hosts:1"] = {"controlURL": "/upnp/control/hosts"}
        self.deviceServiceDefinitions["urn:dslforum-org:service:X_VoIP:1"] = {"controlURL": "/upnp/control/x_voip"}
        self.deviceServiceDefinitions["urn:dslforum-org:service:LANEthernetInterfaceConfig:1"] = {
            "controlURL": "/upnp/control/lanethernetifcfg"}
        self.deviceServiceDefinitions["urn:dslforum-org:service:Layer3Forwarding:1"] = {
            "controlURL": "/upnp/control/layer3forwarding"}
        self.deviceServiceDefinitions["urn:dslforum-org:service:WANIPConnection:1"] = {
            "controlURL": "/upnp/control/wanipconnection1"}
        self.deviceServiceDefinitions["urn:dslforum-org:service:X_AVM-DE_OnTel:1"] = {
            "controlURL": "/upnp/control/x_contact"}
        self.deviceServiceDefinitions["urn:dslforum-org:service:WANCommonInterfaceConfig:1"] = {
            "controlURL": "/upnp/control/wancommonifconfig1"}
        self.deviceServiceDefinitions["urn:dslforum-org:service:X_AVM-DE_UPnP:1"] = {
            "controlURL": "/upnp/control/x_upnp"}
        self.deviceServiceDefinitions["urn:dslforum-org:service:WANDSLInterfaceConfig:1"] = {
            "controlURL": "/upnp/control/wandslifconfig1"}
        self.deviceServiceDefinitions["urn:dslforum-org:service:WANPPPConnection:1"] = {
            "controlURL": "/upnp/control/wanpppconn1"}
        self.deviceServiceDefinitions["urn:dslforum-org:service:X_AVM-DE_Storage:1"] = {
            "controlURL": "/upnp/control/x_storage"}
        self.deviceServiceDefinitions["urn:dslforum-org:service:WANEthernetLinkConfig:1"] = {
            "controlURL": "/upnp/control/wanethlinkconfig1"}

Response: Setup actions for known devices.


Instruction:
Here you have a function in Python 3, explain what it does
def loadDeviceDefinitions(self, urlOfXMLDefinition, timeout=3):

        # setup proxies
        proxies = {}
        if self.__httpsProxy:
            proxies = {"https": self.__httpsProxy}

        if self.__httpProxy:
            proxies = {"http": self.__httpProxy}

        # some devices response differently without a User-Agent
        headers = {"User-Agent": "Mozilla/5.0; SimpleTR64-1"}

        # setup authentication
        auth = None
        if self.__password:
            auth = HTTPDigestAuth(self.__username, self.__password)

        # get the content
        request = requests.get(urlOfXMLDefinition, proxies=proxies, headers=headers, timeout=float(timeout),
                               auth=auth, verify=self.__verify)

        if request.status_code != 200:
            errorStr = DeviceTR64._extractErrorString(request)
            raise ValueError('Could not get CPE definitions "' + urlOfXMLDefinition + '" : ' +
                             str(request.status_code) + ' - ' + request.reason + " -- " + errorStr)

        # parse XML return
        xml = request.text.encode('utf-8')

        return self._loadDeviceDefinitions(urlOfXMLDefinition, xml)

Response: Loads the device definitions from a given URL which points to the root XML in the device.


Instruction:
Can you tell what is the following Python 3 function doing
def _iterateToFindSCPDElements(self, element, baseURIPath):
        for child in element.getchildren():
            tagName = child.tag.lower()
            if tagName.endswith('servicelist'):
                self._processServiceList(child,baseURIPath)

            elif tagName.endswith('devicetype'):
                if "deviceType" not in self.__deviceInformations.keys():
                    self.__deviceInformations["deviceType"] = child.text
            elif tagName.endswith('friendlyname'):
                if "friendlyName" not in self.__deviceInformations.keys():
                    self.__deviceInformations["friendlyName"] = child.text
            elif tagName.endswith('manufacturer'):
                if "manufacturer" not in self.__deviceInformations.keys():
                    self.__deviceInformations["manufacturer"] = child.text
            elif tagName.endswith('manufacturerurl'):
                if "manufacturerURL" not in self.__deviceInformations.keys():
                    self.__deviceInformations["manufacturerURL"] = child.text
            elif tagName.endswith('modeldescription'):
                if "modelDescription" not in self.__deviceInformations.keys():
                    self.__deviceInformations["modelDescription"] = child.text
            elif tagName.endswith('modelname'):
                if "modelName" not in self.__deviceInformations.keys():
                    self.__deviceInformations["modelName"] = child.text
            elif tagName.endswith('modelurl'):
                if "modelURL" not in self.__deviceInformations.keys():
                    self.__deviceInformations["modelURL"] = child.text
            elif tagName.endswith('modelnumber'):
                if "modelNumber" not in self.__deviceInformations.keys():
                    self.__deviceInformations["modelNumber"] = child.text
            elif tagName.endswith('serialnumber'):
                if "serialNumber" not in self.__deviceInformations.keys():
                    self.__deviceInformations["serialNumber"] = child.text
            elif tagName.endswith('presentationurl'):
                if "presentationURL" not in self.__deviceInformations.keys():
                    self.__deviceInformations["presentationURL"] = child.text
            elif tagName.endswith('udn'):
                if "UDN" not in self.__deviceInformations.keys():
                    self.__deviceInformations["UDN"] = child.text
            elif tagName.endswith('upc'):
                if "UPC" not in self.__deviceInformations.keys():
                    self.__deviceInformations["UPC"] = child.text
            elif tagName.endswith('iconlist') or tagName.endswith('specversion'):
                # skip these items
                pass
            else:
                if not tagName.endswith('device') and not tagName.endswith('devicelist'):
                    self.__deviceUnknownKeys[child.tag] = child.text

                self._iterateToFindSCPDElements(child, baseURIPath)

Response: This method is used to iterate through the device definition XML tree and populate the object with the information from the device information.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def loadSCPD(self, serviceType=None, timeout=3, ignoreFailures=False):

        if serviceType is not None:
            self._loadSCPD(serviceType, float(timeout))
        else:
            self.__deviceSCPD = {}
            for serviceType in self.__deviceServiceDefinitions.keys():
                # remove any previous error
                self.__deviceServiceDefinitions[serviceType].pop("error", None)

                try:
                    self._loadSCPD(serviceType, float(timeout))
                except ValueError as e:
                    if not ignoreFailures:
                        # we not ignoring this so rethrow last exception
                        raise
                    else:
                        # add a message in the structure
                        self.__deviceServiceDefinitions[serviceType]["error"] = str(e)

Response: Load the SCPD for a given service type.


Instruction:
Can you generate the documentation for the following Python 3 function
def _parseSCPDActions(self, actionListElement, actions, variableParameterDict):

        # go through all action elements in this list
        for actionElement in actionListElement.getchildren():

            action = {}

            # go through all elements in this action
            for inActionElement in actionElement.getchildren():
                tagName = inActionElement.tag.lower()

                if tagName.endswith("name"):
                    # action name
                    action["name"] = inActionElement.text
                elif tagName.endswith("argumentlist"):
                    # parse the arguments of this action
                    for argumentElement in inActionElement.getchildren():

                        argument = {}

                        # go through the argument definition
                        for inArgumentElement in argumentElement.getchildren():
                            tagName = inArgumentElement.tag.lower()

                            if tagName.endswith("name"):
                                # remember the argument name
                                argument["name"] = inArgumentElement.text
                            elif tagName.endswith("direction"):
                                # is it an in or out argument
                                argument["direction"] = inArgumentElement.text
                            elif tagName.endswith("relatedstatevariable"):
                                # remember the argument and safe it under the variable name to dereference later
                                argument["variable"] = inArgumentElement.text

                                if argument["variable"] not in variableParameterDict.keys():
                                    variableParameterDict[argument["variable"]] = []

                                variableParameterDict[argument["variable"]].append(argument)

                        if "name" not in argument.keys():
                            raise ValueError("Parameter definition does not contain a name.")

                        if "direction" not in argument.keys():
                            raise ValueError("Parameter definition does not contain a direction: " + argument["name"])

                        direction = argument["direction"] + "Parameter"

                        # store the actual argument in the action
                        if direction not in action.keys():
                            action[direction] = {}

                        action[direction][argument["name"]] = argument

                        # cleanup, we stored the argument we dont need these values in there anymore otherwise they
                        # would be redundant
                        del argument["name"]
                        del argument["direction"]

            if "name" not in action.keys():
                raise ValueError("Action has not a name assigned.")

            if action["name"] in actions.keys():
                raise ValueError("Action name defined more than ones: " + action["name"])

            # save the action under its name
            actions[action["name"]] = action

            # cleanup, as we have saved the action under its name in the container it would be redundant
            del action["name"]

Response: Internal method to parse the SCPD definitions.


Instruction:
Given the following Python 3 function, write the documentation
def _parseSCPDVariableTypes(self, variableListElement, variableTypes):

        # iterate through all variables
        for variableElement in variableListElement.getchildren():

            variable = {}

            # iterate through the variable definition
            for inVariableElement in variableElement.getchildren():
                tagName = inVariableElement.tag.lower()

                if tagName.endswith("name"):
                    variable["name"] = inVariableElement.text
                elif tagName.endswith("datatype"):
                    variable["dataType"] = inVariableElement.text
                elif tagName.endswith("defaultvalue"):
                    variable["defaultValue"] = inVariableElement.text

            if "name" not in variable.keys():
                raise ValueError("Variable has no name defined.")

            if "dataType" not in variable.keys():
                raise ValueError("No dataType was defined by variable: " + variable["name"])

            if variable["name"] in variableTypes.keys():
                raise ValueError("Variable has been defined multiple times: " + variable["name"])

            variableTypes[variable["name"]] = variable

Response: Internal method to parse the variable types in the SCPD definitions.


Instruction:
Explain what the following Python 3 code does
def createFromURL(urlOfXMLDefinition):
        url = urlparse(urlOfXMLDefinition)

        if not url.port:
            if url.scheme.lower() == "https":
                port = 443
            else:
                port = 80
        else:
            port = url.port

        return Wifi(url.hostname, port, url.scheme)

Response: Factory method to create a Wifi object from an XML device definition.


Instruction:
Given the following Python 3 function, write the documentation
def getWifiInfo(self, wifiInterfaceId=1, timeout=1):
        namespace = Wifi.getServiceType("getWifiInfo") + str(wifiInterfaceId)
        uri = self.getControlURL(namespace)

        results = self.execute(uri, namespace, "GetInfo", timeout=timeout)

        return WifiBasicInfo(results)

Response: Execute GetInfo action to get Wifi basic information s.


Instruction:
Can you write a function in Python 3 where it
executes GetTotalAssociations action to get the amount of associated Wifi clients.

Response:
def getTotalAssociations(self, wifiInterfaceId=1, timeout=1):
        """Execute GetTotalAssociations action to get the amount of associated Wifi clients.

        :param int wifiInterfaceId: the id of the Wifi interface
        :param float timeout: the timeout to wait for the action to be executed
        :return: the amount of Wifi clients
        :rtype: int

        .. seealso:: :meth:`~simpletr64.actions.Wifi.getGenericAssociatedDeviceInfo`
        """
        namespace = Wifi.getServiceType("getTotalAssociations") + str(wifiInterfaceId)
        uri = self.getControlURL(namespace)

        results = self.execute(uri, namespace, "GetTotalAssociations", timeout=timeout)

        return int(results["NewTotalAssociations"])


Instruction:
Implement a Python 3 function for
executing GetGenericAssociatedDeviceInfo action to get detailed information about a Wifi client.

Response:
def getGenericAssociatedDeviceInfo(self, index, wifiInterfaceId=1, timeout=1):
        """Execute GetGenericAssociatedDeviceInfo action to get detailed information about a Wifi client.

        :param int index: the number of the client
        :param int wifiInterfaceId: the id of the Wifi interface
        :param float timeout: the timeout to wait for the action to be executed
        :return: the detailed information's about a Wifi client
        :rtype: WifiDeviceInfo

        .. seealso:: :meth:`~simpletr64.actions.Wifi.getTotalAssociations`
        """
        namespace = Wifi.getServiceType("getGenericAssociatedDeviceInfo") + str(wifiInterfaceId)
        uri = self.getControlURL(namespace)

        results = self.execute(uri, namespace, "GetGenericAssociatedDeviceInfo", timeout=timeout,
                               NewAssociatedDeviceIndex=index)

        return WifiDeviceInfo(results)


Instruction:
Write a Python 3 script to
execute GetSpecificAssociatedDeviceInfo action to get detailed information about a Wifi client.

Response:
def getSpecificAssociatedDeviceInfo(self, macAddress, wifiInterfaceId=1, timeout=1):
        """Execute GetSpecificAssociatedDeviceInfo action to get detailed information about a Wifi client.

        :param str macAddress: MAC address in the form ``38:C9:86:26:7E:38``; be aware that the MAC address might
            be case sensitive, depending on the router
        :param int wifiInterfaceId: the id of the Wifi interface
        :param float timeout: the timeout to wait for the action to be executed
        :return: the detailed information's about a Wifi client
        :rtype: WifiDeviceInfo

        .. seealso:: :meth:`~simpletr64.actions.Wifi.getGenericAssociatedDeviceInfo`
        """
        namespace = Wifi.getServiceType("getSpecificAssociatedDeviceInfo") + str(wifiInterfaceId)
        uri = self.getControlURL(namespace)

        results = self.execute(uri, namespace, "GetSpecificAssociatedDeviceInfo", timeout=timeout,
                               NewAssociatedDeviceMACAddress=macAddress)

        return WifiDeviceInfo(results, macAddress=macAddress)


Instruction:
Create a Python 3 function to
set enable status for a Wifi interface.

Response:
def setEnable(self, status, wifiInterfaceId=1, timeout=1):
        """Set enable status for a Wifi interface, be careful you don't cut yourself off.

        :param bool status: enable or disable the interface
        :param int wifiInterfaceId: the id of the Wifi interface
        :param float timeout: the timeout to wait for the action to be executed
        """
        namespace = Wifi.getServiceType("setEnable") + str(wifiInterfaceId)
        uri = self.getControlURL(namespace)

        if status:
            setStatus = 1
        else:
            setStatus = 0

        self.execute(uri, namespace, "SetEnable", timeout=timeout, NewEnable=setStatus)


Instruction:
Write a Python 3 script to
set the channel of this Wifi interface

Response:
def setChannel(self, channel, wifiInterfaceId=1, timeout=1):
        """Set the channel of this Wifi interface

        :param int channel: the channel number
        :param int wifiInterfaceId: the id of the Wifi interface
        :param float timeout: the timeout to wait for the action to be executed
        """
        namespace = Wifi.getServiceType("setChannel") + str(wifiInterfaceId)
        uri = self.getControlURL(namespace)

        self.execute(uri, namespace, "SetChannel", timeout=timeout, NewChannel=channel)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def setSSID(self, ssid, wifiInterfaceId=1, timeout=1):
        namespace = Wifi.getServiceType("setChannel") + str(wifiInterfaceId)
        uri = self.getControlURL(namespace)

        self.execute(uri, namespace, "SetChannel", timeout=timeout, NewSSID=ssid)

Response: Set the SSID of the Wifi network