Instruction:
Can you tell what is the following Python 3 function doing
def url_input(url_string, download=True):
    log.debug('URL Input - {0}'.format(url_string))
    try:
        open_xml = urllib.request.urlopen(url_string)
    except urllib.error.URLError as err:
        print('utils.input.url_input received a bad URL, or could not connect')
        raise err
    else:
        #Employ a quick check on the mimetype of the link
        if not open_xml.headers['Content-Type'] == 'text/xml':
            sys.exit('URL request does not appear to be XML')
        filename = open_xml.headers['Content-Disposition'].split('\"')[1]
        if download:
            with open(filename, 'wb') as xml_file:
                xml_file.write(open_xml.read())
        return openaccess_epub.utils.file_root_name(filename)

Response: This method expects a URL string and returns the root name of the xml file.


Instruction:
Write a Python 3 function that can
validate a given listing against the CWL job listing schema.

Response:
def _red_listing_validation(key, listing):
    """
    Raises an RedValidationError, if the given listing does not comply with cwl_job_listing_schema.
    If listing is None or an empty list, no exception is thrown.

    :param key: The input key to build an error message if needed.
    :param listing: The listing to validate
    :raise RedValidationError: If the given listing does not comply with cwl_job_listing_schema
    """

    if listing:
        try:
            jsonschema.validate(listing, cwl_job_listing_schema)
        except ValidationError as e:
            raise RedValidationError('REDFILE listing of input "{}" does not comply with jsonschema: {}'
                                     .format(key, e.context))


Instruction:
Can you implement a function in Python 3 that
returns a list of mounting connectors from the red data.

Response:
def red_get_mount_connectors(red_data, ignore_outputs):
    """
    Returns a list of mounting connectors

    :param red_data: The red data to be searched
    :param ignore_outputs: If outputs should be ignored
    :return: A list of connectors with active mount option.
    """

    keys = []

    batches = red_data.get('batches')
    inputs = red_data.get('inputs')
    if batches:
        for batch in batches:
            keys.extend(red_get_mount_connectors_from_inputs(batch['inputs']))
    elif inputs:
        keys.extend(red_get_mount_connectors_from_inputs(inputs))

    if not ignore_outputs:
        outputs = red_data.get('outputs')
        if batches:
            for batch in batches:
                batch_outputs = batch.get('outputs')
                if batch_outputs:
                    keys.extend(red_get_mount_connectors_from_outputs(batch_outputs))

        elif outputs:
            keys.extend(red_get_mount_connectors_from_outputs(outputs))

    return keys


Instruction:
Write a Python 3 function for
invoking the cleanup functions for all inputs.

Response:
def cleanup(connector_manager, red_data, tmp_dir):
    """
    Invokes the cleanup functions for all inputs.
    """
    for key, arg in red_data['inputs'].items():
        val = arg

        if isinstance(arg, list):
            for index, i in enumerate(arg):
                if not isinstance(i, dict):
                    continue

                # connector_class should be one of 'File' or 'Directory'
                connector_class = i['class']
                input_key = '{}_{}'.format(key, index)
                path = os.path.join(tmp_dir, input_key)
                connector_data = i['connector']
                internal = {URL_SCHEME_IDENTIFIER: path}

                if connector_class == 'File':
                    connector_manager.receive_cleanup(connector_data, input_key, internal)
                elif connector_class == 'Directory':
                    connector_manager.receive_directory_cleanup(connector_data, input_key, internal)

        elif isinstance(arg, dict):
            # connector_class should be one of 'File' or 'Directory'
            connector_class = arg['class']
            input_key = key
            path = os.path.join(tmp_dir, input_key)
            connector_data = val['connector']
            internal = {URL_SCHEME_IDENTIFIER: path}

            if connector_class == 'File':
                connector_manager.receive_cleanup(connector_data, input_key, internal)
            elif connector_class == 'Directory':
                connector_manager.receive_directory_cleanup(connector_data, input_key, internal)

    try:
        os.rmdir(tmp_dir)
    except (OSError, FileNotFoundError):
        # Maybe, raise a warning here, because not all connectors have cleaned up their contents correctly.
        pass


Instruction:
How would you explain what the following Python 3 function does
def _execute_connector(connector_command, top_level_argument, *file_contents, listing=None):
        # create temp_files for every file_content
        temp_files = []
        for file_content in file_contents:
            if file_content is None:
                continue
            tmp_file = tempfile.NamedTemporaryFile('w')
            json.dump(file_content, tmp_file)
            tmp_file.flush()
            temp_files.append(tmp_file)

        tmp_listing_file = None
        if listing:
            tmp_listing_file = tempfile.NamedTemporaryFile('w')
            json.dump(listing, tmp_listing_file)
            tmp_listing_file.flush()

        command = [connector_command, top_level_argument]
        command.extend([t.name for t in temp_files])

        if tmp_listing_file:
            command.append('--listing {}'.format(tmp_listing_file.name))

        result = execute(' '.join(command))

        # close temp_files
        for temp_file in temp_files:
            temp_file.close()

        if tmp_listing_file:
            tmp_listing_file.close()

        return result['returnCode'], result['stdErr']

Response: Executes a connector command and returns the return code and stderr of the connector command.


Instruction:
Here you have a function in Python 3, explain what it does
def directory_listing_content_check(directory_path, listing):
        if listing:
            for sub in listing:
                path = os.path.join(directory_path, sub['basename'])
                if sub['class'] == 'File':
                    if not os.path.isfile(path):
                        return 'listing contains "{}" but this file could not be found on disk.'.format(path)
                elif sub['class'] == 'Directory':
                    if not os.path.isdir(path):
                        return 'listing contains "{}" but this directory could not be found on disk'.format(path)
                    listing = sub.get('listing')
                    if listing:
                        return ConnectorManager.directory_listing_content_check(path, listing)
        return None

Response: Checks if a given listing is present under the given directory path.


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

    devices = []

    try:
        import pycuda.autoinit
        import pycuda.driver as cuda

        for device_id in range(cuda.Device.count()):
            vram = cuda.Device(device_id).total_memory()

            devices.append(GPUDevice(device_id, vram))
    except ImportError:
        raise InsufficientGPUError('No Nvidia-GPUs could be found, because "pycuda" could not be imported.')

    return devices

Response: Imports pycuda at runtime and reads GPU information.


Instruction:
Implement a Python 3 function for
determining sufficient GPUs for the given requirements and returns a list of GPUDevices.

Response:
def match_gpus(available_devices, requirements):
    """
    Determines sufficient GPUs for the given requirements and returns a list of GPUDevices.
    If there aren't sufficient GPUs a InsufficientGPUException is thrown.

    :param available_devices: A list of GPUDevices
    :param requirements: A list of GPURequirements

    :return: A list of sufficient devices
    """

    if not requirements:
        return []

    if not available_devices:
        raise InsufficientGPUError("No GPU devices available, but {} devices required.".format(len(requirements)))

    available_devices = available_devices.copy()

    used_devices = []

    for req in requirements:
        dev = search_device(req, available_devices)
        if dev:
            used_devices.append(dev)
            available_devices.remove(dev)
        else:
            raise InsufficientGPUError("Not all GPU requirements could be fulfilled.")

    return used_devices


Instruction:
Given the following Python 3 function, write the documentation
def get_gpu_requirements(gpus_reqs):
    requirements = []

    if gpus_reqs:
        if type(gpus_reqs) is dict:
            count = gpus_reqs.get('count')
            if count:
                for i in range(count):
                    requirements.append(GPURequirement())
        elif type(gpus_reqs) is list:
            for gpu_req in gpus_reqs:
                requirements.append(GPURequirement(min_vram=gpu_req['minVram']))
        return requirements
    else:
        # If no requirements are supplied
        return []

Response: Extracts the GPU from a dictionary requirements as list of GPURequirements.


Instruction:
Make a summary of the following Python 3 code
def set_nvidia_environment_variables(environment, gpu_ids):

    if gpu_ids:
        nvidia_visible_devices = ""
        for gpu_id in gpu_ids:
            nvidia_visible_devices += "{},".format(gpu_id)
        environment["NVIDIA_VISIBLE_DEVICES"] = nvidia_visible_devices

Response: Sets the environment variables that are set in the Nvidia - GPUs environment variable.


Instruction:
Can you generate the documentation for the following Python 3 function
def is_sufficient(self, device):

        sufficient = True
        if (self.min_vram is not None) and (device.vram < self.min_vram):
            sufficient = False

        return sufficient

Response: Returns whether the device is sufficient for this requirement.


Instruction:
Can you tell what is the following Python 3 function doing
def cache_location():
    '''Cross-platform placement of cached files'''
    plat = platform.platform()
    log.debug('Platform read as: {0}'.format(plat))
    if plat.startswith('Windows'):
        log.debug('Windows platform detected')
        return os.path.join(os.environ['APPDATA'], 'OpenAccess_EPUB')
    elif plat.startswith('Darwin'):
        log.debug('Mac platform detected')
    elif plat.startswith('Linux'):
        log.debug('Linux platform detected')
    else:
        log.warning('Unhandled platform for cache_location')

    #This code is written for Linux and Mac, don't expect success for others
    path = os.path.expanduser('~')
    if path == '~':
        path = os.path.expanduser('~user')
        if path == '~user':
            log.critical('Could not resolve the correct cache location')
            sys.exit('Could not resolve the correct cache location')
    cache_loc = os.path.join(path, '.OpenAccess_EPUB')
    log.debug('Cache located: {0}'.format(cache_loc))
    return cache_loc

Response: Cross - platform placement of cached files


Instruction:
Can you generate the documentation for the following Python 3 function
def load_config_module():
    import imp
    config_path = config_location()
    try:
        config = imp.load_source('config', config_path)
    except IOError:
        log.critical('Config file not found. oaepub exiting...')
        sys.exit('Config file not found. Please run \'oaepub configure\'')
    else:
        log.debug('Config file loaded from {0}'.format(config_path))
        return config

Response: Load the config. py file and return the module object.


Instruction:
Given the following Python 3 function, write the documentation
def get_absolute_path(some_path):
    if os.path.isabs(some_path):
        return some_path
    else:
        return evaluate_relative_path(os.getcwd(), some_path)

