Instruction:
Create a Python 3 function to
run the training and validation on the given data loaders and the given workflow.

Response:
def run(self, data_loaders, workflow, max_epochs, **kwargs):
        """Start running.

        Args:
            data_loaders (list[:obj:`DataLoader`]): Dataloaders for training
                and validation.
            workflow (list[tuple]): A list of (phase, epochs) to specify the
                running order and epochs. E.g, [('train', 2), ('val', 1)] means
                running 2 epochs for training and 1 epoch for validation,
                iteratively.
            max_epochs (int): Total training epochs.
        """
        assert isinstance(data_loaders, list)
        assert mmcv.is_list_of(workflow, tuple)
        assert len(data_loaders) == len(workflow)

        self._max_epochs = max_epochs
        work_dir = self.work_dir if self.work_dir is not None else 'NONE'
        self.logger.info('Start running, host: %s, work_dir: %s',
                         get_host_info(), work_dir)
        self.logger.info('workflow: %s, max: %d epochs', workflow, max_epochs)
        self.call_hook('before_run')

        while self.epoch < max_epochs:
            for i, flow in enumerate(workflow):
                mode, epochs = flow
                if isinstance(mode, str):  # self.train()
                    if not hasattr(self, mode):
                        raise ValueError(
                            'runner has no method named "{}" to run an epoch'.
                            format(mode))
                    epoch_runner = getattr(self, mode)
                elif callable(mode):  # custom train()
                    epoch_runner = mode
                else:
                    raise TypeError('mode in workflow must be a str or '
                                    'callable function, not {}'.format(
                                        type(mode)))
                for _ in range(epochs):
                    if mode == 'train' and self.epoch >= max_epochs:
                        return
                    epoch_runner(data_loaders[i], **kwargs)

        time.sleep(1)  # wait for some hooks like loggers to finish
        self.call_hook('after_run')


Instruction:
How would you implement a function in Python 3 that
registers default training hooks for training.

Response:
def register_training_hooks(self,
                                lr_config,
                                optimizer_config=None,
                                checkpoint_config=None,
                                log_config=None):
        """Register default hooks for training.

        Default hooks include:

        - LrUpdaterHook
        - OptimizerStepperHook
        - CheckpointSaverHook
        - IterTimerHook
        - LoggerHook(s)
        """
        if optimizer_config is None:
            optimizer_config = {}
        if checkpoint_config is None:
            checkpoint_config = {}
        self.register_lr_hooks(lr_config)
        self.register_hook(self.build_hook(optimizer_config, OptimizerHook))
        self.register_hook(self.build_hook(checkpoint_config, CheckpointHook))
        self.register_hook(IterTimerHook())
        if log_config is not None:
            self.register_logger_hooks(log_config)


Instruction:
How would you code a function in Python 3 to
convert a video with ffmpeg.

Response:
def convert_video(in_file, out_file, print_cmd=False, pre_options='',
                  **kwargs):
    """Convert a video with ffmpeg.

    This provides a general api to ffmpeg, the executed command is::

        `ffmpeg -y <pre_options> -i <in_file> <options> <out_file>`

    Options(kwargs) are mapped to ffmpeg commands with the following rules:

    - key=val: "-key val"
    - key=True: "-key"
    - key=False: ""

    Args:
        in_file (str): Input video filename.
        out_file (str): Output video filename.
        pre_options (str): Options appears before "-i <in_file>".
        print_cmd (bool): Whether to print the final ffmpeg command.
    """
    options = []
    for k, v in kwargs.items():
        if isinstance(v, bool):
            if v:
                options.append('-{}'.format(k))
        elif k == 'log_level':
            assert v in [
                'quiet', 'panic', 'fatal', 'error', 'warning', 'info',
                'verbose', 'debug', 'trace'
            ]
            options.append('-loglevel {}'.format(v))
        else:
            options.append('-{} {}'.format(k, v))
    cmd = 'ffmpeg -y {} -i {} {} {}'.format(pre_options, in_file,
                                            ' '.join(options), out_file)
    if print_cmd:
        print(cmd)
    subprocess.call(cmd, shell=True)


Instruction:
Can you generate the documentation for the following Python 3 function
def cut_video(in_file,
              out_file,
              start=None,
              end=None,
              vcodec=None,
              acodec=None,
              log_level='info',
              print_cmd=False,
              **kwargs):
    """Cut a clip from a video.

    Args:
        in_file (str): Input video filename.
        out_file (str): Output video filename.
        start (None or float): Start time (in seconds).
        end (None or float): End time (in seconds).
        vcodec (None or str): Output video codec, None for unchanged.
        acodec (None or str): Output audio codec, None for unchanged.
        log_level (str): Logging level of ffmpeg.
        print_cmd (bool): Whether to print the final ffmpeg command.
    """
    options = {'log_level': log_level}
    if vcodec is None:
        options['vcodec'] = 'copy'
    if acodec is None:
        options['acodec'] = 'copy'
    if start:
        options['ss'] = start
    else:
        start = 0
    if end:
        options['t'] = end - start
    convert_video(in_file, out_file, print_cmd, **options)

Response: Cut a video from a file.


Instruction:
Can you implement a function in Python 3 that
concatenates multiple videos into a single video.

Response:
def concat_video(video_list,
                 out_file,
                 vcodec=None,
                 acodec=None,
                 log_level='info',
                 print_cmd=False,
                 **kwargs):
    """Concatenate multiple videos into a single one.

    Args:
        video_list (list): A list of video filenames
        out_file (str): Output video filename
        vcodec (None or str): Output video codec, None for unchanged
        acodec (None or str): Output audio codec, None for unchanged
        log_level (str): Logging level of ffmpeg.
        print_cmd (bool): Whether to print the final ffmpeg command.
    """
    _, tmp_filename = tempfile.mkstemp(suffix='.txt', text=True)
    with open(tmp_filename, 'w') as f:
        for filename in video_list:
            f.write('file {}\n'.format(osp.abspath(filename)))
    options = {'log_level': log_level}
    if vcodec is None:
        options['vcodec'] = 'copy'
    if acodec is None:
        options['acodec'] = 'copy'
    convert_video(
        tmp_filename,
        out_file,
        print_cmd,
        pre_options='-f concat -safe 0',
        **options)
    os.remove(tmp_filename)


Instruction:
Implement a Python 3 function for
loading a text file and parse the content as a list of strings.

Response:
def list_from_file(filename, prefix='', offset=0, max_num=0):
    """Load a text file and parse the content as a list of strings.

    Args:
        filename (str): Filename.
        prefix (str): The prefix to be inserted to the begining of each item.
        offset (int): The offset of lines.
        max_num (int): The maximum number of lines to be read,
            zeros and negatives mean no limitation.

    Returns:
        list[str]: A list of strings.
    """
    cnt = 0
    item_list = []
    with open(filename, 'r') as f:
        for _ in range(offset):
            f.readline()
        for line in f:
            if max_num > 0 and cnt >= max_num:
                break
            item_list.append(prefix + line.rstrip('\n'))
            cnt += 1
    return item_list


Instruction:
Can you generate a brief explanation for the following Python 3 code
def dict_from_file(filename, key_type=str):
    mapping = {}
    with open(filename, 'r') as f:
        for line in f:
            items = line.rstrip('\n').split()
            assert len(items) >= 2
            key = key_type(items[0])
            val = items[1:] if len(items) > 2 else items[1]
            mapping[key] = val
    return mapping

Response: Load a text file and parse the content as a dict.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def conv3x3(in_planes, out_planes, dilation=1):
    "3x3 convolution with padding"
    return nn.Conv2d(
        in_planes,
        out_planes,
        kernel_size=3,
        padding=dilation,
        dilation=dilation)

Response: 3x3 convolution with padding


Instruction:
Can you generate a brief explanation for the following Python 3 code
def obj_from_dict(info, parent=None, default_args=None):
    assert isinstance(info, dict) and 'type' in info
    assert isinstance(default_args, dict) or default_args is None
    args = info.copy()
    obj_type = args.pop('type')
    if mmcv.is_str(obj_type):
        if parent is not None:
            obj_type = getattr(parent, obj_type)
        else:
            obj_type = sys.modules[obj_type]
    elif not isinstance(obj_type, type):
        raise TypeError('type must be a str or valid type, but got {}'.format(
            type(obj_type)))
    if default_args is not None:
        for name, value in default_args.items():
            args.setdefault(name, value)
    return obj_type(**args)

Response: Initialize an object from a dictionary.


Instruction:
Implement a function in Python 3 to
read an image. Args: img_or_path (ndarray or str): Either a numpy array or image path. If it is a numpy array (loaded image), then it will be returned as is. flag (str): Flags specifying the color type of a loaded image, candidates are `color`, `grayscale` and `unchanged`. Returns: ndarray: Loaded image array.

Response:
def imread(img_or_path, flag='color'):
    """Read an image.

    Args:
        img_or_path (ndarray or str): Either a numpy array or image path.
            If it is a numpy array (loaded image), then it will be returned
            as is.
        flag (str): Flags specifying the color type of a loaded image,
            candidates are `color`, `grayscale` and `unchanged`.

    Returns:
        ndarray: Loaded image array.
    """
    if isinstance(img_or_path, np.ndarray):
        return img_or_path
    elif is_str(img_or_path):
        flag = imread_flags[flag] if is_str(flag) else flag
        check_file_exist(img_or_path,
                         'img file does not exist: {}'.format(img_or_path))
        return cv2.imread(img_or_path, flag)
    else:
        raise TypeError('"img" must be a numpy array or a filename')


Instruction:
How would you implement a function in Python 3 that
reads an image from bytes.