Response: This function returns an absolute path for the input path.


Instruction:
How would you explain what the following Python 3 function does
def file_root_name(name):
    base = os.path.basename(name)
    root = os.path.splitext(base)[0]
    if not root:
        warning = 'file_root_name returned an empty root name from \"{0}\"'
        log.warning(warning.format(name))
    return root

Response: Returns the root name of a file from a full file path.


Instruction:
Explain what the following Python 3 code does
def files_with_ext(extension, directory='.', recursive=False):
    if recursive:
        log.info('Recursively searching {0} for files with extension "{1}"'.format(directory, extension))
        for dirname, subdirnames, filenames in os.walk(directory):
            for filename in filenames:
                filepath = os.path.join(dirname, filename)
                _root, ext = os.path.splitext(filepath)
                if extension.lower() == ext.lower():
                    yield filepath

    else:
        log.info('Looking in {0} for files with extension:  "{1}"'.format(directory, extension))
        for name in os.listdir(directory):
            filepath = os.path.join(directory, name)
            if not os.path.isfile(filepath):  # Skip non-files
                continue
            _root, ext = os.path.splitext(filepath)
            if extension.lower() == ext.lower():
                yield filepath

Response: Generator function that will iterate over all files in the specified directory and return a path to the files which possess a matching extension.


Instruction:
Create a Python 3 function for
checking if a directory already exists and if yes deletes it if it does not.

Response:
def dir_exists(directory):
    """
    If a directory already exists that will be overwritten by some action, this
    will ask the user whether or not to continue with the deletion.

    If the user responds affirmatively, then the directory will be removed. If
    the user responds negatively, then the process will abort.
    """
    log.info('Directory exists! Asking the user')
    reply = input('''The directory {0} already exists.
It will be overwritten if the operation continues.
Replace? [Y/n]'''.format(directory))
    if reply.lower() in ['y', 'yes', '']:
        shutil.rmtree(directory)
        os.makedirs(directory)
    else:
        log.critical('Aborting process, user declined overwriting {0}'.format(directory))
        sys.exit('Aborting process!')


Instruction:
Implement a Python 3 function for
getting the nearest dict entry based on latitude and longitude.

Response:
def get_nearest_by_coordinates(
        data: list, latitude_key: str, longitude_key: str,
        target_latitude: float, target_longitude: float) -> Any:
    """Get the closest dict entry based on latitude/longitude."""
    return min(
        data,
        key=lambda p: haversine(
            target_latitude,
            target_longitude,
            float(p[latitude_key]),
            float(p[longitude_key])
        ))


Instruction:
How would you code a function in Python 3 to
determine the distance between two latitude and longitude pairs.

Response:
def haversine(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
    """Determine the distance between two latitude/longitude pairs."""
    lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])

    # haversine formula
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    calc_a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
    calc_c = 2 * asin(sqrt(calc_a))

    return 6371 * calc_c


Instruction:
Can you generate a brief explanation for the following Python 3 code
def in_file(self, fn: str) -> Iterator[InsertionPoint]:
        logger.debug("finding insertion points in file: %s", fn)
        yield from self.__file_insertions.get(fn, [])

Response: Returns an iterator over all of the insertion points in a given file.


Instruction:
Implement a function in Python 3 to
return an iterator over all of the insertion points located at a specific line.

Response:
def at_line(self, line: FileLine) -> Iterator[InsertionPoint]:
        """
        Returns an iterator over all of the insertion points located at a
        given line.
        """
        logger.debug("finding insertion points at line: %s", str(line))
        filename = line.filename  # type: str
        line_num = line.num  # type: int
        for ins in self.in_file(filename):
            if line_num == ins.location.line:
                logger.debug("found insertion point at line [%s]: %s",
                             str(line), ins)
                yield ins


Instruction:
Given the following Python 3 function, write the documentation
def getUnitCost(self, CorpNum):

        result = self._httpget('/CloseDown/UnitCost', CorpNum)

        return float(result.unitCost)

Response: Get UnitCost of a particular item.


Instruction:
Make a summary of the following Python 3 code
def checkCorpNums(self, MemberCorpNum, CorpNumList):
        if CorpNumList == None or len(CorpNumList) < 1:
            raise PopbillException(-99999999,"조죄할 사업자번호 목록이 입력되지 않았습니다.")

        postData = self._stringtify(CorpNumList)

        return self._httppost('/CloseDown',postData,MemberCorpNum)

Response:
휴폐업조회 대량 확인, 최대 1000건
            args
                MemberCorpNum : 팝빌회원 사업자번호
                CorpNumList : 조회할 사업자번호 배열
            return
                휴폐업정보 Object as List
            raise
                PopbillException


Instruction:
How would you explain what the following Python 3 function does
def loadPng(varNumVol, tplPngSize, strPathPng):
    print('------Load PNGs')
    # Create list of png files to load:
    lstPngPaths = [None] * varNumVol
    for idx01 in range(0, varNumVol):
        lstPngPaths[idx01] = (strPathPng + str(idx01) + '.png')

    # Load png files. The png data will be saved in a numpy array of the
    # following order: aryPngData[x-pixel, y-pixel, PngNumber]. The
    # sp.misc.imread function actually contains three values per pixel (RGB),
    # but since the stimuli are black-and-white, any one of these is sufficient
    # and we discard the others.
    aryPngData = np.zeros((tplPngSize[0],
                           tplPngSize[1],
                           varNumVol))
    for idx01 in range(0, varNumVol):
        aryPngData[:, :, idx01] = np.array(Image.open(lstPngPaths[idx01]))

    # Convert RGB values (0 to 255) to integer ones and zeros:
    aryPngData = (aryPngData > 0).astype(int)

    return aryPngData

Response: Load PNG files and return a 2d numpy array of the size of the image.


Instruction:
Write a Python 3 script for
loading presentation order of motion directions.

Response:
def loadPrsOrd(vecRunLngth, strPathPresOrd, vecVslStim):
    """Load presentation order of motion directions.

    Parameters
    ----------
    vecRunLngth : list
        Number of volumes in every run
    strPathPresOrd : str
        Path to the npy vector containing order of presented motion directions.
    vecVslStim: list
        Key of (stimulus) condition presented in every run
    Returns
    -------
    aryPresOrdAprt : 1d numpy array, shape [n_vols]
        Presentation order of aperture position.
    aryPresOrdMtn : 1d numpy array, shape [n_vols]
        Presentation order of motion direction.
    """
    print('------Load presentation order of motion directions')
    aryPresOrd = np.empty((0, 2))
    for idx01 in range(0, len(vecRunLngth)):
        # reconstruct file name
        # ---> consider: some runs were shorter than others(replace next row)
        filename1 = (strPathPresOrd + str(vecVslStim[idx01]) +
                     '.pickle')
        # filename1 = (strPathPresOrd + str(idx01+1) + '.pickle')
        # load array
        with open(filename1, 'rb') as handle:
            array1 = pickle.load(handle)
        tempCond = array1["Conditions"]
        tempCond = tempCond[:vecRunLngth[idx01], :]
        # add temp array to aryPresOrd
        aryPresOrd = np.concatenate((aryPresOrd, tempCond), axis=0)
    aryPresOrdAprt = aryPresOrd[:, 0].astype(int)
    aryPresOrdMtn = aryPresOrd[:, 1].astype(int)

    return aryPresOrdAprt, aryPresOrdMtn


Instruction:
Create a Python 3 function to
create pixel - wise boxcar functions.

Response:
def crtPwBoxCarFn(varNumVol, aryPngData, aryPresOrd, vecMtDrctn):
    """Create pixel-wise boxcar functions.

    Parameters
    ----------
    input1 : 2d numpy array, shape [n_samples, n_measurements]
        Description of input 1.
    input2 : float, positive
      Description of input 2.
    Returns
    -------
    data : 2d numpy array, shape [n_samples, n_measurements]
        Closed data.
    Reference
    ---------
    [1]
    """
    print('------Create pixel-wise boxcar functions')
    aryBoxCar = np.empty(aryPngData.shape[0:2] + (len(vecMtDrctn),) +
                         (varNumVol,), dtype='int64')
    for ind, num in enumerate(vecMtDrctn):
        aryCondTemp = np.zeros((aryPngData.shape), dtype='int64')
        lgcTempMtDrctn = [aryPresOrd == num][0]
        aryCondTemp[:, :, lgcTempMtDrctn] = np.copy(
            aryPngData[:, :, lgcTempMtDrctn])
        aryBoxCar[:, :, ind, :] = aryCondTemp

    return aryBoxCar


Instruction:
How would you explain what the following Python 3 function does
def crtGauss2D(varSizeX, varSizeY, varPosX, varPosY, varSd):
    varSizeX = int(varSizeX)
    varSizeY = int(varSizeY)

    # aryX and aryY are in reversed order, this seems to be necessary:
    aryY, aryX = sp.mgrid[0:varSizeX,
                          0:varSizeY]

    # The actual creation of the Gaussian array:
    aryGauss = (
        (np.square((aryX - varPosX)) + np.square((aryY - varPosY))) /
        (2.0 * np.square(varSd))
        )
    aryGauss = np.exp(-aryGauss) / (2 * np.pi * np.square(varSd))

    return aryGauss

Response: Create 2D Gaussian kernel.


Instruction:
Explain what the following Python 3 code does
def cnvlGauss2D(idxPrc, aryBoxCar, aryMdlParamsChnk, tplPngSize, varNumVol,
                queOut):
    """Spatially convolve boxcar functions with 2D Gaussian.

    Parameters
    ----------
    idxPrc : 2d numpy array, shape [n_samples, n_measurements]
        Description of input 1.
    aryBoxCar : float, positive
      Description of input 2.
    aryMdlParamsChnk : 2d numpy array, shape [n_samples, n_measurements]
        Description of input 1.
    tplPngSize : float, positive
      Description of input 2.
    varNumVol : 2d numpy array, shape [n_samples, n_measurements]
        Description of input 1.
    queOut : float, positive
      Description of input 2.
    Returns
    -------
    data : 2d numpy array, shape [n_samples, n_measurements]
        Closed data.
    Reference
    ---------
    [1]
    """
    # Number of combinations of model parameters in the current chunk:
    varChnkSze = np.size(aryMdlParamsChnk, axis=0)

    # Determine number of motion directions
    varNumMtnDrtn = aryBoxCar.shape[2]

    # Output array with pRF model time courses:
    aryOut = np.zeros([varChnkSze, varNumMtnDrtn, varNumVol])

    # Loop through different motion directions:
    for idxMtn in range(0, varNumMtnDrtn):
        # Loop through combinations of model parameters:
        for idxMdl in range(0, varChnkSze):

            # Spatial parameters of current model:
            varTmpX = aryMdlParamsChnk[idxMdl, 1]
            varTmpY = aryMdlParamsChnk[idxMdl, 2]
            varTmpSd = aryMdlParamsChnk[idxMdl, 3]

            # Create pRF model (2D):
            aryGauss = crtGauss2D(tplPngSize[0],
                                  tplPngSize[1],
                                  varTmpX,
                                  varTmpY,
                                  varTmpSd)

            # Multiply pixel-time courses with Gaussian pRF models:
            aryPrfTcTmp = np.multiply(aryBoxCar[:, :, idxMtn, :],
                                      aryGauss[:, :, None])

            # Calculate sum across x- and y-dimensions - the 'area under the
            # Gaussian surface'. This is essentially an unscaled version of the
            # pRF time course model (i.e. not yet scaled for size of the pRF).
            aryPrfTcTmp = np.sum(aryPrfTcTmp, axis=(0, 1))

            # Put model time courses into function's output with 2d Gaussian
            # arrray:
            aryOut[idxMdl, idxMtn, :] = aryPrfTcTmp

    # Put column with the indicies of model-parameter-combinations into the
    # output array (in order to be able to put the pRF model time courses into
    # the correct order after the parallelised function):
    lstOut = [idxPrc,
              aryOut]

    # Put output to queue:
    queOut.put(lstOut)

Response: Spatially convolve boxcar functions with 2D Gaussian.


Instruction:
How would you code a function in Python 3 to
create neural time courses from pixel - wise boxcar functions.

Response:
def crtPrfNrlTc(aryBoxCar, varNumMtDrctn, varNumVol, tplPngSize, varNumX,
                varExtXmin,  varExtXmax, varNumY, varExtYmin, varExtYmax,
                varNumPrfSizes, varPrfStdMin, varPrfStdMax, varPar):
    """Create neural model time courses from pixel-wise boxcar functions.

    Parameters
    ----------
    aryBoxCar : 4d numpy array, shape [n_x_pix, n_y_pix, n_mtn_dir, n_vol]
        Description of input 1.
    varNumMtDrctn : float, positive
        Description of input 2.
    varNumVol : float, positive
        Description of input 2.
    tplPngSize : tuple
        Description of input 2.
    varNumX : float, positive
        Description of input 2.
    varExtXmin : float, positive
        Description of input 2.
    varExtXmax : float, positive
        Description of input 2.
    varNumY : float, positive
        Description of input 2.
    varExtYmin : float, positive
        Description of input 2.
    varExtYmax : float, positive
        Description of input 2.
    varNumPrfSizes : float, positive
        Description of input 2.
    varPrfStdMin : float, positive
        Description of input 2.
    varPrfStdMax : float, positive
        Description of input 2.
    varPar : float, positive
        Description of input 2.
    Returns
    -------
    aryNrlTc : 5d numpy array, shape [n_x_pos, n_y_pos, n_sd, n_mtn_dir, n_vol]
        Closed data.
    Reference
    ---------
    [1]
    """
    print('------Create neural time course models')

    # Vector with the x-indicies of the positions in the super-sampled visual
    # space at which to create pRF models.
    vecX = np.linspace(0, (tplPngSize[0] - 1), varNumX, endpoint=True)

    # Vector with the y-indicies of the positions in the super-sampled visual
    # space at which to create pRF models.
    vecY = np.linspace(0, (tplPngSize[1] - 1), varNumY, endpoint=True)

    # We calculate the scaling factor from degrees of visual angle to pixels
    # separately for the x- and the y-directions (the two should be the same).
    varDgr2PixX = tplPngSize[0] / (varExtXmax - varExtXmin)
    varDgr2PixY = tplPngSize[1] / (varExtYmax - varExtYmin)

    # Check whether varDgr2PixX and varDgr2PixY are similar:
    strErrMsg = 'ERROR. The ratio of X and Y dimensions in stimulus ' + \
        'space (in degrees of visual angle) and the ratio of X and Y ' + \
        'dimensions in the upsampled visual space do not agree'
    assert 0.5 > np.absolute((varDgr2PixX - varDgr2PixY)), strErrMsg

    # Vector with pRF sizes to be modelled (still in degree of visual angle):
    vecPrfSd = np.linspace(varPrfStdMin, varPrfStdMax, varNumPrfSizes,
                           endpoint=True)

    # We multiply the vector containing pRF sizes with the scaling factors.
    # Now the vector with the pRF sizes can be used directly for creation of
    # Gaussian pRF models in visual space.
    vecPrfSd = np.multiply(vecPrfSd, varDgr2PixX)

    # Number of pRF models to be created (i.e. number of possible combinations
    # of x-position, y-position, and standard deviation):
    varNumMdls = varNumX * varNumY * varNumPrfSizes

    # Array for the x-position, y-position, and standard deviations for which
    # pRF model time courses are going to be created, where the columns
    # correspond to: (0) an index starting from zero, (1) the x-position, (2)
    # the y-position, and (3) the standard deviation. The parameters are in
    # units of the upsampled visual space.
    aryMdlParams = np.zeros((varNumMdls, 4))

    # Counter for parameter array:
    varCntMdlPrms = 0

    # Put all combinations of x-position, y-position, and standard deviations
    # into the array:

    # Loop through x-positions:
    for idxX in range(0, varNumX):

        # Loop through y-positions:
        for idxY in range(0, varNumY):

            # Loop through standard deviations (of Gaussian pRF models):
            for idxSd in range(0, varNumPrfSizes):

                # Place index and parameters in array:
                aryMdlParams[varCntMdlPrms, 0] = varCntMdlPrms
                aryMdlParams[varCntMdlPrms, 1] = vecX[idxX]
                aryMdlParams[varCntMdlPrms, 2] = vecY[idxY]
                aryMdlParams[varCntMdlPrms, 3] = vecPrfSd[idxSd]

                # Increment parameter index:
                varCntMdlPrms = varCntMdlPrms + 1

    # The long array with all the combinations of model parameters is put into
    # separate chunks for parallelisation, using a list of arrays.
    lstMdlParams = np.array_split(aryMdlParams, varPar)

    # Create a queue to put the results in:
    queOut = mp.Queue()

    # Empty list for results from parallel processes (for pRF model time course
    # results):
    lstPrfTc = [None] * varPar

    # Empty list for processes:
    lstPrcs = [None] * varPar

    print('---------Creating parallel processes')

    # Create processes:
    for idxPrc in range(0, varPar):
        lstPrcs[idxPrc] = mp.Process(target=cnvlGauss2D,
                                     args=(idxPrc, aryBoxCar,
                                           lstMdlParams[idxPrc], tplPngSize,
                                           varNumVol, queOut)
                                     )
        # Daemon (kills processes when exiting):
        lstPrcs[idxPrc].Daemon = True

    # Start processes:
    for idxPrc in range(0, varPar):
        lstPrcs[idxPrc].start()

    # Collect results from queue:
    for idxPrc in range(0, varPar):
        lstPrfTc[idxPrc] = queOut.get(True)

    # Join processes:
    for idxPrc in range(0, varPar):
        lstPrcs[idxPrc].join()

    print('---------Collecting results from parallel processes')
    # Put output arrays from parallel process into one big array
    lstPrfTc = sorted(lstPrfTc)
    aryPrfTc = np.empty((0, varNumMtDrctn, varNumVol))
    for idx in range(0, varPar):
        aryPrfTc = np.concatenate((aryPrfTc, lstPrfTc[idx][1]), axis=0)

    # check that all the models were collected correctly
    assert aryPrfTc.shape[0] == varNumMdls

    # Clean up:
    del(aryMdlParams)
    del(lstMdlParams)
    del(lstPrfTc)

    # Array representing the low-resolution visual space, of the form
    # aryPrfTc[x-position, y-position, pRF-size, varNum Vol], which will hold
    # the pRF model time courses.
    aryNrlTc = np.zeros([varNumX, varNumY, varNumPrfSizes, varNumMtDrctn,
                         varNumVol])

    # We use the same loop structure for organising the pRF model time courses
    # that we used for creating the parameter array. Counter:
    varCntMdlPrms = 0

    # Put all combinations of x-position, y-position, and standard deviations
    # into the array:

    # Loop through x-positions:
    for idxX in range(0, varNumX):

        # Loop through y-positions:
        for idxY in range(0, varNumY):

            # Loop through standard deviations (of Gaussian pRF models):
            for idxSd in range(0, varNumPrfSizes):

                # Put the pRF model time course into its correct position in
                # the 4D array, leaving out the first column (which contains
                # the index):
                aryNrlTc[idxX, idxY, idxSd, :, :] = aryPrfTc[
                    varCntMdlPrms, :, :]

                # Increment parameter index:
                varCntMdlPrms = varCntMdlPrms + 1

    return aryNrlTc


Instruction:
Implement a function in Python 3 to
create 2D Gaussian kernel. Parameters ---------- aryNrlTc : 5d numpy array, shape [n_x_pos, n_y_pos, n_sd, n_mtn_dir, n_vol] Description of input 1. varNumVol : float, positive Description of input 2. varTr : float, positive Description of input 1. tplPngSize : tuple Description of input 1. varNumMtDrctn : int, positive Description of input 1. switchHrfSet : Description of input 1. lgcOldSchoolHrf : int, positive Description of input 1. varPar : int, positive Description of input 1. Returns ------- data : 2d numpy array, shape [n_samples, n_measurements] Closed data. Reference --------- [1]