Response:
def imfrombytes(content, flag='color'):
    """Read an image from bytes.

    Args:
        content (bytes): Image bytes got from files or other streams.
        flag (str): Same as :func:`imread`.

    Returns:
        ndarray: Loaded image array.
    """
    img_np = np.frombuffer(content, np.uint8)
    flag = imread_flags[flag] if is_str(flag) else flag
    img = cv2.imdecode(img_np, flag)
    return img


Instruction:
Write a Python 3 script to
write image to file_path.

Response:
def imwrite(img, file_path, params=None, auto_mkdir=True):
    """Write image to file

    Args:
        img (ndarray): Image array to be written.
        file_path (str): Image file path.
        params (None or list): Same as opencv's :func:`imwrite` interface.
        auto_mkdir (bool): If the parent folder of `file_path` does not exist,
            whether to create it automatically.

    Returns:
        bool: Successful or not.
    """
    if auto_mkdir:
        dir_name = osp.abspath(osp.dirname(file_path))
        mkdir_or_exist(dir_name)
    return cv2.imwrite(file_path, img, params)


Instruction:
Write a Python 3 script for
converting a BGR image to grayscale image.

Response:
def bgr2gray(img, keepdim=False):
    """Convert a BGR image to grayscale image.

    Args:
        img (ndarray): The input image.
        keepdim (bool): If False (by default), then return the grayscale image
            with 2 dims, otherwise 3 dims.

    Returns:
        ndarray: The converted grayscale image.
    """
    out_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    if keepdim:
        out_img = out_img[..., None]
    return out_img


Instruction:
Given the following Python 3 function, write the documentation
def gray2bgr(img):
    img = img[..., None] if img.ndim == 2 else img
    out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
    return out_img

Response: Convert a grayscale image to BGR image.


Instruction:
Write a Python 3 function that can
cast elements of an iterable object into some type.

Response:
def iter_cast(inputs, dst_type, return_type=None):
    """Cast elements of an iterable object into some type.

    Args:
        inputs (Iterable): The input object.
        dst_type (type): Destination type.
        return_type (type, optional): If specified, the output object will be
            converted to this type, otherwise an iterator.

    Returns:
        iterator or specified type: The converted object.
    """
    if not isinstance(inputs, collections_abc.Iterable):
        raise TypeError('inputs must be an iterable object')
    if not isinstance(dst_type, type):
        raise TypeError('"dst_type" must be a valid type')

    out_iterable = six.moves.map(dst_type, inputs)

    if return_type is None:
        return out_iterable
    else:
        return return_type(out_iterable)


Instruction:
Can you write a function in Python 3 where it
checks whether the given sequence is of some type.

Response:
def is_seq_of(seq, expected_type, seq_type=None):
    """Check whether it is a sequence of some type.

    Args:
        seq (Sequence): The sequence to be checked.
        expected_type (type): Expected type of sequence items.
        seq_type (type, optional): Expected sequence type.

    Returns:
        bool: Whether the sequence is valid.
    """
    if seq_type is None:
        exp_seq_type = collections_abc.Sequence
    else:
        assert isinstance(seq_type, type)
        exp_seq_type = seq_type
    if not isinstance(seq, exp_seq_type):
        return False
    for item in seq:
        if not isinstance(item, expected_type):
            return False
    return True


Instruction:
Create a Python 3 function to
slice a list into several sub lists by a list of given length.

Response:
def slice_list(in_list, lens):
    """Slice a list into several sub lists by a list of given length.

    Args:
        in_list (list): The list to be sliced.
        lens(int or list): The expected length of each out list.

    Returns:
        list: A list of sliced list.
    """
    if not isinstance(lens, list):
        raise TypeError('"indices" must be a list of integers')
    elif sum(lens) != len(in_list):
        raise ValueError(
            'sum of lens and list length does not match: {} != {}'.format(
                sum(lens), len(in_list)))
    out_list = []
    idx = 0
    for i in range(len(lens)):
        out_list.append(in_list[idx:idx + lens[i]])
        idx += lens[i]
    return out_list


Instruction:
Can you generate a brief explanation for the following Python 3 code
def average(self, n=0):
        assert n >= 0
        for key in self.val_history:
            values = np.array(self.val_history[key][-n:])
            nums = np.array(self.n_history[key][-n:])
            avg = np.sum(values * nums) / np.sum(nums)
            self.output[key] = avg
        self.ready = True

Response: Average latest n values or all values