Response:
def cnvlPwBoxCarFn(aryNrlTc, varNumVol, varTr, tplPngSize, varNumMtDrctn,
                   switchHrfSet, lgcOldSchoolHrf, varPar,):
    """Create 2D Gaussian kernel.

    Parameters
    ----------
    aryNrlTc : 5d numpy array, shape [n_x_pos, n_y_pos, n_sd, n_mtn_dir, n_vol]
        Description of input 1.
    varNumVol : float, positive
        Description of input 2.
    varTr : float, positive
        Description of input 1.
    tplPngSize : tuple
        Description of input 1.
    varNumMtDrctn : int, positive
        Description of input 1.
    switchHrfSet :
        Description of input 1.
    lgcOldSchoolHrf : int, positive
        Description of input 1.
    varPar : int, positive
        Description of input 1.
    Returns
    -------
    data : 2d numpy array, shape [n_samples, n_measurements]
        Closed data.
    Reference
    ---------
    [1]
    """
    print('------Convolve every pixel box car function with hrf function(s)')

    # Create hrf time course function:
    if switchHrfSet == 3:
        lstHrf = [spmt, dspmt, ddspmt]
    elif switchHrfSet == 2:
        lstHrf = [spmt, dspmt]
    elif switchHrfSet == 1:
        lstHrf = [spmt]

    # adjust the input, if necessary, such that input is 2D, with last dim time
    tplInpShp = aryNrlTc.shape
    aryNrlTc = np.reshape(aryNrlTc, (-1, aryNrlTc.shape[-1]))

    # Put input data into chunks:
    lstNrlTc = np.array_split(aryNrlTc, varPar)

    # Create a queue to put the results in:
    queOut = mp.Queue()

    # Empty list for processes:
    lstPrcs = [None] * varPar

    # Empty list for results of parallel processes:
    lstConv = [None] * varPar

    print('---------Creating parallel processes')

    if lgcOldSchoolHrf:
        for idxPrc in range(0, varPar):
            lstPrcs[idxPrc] = mp.Process(target=cnvlTcOld,
                                         args=(idxPrc,
                                               lstNrlTc[idxPrc],
                                               varTr,
                                               varNumVol,
                                               queOut)
                                         )
            # Daemon (kills processes when exiting):
            lstPrcs[idxPrc].Daemon = True

    else:
        # Create processes:
        for idxPrc in range(0, varPar):
            lstPrcs[idxPrc] = mp.Process(target=cnvlTc,
                                         args=(idxPrc,
                                               lstNrlTc[idxPrc],
                                               lstHrf,
                                               varTr,
                                               varNumVol,
                                               queOut)
                                         )

            # Daemon (kills processes when exiting):
            lstPrcs[idxPrc].Daemon = True

    # Start processes:
    for idxPrc in range(0, varPar):
        lstPrcs[idxPrc].start()

    # Collect results from queue:
    for idxPrc in range(0, varPar):
        lstConv[idxPrc] = queOut.get(True)

    # Join processes:
    for idxPrc in range(0, varPar):
        lstPrcs[idxPrc].join()

    print('---------Collecting results from parallel processes')
    # Put output into correct order:
    lstConv = sorted(lstConv)
    # Concatenate convolved pixel time courses (into the same order
    aryNrlTcConv = np.zeros((0, switchHrfSet, varNumVol))
    for idxRes in range(0, varPar):
        aryNrlTcConv = np.concatenate((aryNrlTcConv, lstConv[idxRes][1]),
                                      axis=0)
    # clean up
    del(aryNrlTc)
    del(lstConv)

    # Reshape results:
    tplOutShp = tplInpShp[:-2] + (varNumMtDrctn * len(lstHrf), ) + \
        (tplInpShp[-1], )

    # Return:
    return np.reshape(aryNrlTcConv, tplOutShp)


Instruction:
Can you tell what is the following Python 3 function doing
def rsmplInHighRes(aryBoxCarConv,
                   tplPngSize,
                   tplVslSpcHighSze,
                   varNumMtDrctn,
                   varNumVol):
    """Resample pixel-time courses in high-res visual space.

    Parameters
    ----------
    input1 : 2d numpy array, shape [n_samples, n_measurements]
        Description of input 1.
    input2 : float, positive
      Description of input 2.
    Returns
    -------
    data : 2d numpy array, shape [n_samples, n_measurements]
        Closed data.
    Reference
    ---------
    [1]
    """
    # Array for super-sampled pixel-time courses:
    aryBoxCarConvHigh = np.zeros((tplVslSpcHighSze[0],
                                  tplVslSpcHighSze[1],
                                  varNumMtDrctn,
                                  varNumVol))

    # Loop through volumes:
    for idxMtn in range(0, varNumMtDrctn):

        for idxVol in range(0, varNumVol):

            # Range for the coordinates:
            vecRange = np.arange(0, tplPngSize[0])

            # The following array describes the coordinates of the pixels in
            # the flattened array (i.e. "vecOrigPixVal"). In other words, these
            # are the row and column coordinates of the original pizel values.
            crd2, crd1 = np.meshgrid(vecRange, vecRange)
            aryOrixPixCoo = np.column_stack((crd1.flatten(), crd2.flatten()))

            # The following vector will contain the actual original pixel
            # values:

            vecOrigPixVal = aryBoxCarConv[:, :, idxMtn, idxVol]
            vecOrigPixVal = vecOrigPixVal.flatten()

            # The sampling interval for the creation of the super-sampled pixel
            # data (complex numbers are used as a convention for inclusive
            # intervals in "np.mgrid()").:

            varStpSzeX = np.complex(tplVslSpcHighSze[0])
            varStpSzeY = np.complex(tplVslSpcHighSze[1])

            # The following grid has the coordinates of the points at which we
            # would like to re-sample the pixel data:
            aryPixGridX, aryPixGridY = np.mgrid[0:tplPngSize[0]:varStpSzeX,
                                                0:tplPngSize[1]:varStpSzeY]

            # The actual resampling:
            aryResampled = griddata(aryOrixPixCoo,
                                    vecOrigPixVal,
                                    (aryPixGridX, aryPixGridY),
                                    method='nearest')

            # Put super-sampled pixel time courses into array:
            aryBoxCarConvHigh[:, :, idxMtn, idxVol] = aryResampled

    return aryBoxCarConvHigh

Response: Resample pixel - time courses in high - res visual space.


Instruction:
Create a Python 3 function to
parse the Command Line Arguments using argparse.

Response:
def get_arg_parse():
    """Parses the Command Line Arguments using argparse."""
    # Create parser object:
    objParser = argparse.ArgumentParser()

    # Add argument to namespace -strCsvPrf results file path:
    objParser.add_argument('-strCsvPrf', required=True,
                           metavar='/path/to/my_prior_res',
                           help='Absolute file path of prior pRF results. \
                                 Ignored if in testing mode.'
                           )

    # Add argument to namespace -strStmApr results file path:
    objParser.add_argument('-strStmApr', required=True,
                           metavar='/path/to/my_prior_res',
                           help='Absolute file path to npy file with \
                                 stimulus apertures. Ignored if in testing \
                                 mode.'
                           )

    # Add argument to namespace -lgcNoise flag:
    objParser.add_argument('-lgcNoise', dest='lgcNoise',
                           action='store_true', default=False,
                           help='Should noise be added to the simulated pRF\
                                 time course?')

    # Add argument to namespace -lgcRtnNrl flag:
    objParser.add_argument('-lgcRtnNrl', dest='lgcRtnNrl',
                           action='store_true', default=False,
                           help='Should neural time course, unconvolved with \
                                 hrf, be returned as well?')

    objParser.add_argument('-supsur', nargs='+',
                           help='List of floats that represent the ratio of \
                                 size neg surround to size pos center.',
                           type=float, default=None)

    # Namespace object containign arguments and values:
    objNspc = objParser.parse_args()

    return objNspc


Instruction:
Make a summary of the following Python 3 code
def login_required(wrapped):
    @wraps(wrapped)
    def wrapper(*args, **kwargs):
        request = args[1]

        auth_collection = settings.AUTH_COLLECTION[
            settings.AUTH_COLLECTION.rfind('.') + 1:
        ].lower()
        auth_document = request.environ.get(auth_collection)

        if auth_document and auth_document.is_authorized(request):
            setattr(request, auth_collection, auth_document)
            return wrapped(*args, **kwargs)

        return Response(response=serialize(UnauthorizedError()), status=401)

    if hasattr(wrapped, 'decorators'):
        wrapper.decorators = wrapped.decorators
        wrapper.decorators.append('login_required')
    else:
        wrapper.decorators = ['login_required']

    return wrapper

Response:
Decorator that ensures that the user is logged in and authorized to execute requests
    Except if the method is in authorized_methods of the auth_collection
 SARL


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _doAtomicFileCreation(filePath):
    try:
        _os.close(_os.open(filePath, _os.O_CREAT | _os.O_EXCL))
        return True
    except OSError as e:
        if e.errno == _errno.EEXIST:
            return False
        else:
            raise e

Response: Tries to atomically create the requested file.


Instruction:
Write a Python 3 script to
find the next available file-name in a sequence. This function will create a file of zero size and will return the path to it to the caller. No files which exist will be altered in this operation and concurrent executions of this function will return separate files. In case of conflict, the function will attempt to generate a new file name up to maxattempts number of times before failing. The sequence will start from the base argument (default: 0). If used with the prefix/suffix, it will look for the next file in the sequence ignoring any gaps. Hence, if the files "a.0.txt" and "a.3.txt" exist, then the next file returned will be "a.4.txt" when called with prefix="a." and suffix=".txt". In case fnameGen is provided, the first generated filename which does not exist will be created and its path will be returned. Hence, if the files "a.0.txt" and "a.3.txt" exist, then the next file returned will be "a.1.txt" when called with fnameGen = lambda x : "a." + str(x) + ".txt" Args: folder - string which has path to the folder where the file should be created (default: '.') prefix - prefix of the file to be generated (default: '') suffix - suffix of the file to be generated (default: '') fnameGen - function which generates the filenames given a number as input (default: None) base - the first index to count (default: 0) maxattempts - number of attempts to create the file before failing with OSError (default: 10) Returns: Path of the file which follows the provided pattern and can be opened for writing. Raises: RuntimeError - If an incorrect combination of arguments is provided. OSError - If is unable to create a file (wrong path, drive full, illegal character in filename, etc.).

Response:
def findNextFile(folder='.',
                 prefix=None,
                 suffix=None,
                 fnameGen=None,
                 base=0,
                 maxattempts=10):
    """Finds the next available file-name in a sequence.

    This function will create a file of zero size and will return the path to
    it to the caller. No files which exist will be altered in this operation
    and concurrent executions of this function will return separate files. In
    case of conflict, the function will attempt to generate a new file name up
    to maxattempts number of times before failing.

    The sequence will start from the base argument (default: 0).

    If used with the prefix/suffix, it will look for the next file in the
    sequence ignoring any gaps. Hence, if the files "a.0.txt" and "a.3.txt"
    exist, then the next file returned will be "a.4.txt" when called with
    prefix="a." and suffix=".txt".

    In case fnameGen is provided, the first generated filename which does not
    exist will be created and its path will be returned. Hence, if the files
    "a.0.txt" and "a.3.txt" exist, then the next file returned will be
    "a.1.txt" when called with fnameGen = lambda x : "a." + str(x) + ".txt"

    Args:
        folder      - string which has path to the folder where the file should
                      be created (default: '.')
        prefix      - prefix of the file to be generated (default: '')
        suffix      - suffix of the file to be generated (default: '')
        fnameGen    - function which generates the filenames given a number as
                      input (default: None)
        base        - the first index to count (default: 0)
        maxattempts - number of attempts to create the file before failing with
                      OSError (default: 10)

    Returns:
        Path of the file which follows the provided pattern and can be opened
        for writing.

    Raises:
        RuntimeError - If an incorrect combination of arguments is provided.
        OSError      - If is unable to create a file (wrong path, drive full,
                       illegal character in filename, etc.).
    """
    expFolder = _os.path.expanduser(_os.path.expandvars(folder))
    return _findNextFile(expFolder, prefix, suffix, fnameGen,
                         base, maxattempts, 0)


Instruction:
Can you write a function in Python 3 where it
executes the command line script and returns the path of the next available file in the sequence.

Response:
def _run(passedArgs=None, stderr=None, stdout=None, exitFn=None):
    """Executes the script, gets prefix/suffix from the command prompt and
    produces output on STDOUT. For help with command line options, invoke
    script with '--help'.
    """

    description = """Finds the next available file-name in a sequence.

    This program will create a file of zero size and will output the path to it
    on STDOUT. No files which exist will be altered in this operation and
    concurrent invocations of this program will return separate files. In case
    of conflict, this program will attempt to generate a new file name up to
    'maxattempts' number of times before failing. (See --max-attempts)

    The sequence will start from the base argument (See --base, default: 0).

    This program will look for the next file in the sequence ignoring any gaps.
    Hence, if the files "a.0.txt" and "a.3.txt" exist, then the next file
    returned will be "a.4.txt" when called with prefix="a." and suffix=".txt".

    Returns:
        Path of the file which follows the provided pattern and can be opened
        for writing.

        Otherwise, it prints an error (wrong path, drive full, illegal
        character in filename, etc.) to stderr and exits with a non-zero error
        code.
    """

    argParser = _argparse.ArgumentParser(
            description=description,
            formatter_class=_argparse.RawTextHelpFormatter)

    argParser.add_argument('prefix',
                           help='Prefix for the sequence of files.')
    argParser.add_argument('suffix',
                           help='Suffix for the sequence of files.',
                           nargs='?',
                           default='')
    argParser.add_argument('folder',
                           help='The folder where the file will be created.',
                           nargs='?',
                           default=_os.getcwd())
    argParser.add_argument('-m', '--max-attempts',
                           help='Number of attempts to make before giving up.',
                           default=10)
    argParser.add_argument('-b', '--base',
                           help='From where to start counting (default: 0).',
                           default=0)

    passedArgs = passedArgs if passedArgs is not None else _sys.argv[1:]
    args = argParser.parse_args(passedArgs)

    stdout = _sys.stdout if stdout is None else stdout
    stderr = _sys.stderr if stderr is None else stderr

    try:
        nextFile = findNextFile(args.folder, prefix=args.prefix,
                                suffix=args.suffix,
                                maxattempts=args.max_attempts,
                                base=args.base)
        # The newline will be converted to the correct platform specific line
        # ending as `sys.stdout` is opened in non-binary mode.
        # Hence, we do not need to explicitly print out `\r\n` for Windows.
        stdout.write(nextFile + u'\n')
    except OSError as e:
        stderr.write(_os.strerror(e.errno) + u'\n')
        _sys.exit(e.errno)


Instruction:
Can you create a Python 3 function that
returns the value str truncated to MAX_ERROR_STR_LEN characters. If the value is truncated it will be truncated to MAX_ERROR_STR_LEN characters. If the value is truncated it will be appended to the end.

Response:
def _errstr(value):
    """Returns the value str, truncated to MAX_ERROR_STR_LEN characters. If
    it's truncated, the returned value will have '...' on the end.
    """

    value = str(value) # We won't make the caller convert value to a string each time.
    if len(value) > MAX_ERROR_STR_LEN:
        return value[:MAX_ERROR_STR_LEN] + '...'
    else:
        return value


Instruction:
Can you generate the documentation for the following Python 3 function
def _getStrippedValue(value, strip):
    if strip is None:
        value = value.strip() # Call strip() with no arguments to strip whitespace.
    elif isinstance(strip, str):
        value = value.strip(strip) # Call strip(), passing the strip argument.
    elif strip is False:
        pass # Don't strip anything.
    return value

Response:
Like the strip method except the strip argument describes
    different behavior.


Instruction:
Given the following Python 3 function, write the documentation
def _raiseValidationException(standardExcMsg, customExcMsg=None):
    if customExcMsg is None:
        raise ValidationException(str(standardExcMsg))
    else:
        raise ValidationException(str(customExcMsg))

Response: Raise ValidationException with standardExcMsg unless customExcMsg is specified.


Instruction:
Here you have a function in Python 3, explain what it does
def _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg=None):

    # TODO - add a allowlistFirst and blocklistFirst to determine which is checked first. (Right now it's allowlist)

    value = str(value)

    # Optionally strip whitespace or other characters from value.
    value = _getStrippedValue(value, strip)

    # Validate for blank values.
    if not blank and value == '':
        # value is blank but blanks aren't allowed.
        _raiseValidationException(_('Blank values are not allowed.'), excMsg)
    elif blank and value == '':
        return True, value # The value is blank and blanks are allowed, so return True to indicate that the caller should return value immediately.

    # NOTE: We check if something matches the allow-list first, then we check the block-list second.

    # Check the allowlistRegexes.
    if allowlistRegexes is not None:
        for regex in allowlistRegexes:
            if isinstance(regex, re.Pattern):
                if regex.search(value, re.IGNORECASE) is not None:
                    return True, value # The value is in the allowlist, so return True to indicate that the caller should return value immediately.
            else:
                if re.search(regex, value, re.IGNORECASE) is not None:
                    return True, value # The value is in the allowlist, so return True to indicate that the caller should return value immediately.

    # Check the blocklistRegexes.
    if blocklistRegexes is not None:
        for blocklistRegexItem in blocklistRegexes:
            if isinstance(blocklistRegexItem, str):
                regex, response = blocklistRegexItem, DEFAULT_BLOCKLIST_RESPONSE
            else:
                regex, response = blocklistRegexItem

            if isinstance(regex, re.Pattern) and regex.search(value, re.IGNORECASE) is not None:
                _raiseValidationException(response, excMsg) # value is on a blocklist
            elif re.search(regex, value, re.IGNORECASE) is not None:
                _raiseValidationException(response, excMsg) # value is on a blocklist

    return False, value

Response: Internal function to perform the prevalidation check of the value passed for the parameter.


Instruction:
How would you implement a function in Python 3 that
checks that the input parameters are valid for the current base class. Returns None if the input parameters are invalid. Raises a PySimpleValidateException if any of the arguments are invalid.

Response:
def _validateGenericParameters(blank, strip, allowlistRegexes, blocklistRegexes):
    """Returns None if the blank, strip, and blocklistRegexes parameters are valid
    of PySimpleValidate's validation functions have. Raises a PySimpleValidateException
    if any of the arguments are invalid."""

    # Check blank parameter.
    if not isinstance(blank, bool):
        raise PySimpleValidateException('blank argument must be a bool')

    # Check strip parameter.
    if not isinstance(strip, (bool, str, type(None))):
        raise PySimpleValidateException('strip argument must be a bool, None, or str')

    # Check allowlistRegexes parameter (including each regex in it).
    if allowlistRegexes is None:
        allowlistRegexes = [] # allowlistRegexes defaults to a blank list.

    try:
        len(allowlistRegexes) # Make sure allowlistRegexes is a sequence.
    except:
        raise PySimpleValidateException('allowlistRegexes must be a sequence of regex_strs')
    for response in allowlistRegexes:
        if not isinstance(response[0], str):
            raise PySimpleValidateException('allowlistRegexes must be a sequence of regex_strs')

    # Check allowlistRegexes parameter (including each regex in it).
    # NOTE: blocklistRegexes is NOT the same format as allowlistRegex, it can
    # include an "invalid input reason" string to display if the input matches
    # the blocklist regex.
    if blocklistRegexes is None:
        blocklistRegexes = [] # blocklistRegexes defaults to a blank list.

    try:
        len(blocklistRegexes) # Make sure blocklistRegexes is a sequence of (regex_str, str) or strs.
    except:
        raise PySimpleValidateException('blocklistRegexes must be a sequence of (regex_str, str) tuples or regex_strs')
    for response in blocklistRegexes:
        if isinstance(response, str):
            continue
        if len(response) != 2:
            raise PySimpleValidateException('blocklistRegexes must be a sequence of (regex_str, str) tuples or regex_strs')
        if not isinstance(response[0], str) or not isinstance(response[1], str):
            raise PySimpleValidateException('blocklistRegexes must be a sequence of (regex_str, str) tuples or regex_strs')