Instruction:
Here you have a function in Python 3, explain what it does
def scatter(input, devices, streams=None):
    if streams is None:
        streams = [None] * len(devices)

    if isinstance(input, list):
        chunk_size = (len(input) - 1) // len(devices) + 1
        outputs = [
            scatter(input[i], [devices[i // chunk_size]],
                    [streams[i // chunk_size]]) for i in range(len(input))
        ]
        return outputs
    elif isinstance(input, torch.Tensor):
        output = input.contiguous()
        # TODO: copy to a pinned buffer first (if copying from CPU)
        stream = streams[0] if output.numel() > 0 else None
        with torch.cuda.device(devices[0]), torch.cuda.stream(stream):
            output = output.cuda(devices[0], non_blocking=True)
        return output
    else:
        raise Exception('Unknown type {}.'.format(type(input)))

Response: Scatters tensor across multiple GPUs.


Instruction:
Create a Python 3 function to
convert various input types to color tuples.

Response:
def color_val(color):
    """Convert various input to color tuples.

    Args:
        color (:obj:`Color`/str/tuple/int/ndarray): Color inputs

    Returns:
        tuple[int]: A tuple of 3 integers indicating BGR channels.
    """
    if is_str(color):
        return Color[color].value
    elif isinstance(color, Color):
        return color.value
    elif isinstance(color, tuple):
        assert len(color) == 3
        for channel in color:
            assert channel >= 0 and channel <= 255
        return color
    elif isinstance(color, int):
        assert color >= 0 and color <= 255
        return color, color, color
    elif isinstance(color, np.ndarray):
        assert color.ndim == 1 and color.size == 3
        assert np.all((color >= 0) & (color <= 255))
        color = color.astype(np.uint8)
        return tuple(color)
    else:
        raise TypeError('Invalid type for color: {}'.format(type(color)))


Instruction:
Write a Python 3 function for
adding check points in a single line. This method is suitable for running a task on a list of items. A timer will be registered when the method is called for the first time. :Example: >>> import time >>> import mmcv >>> for i in range(1, 6): >>> # simulate a code block >>> time.sleep(i) >>> mmcv.check_time('task1') 2.000 3.000 4.000 5.000 Args: timer_id (str): Timer identifier.

Response:
def check_time(timer_id):
    """Add check points in a single line.

    This method is suitable for running a task on a list of items. A timer will
    be registered when the method is called for the first time.

    :Example:

    >>> import time
    >>> import mmcv
    >>> for i in range(1, 6):
    >>>     # simulate a code block
    >>>     time.sleep(i)
    >>>     mmcv.check_time('task1')
    2.000
    3.000
    4.000
    5.000

    Args:
        timer_id (str): Timer identifier.
    """
    if timer_id not in _g_timers:
        _g_timers[timer_id] = Timer()
        return 0
    else:
        return _g_timers[timer_id].since_last_check()


Instruction:
Create a Python 3 function for
returning the total time since the timer started.

Response:
def since_start(self):
        """Total time since the timer is started.

        Returns (float): Time in seconds.
        """
        if not self._is_running:
            raise TimerError('timer is not running')
        self._t_last = time()
        return self._t_last - self._t_start


Instruction:
Can you implement a function in Python 3 that
returns the time since the last checking.

Response:
def since_last_check(self):
        """Time since the last checking.

        Either :func:`since_start` or :func:`since_last_check` is a checking
        operation.

        Returns (float): Time in seconds.
        """
        if not self._is_running:
            raise TimerError('timer is not running')
        dur = time() - self._t_last
        self._t_last = time()
        return dur


Instruction:
Can you write a function in Python 3 where it
shows optical flow. Args: flow (ndarray or str): The optical flow to be displayed. win_name (str): The window name. wait_time (int): Value of waitKey param.

Response:
def flowshow(flow, win_name='', wait_time=0):
    """Show optical flow.

    Args:
        flow (ndarray or str): The optical flow to be displayed.
        win_name (str): The window name.
        wait_time (int): Value of waitKey param.
    """
    flow = flowread(flow)
    flow_img = flow2rgb(flow)
    imshow(rgb2bgr(flow_img), win_name, wait_time)


Instruction:
Implement a function in Python 3 to
convert a flow map to RGB image.

Response:
def flow2rgb(flow, color_wheel=None, unknown_thr=1e6):
    """Convert flow map to RGB image.

    Args:
        flow (ndarray): Array of optical flow.
        color_wheel (ndarray or None): Color wheel used to map flow field to
            RGB colorspace. Default color wheel will be used if not specified.
        unknown_thr (str): Values above this threshold will be marked as
            unknown and thus ignored.

    Returns:
        ndarray: RGB image that can be visualized.
    """
    assert flow.ndim == 3 and flow.shape[-1] == 2
    if color_wheel is None:
        color_wheel = make_color_wheel()
    assert color_wheel.ndim == 2 and color_wheel.shape[1] == 3
    num_bins = color_wheel.shape[0]

    dx = flow[:, :, 0].copy()
    dy = flow[:, :, 1].copy()

    ignore_inds = (np.isnan(dx) | np.isnan(dy) | (np.abs(dx) > unknown_thr) |
                   (np.abs(dy) > unknown_thr))
    dx[ignore_inds] = 0
    dy[ignore_inds] = 0

    rad = np.sqrt(dx**2 + dy**2)
    if np.any(rad > np.finfo(float).eps):
        max_rad = np.max(rad)
        dx /= max_rad
        dy /= max_rad

    [h, w] = dx.shape

    rad = np.sqrt(dx**2 + dy**2)
    angle = np.arctan2(-dy, -dx) / np.pi

    bin_real = (angle + 1) / 2 * (num_bins - 1)
    bin_left = np.floor(bin_real).astype(int)
    bin_right = (bin_left + 1) % num_bins
    w = (bin_real - bin_left.astype(np.float32))[..., None]
    flow_img = (
        1 - w) * color_wheel[bin_left, :] + w * color_wheel[bin_right, :]
    small_ind = rad <= 1
    flow_img[small_ind] = 1 - rad[small_ind, None] * (1 - flow_img[small_ind])
    flow_img[np.logical_not(small_ind)] *= 0.75

    flow_img[ignore_inds, :] = 0

    return flow_img


Instruction:
Make a summary of the following Python 3 code
def make_color_wheel(bins=None):
    if bins is None:
        bins = [15, 6, 4, 11, 13, 6]
    assert len(bins) == 6

    RY, YG, GC, CB, BM, MR = tuple(bins)

    ry = [1, np.arange(RY) / RY, 0]
    yg = [1 - np.arange(YG) / YG, 1, 0]
    gc = [0, 1, np.arange(GC) / GC]
    cb = [0, 1 - np.arange(CB) / CB, 1]
    bm = [np.arange(BM) / BM, 0, 1]
    mr = [1, 0, 1 - np.arange(MR) / MR]

    num_bins = RY + YG + GC + CB + BM + MR

    color_wheel = np.zeros((3, num_bins), dtype=np.float32)

    col = 0
    for i, color in enumerate([ry, yg, gc, cb, bm, mr]):
        for j in range(3):
            color_wheel[j, col:col + bins[i]] = color[j]
        col += bins[i]

    return color_wheel.T

Response: Build a color wheel for each available resource.


Instruction:
How would you implement a function in Python 3 that
computes the precision@k for the specified values of k

Response:
def accuracy(output, target, topk=(1, )):
    """Computes the precision@k for the specified values of k"""
    with torch.no_grad():
        maxk = max(topk)
        batch_size = target.size(0)

        _, pred = output.topk(maxk, 1, True, True)
        pred = pred.t()
        correct = pred.eq(target.view(1, -1).expand_as(pred))

        res = []
        for k in topk:
            correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
            res.append(correct_k.mul_(100.0 / batch_size))
        return res


Instruction:
Make a summary of the following Python 3 code
def scatter(inputs, target_gpus, dim=0):

    def scatter_map(obj):
        if isinstance(obj, torch.Tensor):
            return OrigScatter.apply(target_gpus, None, dim, obj)
        if isinstance(obj, DataContainer):
            if obj.cpu_only:
                return obj.data
            else:
                return Scatter.forward(target_gpus, obj.data)
        if isinstance(obj, tuple) and len(obj) > 0:
            return list(zip(*map(scatter_map, obj)))
        if isinstance(obj, list) and len(obj) > 0:
            out = list(map(list, zip(*map(scatter_map, obj))))
            return out
        if isinstance(obj, dict) and len(obj) > 0:
            out = list(map(type(obj), zip(*map(scatter_map, obj.items()))))
            return out
        return [obj for targets in target_gpus]

    # After scatter_map is called, a scatter_map cell will exist. This cell
    # has a reference to the actual function scatter_map, which has references
    # to a closure that has a reference to the scatter_map cell (because the
    # fn is recursive). To avoid this reference cycle, we set the function to
    # None, clearing the cell
    try:
        return scatter_map(inputs)
    finally:
        scatter_map = None

Response: Scatter inputs to target gpus.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def scatter_kwargs(inputs, kwargs, target_gpus, dim=0):
    inputs = scatter(inputs, target_gpus, dim) if inputs else []
    kwargs = scatter(kwargs, target_gpus, dim) if kwargs else []
    if len(inputs) < len(kwargs):
        inputs.extend([() for _ in range(len(kwargs) - len(inputs))])
    elif len(kwargs) < len(inputs):
        kwargs.extend([{} for _ in range(len(inputs) - len(kwargs))])
    inputs = tuple(inputs)
    kwargs = tuple(kwargs)
    return inputs, kwargs

Response: Scatter with support for kwargs dictionary


Instruction:
Make a summary of the following Python 3 code
async def fetch(self) -> Response:
        if self.request_config.get('DELAY', 0) > 0:
            await asyncio.sleep(self.request_config['DELAY'])

        timeout = self.request_config.get('TIMEOUT', 10)
        try:
            async with async_timeout.timeout(timeout):
                resp = await self._make_request()
            try:
                resp_data = await resp.text(encoding=self.encoding)
            except UnicodeDecodeError:
                resp_data = await resp.read()

            response = Response(
                url=self.url,
                method=self.method,
                encoding=resp.get_encoding(),
                html=resp_data,
                metadata=self.metadata,
                cookies=resp.cookies,
                headers=resp.headers,
                history=resp.history,
                status=resp.status,
                aws_json=resp.json,
                aws_text=resp.text,
                aws_read=resp.read)
            # Retry middleware
            aws_valid_response = self.request_config.get('VALID')
            if aws_valid_response and iscoroutinefunction(aws_valid_response):
                response = await aws_valid_response(response)
            if response.ok:
                return response
            else:
                return await self._retry(error_msg='request url failed!')
        except asyncio.TimeoutError:
            return await self._retry(error_msg='timeout')
        except Exception as e:
            return await self._retry(error_msg=e)
        finally:
            # Close client session
            await self._close_request_session()

Response: Fetch all the information by using aiohttp


Instruction:
Make a summary of the following Python 3 code
def request(self, *args, **kwargs):
        middleware = args[0]

        @wraps(middleware)
        def register_middleware(*args, **kwargs):
            self.request_middleware.append(middleware)
            return middleware

        return register_middleware()

Response: Define a Decorate to be called before a request.


Instruction:
How would you explain what the following Python 3 function does
def response(self, *args, **kwargs):
        middleware = args[0]

        @wraps(middleware)
        def register_middleware(*args, **kwargs):
            self.response_middleware.appendleft(middleware)
            return middleware

        return register_middleware()

Response: Define a Decorate to be called after a response.


Instruction:
Explain what the following Python 3 code does
async def json(self,
                   *,
                   encoding: str = None,
                   loads: JSONDecoder = DEFAULT_JSON_DECODER,
                   content_type: Optional[str] = 'application/json') -> Any:
        """Read and decodes JSON response."""
        return await self._aws_json(
            encoding=encoding, loads=loads, content_type=content_type)

Response: Read and decodes JSON response.


Instruction:
Write a Python 3 script for
reading response payload and decode.

Response:
async def text(self,
                   *,
                   encoding: Optional[str] = None,
                   errors: str = 'strict') -> str:
        """Read response payload and decode."""
        return await self._aws_text(encoding=encoding, errors=errors)


Instruction:
Write a Python 3 script for
running hook before or after spider start crawling

Response:
async def _run_spider_hook(self, hook_func):
        """
        Run hook before/after spider start crawling
        :param hook_func: aws function
        :return:
        """
        if callable(hook_func):
            try:
                aws_hook_func = hook_func(weakref.proxy(self))
                if isawaitable(aws_hook_func):
                    await aws_hook_func
            except Exception as e:
                self.logger.error(f'<Hook {hook_func.__name__}: {e}')


Instruction:
Here you have a function in Python 3, explain what it does
async def process_callback_result(self, callback_result):
        callback_result_name = type(callback_result).__name__
        process_func_name = self.callback_result_map.get(
            callback_result_name, '')
        process_func = getattr(self, process_func_name, None)
        if process_func is not None:
            await process_func(callback_result)
        else:
            raise InvalidCallbackResult(
                f'<Parse invalid callback result type: {callback_result_name}>'
            )

Response: Corresponding processing for the invalid callback result.


Instruction:
Implement a Python 3 function for
starting an async spider.

Response:
async def async_start(
            cls,
            middleware: typing.Union[typing.Iterable, Middleware] = None,
            loop=None,
            after_start=None,
            before_stop=None,
            **kwargs):
        """
        Start an async spider
        :param middleware: customize middleware or a list of middleware
        :param loop:
        :param after_start: hook
        :param before_stop: hook
        :return:
        """
        loop = loop or asyncio.get_event_loop()
        spider_ins = cls(middleware=middleware, loop=loop, is_async_start=True)
        await spider_ins._start(
            after_start=after_start, before_stop=before_stop)


Instruction:
Can you tell what is the following Python 3 function doing
def start(cls,
              middleware: typing.Union[typing.Iterable, Middleware] = None,
              loop=None,
              after_start=None,
              before_stop=None,
              close_event_loop=True,
              **kwargs):
        """
        Start a spider
        :param after_start: hook
        :param before_stop: hook
        :param middleware: customize middleware or a list of middleware
        :param loop: event loop
        :param close_event_loop: bool
        :return:
        """
        loop = loop or asyncio.new_event_loop()
        spider_ins = cls(middleware=middleware, loop=loop)

        # Actually start crawling
        spider_ins.loop.run_until_complete(
            spider_ins._start(
                after_start=after_start, before_stop=before_stop)
        )
        spider_ins.loop.run_until_complete(
            spider_ins.loop.shutdown_asyncgens())
        if close_event_loop:
            spider_ins.loop.close()

Response: Start a spider with the given middleware.


Instruction:
Create a Python 3 function to
process coroutine callback function

Response:
async def handle_callback(self, aws_callback: typing.Coroutine, response):
        """Process coroutine callback function"""
        callback_result = None

        try:
            callback_result = await aws_callback
        except NothingMatchedError as e:
            self.logger.error(f'<Item: {str(e).lower()}>')
        except Exception as e:
            self.logger.error(f'<Callback[{aws_callback.__name__}]: {e}')
        return callback_result, response


Instruction:
Create a Python 3 function for
wrapping request with middleware.

Response:
async def handle_request(self, request: Request
                             ) -> typing.Tuple[AsyncGeneratorType, Response]:
        """
        Wrap request with middleware.
        :param request:
        :return:
        """
        callback_result, response = None, None

        await self._run_request_middleware(request)
        try:
            callback_result, response = await request.fetch_callback(self.sem)
        except NotImplementedParseError as e:
            self.logger.error(e)
        except NothingMatchedError as e:
            self.logger.error(f'<Item: {str(e).lower()}>')
        except Exception as e:
            self.logger.error(f'<Callback[{request.callback.__name__}]: {e}')
        await self._run_response_middleware(request, response)
        await self._process_response(request=request, response=response)
        return callback_result, response


Instruction:
Can you generate the documentation for the following Python 3 function
async def stop(self, _signal):
        self.logger.info(f'Stopping spider: {self.name}')
        await self._cancel_tasks()
        self.loop.stop()

Response: Stop all running tasks cancel remaining tasks then stop loop.


Instruction:
Implement a function in Python 3 to
parse a match and return the key value pair.

Response:
def _parse_match(self, match):
        """
        If there is a group dict, return the dict;
            even if there's only one value in the dict, return a dictionary;
        If there is a group in match, return the group;
            if there is only one value in the group, return the value;
        if there has no group, return the whole matched string;
        if there are many groups, return a tuple;
        :param match:
        :return:
        """
        if not match:
            if self.default:
                return self.default
            else:
                raise NothingMatchedError(
                    f"Extract `{self._re_select}` error, "
                    f"please check selector or set parameter named `default`")
        else:
            string = match.group()
            groups = match.groups()
            group_dict = match.groupdict()
            if group_dict:
                return group_dict
            if groups:
                return groups[0] if len(groups) == 1 else groups
            return string


Instruction:
How would you explain what the following Python 3 function does
def get_db(self, db='test'):
        if db not in self._db:
            self._db[db] = self.client(db)[db]

        return self._db[db]

Response: Get a db instance


Instruction:
Can you generate a brief explanation for the following Python 3 code
def normalize_task_v2(task):
    '''Ensures tasks have an action key and strings are converted to python objects'''

    result = dict()
    mod_arg_parser = ModuleArgsParser(task)
    try:
        action, arguments, result['delegate_to'] = mod_arg_parser.parse()
    except AnsibleParserError as e:
        try:
            task_info = "%s:%s" % (task[FILENAME_KEY], task[LINE_NUMBER_KEY])
            del task[FILENAME_KEY]
            del task[LINE_NUMBER_KEY]
        except KeyError:
            task_info = "Unknown"
        try:
            import pprint
            pp = pprint.PrettyPrinter(indent=2)
            task_pprint = pp.pformat(task)
        except ImportError:
            task_pprint = task
        raise SystemExit("Couldn't parse task at %s (%s)\n%s" % (task_info, e.message, task_pprint))

    # denormalize shell -> command conversion
    if '_uses_shell' in arguments:
        action = 'shell'
        del(arguments['_uses_shell'])

    for (k, v) in list(task.items()):
        if k in ('action', 'local_action', 'args', 'delegate_to') or k == action:
            # we don't want to re-assign these values, which were
            # determined by the ModuleArgsParser() above
            continue
        else:
            result[k] = v

    result['action'] = dict(__ansible_module__=action)

    if '_raw_params' in arguments:
        result['action']['__ansible_arguments__'] = arguments['_raw_params'].split(' ')
        del(arguments['_raw_params'])
    else:
        result['action']['__ansible_arguments__'] = list()

    if 'argv' in arguments and not result['action']['__ansible_arguments__']:
        result['action']['__ansible_arguments__'] = arguments['argv']
        del(arguments['argv'])

    result['action'].update(arguments)
    return result

Response: Normalizes a task dict to be compatible with the Ansible version 2 API.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def parse_yaml_linenumbers(data, filename):

    def compose_node(parent, index):
        # the line number where the previous token has ended (plus empty lines)
        line = loader.line
        node = Composer.compose_node(loader, parent, index)
        node.__line__ = line + 1
        return node

    def construct_mapping(node, deep=False):
        if ANSIBLE_VERSION < 2:
            mapping = Constructor.construct_mapping(loader, node, deep=deep)
        else:
            mapping = AnsibleConstructor.construct_mapping(loader, node, deep=deep)
        if hasattr(node, '__line__'):
            mapping[LINE_NUMBER_KEY] = node.__line__
        else:
            mapping[LINE_NUMBER_KEY] = mapping._line_number
        mapping[FILENAME_KEY] = filename
        return mapping

    try:
        if ANSIBLE_VERSION < 2:
            loader = yaml.Loader(data)
        else:
            import inspect
            kwargs = {}
            if 'vault_password' in inspect.getargspec(AnsibleLoader.__init__).args:
                kwargs['vault_password'] = DEFAULT_VAULT_PASSWORD
            loader = AnsibleLoader(data, **kwargs)
        loader.compose_node = compose_node
        loader.construct_mapping = construct_mapping
        data = loader.get_single_data()
    except (yaml.parser.ParserError, yaml.scanner.ScannerError) as e:
        raise SystemExit("Failed to parse YAML in %s: %s" % (filename, str(e)))
    return data

Response: Parses a YAML file with line numbers.


Instruction:
Explain what the following Python 3 code does
def append_skipped_rules(pyyaml_data, file_text, file_type):
    yaml = ruamel.yaml.YAML()
    ruamel_data = yaml.load(file_text)

    if file_type in ('tasks', 'handlers'):
        ruamel_tasks = ruamel_data
        pyyaml_tasks = pyyaml_data
    elif file_type == 'playbook':
        try:
            ruamel_tasks = []
            pyyaml_tasks = []
            for ruamel_play, pyyaml_play in zip(ruamel_data, pyyaml_data):
                ruamel_tasks.extend(ruamel_play.get('tasks'))
                pyyaml_tasks.extend(pyyaml_play.get('tasks'))
        except (AttributeError, TypeError):
            return pyyaml_data
    elif file_type == 'meta':
        if not isinstance(pyyaml_data, list):
            return pyyaml_data
        ruamel_tasks = [ruamel_data]
        pyyaml_tasks = pyyaml_data
    else:
        return pyyaml_data

    if len(ruamel_tasks) != len(pyyaml_tasks):
        return pyyaml_data

    for ruamel_task, pyyaml_task in zip(ruamel_tasks, pyyaml_tasks):
        skipped_rules = _get_rule_skips_from_task(ruamel_task)
        if skipped_rules:
            pyyaml_task['skipped_rules'] = skipped_rules

    return pyyaml_data

Response: Adds the skipped rules to the task or meta yaml block.


Instruction:
Can you generate the documentation for the following Python 3 function
def __should_write_changes(self, old_value: StoreItem, new_value: StoreItem) -> bool:

        # If old_value is none or if the new_value's e_tag is '*', then we return True
        if old_value is None or (hasattr(new_value, 'e_tag') and new_value.e_tag == '*'):
            return True
        # If none of the above cases, we verify that e_tags exist on both arguments
        elif hasattr(new_value, 'e_tag') and hasattr(old_value, 'e_tag'):
            if new_value.e_tag is not None and old_value.e_tag is None:
                return True
            # And then we do a comparing between the old and new e_tag values to decide if the new data will be written
            if old_value.e_tag == new_value.e_tag or int(old_value.e_tag) <= int(new_value.e_tag):
                return True
            else:
                return False
        else:
            return False

Response: Helper method that compares two StoreItems and returns True if the new data should be written otherwise returns False.


Instruction:
Can you tell what is the following Python 3 function doing
async def run_middleware(self, context: TurnContext, callback: Callable=None):
        return await self._middleware.receive_activity_with_status(context, callback)

Response: Called by the parent class to run the adapters middleware set and calls the callback handler at the end of the chain.


Instruction:
Explain what the following Python 3 code does
def use(self, *middleware: Middleware):
        for (idx, m) in enumerate(middleware):
            if hasattr(m, 'on_process_request') and callable(m.on_process_request):
                self._middleware.append(m)
                return self
            else:
                raise TypeError('MiddlewareSet.use(): invalid middleware at index "%s" being added.' % idx)

Response: Registers middleware plugins with the bot or set.


Instruction:
Write a Python 3 function that can
send information about the page viewed in the application.

Response:
def track_pageview(self, name: str, url:str, duration: int = 0, properties : Dict[str, object]=None,
                        measurements: Dict[str, object]=None) -> None:
        """
        Send information about the page viewed in the application (a web page for instance).
        :param name: the name of the page that was viewed.
        :param url: the URL of the page that was viewed.
        :param duration: the duration of the page view in milliseconds. (defaults to: 0)
        :param properties: the set of custom properties the client wants attached to this data item. (defaults to: None)
        :param measurements: the set of custom measurements the client wants to attach to this data item. (defaults to: None)
        """
        self._client.track_pageview(name, url, duration, properties, measurements)


Instruction:
Explain what the following Python 3 code does
def track_exception(self, type_exception: type = None, value : Exception =None, tb : traceback =None,
                        properties: Dict[str, object]=None, measurements: Dict[str, object]=None) -> None:
        """
        Send information about a single exception that occurred in the application.
        :param type_exception: the type of the exception that was thrown.
        :param value: the exception that the client wants to send.
        :param tb: the traceback information as returned by :func:`sys.exc_info`.
        :param properties: the set of custom properties the client wants attached to this data item. (defaults to: None)
        :param measurements: the set of custom measurements the client wants to attach to this data item. (defaults to: None)
        """
        self._client.track_exception(type_exception, value, tb, properties, measurements)

Response: Send information about a single exception that occurred in the application.


Instruction:
Create a Python 3 function for
sending information about a single event that has occurred in the context of the application.

Response:
def track_event(self, name: str, properties: Dict[str, object] = None,
                    measurements: Dict[str, object] = None) -> None:
        """
        Send information about a single event that has occurred in the context of the application.
        :param name: the data to associate to this event.
        :param properties: the set of custom properties the client wants attached to this data item. (defaults to: None)
        :param measurements: the set of custom measurements the client wants to attach to this data item. (defaults to: None)
        """
        self._client.track_event(name, properties, measurements)


Instruction:
Write a Python 3 script for
sending a metric to the application.

Response:
def track_metric(self, name: str, value: float, type: TelemetryDataPointType =None,
                    count: int =None, min: float=None, max: float=None, std_dev: float=None,
                    properties: Dict[str, object]=None) -> NotImplemented:
        """
        Send information about a single metric data point that was captured for the application.
        :param name: The name of the metric that was captured.
        :param value: The value of the metric that was captured.
        :param type: The type of the metric. (defaults to: TelemetryDataPointType.aggregation`)
        :param count: the number of metrics that were aggregated into this data point. (defaults to: None)
        :param min: the minimum of all metrics collected that were aggregated into this data point. (defaults to: None)
        :param max: the maximum of all metrics collected that were aggregated into this data point. (defaults to: None)
        :param std_dev: the standard deviation of all metrics collected that were aggregated into this data point. (defaults to: None)
        :param properties: the set of custom properties the client wants attached to this data item. (defaults to: None)
        """
        self._client.track_metric(name, value, type, count, min, max, std_dev, properties)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def track_trace(self, name: str, properties: Dict[str, object]=None, severity=None):
        self._client.track_trace(name, properties, severity)

Response: Send a single trace statement.


Instruction:
Here you have a function in Python 3, explain what it does
def track_request(self, name: str, url: str, success: bool, start_time: str=None,
                    duration: int=None, response_code: str =None, http_method: str=None,
                    properties: Dict[str, object]=None, measurements: Dict[str, object]=None,
                    request_id: str=None):
        """
        Sends a single request that was captured for the application.
        :param name: The name for this request. All requests with the same name will be grouped together.
        :param url: The actual URL for this request (to show in individual request instances).
        :param success: True if the request ended in success, False otherwise.
        :param start_time: the start time of the request. The value should look the same as the one returned by :func:`datetime.isoformat()` (defaults to: None)
        :param duration: the number of milliseconds that this request lasted. (defaults to: None)
        :param response_code: the response code that this request returned. (defaults to: None)
        :param http_method: the HTTP method that triggered this request. (defaults to: None)
        :param properties: the set of custom properties the client wants attached to this data item. (defaults to: None)
        :param measurements: the set of custom measurements the client wants to attach to this data item. (defaults to: None)
        :param request_id: the id for this request. If None, a new uuid will be generated. (defaults to: None)
        """
        self._client.track_request(name, url, success, start_time, duration, response_code, http_method, properties,
                                    measurements, request_id)

Response: Send a single request to the application.


Instruction:
Can you write a function in Python 3 where it
sends a single dependency telemetry that was captured for the application.

Response:
def track_dependency(self, name:str, data:str, type:str=None, target:str=None, duration:int=None,
                        success:bool=None, result_code:str=None, properties:Dict[str, object]=None,
                        measurements:Dict[str, object]=None, dependency_id:str=None):
        """
        Sends a single dependency telemetry that was captured for the application.
        :param name: the name of the command initiated with this dependency call. Low cardinality value. Examples are stored procedure name and URL path template.
        :param data: the command initiated by this dependency call. Examples are SQL statement and HTTP URL with all query parameters.
        :param type: the dependency type name. Low cardinality value for logical grouping of dependencies and interpretation of other fields like commandName and resultCode. Examples are SQL, Azure table, and HTTP. (default to: None)
        :param target: the target site of a dependency call. Examples are server name, host address. (default to: None)
        :param duration: the number of milliseconds that this dependency call lasted. (defaults to: None)
        :param success: true if the dependency call ended in success, false otherwise. (defaults to: None)
        :param result_code: the result code of a dependency call. Examples are SQL error code and HTTP status code. (defaults to: None)
        :param properties: the set of custom properties the client wants attached to this data item. (defaults to: None)
        :param measurements: the set of custom measurements the client wants to attach to this data item. (defaults to: None)
        :param id: the id for this dependency call. If None, a new uuid will be generated. (defaults to: None)
        """
        self._client.track_dependency(name, data, type, target, duration, success, result_code, properties,
                                        measurements, dependency_id)


Instruction:
Can you generate the documentation for the following Python 3 function
def create_property(self, name:str) -> StatePropertyAccessor:
        if not name:
            raise TypeError('BotState.create_property(): BotState cannot be None or empty.')
        return BotStatePropertyAccessor(self, name)

Response: Create a property definition and register it with this BotState.


Instruction:
Explain what the following Python 3 code does
async def load(self, turn_context: TurnContext, force: bool = False) -> None:
        if turn_context == None:
            raise TypeError('BotState.load(): turn_context cannot be None.')

        cached_state = turn_context.turn_state.get(self._context_service_key)
        storage_key = self.get_storage_key(turn_context)

        if (force or not cached_state or not cached_state.state) :
            items = await self._storage.read([storage_key])
            val = items.get(storage_key)
            turn_context.turn_state[self._context_service_key] = CachedBotState(val)

Response: Loads the current state object for this turn.


Instruction:
Given the following Python 3 function, write the documentation
async def save_changes(self, turn_context: TurnContext, force: bool = False) -> None:
        if turn_context == None:
            raise TypeError('BotState.save_changes(): turn_context cannot be None.')

        cached_state = turn_context.turn_state.get(self._context_service_key)

        if force or (cached_state != None and cached_state.is_changed == True):
            storage_key = self.get_storage_key(turn_context)
            changes : Dict[str, object] = { storage_key: cached_state.state }
            await self._storage.write(changes)
            cached_state.hash = cached_state.compute_hash(cached_state.state)

Response: Saves the state of the current state object to the storage.


Instruction:
Make a summary of the following Python 3 code
async def clear_state(self, turn_context: TurnContext):
        if turn_context == None:
            raise TypeError('BotState.clear_state(): turn_context cannot be None.')

        #  Explicitly setting the hash will mean IsChanged is always true. And that will force a Save.
        cache_value = CachedBotState()
        cache_value.hash = ''
        turn_context.turn_state[self._context_service_key] = cache_value

Response: Clears any state currently stored in this state scope.


Instruction:
Can you write a function in Python 3 where it
deletes any state currently stored in this state scope.

Response:
async def delete(self, turn_context: TurnContext) -> None:
        """
        Delete any state currently stored in this state scope.

        :param turn_context: The context object for this turn.
        :return: None
        """
        if turn_context == None:
            raise TypeError('BotState.delete(): turn_context cannot be None.')

        turn_context.turn_state.pop(self._context_service_key)

        storage_key = self.get_storage_key(turn_context)
        await self._storage.delete({ storage_key })


Instruction:
Create a Python 3 function for
setting the value of a property on the state cache.

Response:
async def set_property_value(self, turn_context: TurnContext, property_name: str, value: object) -> None:
        """
        Deletes a property from the state cache in the turn context.

        :param turn_context: The context object for this turn.
        :param property_name: The value to set on the property.
        :return: None
        """

        if turn_context == None:
            raise TypeError('BotState.delete_property(): turn_context cannot be None.')
        if not property_name:
            raise TypeError('BotState.delete_property(): property_name cannot be None.')
        cached_state = turn_context.turn_state.get(self._context_service_key)
        cached_state.state[property_name] = value


Instruction:
Can you create a Python 3 function that
continues a conversation with a user.

Response:
async def continue_conversation(self, reference: ConversationReference, logic):
        """
        Continues a conversation with a user. This is often referred to as the bots "Proactive Messaging"
        flow as its lets the bot proactively send messages to a conversation or user that its already
        communicated with. Scenarios like sending notifications or coupons to a user are enabled by this
        method.
        :param reference:
        :param logic:
        :return:
        """
        request = TurnContext.apply_conversation_reference(Activity(), reference, is_incoming=True)
        context = self.create_context(request)
        return await self.run_middleware(context, logic)


Instruction:
Can you generate the documentation for the following Python 3 function
async def create_conversation(self, reference: ConversationReference, logic):
        try:
            if reference.service_url is None:
                raise TypeError('BotFrameworkAdapter.create_conversation(): reference.service_url cannot be None.')

            # Create conversation
            parameters = ConversationParameters(bot=reference.bot)
            client = self.create_connector_client(reference.service_url)

            resource_response = await client.conversations.create_conversation(parameters)
            request = TurnContext.apply_conversation_reference(Activity(), reference, is_incoming=True)
            request.conversation = ConversationAccount(id=resource_response.id)
            if resource_response.service_url:
                request.service_url = resource_response.service_url

            context = self.create_context(request)
            return await self.run_middleware(context, logic)

        except Exception as e:
            raise e

Response: Starts a new conversation with a user.


Instruction:
How would you explain what the following Python 3 function does
async def process_activity(self, req, auth_header: str, logic: Callable):
        activity = await self.parse_request(req)
        auth_header = auth_header or ''

        await self.authenticate_request(activity, auth_header)
        context = self.create_context(activity)

        return await self.run_middleware(context, logic)

Response: Processes an activity received by the bots web server.


Instruction:
How would you explain what the following Python 3 function does
async def authenticate_request(self, request: Activity, auth_header: str):
        await JwtTokenValidation.authenticate_request(request, auth_header, self._credential_provider)

Response: Allows for overriding of authentication in unit tests.


Instruction:
How would you explain what the following Python 3 function does
async def parse_request(req):

        async def validate_activity(activity: Activity):
            if not isinstance(activity.type, str):
                raise TypeError('BotFrameworkAdapter.parse_request(): invalid or missing activity type.')
            return True

        if not isinstance(req, Activity):
            # If the req is a raw HTTP Request, try to deserialize it into an Activity and return the Activity.
            if hasattr(req, 'body'):
                try:
                    activity = Activity().deserialize(req.body)
                    is_valid_activity = await validate_activity(activity)
                    if is_valid_activity:
                        return activity
                except Exception as e:
                    raise e
            elif 'body' in req:
                try:
                    activity = Activity().deserialize(req['body'])
                    is_valid_activity = await validate_activity(activity)
                    if is_valid_activity:
                        return activity
                except Exception as e:
                    raise e
            else:
                raise TypeError('BotFrameworkAdapter.parse_request(): received invalid request')
        else:
            # The `req` has already been deserialized to an Activity, so verify the Activity.type and return it.
            is_valid_activity = await validate_activity(req)
            if is_valid_activity:
                return req

Response: Parses and validates a request and returns the corresponding object.


Instruction:
How would you explain what the following Python 3 function does
async def update_activity(self, context: TurnContext, activity: Activity):
        try:
            client = self.create_connector_client(activity.service_url)
            return await client.conversations.update_activity(
                activity.conversation.id,
                activity.conversation.activity_id,
                activity)
        except Exception as e:
            raise e

Response: Updates an activity that was previously sent to a channel.


Instruction:
Given the following Python 3 function, write the documentation
async def delete_activity(self, context: TurnContext, conversation_reference: ConversationReference):
        try:
            client = self.create_connector_client(conversation_reference.service_url)
            await client.conversations.delete_activity(conversation_reference.conversation.id,
                                                             conversation_reference.activity_id)
        except Exception as e:
            raise e

Response: Deletes an activity that was previously sent to a channel.


Instruction:
How would you code a function in Python 3 to
delete a member from the current conversation.

Response:
async def delete_conversation_member(self, context: TurnContext, member_id: str) -> None:
        """
        Deletes a member from the current conversation.
        :param context:
        :param member_id:
        :return:
        """
        try:
            if not context.activity.service_url:
                raise TypeError('BotFrameworkAdapter.delete_conversation_member(): missing service_url')
            if not context.activity.conversation or not context.activity.conversation.id:
                raise TypeError('BotFrameworkAdapter.delete_conversation_member(): missing conversation or '
                                'conversation.id')
            service_url = context.activity.service_url
            conversation_id = context.activity.conversation.id
            client = self.create_connector_client(service_url)
            return await client.conversations.delete_conversation_member(conversation_id, member_id)
        except AttributeError as attr_e:
            raise attr_e
        except Exception as e:
            raise e


Instruction:
Can you generate the documentation for the following Python 3 function
async def get_activity_members(self, context: TurnContext, activity_id: str):
        try:
            if not activity_id:
                activity_id = context.activity.id
            if not context.activity.service_url:
                raise TypeError('BotFrameworkAdapter.get_activity_member(): missing service_url')
            if not context.activity.conversation or not context.activity.conversation.id:
                raise TypeError('BotFrameworkAdapter.get_activity_member(): missing conversation or conversation.id')
            if not activity_id:
                raise TypeError('BotFrameworkAdapter.get_activity_member(): missing both activity_id and '
                                'context.activity.id')
            service_url = context.activity.service_url
            conversation_id = context.activity.conversation.id
            client = self.create_connector_client(service_url)
            return await client.conversations.get_activity_members(conversation_id, activity_id)
        except Exception as e:
            raise e

Response: Get the members of a given activity.


Instruction:
Can you create a Python 3 function that
gets the members of a current conversation.

Response:
async def get_conversation_members(self, context: TurnContext):
        """
        Lists the members of a current conversation.
        :param context:
        :return:
        """
        try:
            if not context.activity.service_url:
                raise TypeError('BotFrameworkAdapter.get_conversation_members(): missing service_url')
            if not context.activity.conversation or not context.activity.conversation.id:
                raise TypeError('BotFrameworkAdapter.get_conversation_members(): missing conversation or '
                                'conversation.id')
            service_url = context.activity.service_url
            conversation_id = context.activity.conversation.id
            client = self.create_connector_client(service_url)
            return await client.conversations.get_conversation_members(conversation_id)
        except Exception as e:
            raise e


Instruction:
How would you code a function in Python 3 to
get the Conversations in which this bot has participated for a given channel server.

Response:
async def get_conversations(self, service_url: str, continuation_token: str=None):
        """
        Lists the Conversations in which this bot has participated for a given channel server. The channel server
        returns results in pages and each page will include a `continuationToken` that can be used to fetch the next
        page of results from the server.
        :param service_url:
        :param continuation_token:
        :return:
        """
        client = self.create_connector_client(service_url)
        return await client.conversations.get_conversations(continuation_token)


Instruction:
Write a Python 3 function that can
create a connector client.

Response:
def create_connector_client(self, service_url: str) -> ConnectorClient:
        """
        Allows for mocking of the connector client in unit tests.
        :param service_url:
        :return:
        """
        client = ConnectorClient(self._credentials, base_url=service_url)
        client.config.add_user_agent(USER_AGENT)
        return client


Instruction:
Can you tell what is the following Python 3 function doing
def add_dialog(self, dialog: Dialog) -> object:
        self._dialogs.add(dialog)
        if not self.initial_dialog_id:
            self.initial_dialog_id = dialog.id
        return self

Response: Adds a dialog to the ComponentDialog object.


Instruction:
Can you implement a function in Python 3 that
authenticates the request and sets the service url in the set of trusted urls.

Response:
async def authenticate_request(activity: Activity, auth_header: str, credentials: CredentialProvider) -> ClaimsIdentity:
        """Authenticates the request and sets the service url in the set of trusted urls.

        :param activity: The incoming Activity from the Bot Framework or the Emulator
        :type activity: ~botframework.connector.models.Activity
        :param auth_header: The Bearer token included as part of the request
        :type auth_header: str
        :param credentials: The set of valid credentials, such as the Bot Application ID
        :type credentials: CredentialProvider

        :raises Exception:
        """
        if not auth_header:
            # No auth header was sent. We might be on the anonymous code path.
            is_auth_disabled = await credentials.is_authentication_disabled()
            if is_auth_disabled:
                # We are on the anonymous code path.
                return

            # No Auth Header. Auth is required. Request is not authorized.
            raise Exception('Unauthorized Access. Request is not authorized')

        claims_identity = await JwtTokenValidation.validate_auth_header(auth_header, credentials, activity.channel_id, activity.service_url)

        # On the standard Auth path, we need to trust the URL that was incoming.
        MicrosoftAppCredentials.trust_service_url(activity.service_url)

        return claims_identity


Instruction:
Write a Python 3 script to
return the full wheel distribution name with - replaced with _

Response:
def wheel_dist_name(self):
        """Return distribution full name with - replaced with _"""
        return '-'.join((safer_name(self.distribution.get_name()),
                         safer_version(self.distribution.get_version())))


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

        impl_tag, abi_tag, plat_tag = self.get_tag()

        archive_basename = "%s-%s-%s-%s" % (
            self.wheel_dist_name,
            impl_tag,
            abi_tag,
            plat_tag)
        return archive_basename

Response: Return archive name without extension


Instruction:
Can you write a function in Python 3 where it
generates a list of tuples that define a specific requirement for a specific locale.

Response:
def setupcfg_requirements(self):
        """Generate requirements from setup.cfg as
        ('Requires-Dist', 'requirement; qualifier') tuples. From a metadata
        section in setup.cfg:

        [metadata]
        provides-extra = extra1
            extra2
        requires-dist = requirement; qualifier
            another; qualifier2
            unqualified

        Yields

        ('Provides-Extra', 'extra1'),
        ('Provides-Extra', 'extra2'),
        ('Requires-Dist', 'requirement; qualifier'),
        ('Requires-Dist', 'another; qualifier2'),
        ('Requires-Dist', 'unqualified')
        """
        metadata = self.distribution.get_option_dict('metadata')

        # our .ini parser folds - to _ in key names:
        for key, title in (('provides_extra', 'Provides-Extra'),
                           ('requires_dist', 'Requires-Dist')):
            if not key in metadata:
                continue
            field = metadata[key]
            for line in field[1].splitlines():
                line = line.strip()
                if not line:
                    continue
                yield (title, line)


Instruction:
How would you code a function in Python 3 to
add additional requirements from setup. cfg to file metadata_path

Response:
def add_requirements(self, metadata_path):
        """Add additional requirements from setup.cfg to file metadata_path"""
        additional = list(self.setupcfg_requirements())
        if not additional: return
        pkg_info = read_pkg_info(metadata_path)
        if 'Provides-Extra' in pkg_info or 'Requires-Dist' in pkg_info:
            warnings.warn('setup.cfg requirements overwrite values from setup.py')
            del pkg_info['Provides-Extra']
            del pkg_info['Requires-Dist']
        for k, v in additional:
            pkg_info[k] = v
        write_pkg_info(metadata_path, pkg_info)


Instruction:
Can you create a Python 3 function that
converts an egg - info directory into a. dist - info directory.

Response:
def egg2dist(self, egginfo_path, distinfo_path):
        """Convert an .egg-info directory into a .dist-info directory"""
        def adios(p):
            """Appropriately delete directory, file or link."""
            if os.path.exists(p) and not os.path.islink(p) and os.path.isdir(p):
                shutil.rmtree(p)
            elif os.path.exists(p):
                os.unlink(p)

        adios(distinfo_path)

        if not os.path.exists(egginfo_path):
            # There is no egg-info. This is probably because the egg-info
            # file/directory is not named matching the distribution name used
            # to name the archive file. Check for this case and report
            # accordingly.
            import glob
            pat = os.path.join(os.path.dirname(egginfo_path), '*.egg-info')
            possible = glob.glob(pat)
            err = "Egg metadata expected at %s but not found" % (egginfo_path,)
            if possible:
                alt = os.path.basename(possible[0])
                err += " (%s found - possible misnamed archive file?)" % (alt,)

            raise ValueError(err)

        if os.path.isfile(egginfo_path):
            # .egg-info is a single file
            pkginfo_path = egginfo_path
            pkg_info = self._pkginfo_to_metadata(egginfo_path, egginfo_path)
            os.mkdir(distinfo_path)
        else:
            # .egg-info is a directory
            pkginfo_path = os.path.join(egginfo_path, 'PKG-INFO')
            pkg_info = self._pkginfo_to_metadata(egginfo_path, pkginfo_path)

            # ignore common egg metadata that is useless to wheel
            shutil.copytree(egginfo_path, distinfo_path,
                            ignore=lambda x, y: set(('PKG-INFO',
                                                     'requires.txt',
                                                     'SOURCES.txt',
                                                     'not-zip-safe',)))

            # delete dependency_links if it is only whitespace
            dependency_links_path = os.path.join(distinfo_path, 'dependency_links.txt')
            with open(dependency_links_path, 'r') as dependency_links_file:
                dependency_links = dependency_links_file.read().strip()
            if not dependency_links:
                adios(dependency_links_path)

        write_pkg_info(os.path.join(distinfo_path, 'METADATA'), pkg_info)

        # XXX deprecated. Still useful for current distribute/setuptools.
        metadata_path = os.path.join(distinfo_path, 'METADATA')
        self.add_requirements(metadata_path)

        # XXX intentionally a different path than the PEP.
        metadata_json_path = os.path.join(distinfo_path, 'metadata.json')
        pymeta = pkginfo_to_dict(metadata_path,
                                 distribution=self.distribution)

        if 'description' in pymeta:
            description_filename = 'DESCRIPTION.rst'
            description_text = pymeta.pop('description')
            description_path = os.path.join(distinfo_path,
                                            description_filename)
            with open(description_path, "wb") as description_file:
                description_file.write(description_text.encode('utf-8'))
            pymeta['extensions']['python.details']['document_names']['description'] = description_filename

        # XXX heuristically copy any LICENSE/LICENSE.txt?
        license = self.license_file()
        if license:
            license_filename = 'LICENSE.txt'
            shutil.copy(license, os.path.join(self.distinfo_dir, license_filename))
            pymeta['extensions']['python.details']['document_names']['license'] = license_filename

        with open(metadata_json_path, "w") as metadata_json:
            json.dump(pymeta, metadata_json, sort_keys=True)

        adios(egginfo_path)


Instruction:
Can you tell what is the following Python 3 function doing
def get_conversations(
            self, continuation_token=None, custom_headers=None, raw=False, **operation_config):
        """GetConversations.

        List the Conversations in which this bot has participated.
        GET from this method with a skip token
        The return value is a ConversationsResult, which contains an array of
        ConversationMembers and a skip token.  If the skip token is not empty,
        then
        there are further values to be returned. Call this method again with
        the returned token to get more values.
        Each ConversationMembers object contains the ID of the conversation and
        an array of ChannelAccounts that describe the members of the
        conversation.

        :param continuation_token: skip or continuation token
        :type continuation_token: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: ConversationsResult or ClientRawResponse if raw=true
        :rtype: ~botframework.connector.models.ConversationsResult or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<botframework.connector.models.ErrorResponseException>`
        """
        # Construct URL
        url = self.get_conversations.metadata['url']

        # Construct parameters
        query_parameters = {}
        if continuation_token is not None:
            query_parameters['continuationToken'] = self._serialize.query("continuation_token", continuation_token, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters, header_parameters)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None
        if response.status_code == 200:
            deserialized = self._deserialize('ConversationsResult', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

Response: This method returns the list of conversations in which this bot has participated.


Instruction:
Write a Python 3 script to
create a new conversation from the given parameters.

Response:
def create_conversation(
            self, parameters, custom_headers=None, raw=False, **operation_config):
        """CreateConversation.

        Create a new Conversation.
        POST to this method with a
        * Bot being the bot creating the conversation
        * IsGroup set to true if this is not a direct message (default is
        false)
        * Array containing the members to include in the conversation
        The return value is a ResourceResponse which contains a conversation id
        which is suitable for use
        in the message payload and REST API uris.
        Most channels only support the semantics of bots initiating a direct
        message conversation.  An example of how to do that would be:
        ```
        var resource = await connector.conversations.CreateConversation(new
        ConversationParameters(){ Bot = bot, members = new ChannelAccount[] {
        new ChannelAccount("user1") } );
        await connect.Conversations.SendToConversationAsync(resource.Id, new
        Activity() ... ) ;
        ```.

        :param parameters: Parameters to create the conversation from
        :type parameters:
         ~botframework.connector.models.ConversationParameters
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: ConversationResourceResponse or ClientRawResponse if raw=true
        :rtype: ~botframework.connector.models.ConversationResourceResponse or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<botframework.connector.models.ErrorResponseException>`
        """
        # Construct URL
        url = self.create_conversation.metadata['url']

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        body_content = self._serialize.body(parameters, 'ConversationParameters')

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters, body_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200, 201, 202]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None
        if response.status_code == 200:
            deserialized = self._deserialize('ConversationResourceResponse', response)
        if response.status_code == 201:
            deserialized = self._deserialize('ConversationResourceResponse', response)
        if response.status_code == 202:
            deserialized = self._deserialize('ConversationResourceResponse', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized


Instruction:
Here you have a function in Python 3, explain what it does
def get_conversation_paged_members(
            self, conversation_id, page_size=None, continuation_token=None, custom_headers=None, raw=False, **operation_config):
        """GetConversationPagedMembers.

        Enumerate the members of a conversation one page at a time.
        This REST API takes a ConversationId. Optionally a pageSize and/or
        continuationToken can be provided. It returns a PagedMembersResult,
        which contains an array
        of ChannelAccounts representing the members of the conversation and a
        continuation token that can be used to get more values.
        One page of ChannelAccounts records are returned with each call. The
        number of records in a page may vary between channels and calls. The
        pageSize parameter can be used as
        a suggestion. If there are no additional results the response will not
        contain a continuation token. If there are no members in the
        conversation the Members will be empty or not present in the response.
        A response to a request that has a continuation token from a prior
        request may rarely return members from a previous request.

        :param conversation_id: Conversation ID
        :type conversation_id: str
        :param page_size: Suggested page size
        :type page_size: int
        :param continuation_token: Continuation Token
        :type continuation_token: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: PagedMembersResult or ClientRawResponse if raw=true
        :rtype: ~botframework.connector.models.PagedMembersResult or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = self.get_conversation_paged_members.metadata['url']
        path_format_arguments = {
            'conversationId': self._serialize.url("conversation_id", conversation_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        if page_size is not None:
            query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
        if continuation_token is not None:
            query_parameters['continuationToken'] = self._serialize.query("continuation_token", continuation_token, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters, header_parameters)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None
        if response.status_code == 200:
            deserialized = self._deserialize('PagedMembersResult', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

Response: This method returns the list of members of a conversation in a page at a time.


Instruction:
Write a Python 3 script for
sending information about the page viewed in the application.

Response:
def track_pageview(self, name: str, url, duration: int = 0, properties : Dict[str, object]=None,
                        measurements: Dict[str, object]=None) -> None:
        """
        Send information about the page viewed in the application (a web page for instance).
        :param name: the name of the page that was viewed.
        :param url: the URL of the page that was viewed.
        :param duration: the duration of the page view in milliseconds. (defaults to: 0)
        :param properties: the set of custom properties the client wants attached to this data item. (defaults to: None)
        :param measurements: the set of custom measurements the client wants to attach to this data item. (defaults to: None)
        """
        raise NotImplementedError('BotTelemetryClient.track_request(): is not implemented.')


Instruction:
Here you have a function in Python 3, explain what it does
def track_exception(self, type: type = None, value : Exception =None, tb : traceback =None,
                        properties: Dict[str, object]=None, measurements: Dict[str, object]=None) -> None:
        """
        Send information about a single exception that occurred in the application.
        :param type: the type of the exception that was thrown.
        :param value: the exception that the client wants to send.
        :param tb: the traceback information as returned by :func:`sys.exc_info`.
        :param properties: the set of custom properties the client wants attached to this data item. (defaults to: None)
        :param measurements: the set of custom measurements the client wants to attach to this data item. (defaults to: None)
        """
        raise NotImplementedError('BotTelemetryClient.track_request(): is not implemented.')

Response: Send information about a single exception that occurred in the application.


Instruction:
Can you tell what is the following Python 3 function doing
def track_metric(self, name: str, value: float, type: TelemetryDataPointType =None,
                    count: int =None, min: float=None, max: float=None, std_dev: float=None,
                    properties: Dict[str, object]=None) -> NotImplemented:
        """
        Send information about a single metric data point that was captured for the application.
        :param name: The name of the metric that was captured.
        :param value: The value of the metric that was captured.
        :param type: The type of the metric. (defaults to: TelemetryDataPointType.aggregation`)
        :param count: the number of metrics that were aggregated into this data point. (defaults to: None)
        :param min: the minimum of all metrics collected that were aggregated into this data point. (defaults to: None)
        :param max: the maximum of all metrics collected that were aggregated into this data point. (defaults to: None)
        :param std_dev: the standard deviation of all metrics collected that were aggregated into this data point. (defaults to: None)
        :param properties: the set of custom properties the client wants attached to this data item. (defaults to: None)
        """
        raise NotImplementedError('BotTelemetryClient.track_metric(): is not implemented.')

Response: Send information about a single metric data point that was captured for the application.


Instruction:
Write a Python 3 function for
sending a single request that was captured for the application. :param name: The name for this request. All requests with the same name will be grouped together. :param url: The actual URL for this request (to show in individual request instances). :param success: True if the request ended in success, False otherwise. :param start_time: the start time of the request. The value should look the same as the one returned by :func:`datetime.isoformat()` (defaults to: None) :param duration: the number of milliseconds that this request lasted. (defaults to: None) :param response_code: the response code that this request returned. (defaults to: None) :param http_method: the HTTP method that triggered this request. (defaults to: None) :param properties: the set of custom properties the client wants attached to this data item. (defaults to: None) :param measurements: the set of custom measurements the client wants to attach to this data item. (defaults to: None) :param request_id: the id for this request. If None, a new uuid will be generated. (defaults to: None)

Response:
def track_request(self, name: str, url: str, success: bool, start_time: str=None,
                    duration: int=None, response_code: str =None, http_method: str=None,
                    properties: Dict[str, object]=None, measurements: Dict[str, object]=None,
                    request_id: str=None):
        """
        Sends a single request that was captured for the application.
        :param name: The name for this request. All requests with the same name will be grouped together.
        :param url: The actual URL for this request (to show in individual request instances).
        :param success: True if the request ended in success, False otherwise.
        :param start_time: the start time of the request. The value should look the same as the one returned by :func:`datetime.isoformat()` (defaults to: None)
        :param duration: the number of milliseconds that this request lasted. (defaults to: None)
        :param response_code: the response code that this request returned. (defaults to: None)
        :param http_method: the HTTP method that triggered this request. (defaults to: None)
        :param properties: the set of custom properties the client wants attached to this data item. (defaults to: None)
        :param measurements: the set of custom measurements the client wants to attach to this data item. (defaults to: None)
        :param request_id: the id for this request. If None, a new uuid will be generated. (defaults to: None)
        """
        raise NotImplementedError('BotTelemetryClient.track_request(): is not implemented.')


Instruction:
Explain what the following Python 3 code does
def track_dependency(self, name:str, data:str, type:str=None, target:str=None, duration:int=None,
                        success:bool=None, result_code:str=None, properties:Dict[str, object]=None,
                        measurements:Dict[str, object]=None, dependency_id:str=None):
        """
        Sends a single dependency telemetry that was captured for the application.
        :param name: the name of the command initiated with this dependency call. Low cardinality value. Examples are stored procedure name and URL path template.
        :param data: the command initiated by this dependency call. Examples are SQL statement and HTTP URL with all query parameters.
        :param type: the dependency type name. Low cardinality value for logical grouping of dependencies and interpretation of other fields like commandName and resultCode. Examples are SQL, Azure table, and HTTP. (default to: None)
        :param target: the target site of a dependency call. Examples are server name, host address. (default to: None)
        :param duration: the number of milliseconds that this dependency call lasted. (defaults to: None)
        :param success: true if the dependency call ended in success, false otherwise. (defaults to: None)
        :param result_code: the result code of a dependency call. Examples are SQL error code and HTTP status code. (defaults to: None)
        :param properties: the set of custom properties the client wants attached to this data item. (defaults to: None)
        :param measurements: the set of custom measurements the client wants to attach to this data item. (defaults to: None)
        :param id: the id for this dependency call. If None, a new uuid will be generated. (defaults to: None)
        """
        raise NotImplementedError('BotTelemetryClient.track_dependency(): is not implemented.')

Response: This method is used to track the execution of a dependency call.


Instruction:
Make a summary of the following Python 3 code
def text(text: str, speak: str = None, input_hint: Union[InputHints, str] = InputHints.accepting_input) -> Activity:
        message = Activity(type=ActivityTypes.message, text=text, input_hint=input_hint)
        if speak:
            message.speak = speak

        return message

Response: Create a simple text activity.


Instruction:
Implement a function in Python 3 to
return an activity that includes a set of suggested actions and optional text.

Response:
def suggested_actions(actions: List[CardAction], text: str = None, speak: str = None,
                          input_hint: Union[InputHints, str] = InputHints.accepting_input) -> Activity:
        """
        Returns a message that includes a set of suggested actions and optional text.

        :Example:
        message = MessageFactory.suggested_actions([CardAction(title='a', type=ActionTypes.im_back, value='a'),
                                                    CardAction(title='b', type=ActionTypes.im_back, value='b'),
                                                    CardAction(title='c', type=ActionTypes.im_back, value='c')], 'Choose a color')
        await context.send_activity(message)

        :param actions:
        :param text:
        :param speak:
        :param input_hint:
        :return:
        """
        actions = SuggestedActions(actions=actions)
        message = Activity(type=ActivityTypes.message, input_hint=input_hint, suggested_actions=actions)
        if text:
            message.text = text
        if speak:
            message.speak = speak
        return message


Instruction:
Can you generate a brief explanation for the following Python 3 code
def attachment(attachment: Attachment, text: str = None, speak: str = None,
                   input_hint: Union[InputHints, str] = None):
        """
        Returns a single message activity containing an attachment.

        :Example:
        message = MessageFactory.attachment(CardFactory.hero_card(HeroCard(title='White T-Shirt',
                                                                  images=[CardImage(url='https://example.com/whiteShirt.jpg')],
                                                                  buttons=[CardAction(title='buy')])))
        await context.send_activity(message)

        :param attachment:
        :param text:
        :param speak:
        :param input_hint:
        :return:
        """
        return attachment_activity(AttachmentLayoutTypes.list, [attachment], text, speak, input_hint)

Response: Returns a single message activity containing an attachment.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def list(attachments: List[Attachment], text: str = None, speak: str = None,
             input_hint: Union[InputHints, str] = None) -> Activity:
        """
        Returns a message that will display a set of attachments in list form.

        :Example:
        message = MessageFactory.list([CardFactory.hero_card(HeroCard(title='title1',
                                                             images=[CardImage(url='imageUrl1')],
                                                             buttons=[CardAction(title='button1')])),
                                       CardFactory.hero_card(HeroCard(title='title2',
                                                             images=[CardImage(url='imageUrl2')],
                                                             buttons=[CardAction(title='button2')])),
                                       CardFactory.hero_card(HeroCard(title='title3',
                                                             images=[CardImage(url='imageUrl3')],
                                                             buttons=[CardAction(title='button3')]))])
        await context.send_activity(message)

        :param attachments:
        :param text:
        :param speak:
        :param input_hint:
        :return:
        """
        return attachment_activity(AttachmentLayoutTypes.list, attachments, text, speak, input_hint)

Response: Returns a message that will display a set of attachments in list form.


Instruction:
Given the following Python 3 function, write the documentation
def content_url(url: str, content_type: str, name: str = None, text: str = None, speak: str = None,
                    input_hint: Union[InputHints, str] = None):
        """
        Returns a message that will display a single image or video to a user.

        :Example:
        message = MessageFactory.content_url('https://example.com/hawaii.jpg', 'image/jpeg',
                                             'Hawaii Trip', 'A photo from our family vacation.')
        await context.send_activity(message)

        :param url:
        :param content_type:
        :param name:
        :param text:
        :param speak:
        :param input_hint:
        :return:
        """
        attachment = Attachment(content_type=content_type, content_url=url)
        if name:
            attachment.name = name
        return attachment_activity(AttachmentLayoutTypes.list, [attachment], text, speak, input_hint)

Response: A function that returns a message that will display a single image or video to a user.


Instruction:
Can you generate a brief explanation for the following Python 3 code
async def authenticate_token_service_url(auth_header: str, credentials: CredentialProvider, service_url: str, channel_id: str) -> ClaimsIdentity:
        identity = await asyncio.ensure_future(
            ChannelValidation.authenticate_token(auth_header, credentials, channel_id))

        service_url_claim = identity.get_claim_value(ChannelValidation.SERVICE_URL_CLAIM)
        if service_url_claim != service_url:
            # Claim must match. Not Authorized.
            raise Exception('Unauthorized. service_url claim do not match.')

        return identity

Response: Authenticate the token with the given service url.


Instruction:
Here you have a function in Python 3, explain what it does
async def authenticate_token(auth_header: str, credentials: CredentialProvider, channel_id: str) -> ClaimsIdentity:
        token_extractor = JwtTokenExtractor(
            ChannelValidation.TO_BOT_FROM_CHANNEL_TOKEN_VALIDATION_PARAMETERS,
            Constants.TO_BOT_FROM_CHANNEL_OPEN_ID_METADATA_URL,
            Constants.ALLOWED_SIGNING_ALGORITHMS)

        identity = await asyncio.ensure_future(
            token_extractor.get_identity_from_auth_header(auth_header, channel_id))
        if not identity:
            # No valid identity. Not Authorized.
            raise Exception('Unauthorized. No valid identity.')

        if not identity.isAuthenticated:
            # The token is in some way invalid. Not Authorized.
            raise Exception('Unauthorized. Is not authenticated')

        # Now check that the AppID in the claimset matches
        # what we're looking for. Note that in a multi-tenant bot, this value
        # comes from developer code that may be reaching out to a service, hence the
        # Async validation.

        # Look for the "aud" claim, but only if issued from the Bot Framework
        if identity.get_claim_value(Constants.ISSUER_CLAIM) != Constants.TO_BOT_FROM_CHANNEL_TOKEN_ISSUER:
            # The relevant Audience Claim MUST be present. Not Authorized.
            raise Exception('Unauthorized. Audience Claim MUST be present.')

        # The AppId from the claim in the token must match the AppId specified by the developer.
        # Note that the Bot Framework uses the Audience claim ("aud") to pass the AppID.
        aud_claim = identity.get_claim_value(Constants.AUDIENCE_CLAIM)
        is_valid_app_id = await asyncio.ensure_future(credentials.is_valid_appid(aud_claim or ""))
        if not is_valid_app_id:
            # The AppId is not valid or not present. Not Authorized.
            raise Exception('Unauthorized. Invalid AppId passed on token: ', aud_claim)

        return identity

Response: Authenticate a token using the given credentials.