Instruction:
Can you implement a function in Python 3 that
raises an exception if the arguments are invalid.

Response:
def _validateParamsFor_validateNum(min=None, max=None, lessThan=None, greaterThan=None):
    """Raises an exception if the arguments are invalid. This is called by
    the validateNum(), validateInt(), and validateFloat() functions to
    check its arguments. This code was refactored out to a separate function
    so that the PyInputPlus module (or other modules) could check their
    parameters' arguments for inputNum() etc.
    """

    if (min is not None) and (greaterThan is not None):
        raise PySimpleValidateException('only one argument for min or greaterThan can be passed, not both')
    if (max is not None) and (lessThan is not None):
        raise PySimpleValidateException('only one argument for max or lessThan can be passed, not both')

    if (min is not None) and (max is not None) and (min > max):
        raise PySimpleValidateException('the min argument must be less than or equal to the max argument')
    if (min is not None) and (lessThan is not None) and (min >= lessThan):
        raise PySimpleValidateException('the min argument must be less than the lessThan argument')
    if (max is not None) and (greaterThan is not None) and (max <= greaterThan):
        raise PySimpleValidateException('the max argument must be greater than the greaterThan argument')

    for name, val in (('min', min), ('max', max),
                      ('lessThan', lessThan), ('greaterThan', greaterThan)):
        if not isinstance(val, (int, float, type(None))):
            raise PySimpleValidateException(name + ' argument must be int, float, or NoneType')


Instruction:
How would you implement a function in Python 3 that
raises ValidationException if value is not a string.

Response:
def validateStr(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):
    """Raises ValidationException if value is not a string. This function
    is identical to the built-in input() function, but also offers the
    PySimpleValidate features of not allowing blank values by default,
    automatically stripping whitespace, and having allowlist/blocklist
    regular expressions.

    Returns value, so it can be used inline in an expression:

        print('Hello, ' + validateStr(your_name))

    * value (str): The value being validated as a string.
    * blank (bool): If True, a blank string will be accepted. Defaults to False. Defaults to False.
    * strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
    * allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
    * blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
    * excMsg (str): A custom message to use in the raised ValidationException.

    >>> import pysimplevalidate as pysv
    >>> pysv.validateStr('hello')
    'hello'
    >>> pysv.validateStr('')
    Traceback (most recent call last):
      ...
    pysimplevalidate.ValidationException: Blank values are not allowed.
    >>> pysv.validateStr('', blank=True)
    ''
    >>> pysv.validateStr('    hello    ')
    'hello'
    >>> pysv.validateStr('hello', blocklistRegexes=['hello'])
    Traceback (most recent call last):
      ...
    pysimplevalidate.ValidationException: This response is invalid.
    >>> pysv.validateStr('hello', blocklistRegexes=[('hello', 'Hello is not allowed')])
    Traceback (most recent call last):
        ...
    pysimplevalidate.ValidationException: Hello is not allowed
    >>> pysv.validateStr('hello', allowlistRegexes=['hello'], blocklistRegexes=['llo'])
    'hello'
    """

    # Validate parameters.
    _validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=None, blocklistRegexes=blocklistRegexes)
    returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)

    return value


Instruction:
How would you code a function in Python 3 to
raise ValidationException if value is not a number or int.

Response:
def validateNum(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, _numType='num',
                min=None, max=None, lessThan=None, greaterThan=None, excMsg=None):
    """Raises ValidationException if value is not a float or int.

    Returns value, so it can be used inline in an expression:

        print(2 + validateNum(your_number))

    Note that since int() and float() ignore leading or trailing whitespace
    when converting a string to a number, so does this validateNum().

    * value (str): The value being validated as an int or float.
    * blank (bool): If True, a blank string will be accepted. Defaults to False.
    * strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
    * allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
    * blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
    * _numType (str): One of 'num', 'int', or 'float' for the kind of number to validate against, where 'num' means int or float.
    * min (int, float): The (inclusive) minimum value for the value to pass validation.
    * max (int, float): The (inclusive) maximum value for the value to pass validation.
    * lessThan (int, float): The (exclusive) minimum value for the value to pass validation.
    * greaterThan (int, float): The (exclusive) maximum value for the value to pass validation.
    * excMsg (str): A custom message to use in the raised ValidationException.

    If you specify min or max, you cannot also respectively specify lessThan
    or greaterThan. Doing so will raise PySimpleValidateException.

    >>> import pysimplevalidate as pysv
    >>> pysv.validateNum('3')
    3
    >>> pysv.validateNum('3.0')
    3.0
    >>> pysv.validateNum('    3.0    ')
    3.0
    >>> pysv.validateNum('549873259847598437598435798435793.589985743957435794357')
    5.498732598475984e+32
    >>> pysv.validateNum('4', lessThan=4)
    Traceback (most recent call last):
        ...
    pysimplevalidate.ValidationException: Number must be less than 4.
    >>> pysv.validateNum('4', max=4)
    4
    >>> pysv.validateNum('4', min=2, max=5)
    4
    """

    # Validate parameters.
    _validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=None, blocklistRegexes=blocklistRegexes)
    _validateParamsFor_validateNum(min=min, max=max, lessThan=lessThan, greaterThan=greaterThan)

    returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
    if returnNow:
        # If we can convert value to an int/float, then do so. For example,
        # if an allowlist regex allows '42', then we should return 42/42.0.
        if (_numType == 'num' and '.' in value) or (_numType == 'float'):
            try:
                return float(value)
            except ValueError:
                return value # Return the value as is.
        if (_numType == 'num' and '.' not in value) or (_numType == 'int'):
            try:
                return int(value)
            except ValueError:
                return value # Return the value as is.

    # Validate the value's type (and convert value back to a number type).
    if (_numType == 'num' and '.' in value):
        # We are expecting a "num" (float or int) type and the user entered a float.
        try:
            value = float(value)
        except:
            _raiseValidationException(_('%r is not a number.') % (_errstr(value)), excMsg)
    elif (_numType == 'num' and '.' not in value):
        # We are expecting a "num" (float or int) type and the user entered an int.
        try:
            value = int(value)
        except:
            _raiseValidationException(_('%r is not a number.') % (_errstr(value)), excMsg)
    elif _numType == 'float':
        try:
            value = float(value)
        except:
            _raiseValidationException(_('%r is not a float.') % (_errstr(value)), excMsg)
    elif _numType == 'int':
        try:
            if float(value) % 1 != 0:
                # The number is a float that doesn't end with ".0"
                _raiseValidationException(_('%r is not an integer.') % (_errstr(value)), excMsg)
            value = int(float(value))
        except:
            _raiseValidationException(_('%r is not an integer.') % (_errstr(value)), excMsg)

    # Validate against min argument.
    if min is not None and value < min:
        _raiseValidationException(_('Number must be at minimum %s.') % (min), excMsg)

    # Validate against max argument.
    if max is not None and value > max:
        _raiseValidationException(_('Number must be at maximum %s.') % (max), excMsg)

    # Validate against max argument.
    if lessThan is not None and value >= lessThan:
        _raiseValidationException(_('Number must be less than %s.') % (lessThan), excMsg)

    # Validate against max argument.
    if greaterThan is not None and value <= greaterThan:
        _raiseValidationException(_('Number must be greater than %s.') % (greaterThan), excMsg)

    return value


Instruction:
Write a Python 3 script for
raising ValidationException if value is not an int.

Response:
def validateInt(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None,
                min=None, max=None, lessThan=None, greaterThan=None, excMsg=None):
    """Raises ValidationException if value is not a int.

    Returns value, so it can be used inline in an expression:

        print(2 + validateInt(your_number))

    Note that since int() and ignore leading or trailing whitespace
    when converting a string to a number, so does this validateNum().

    * value (str): The value being validated as an int or float.
    * blank (bool): If True, a blank string will be accepted. Defaults to False.
    * strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
    * allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
    * blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
    * _numType (str): One of 'num', 'int', or 'float' for the kind of number to validate against, where 'num' means int or float.
    * min (int, float): The (inclusive) minimum value for the value to pass validation.
    * max (int, float): The (inclusive) maximum value for the value to pass validation.
    * lessThan (int, float): The (exclusive) minimum value for the value to pass validation.
    * greaterThan (int, float): The (exclusive) maximum value for the value to pass validation.
    * excMsg (str): A custom message to use in the raised ValidationException.

    If you specify min or max, you cannot also respectively specify lessThan
    or greaterThan. Doing so will raise PySimpleValidateException.

    >>> import pysimplevalidate as pysv
    >>> pysv.validateInt('42')
    42
    >>> pysv.validateInt('forty two')
    Traceback (most recent call last):
        ...
    pysimplevalidate.ValidationException: 'forty two' is not an integer.
    """
    return validateNum(value=value, blank=blank, strip=strip, allowlistRegexes=None,
                       blocklistRegexes=blocklistRegexes, _numType='int', min=min, max=max,
                       lessThan=lessThan, greaterThan=greaterThan)


Instruction:
Can you write a function in Python 3 where it
raises PySimpleValidateException if the arguments are invalid.

Response:
def _validateParamsFor_validateChoice(choices, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None,
                   numbered=False, lettered=False, caseSensitive=False, excMsg=None):
    """Raises PySimpleValidateException if the arguments are invalid. This is called by
    the validateChoice() function to check its arguments. This code was
    refactored out to a separate function so that the PyInputPlus module (or
    other modules) could check their parameters' arguments for inputChoice().
    """

    if not isinstance(caseSensitive, bool):
        raise PySimpleValidateException('caseSensitive argument must be a bool')

    try:
        len(choices)
    except:
        raise PySimpleValidateException('choices arg must be a sequence')
    if blank == False and len(choices) < 2:
        raise PySimpleValidateException('choices must have at least two items if blank is False')
    elif blank == True and len(choices) < 1:
        raise PySimpleValidateException('choices must have at least one item')

    _validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=None, blocklistRegexes=blocklistRegexes)

    for choice in choices:
        if not isinstance(choice, str):
            raise PySimpleValidateException('choice %r must be a string' % (_errstr(choice)))
    if lettered and len(choices) > 26:
        raise PySimpleValidateException('lettered argument cannot be True if there are more than 26 choices')
    if numbered and lettered:
        raise PySimpleValidateException('numbered and lettered arguments cannot both be True')

    if len(choices) != len(set(choices)):
        raise PySimpleValidateException('duplicate entries in choices argument')

    if not caseSensitive and len(choices) != len(set([choice.upper() for choice in choices])):
        raise PySimpleValidateException('duplicate case-insensitive entries in choices argument')


Instruction:
Create a Python 3 function for
raising ValidationException if value is not one of the values in choices. Returns the selected choice.

Response:
def validateChoice(value, choices, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None,
                   numbered=False, lettered=False, caseSensitive=False, excMsg=None):
    """Raises ValidationException if value is not one of the values in
    choices. Returns the selected choice.

    Returns the value in choices that was selected, so it can be used inline
    in an expression:

        print('You chose ' + validateChoice(your_choice, ['cat', 'dog']))

    Note that value itself is not returned: validateChoice('CAT', ['cat', 'dog'])
    will return 'cat', not 'CAT'.

    If lettered is True, lower or uppercase letters will be accepted regardless
    of what caseSensitive is set to. The caseSensitive argument only matters
    for matching with the text of the strings in choices.

    * value (str): The value being validated.
    * blank (bool): If True, a blank string will be accepted. Defaults to False.
    * strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
    * allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
    * blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
    * numbered (bool): If True, this function will also accept a string of the choice's number, i.e. '1' or '2'.
    * lettered (bool): If True, this function will also accept a string of the choice's letter, i.e. 'A' or 'B' or 'a' or 'b'.
    * caseSensitive (bool): If True, then the exact case of the option must be entered.
    * excMsg (str): A custom message to use in the raised ValidationException.

    Returns the choice selected as it appeared in choices. That is, if 'cat'
    was a choice and the user entered 'CAT' while caseSensitive is False,
    this function will return 'cat'.

    >>> import pysimplevalidate as pysv
    >>> pysv.validateChoice('dog', ['dog', 'cat', 'moose'])
    'dog'

    >>> pysv.validateChoice('DOG', ['dog', 'cat', 'moose'])
    'dog'

    >>> pysv.validateChoice('2', ['dog', 'cat', 'moose'], numbered=True)
    'cat'

    >>> pysv.validateChoice('a', ['dog', 'cat', 'moose'], lettered=True)
    'dog'

    >>> pysv.validateChoice('C', ['dog', 'cat', 'moose'], lettered=True)
    'moose'

    >>> pysv.validateChoice('dog', ['dog', 'cat', 'moose'], lettered=True)
    'dog'

    >>> pysv.validateChoice('spider', ['dog', 'cat', 'moose'])
    Traceback (most recent call last):
        ...
    pysimplevalidate.ValidationException: 'spider' is not a valid choice.
    """

    # Validate parameters.
    _validateParamsFor_validateChoice(choices=choices, blank=blank, strip=strip, allowlistRegexes=None,
        blocklistRegexes=blocklistRegexes, numbered=numbered, lettered=lettered, caseSensitive=caseSensitive)

    if '' in choices:
        # blank needs to be set to True here, otherwise '' won't be accepted as a choice.
        blank = True

    returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
    if returnNow:
        return value

    # Validate against choices.
    if value in choices:
        return value
    if numbered and value.isdigit() and 0 < int(value) <= len(choices): # value must be 1 to len(choices)
        # Numbered options begins at 1, not 0.
        return choices[int(value) - 1] # -1 because the numbers are 1 to len(choices) but the index are 0 to len(choices) - 1
    if lettered and len(value) == 1 and value.isalpha() and 0 < ord(value.upper()) - 64 <= len(choices):
        # Lettered options are always case-insensitive.
        return choices[ord(value.upper()) - 65]
    if not caseSensitive and value.upper() in [choice.upper() for choice in choices]:
        # Return the original item in choices that value has a case-insensitive match with.
        return choices[[choice.upper() for choice in choices].index(value.upper())]

    _raiseValidationException(_('%r is not a valid choice.') % (_errstr(value)), excMsg)


Instruction:
Can you generate the documentation for the following Python 3 function
def _validateParamsFor__validateToDateTimeFormat(formats, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):
    _validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)
    if formats is None:
        raise PySimpleValidateException('formats parameter must be specified')

    if isinstance(formats, str):
        raise PySimpleValidateException('formats argument must be a non-str sequence of strftime format strings')

    try:
        len(formats)
    except:
        raise PySimpleValidateException('formats argument must be a non-str sequence of strftime format strings')

    for format in formats:
        try:
            time.strftime(format) # This will raise an exception if the format is invalid.
        except:
            raise PySimpleValidateException('formats argument contains invalid strftime format strings')

Response: Raises PySimpleValidateException if the arguments are invalid.


Instruction:
Create a Python 3 function for
raising ValidationException if value is not a time formatted in one of the formats formats. Returns a datetime. time object of value.

Response:
def validateTime(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None,
                 formats=('%H:%M:%S', '%H:%M', '%X'), excMsg=None):
    """Raises ValidationException if value is not a time formatted in one
    of the formats formats. Returns a datetime.time object of value.

    * value (str): The value being validated as a time.
    * blank (bool): If True, a blank string will be accepted. Defaults to False.
    * strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
    * allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
    * blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
    * formats: A tuple of strings that can be passed to time.strftime, dictating the possible formats for a valid time.
    * excMsg (str): A custom message to use in the raised ValidationException.

    >>> import pysimplevalidate as pysv
    >>> pysv.validateTime('12:00:01')
    datetime.time(12, 0, 1)
    >>> pysv.validateTime('13:00:01')
    datetime.time(13, 0, 1)
    >>> pysv.validateTime('25:00:01')
    Traceback (most recent call last):
        ...
    pysimplevalidate.ValidationException: '25:00:01' is not a valid time.
    >>> pysv.validateTime('hour 12 minute 01', formats=['hour %H minute %M'])
    datetime.time(12, 1)
    """

    # TODO - handle this

    # Reuse the logic in _validateToDateTimeFormat() for this function.
    try:
        dt = _validateToDateTimeFormat(value, formats, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)
        return datetime.time(dt.hour, dt.minute, dt.second, dt.microsecond)
    except ValidationException:
        _raiseValidationException(_('%r is not a valid time.') % (_errstr(value)), excMsg)


Instruction:
Create a Python 3 function to
raise ValidationException if value is not a time formatted in one of the formats formats. Returns a datetime. date object of value.

Response:
def validateDate(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None,
                 formats=('%Y/%m/%d', '%y/%m/%d', '%m/%d/%Y', '%m/%d/%y', '%x'), excMsg=None):
    """Raises ValidationException if value is not a time formatted in one
    of the formats formats. Returns a datetime.date object of value.

    * value (str): The value being validated as a time.
    * blank (bool): If True, a blank string for value will be accepted.
    * strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
    * allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
    * blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
    * formats: A tuple of strings that can be passed to time.strftime, dictating the possible formats for a valid date.
    * excMsg (str): A custom message to use in the raised ValidationException.

    >>> import pysimplevalidate as pysv
    >>> pysv.validateDate('2/29/2004')
    datetime.date(2004, 2, 29)
    >>> pysv.validateDate('2/29/2005')
    Traceback (most recent call last):
        ...
    pysimplevalidate.ValidationException: '2/29/2005' is not a valid date.
    >>> pysv.validateDate('September 2019', formats=['%B %Y'])
    datetime.date(2019, 9, 1)
    """
    # Reuse the logic in _validateToDateTimeFormat() for this function.
    try:
        dt = _validateToDateTimeFormat(value, formats, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)
        return datetime.date(dt.year, dt.month, dt.day)
    except ValidationException:
        _raiseValidationException(_('%r is not a valid date.') % (_errstr(value)), excMsg)


Instruction:
How would you explain what the following Python 3 function does
def validateDatetime(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None,
                     formats=('%Y/%m/%d %H:%M:%S', '%y/%m/%d %H:%M:%S', '%m/%d/%Y %H:%M:%S', '%m/%d/%y %H:%M:%S', '%x %H:%M:%S',
                              '%Y/%m/%d %H:%M', '%y/%m/%d %H:%M', '%m/%d/%Y %H:%M', '%m/%d/%y %H:%M', '%x %H:%M',
                              '%Y/%m/%d %H:%M:%S', '%y/%m/%d %H:%M:%S', '%m/%d/%Y %H:%M:%S', '%m/%d/%y %H:%M:%S', '%x %H:%M:%S'), excMsg=None):
    """Raises ValidationException if value is not a datetime formatted in one
    of the formats formats. Returns a datetime.datetime object of value.

    * value (str): The value being validated as a datetime.
    * blank (bool): If True, a blank string will be accepted. Defaults to False.
    * strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
    * allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
    * blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
    * formats: A tuple of strings that can be passed to time.strftime, dictating the possible formats for a valid datetime.
    * excMsg (str): A custom message to use in the raised ValidationException.

    >>> import pysimplevalidate as pysv
    >>> pysv.validateDatetime('2018/10/31 12:00:01')
    datetime.datetime(2018, 10, 31, 12, 0, 1)
    >>> pysv.validateDatetime('10/31/2018 12:00:01')
    datetime.datetime(2018, 10, 31, 12, 0, 1)
    >>> pysv.validateDatetime('10/31/2018')
    Traceback (most recent call last):
        ...
    pysimplevalidate.ValidationException: '10/31/2018' is not a valid date and time.
    """

    # Reuse the logic in _validateToDateTimeFormat() for this function.
    try:
        return _validateToDateTimeFormat(value, formats, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)
    except ValidationException:
        _raiseValidationException(_('%r is not a valid date and time.') % (_errstr(value)), excMsg)

Response:
Raises ValidationException if value is not a datetime formatted in one
    of the formats formats. Returns a datetime. datetime object of the datetime formatted in one
   .


Instruction:
Can you generate the documentation for the following Python 3 function
def validateFilename(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):

    returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
    if returnNow:
        return value

    if (value != value.strip()) or (any(c in value for c in '\\/:*?"<>|')):
        _raiseValidationException(_('%r is not a valid filename.') % (_errstr(value)), excMsg)
    return value

Response: Raises ValidationException if value is not a valid filename.


Instruction:
Explain what the following Python 3 code does
def validateFilepath(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None, mustExist=False):
    returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
    if returnNow:
        return value

    if (value != value.strip()) or (any(c in value for c in '*?"<>|')): # Same as validateFilename, except we allow \ and / and :
        if ':' in value:
            if value.find(':', 2) != -1 or not value[0].isalpha():
                # For Windows: Colon can only be found at the beginning, e.g. 'C:\', or the first letter is not a letter drive.
                _raiseValidationException(_('%r is not a valid file path.') % (_errstr(value)), excMsg)
        _raiseValidationException(_('%r is not a valid file path.') % (_errstr(value)), excMsg)
    return value
    raise NotImplementedError()

Response: Raises ValidationException if value is not a valid file path. Returns the value argument.


Instruction:
Can you generate the documentation for the following Python 3 function
def validateIP(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):
    # Validate parameters.
    _validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)

    returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
    if returnNow:
        return value

    # Reuse the logic in validateRegex()
    try:
        try:
            # Check if value is an IPv4 address.
            if validateRegex(value=value, regex=IPV4_REGEX, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes):
                return value
        except:
            pass # Go on to check if it's an IPv6 address.

        # Check if value is an IPv6 address.
        if validateRegex(value=value, regex=IPV6_REGEX, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes):
            return value
    except ValidationException:
        _raiseValidationException(_('%r is not a valid IP address.') % (_errstr(value)), excMsg)

Response: Raises ValidationException if value is not an IPv4 or IPv6 address.


Instruction:
Can you write a function in Python 3 where it
raises ValidationException if value does not match the regular expression in regex.

Response:
def validateRegex(value, regex, flags=0, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):
    """Raises ValidationException if value does not match the regular expression in regex.
    Returns the value argument.

    This is similar to calling inputStr() and using the allowlistRegexes
    keyword argument, however, validateRegex() allows you to pass regex
    flags such as re.IGNORECASE or re.VERBOSE. You can also pass a regex
    object directly.

    If you want to check if a string is a regular expression string, call
    validateRegexStr().

    * value (str): The value being validated as a regular expression string.
    * regex (str, regex): The regular expression to match the value against.
    * flags (int): Identical to the flags argument in re.compile(). Pass re.VERBOSE et al here.
    * blank (bool): If True, a blank string will be accepted. Defaults to False.
    * strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
    * allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
    * blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
    * excMsg (str): A custom message to use in the raised ValidationException.

    >>> pysv.validateRegex('cat bat rat', r'(cat)|(dog)|(moose)', re.IGNORECASE)
    'cat'
    >>> pysv.validateRegex('He said "Hello".', r'"(.*?)"', re.IGNORECASE)
    '"Hello"'
    """

    # Validate parameters.
    _validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)

    returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
    if returnNow:
        return value

    # Search value with regex, whether regex is a str or regex object.
    if isinstance(regex, str):
        # TODO - check flags to see they're valid regex flags.
        mo = re.compile(regex, flags).search(value)
    elif isinstance(regex, REGEX_TYPE):
        mo = regex.search(value)
    else:
        raise PySimpleValidateException('regex must be a str or regex object')

    if mo is not None:
        return mo.group()
    else:
        _raiseValidationException(_('%r does not match the specified pattern.') % (_errstr(value)), excMsg)


Instruction:
Here you have a function in Python 3, explain what it does
def validateRegexStr(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):

    # TODO - I'd be nice to check regexes in other languages, i.e. JS and Perl.
    _validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)

    returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
    if returnNow:
        return value

    try:
        return re.compile(value)
    except Exception as ex:
        _raiseValidationException(_('%r is not a valid regular expression: %s') % (_errstr(value), ex), excMsg)

Response: Raises ValidationException if value can t be used as a regular expression string. Returns the value argument as a regex object.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def validateURL(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):

    # Reuse the logic in validateRegex()
    try:
        result = validateRegex(value=value, regex=URL_REGEX, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)
        if result is not None:
            return result
    except ValidationException:
        # 'localhost' is also an acceptable URL:
        if value == 'localhost':
            return value

        _raiseValidationException(_('%r is not a valid URL.') % (value), excMsg)

Response: Raises ValidationException if value is not a URL.


Instruction:
Can you generate the documentation for the following Python 3 function
def validateEmail(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):

    # Reuse the logic in validateRegex()
    try:
        result = validateRegex(value=value, regex=EMAIL_REGEX, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)
        if result is not None:
            return result
    except ValidationException:
        _raiseValidationException(_('%r is not a valid email address.') % (value), excMsg)

Response: Raises ValidationException if value is not an email address. Returns the value argument.


Instruction:
Write a Python 3 function for
raising ValidationException if value is not a yes or no response.

Response:
def validateYesNo(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, yesVal='yes', noVal='no', caseSensitive=False, excMsg=None):
    """Raises ValidationException if value is not a yes or no response.
    Returns the yesVal or noVal argument, not value.

    Note that value can be any case (by default) and can also just match the

    * value (str): The value being validated as an email address.
    * blank (bool):  If True, a blank string will be accepted. Defaults to False.
    * strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
    * allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
    * blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
    * caseSensitive (bool): Determines if value must match the case of yesVal and noVal. Defaults to False.
    * excMsg (str): A custom message to use in the raised ValidationException.

    >>> import pysimplevalidate as pysv
    >>> pysv.validateYesNo('y')
    'yes'
    >>> pysv.validateYesNo('YES')
    'yes'
    >>> pysv.validateYesNo('No')
    'no'
    >>> pysv.validateYesNo('OUI', yesVal='oui', noVal='no')
    'oui'
    """

    # Validate parameters. TODO - can probably improve this to remove the duplication.
    _validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)

    returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
    if returnNow:
        return value

    yesVal = str(yesVal)
    noVal = str(noVal)
    if len(yesVal) == 0:
        raise PySimpleValidateException('yesVal argument must be a non-empty string.')
    if len(noVal) == 0:
        raise PySimpleValidateException('noVal argument must be a non-empty string.')
    if (yesVal == noVal) or (not caseSensitive and yesVal.upper() == noVal.upper()):
        raise PySimpleValidateException('yesVal and noVal arguments must be different.')
    if (yesVal[0] == noVal[0]) or (not caseSensitive and yesVal[0].upper() == noVal[0].upper()):
        raise PySimpleValidateException('first character of yesVal and noVal arguments must be different')

    returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
    if returnNow:
        return value

    if caseSensitive:
        if value in (yesVal, yesVal[0]):
            return yesVal
        elif value in (noVal, noVal[0]):
            return noVal
    else:
        if value.upper() in (yesVal.upper(), yesVal[0].upper()):
            return yesVal
        elif value.upper() in (noVal.upper(), noVal[0].upper()):
            return noVal

    _raiseValidationException(_('%r is not a valid %s/%s response.') % (_errstr(value), yesVal, noVal), excMsg)


Instruction:
Write a Python 3 script to
raise ValidationException if value is not an email address. Returns the yesVal or noVal argument.

Response:
def validateBool(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, trueVal='True', falseVal='False', caseSensitive=False, excMsg=None):
    """Raises ValidationException if value is not an email address.
    Returns the yesVal or noVal argument, not value.

    * value (str): The value being validated as an email address.
    * blank (bool):  If True, a blank string will be accepted. Defaults to False.
    * strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
    * allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
    * blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
    * excMsg (str): A custom message to use in the raised ValidationException.

    >>> import pysimplevalidate as pysv
    >>> pysv.validateYesNo('y')
    'yes'
    >>> pysv.validateYesNo('YES')
    'yes'
    >>> pysv.validateYesNo('No')
    'no'
    >>> pysv.validateYesNo('OUI', yesVal='oui', noVal='no')
    'oui'
    """

    # Validate parameters. TODO - can probably improve this to remove the duplication.
    _validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)

    returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
    if returnNow:
        return value

    # Replace the exception messages used in validateYesNo():
    trueVal = str(trueVal)
    falseVal = str(falseVal)
    if len(trueVal) == 0:
        raise PySimpleValidateException('trueVal argument must be a non-empty string.')
    if len(falseVal) == 0:
        raise PySimpleValidateException('falseVal argument must be a non-empty string.')
    if (trueVal == falseVal) or (not caseSensitive and trueVal.upper() == falseVal.upper()):
        raise PySimpleValidateException('trueVal and noVal arguments must be different.')
    if (trueVal[0] == falseVal[0]) or (not caseSensitive and trueVal[0].upper() == falseVal[0].upper()):
        raise PySimpleValidateException('first character of trueVal and noVal arguments must be different')

    result = validateYesNo(value, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes, yesVal=trueVal, noVal=falseVal, caseSensitive=caseSensitive, excMsg=None)

    # Return a bool value instead of a string.
    if result == trueVal:
        return True
    elif result == falseVal:
        return False
    else:
        assert False, 'inner validateYesNo() call returned something that was not yesVal or noVal. This should never happen.'


Instruction:
Can you generate the documentation for the following Python 3 function
def validateState(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None, returnStateName=False):

    # TODO - note that this is USA-centric. I should work on trying to make this more international.

    # Validate parameters.
    _validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)

    returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
    if returnNow:
        return value

    if value.upper() in USA_STATES_UPPER.keys(): # check if value is a state abbreviation
        if returnStateName:
            return USA_STATES[value.upper()] # Return full state name.
        else:
            return value.upper() # Return abbreviation.
    elif value.title() in USA_STATES.values(): # check if value is a state name
        if returnStateName:
            return value.title() # Return full state name.
        else:
            return USA_STATES_REVERSED[value.title()] # Return abbreviation.

    _raiseValidationException(_('%r is not a state.') % (_errstr(value)), excMsg)

Response:
Raises ValidationException if value is not a USA state. Returns the capitalized state abbreviation unless returnStateName is True
    Returns the titlecased state name.