Instruction:
Here you have a function in Python 3, explain what it does
def pyprf_opt_brute(strCsvCnfg, objNspc, lgcTest=False, strPathHrf=None,
                    varRat=None):
    """
    Function for optimizing given pRF paramaters using brute-force grid search.

    Parameters
    ----------
    strCsvCnfg : str
        Absolute file path of config file.
    objNspc : object
        Name space from command line arguments.
    lgcTest : Boolean
        Whether this is a test (pytest). If yes, absolute path of pyprf libary
        will be prepended to config file paths.
    strPathHrf : str or None:
        Path to npy file with custom hrf parameters. If None, default
        parameters will be used.
    varRat : float, default None
        Ratio of size suppressive surround to size of center pRF

    """
    # *************************************************************************
    # *** Check time
    print('---pRF analysis')
    varTme01 = time.time()
    # *************************************************************************

    # *************************************************************************
    # *** Preparations

    # Load config parameters from csv file into dictionary:
    dicCnfg = load_config(strCsvCnfg, lgcTest=lgcTest)

    # Load config parameters from dictionary into namespace:
    cfg = cls_set_config(dicCnfg)

    # Conditional imports:
    if cfg.strVersion == 'gpu':
        from pyprf_feature.analysis.find_prf_gpu import find_prf_gpu
    if ((cfg.strVersion == 'cython') or (cfg.strVersion == 'numpy')):
        from pyprf_feature.analysis.find_prf_cpu import find_prf_cpu

    # Convert preprocessing parameters (for temporal smoothing)
    # from SI units (i.e. [s]) into units of data array (volumes):
    cfg.varSdSmthTmp = np.divide(cfg.varSdSmthTmp, cfg.varTr)
    # *************************************************************************

    # *************************************************************************
    # *** Preprocessing

    # The functional data will be masked and demeaned:
    aryLgcMsk, aryLgcVar, hdrMsk, aryAff, aryFunc, tplNiiShp = prep_func(
        cfg.strPathNiiMask, cfg.lstPathNiiFunc, varAvgThr=-100.)

    # set the precision of the header to np.float32 so that the prf results
    # will be saved in this precision later
    hdrMsk.set_data_dtype(np.float32)

    print('---Number of voxels included in analysis: ' +
          str(np.sum(aryLgcVar)))

    # *************************************************************************
    # *** Checks

    # Make sure that if gpu fitting is used, the number of cross-validations is
    # set to 1, not higher
    if cfg.strVersion == 'gpu':
        strErrMsg = 'Stopping program. ' + \
            'Cross-validation on GPU is currently not supported. ' + \
            'Set varNumXval equal to 1 in csv file in order to continue. '
        assert cfg.varNumXval == 1, strErrMsg

    # For the GPU version, we need to set down the parallelisation to 1 now,
    # because no separate CPU threads are to be created. We may still use CPU
    # parallelisation for preprocessing, which is why the parallelisation
    # factor is only reduced now, not earlier.
    if cfg.strVersion == 'gpu':
        cfg.varPar = 1

    # check whether we need to crossvalidate
    if np.greater(cfg.varNumXval, 1):
        cfg.lgcXval = True
    elif np.equal(cfg.varNumXval, 1):
        cfg.lgcXval = False
    strErrMsg = 'Stopping program. ' + \
        'Set numXval (number of crossvalidation folds) to 1 or higher'
    assert np.greater_equal(cfg.varNumXval, 1), strErrMsg

    # derive number of feature for fitting
    if varRat is not None:
        # since there will be a beta parameter estimate both for the center and
        # the surround, we multiply by 2
        varNumFtr = int(2*cfg.switchHrfSet)
    else:
        varNumFtr = cfg.switchHrfSet

    # *************************************************************************

    # *************************************************************************
    # Load previous pRF fitting results
    print('---String to prior results provided by user:')
    print(objNspc.strPthPrior)

    # Load the x, y, sigma winner parameters from pyprf_feature
    lstWnrPrm = [objNspc.strPthPrior + '_x_pos.nii.gz',
                 objNspc.strPthPrior + '_y_pos.nii.gz',
                 objNspc.strPthPrior + '_SD.nii.gz',
                 objNspc.strPthPrior + '_eccentricity.nii.gz']
    lstPrmInt, objHdr, aryAff = load_res_prm(lstWnrPrm,
                                             lstFlsMsk=[cfg.strPathNiiMask])
    # Convert list to array
    assert len(lstPrmInt) == 1
    aryIntGssPrm = lstPrmInt[0]
    del(lstPrmInt)

    # Some voxels were excluded because they did not have sufficient mean
    # and/or variance - exclude their nitial parameters, too
    aryIntGssPrm = aryIntGssPrm[aryLgcVar, :]

    # *************************************************************************

    # *************************************************************************
    # *** Sort voxels by polar angle/previous parameters

    # Calculate the polar angles that were found in independent localiser
    aryPlrAng = np.arctan2(aryIntGssPrm[:, 1], aryIntGssPrm[:, 0])

    # Calculate the unique polar angles that are expected from grid search
    aryUnqPlrAng = np.linspace(0.0, 2*np.pi, objNspc.varNumOpt2,
                               endpoint=False)

    # Expected polar angle values are range from 0 to 2*pi, while
    # the calculated angle values will range from -pi to pi
    # Thus, bring empirical values from range -pi, pi to range 0, 2pi
    aryPlrAng = (aryPlrAng + 2 * np.pi) % (2 * np.pi)

    # For every empirically found polar angle get the index of the nearest
    # theoretically expected polar angle, this is to offset small imprecisions
    aryUnqPlrAngInd, aryDstPlrAng = find_near_pol_ang(aryPlrAng, aryUnqPlrAng)

    # Make sure that the maximum distance from a found polar angle to a grid
    # point is smaller than the distance between two neighbor grid points
    assert np.max(aryDstPlrAng) < np.divide(2*np.pi, objNspc.varNumOpt2)

    # Update unique polar angles such that it contains only the ones which
    # were found in data
    aryUnqPlrAng = aryUnqPlrAng[np.unique(aryUnqPlrAngInd)]
    # Update indices
    aryUnqPlrAngInd, aryDstPlrAng = find_near_pol_ang(aryPlrAng, aryUnqPlrAng)

    # Get logical arrays that index voxels with particular polar angle
    lstLgcUnqPlrAng = []
    for indPlrAng in range(len(aryUnqPlrAng)):
        lstLgcUnqPlrAng.append([aryUnqPlrAngInd == indPlrAng][0])

    print('---Number of radial position options provided by user: ' +
          str(objNspc.varNumOpt1))
    print('---Number of angular position options provided by user: ' +
          str(objNspc.varNumOpt2))
    print('---Number of unique polar angles found in prior estimates: ' +
          str(len(aryUnqPlrAng)))
    print('---Maximum displacement in radial direction that is allowed: ' +
          str(objNspc.varNumOpt3))
    print('---Fitted modelled are restricted to stimulated area: ' +
          str(objNspc.lgcRstrCentre))

    # *************************************************************************
    # *** Perform prf fitting

    # Create array for collecting winner parameters
    aryBstXpos = np.zeros((aryPlrAng.shape[0]))
    aryBstYpos = np.zeros((aryPlrAng.shape[0]))
    aryBstSd = np.zeros((aryPlrAng.shape[0]))
    aryBstR2 = np.zeros((aryPlrAng.shape[0]))
    aryBstBts = np.zeros((aryPlrAng.shape[0], varNumFtr))
    if np.greater(cfg.varNumXval, 1):
        aryBstR2Single = np.zeros((aryPlrAng.shape[0],
                                   len(cfg.lstPathNiiFunc)))

    # loop over all found instances of polar angle/previous parameters
    for indPlrAng in range(len(aryUnqPlrAng)):

        print('------Polar angle number ' + str(indPlrAng+1) + ' out of ' +
              str(len(aryUnqPlrAng)))

        # get the polar angle for the current voxel batch
        varPlrAng = np.array(aryUnqPlrAng[indPlrAng])

        # get logical array to index voxels with this particular polar angle
        lgcUnqPlrAng = lstLgcUnqPlrAng[indPlrAng]

        # get prior eccentricities for current voxel batch
        vecPrrEcc = aryIntGssPrm[lgcUnqPlrAng, 3]

        print('---------Number of voxels of this polar angle: ' +
              str(np.sum(lgcUnqPlrAng)))

        # *********************************************************************

        # *********************************************************************
        # *** Create time course models for this particular polar angle

        # Vector with the radial position:
        vecRad = np.linspace(0.0, cfg.varExtXmax, objNspc.varNumOpt1,
                             endpoint=True)

        # Get all possible combinations on the grid, using matrix indexing ij
        # of output
        aryRad, aryTht = np.meshgrid(vecRad, varPlrAng, indexing='ij')

        # Flatten arrays to be able to combine them with meshgrid
        vecRad = aryRad.flatten()
        vecTht = aryTht.flatten()

        # Convert from polar to cartesian
        vecX, vecY = map_pol_to_crt(vecTht, vecRad)

        # Vector with standard deviations pRF models (in degree of vis angle):
        vecPrfSd = np.linspace(cfg.varPrfStdMin, cfg.varPrfStdMax,
                               cfg.varNumPrfSizes, endpoint=True)

        # Create model parameters
        varNumMdls = len(vecX) * len(vecPrfSd)
        aryMdlParams = np.zeros((varNumMdls, 3), dtype=np.float32)

        varCntMdlPrms = 0

        # Loop through x-positions:
        for idxXY in range(0, len(vecX)):

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

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

                # Increment parameter index:
                varCntMdlPrms += 1

        # Convert winner parameters from degrees of visual angle to pixel
        vecIntX, vecIntY, vecIntSd = rmp_deg_pixel_xys(aryMdlParams[:, 0],
                                                       aryMdlParams[:, 1],
                                                       aryMdlParams[:, 2],
                                                       cfg.tplVslSpcSze,
                                                       cfg.varExtXmin,
                                                       cfg.varExtXmax,
                                                       cfg.varExtYmin,
                                                       cfg.varExtYmax)

        aryMdlParamsPxl = np.column_stack((vecIntX, vecIntY, vecIntSd))

        if objNspc.lgcRstrCentre:
            # Calculate the areas that were stimulated during the experiment
            arySptExpInf = np.load(cfg.strSptExpInf)
            arySptExpInf = np.rot90(arySptExpInf, k=3)
            aryStimArea = np.sum(arySptExpInf, axis=-1).astype(np.bool)

            # Get logical to exclude models with pRF centre outside stim area
            lgcMdlInc = aryStimArea[aryMdlParamsPxl[:, 0].astype(np.int32),
                                    aryMdlParamsPxl[:, 1].astype(np.int32)]
            # Exclude models with prf center outside stimulated area
            aryMdlParams = aryMdlParams[lgcMdlInc, :]
            aryMdlParamsPxl = aryMdlParamsPxl[lgcMdlInc, :]

        # Create model time courses
        aryPrfTc = model_creation_opt(dicCnfg, aryMdlParamsPxl,
                                      strPathHrf=strPathHrf, varRat=varRat,
                                      lgcPrint=False)

        # The model time courses will be preprocessed such that they are
        # smoothed (temporally) with same factor as the data and that they will
        # be z-scored:
        aryPrfTc = prep_models(aryPrfTc, varSdSmthTmp=cfg.varSdSmthTmp,
                               lgcPrint=False)

        # *********************************************************************
        # *** Create logical to restrict model fitting in radial direction

        if objNspc.varNumOpt3 is not None:

            # Calculate eccentricity of currently tested model parameters
            vecMdlEcc = np.sqrt(np.add(np.square(aryMdlParams[:, 0]),
                                       np.square(aryMdlParams[:, 1])))
            # Compare model eccentricity against prior eccentricity
            vecPrrEccGrd, vecMdlEccGrd = np.meshgrid(vecPrrEcc, vecMdlEcc,
                                                     indexing='ij')
            # Consider allowed eccentricity shift as specified by user
            lgcRstr = np.logical_and(np.less_equal(vecMdlEccGrd,
                                                   np.add(vecPrrEccGrd,
                                                          objNspc.varNumOpt3)),
                                     np.greater(vecMdlEccGrd,
                                                np.subtract(vecPrrEccGrd,
                                                            objNspc.varNumOpt3)
                                                )
                                     )
        else:
            lgcRstr = np.ones((np.sum(lgcUnqPlrAng),
                               aryMdlParams.shape[0]), dtype=np.bool)

        # *********************************************************************
        # *** Check for every voxel there is at least one model being tried

        # Is there at least 1 model for each voxel?
        lgcMdlPerVxl = np.greater(np.sum(lgcRstr, axis=1), 0)
        print('---------Number of voxels fitted: ' + str(np.sum(lgcMdlPerVxl)))

        # Those voxels for which no model would be tried, for example because
        # the pRF parameters estimated in the prior were outside the stimulated
        # area, are escluded from model fitting by setting their logical False
        lgcUnqPlrAng[lgcUnqPlrAng] = lgcMdlPerVxl

        # We need to update the index table for restricting model fitting
        lgcRstr = lgcRstr[lgcMdlPerVxl, :]

        # *********************************************************************
        # *** Find best model for voxels with this particular polar angle

        # Only perform the fitting if there are voxels with models to optimize
        if np.any(lgcUnqPlrAng):
            # Empty list for results (parameters of best fitting pRF model):
            lstPrfRes = [None] * cfg.varPar

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

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

            # Put logical for model restriction in list
            lstRst = np.array_split(lgcRstr, cfg.varPar)
            del(lgcRstr)

            # Create list with chunks of func data for parallel processes:
            lstFunc = np.array_split(aryFunc[lgcUnqPlrAng, :], cfg.varPar)

            # CPU version (using numpy or cython for pRF finding):
            if ((cfg.strVersion == 'numpy') or (cfg.strVersion == 'cython')):

                # Create processes:
                for idxPrc in range(0, cfg.varPar):
                    lstPrcs[idxPrc] = mp.Process(target=find_prf_cpu,
                                                 args=(idxPrc,
                                                       lstFunc[idxPrc],
                                                       aryPrfTc,
                                                       aryMdlParams,
                                                       cfg.strVersion,
                                                       cfg.lgcXval,
                                                       cfg.varNumXval,
                                                       queOut),
                                                 kwargs={'lgcRstr':
                                                         lstRst[idxPrc],
                                                         'lgcPrint': False},
                                                 )
                    # Daemon (kills processes when exiting):
                    lstPrcs[idxPrc].Daemon = True

            # GPU version (using tensorflow for pRF finding):
            elif cfg.strVersion == 'gpu':

                # Create processes:
                for idxPrc in range(0, cfg.varPar):
                    lstPrcs[idxPrc] = mp.Process(target=find_prf_gpu,
                                                 args=(idxPrc,
                                                       aryMdlParams,
                                                       lstFunc[idxPrc],
                                                       aryPrfTc,
                                                       queOut),
                                                 kwargs={'lgcRstr':
                                                         lstRst[idxPrc],
                                                         'lgcPrint': False},
                                                 )
                    # Daemon (kills processes when exiting):
                    lstPrcs[idxPrc].Daemon = True

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

            # Delete reference to list with function data (the data continues
            # to exists in child process):
            del(lstFunc)

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

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

            # *****************************************************************

            # *****************************************************************
            # *** Prepare pRF finding results for export

            # Put output into correct order:
            lstPrfRes = sorted(lstPrfRes)

            # collect results from parallelization
            aryBstTmpXpos = joinRes(lstPrfRes, cfg.varPar, 1, inFormat='1D')
            aryBstTmpYpos = joinRes(lstPrfRes, cfg.varPar, 2, inFormat='1D')
            aryBstTmpSd = joinRes(lstPrfRes, cfg.varPar, 3, inFormat='1D')
            aryBstTmpR2 = joinRes(lstPrfRes, cfg.varPar, 4, inFormat='1D')
            aryBstTmpBts = joinRes(lstPrfRes, cfg.varPar, 5, inFormat='2D')
            if np.greater(cfg.varNumXval, 1):
                aryTmpBstR2Single = joinRes(lstPrfRes, cfg.varPar, 6,
                                            inFormat='2D')
            # Delete unneeded large objects:
            del(lstPrfRes)

            # *****************************************************************

            # *****************************************************************
            # Put findings for voxels with specific polar angle into ary with
            # result for all voxels
            aryBstXpos[lgcUnqPlrAng] = aryBstTmpXpos
            aryBstYpos[lgcUnqPlrAng] = aryBstTmpYpos
            aryBstSd[lgcUnqPlrAng] = aryBstTmpSd
            aryBstR2[lgcUnqPlrAng] = aryBstTmpR2
            aryBstBts[lgcUnqPlrAng, :] = aryBstTmpBts
            if np.greater(cfg.varNumXval, 1):
                aryBstR2Single[lgcUnqPlrAng, :] = aryTmpBstR2Single

            # *****************************************************************

    # *************************************************************************
    # Calculate polar angle map:
    aryPlrAng = np.arctan2(aryBstYpos, aryBstXpos)
    # Calculate eccentricity map (r = sqrt( x^2 + y^2 ) ):
    aryEcc = np.sqrt(np.add(np.square(aryBstXpos),
                            np.square(aryBstYpos)))

    # It is possible that after optimization the pRF has moved to location 0, 0
    # In this cases, the polar angle parameter is arbitrary and will be
    # assigned either 0 or pi. To preserve smoothness of the map, assign the
    # initial polar angle value from independent localiser
    lgcMvdOrgn = np.logical_and(aryBstXpos == 0.0, aryBstYpos == 0.0)
    lgcMvdOrgn = np.logical_and(lgcMvdOrgn, aryBstSd > 0)
    aryIntPlrAng = np.arctan2(aryIntGssPrm[:, 1], aryIntGssPrm[:, 0])
    aryPlrAng[lgcMvdOrgn] = np.copy(aryIntPlrAng[lgcMvdOrgn])

    # *************************************************************************

    # *************************************************************************
    # Export each map of best parameters as a 3D nii file

    print('---------Exporting results')

    # Append 'hrf' to cfg.strPathOut, if fitting was done with custom hrf
    if strPathHrf is not None:
        cfg.strPathOut = cfg.strPathOut + '_hrf'

    # Xoncatenate all the best voxel maps
    aryBstMaps = np.stack([aryBstXpos, aryBstYpos, aryBstSd, aryBstR2,
                           aryPlrAng, aryEcc], axis=1)

    # List with name suffices of output images:
    lstNiiNames = ['_x_pos_brute',
                   '_y_pos_brute',
                   '_SD_brute',
                   '_R2_brute',
                   '_polar_angle_brute',
                   '_eccentricity_brute']

    if varRat is not None:
        lstNiiNames = [strNii + '_' + str(varRat) for strNii in lstNiiNames]

    # Create full path names from nii file names and output path
    lstNiiNames = [cfg.strPathOut + strNii + '.nii.gz' for strNii in
                   lstNiiNames]

    # export map results as seperate 3D nii files
    export_nii(aryBstMaps, lstNiiNames, aryLgcMsk, aryLgcVar, tplNiiShp,
               aryAff, hdrMsk, outFormat='3D')

    # *************************************************************************

    # *************************************************************************
    # Save beta parameter estimates for every feature:

    # List with name suffices of output images:
    lstNiiNames = ['_Betas_brute']

    if varRat is not None:
        lstNiiNames = [strNii + '_' + str(varRat) for strNii in lstNiiNames]

    # Create full path names from nii file names and output path
    lstNiiNames = [cfg.strPathOut + strNii + '.nii.gz' for strNii in
                   lstNiiNames]

    # export beta parameter as a single 4D nii file
    export_nii(aryBstBts, lstNiiNames, aryLgcMsk, aryLgcVar, tplNiiShp,
               aryAff, hdrMsk, outFormat='4D')

    # *************************************************************************

    # *************************************************************************
    # Save R2 maps from crossvalidation (saved for every run) as nii:

    if np.greater(cfg.varNumXval, 1):

        # truncate extremely negative R2 values
        aryBstR2Single[np.where(np.less_equal(aryBstR2Single, -1.0))] = -1.0

        # List with name suffices of output images:
        lstNiiNames = ['_R2_single_brute']

        if varRat is not None:
            lstNiiNames = [strNii + '_' + str(varRat) for strNii in
                           lstNiiNames]

        # Create full path names from nii file names and output path
        lstNiiNames = [cfg.strPathOut + strNii + '.nii.gz' for strNii in
                       lstNiiNames]

        # export R2 maps as a single 4D nii file
        export_nii(aryBstR2Single, lstNiiNames, aryLgcMsk, aryLgcVar,
                   tplNiiShp, aryAff, hdrMsk, outFormat='4D')

    # *************************************************************************

    # *************************************************************************
    # *** Report time

    varTme02 = time.time()
    varTme03 = varTme02 - varTme01
    print('---Elapsed time: ' + str(varTme03) + ' s')
    print('---Done.')

Response: Function for optimizing given pRF paramaters using brute - force grid search.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_lbry_api_function_docs(url=LBRY_API_RAW_JSON_URL):

    try:
        # Grab the page content
        docs_page = urlopen(url)

        # Read the contents of the actual url we grabbed and decode them into UTF-8
        contents = docs_page.read().decode("utf-8")

        # Return the contents loaded as JSON
        return loads(contents)

        # If we get an exception, simply exit
    except URLError as UE:
        print(UE)

    except Exception as E:
        print(E)

    return []

Response: Scrapes the given URL to obtain the documentation for the LBRY API and returns the contents as JSON


Instruction:
Can you generate a brief explanation for the following Python 3 code
def generate_method_definition(func):
    indent = 4

    # initial definition
    method_definition = (" " * indent) + "def " + func["name"]

    # Here we just create a queue and put all the parameters
    # into the queue in the order that they were given,
    params_required = [
        param for param in func["arguments"] if param["is_required"]
    ]
    params_optional = [
        param for param in func["arguments"]
        if not param["is_required"]
    ]

    # Open the parameter definitions
    method_definition += "(self, "

    for param in params_required:
        # Put the parameter into the queue

        method_definition += param["name"]
        method_definition += ", "

    for param in params_optional:
        method_definition += param["name"]

        # Default methods not required
        method_definition += "=None, "

    # Peel off the final ", " and close off the parameter definition
    method_definition = method_definition.rstrip(", ") + "):\n"

    indent += 4

    # re-indent
    method_definition += " " * indent

    # Begin with description.

    method_definition += '"""' + func["description"]

    # re-indent
    method_definition += "\n\n" + " " * indent

    # Go through each parameter and insert description & type hint
    for param in params_required + params_optional:
        # Add the type
        method_definition += ":param " + DTYPE_MAPPING[param["type"].lower()]

        # Add the name
        method_definition += " " + param["name"] + ": "

        # Add the description
        method_definition += param["description"]

        # Add optionality & reindent
        method_definition += "\n" if param[
            "is_required"] else " (Optional)\n"

        method_definition += " " * indent

    open_index = func["returns"].find('(')
    close_index = func["returns"].find(
        ')', (open_index if open_index > -1 else 0))

    func["returns"] = func["returns"].replace("\t", " " * 4)
    return_string = func["returns"].replace("\n", "")

    if open_index < close_index and func["returns"][
                                    open_index + 1:close_index] in DTYPE_MAPPING:
        method_definition += ":rtype: " + DTYPE_MAPPING[
            func["returns"][open_index + 1:close_index]]

        func["returns"] = func["returns"].replace(
            func["returns"][open_index:close_index + 1], "")

        method_definition += "\n" + " " * indent

    method_definition += ":return: " + return_string

    for i in range(0, len(return_string) + 1, 80 - (indent + 2)):
        method_definition += return_string[i:i + (
                80 - (indent + 2))] + "\n" + " " * indent

    # Close it off & reindent
    method_definition += '"""' + "\n" + " " * indent

    # Create the params map
    params_map = "__params_map = {"

    # Save the indent
    params_indent, num_params = len(
        params_map), len(params_required) + len(params_optional)

    # Append the map to the method_definition
    method_definition += params_map

    # Go through the required parameters first
    for i, param in enumerate(params_required + params_optional):

        # append the methods to the map
        method_definition += "'" + param["name"] + "': " + param["name"]

        if not param["is_required"]:
            method_definition + " if " + param[
                "name"] + "is not None else None"

        # add commas or ending bracket if needed & reindent correctly
        method_definition += ",\n" + " " * indent + ' ' * params_indent if i + 1 < num_params else ""

    method_definition += '}\n\n' + ' ' * indent

    method_definition += "return self.make_request(SERVER_ADDRESS, '" + func["name"] + "', " \
                         + params_map.rstrip(" = {") + ", timeout=self.timeout)\n\n"

    return method_definition

Response: Generates the body for the given function and returns the string containing the function definition


Instruction:
Given the following Python 3 function, write the documentation
def generate_lbryd_wrapper(url=LBRY_API_RAW_JSON_URL, read_file=__LBRYD_BASE_FPATH__, write_file=LBRYD_FPATH):

    functions = get_lbry_api_function_docs(url)

    # Open the actual file for appending
    with open(write_file, 'w') as lbry_file:

        lbry_file.write("# This file was generated at build time using the generator function\n")
        lbry_file.write("# You may edit but do so with caution\n")

        with open(read_file, 'r') as template:
            header = template.read()

        lbry_file.write(header)

        # Iterate through all the functions we retrieved
        for func in functions:

            method_definition = generate_method_definition(func)

            # Write to file
            lbry_file.write(method_definition)

    try:
        from yapf.yapflib.yapf_api import FormatFile

        # Now we should format the file using the yapf formatter
        FormatFile(write_file, in_place=True)

    except ImportError as IE:
        print("[Warning]: yapf is not installed, so the generated code will not follow an easy-to-read standard")
        print(IE)

Response: Generates the actual functions for lbryd_api. py based on the given url and writes the generated file to write_file.


Instruction:
Write a Python 3 script for
loading nii file and return array containing nii data.

Response:
def load_nii(strPathIn, varSzeThr=5000.0):
    """
    Load nii file.

    Parameters
    ----------
    strPathIn : str
        Path to nii file to load.
    varSzeThr : float
        If the nii file is larger than this threshold (in MB), the file is
        loaded volume-by-volume in order to prevent memory overflow. Default
        threshold is 1000 MB.

    Returns
    -------
    aryNii : np.array
        Array containing nii data. 32 bit floating point precision.
    objHdr : header object
        Header of nii file.
    aryAff : np.array
        Array containing 'affine', i.e. information about spatial positioning
        of nii data.

    Notes
    -----
    If the nii file is larger than the specified threshold (`varSzeThr`), the
    file is loaded volume-by-volume in order to prevent memory overflow. The
    reason for this is that nibabel imports data at float64 precision, which
    can lead to a memory overflow even for relatively small files.
    """
    # Load nii file (this does not load the data into memory yet):
    objNii = nb.load(strPathIn)

    # Get size of nii file:
    varNiiSze = os.path.getsize(strPathIn)

    # Convert to MB:
    varNiiSze = np.divide(float(varNiiSze), 1000000.0)

    # Load volume-by-volume or all at once, depending on file size:
    if np.greater(varNiiSze, float(varSzeThr)):

        # Load large nii file

        print(('---------Large file size ('
              + str(np.around(varNiiSze))
              + ' MB), reading volume-by-volume'))

        # Get image dimensions:
        tplSze = objNii.shape

        # Create empty array for nii data:
        aryNii = np.zeros(tplSze, dtype=np.float32)

        # Loop through volumes:
        for idxVol in range(tplSze[3]):
            aryNii[..., idxVol] = np.asarray(
                  objNii.dataobj[..., idxVol]).astype(np.float32)

    else:

        # Load small nii file

        # Load nii file (this doesn't load the data into memory yet):
        objNii = nb.load(strPathIn)

        # Load data into array:
        aryNii = np.asarray(objNii.dataobj).astype(np.float32)

    # Get headers:
    objHdr = objNii.header

    # Get 'affine':
    aryAff = objNii.affine

    # Output nii data (as numpy array), header, and 'affine':
    return aryNii, objHdr, aryAff


Instruction:
Can you implement a function in Python 3 that
loads result parameters from multiple nii files with optional mask.

Response:
def load_res_prm(lstFunc, lstFlsMsk=None):
    """Load result parameters from multiple nii files, with optional mask.

    Parameters
    ----------
    lstFunc : list,
        list of str with file names of 3D or 4D nii files
    lstFlsMsk : list, optional
        list of str with paths to 3D nii files that can act as mask/s
    Returns
    -------
    lstPrmAry : list
        The list will contain as many numpy arrays as masks were provided.
        Each array is 2D with shape [nr voxel in mask, nr nii files in lstFunc]
    objHdr : header object
        Header of nii file.
    aryAff : np.array
        Array containing 'affine', i.e. information about spatial positioning
        of nii data.

    """

    # load parameter/functional maps into a list
    lstPrm = []
    for ind, path in enumerate(lstFunc):
        aryFnc = load_nii(path)[0].astype(np.float32)
        if aryFnc.ndim == 3:
            lstPrm.append(aryFnc)
        # handle cases where nii array is 4D, in this case split arrays up in
        # 3D arrays and appenbd those
        elif aryFnc.ndim == 4:
            for indAx in range(aryFnc.shape[-1]):
                lstPrm.append(aryFnc[..., indAx])

    # load mask/s if available
    if lstFlsMsk is not None:
        lstMsk = [None] * len(lstFlsMsk)
        for ind, path in enumerate(lstFlsMsk):
            aryMsk = load_nii(path)[0].astype(np.bool)
            lstMsk[ind] = aryMsk
    else:
        print('------------No masks were provided')

    if lstFlsMsk is None:
        # if no mask was provided we just flatten all parameter array in list
        # and return resulting list
        lstPrmAry = [ary.flatten() for ary in lstPrm]
    else:
        # if masks are available, we loop over masks and then over parameter
        # maps to extract selected voxels and parameters
        lstPrmAry = [None] * len(lstFlsMsk)
        for indLst, aryMsk in enumerate(lstMsk):
            # prepare array that will hold parameter values of selected voxels
            aryPrmSel = np.empty((np.sum(aryMsk), len(lstPrm)),
                                 dtype=np.float32)
            # loop over different parameter maps
            for indAry, aryPrm in enumerate(lstPrm):
                # get voxels specific to this mask
                aryPrmSel[:, indAry] = aryPrm[aryMsk, ...]
            # put array away in list, if only one parameter map was provided
            # the output will be squeezed
            lstPrmAry[indLst] = aryPrmSel

    # also get header object and affine array
    # we simply take it for the first functional nii file, cause that is the
    # only file that has to be provided by necessity
    objHdr, aryAff = load_nii(lstFunc[0])[1:]

    return lstPrmAry, objHdr, aryAff


Instruction:
Write a Python 3 function for
exporting nii file(s). Parameters ---------- ary2dNii : numpy array Numpy array with results to be exported to nii. lstNiiNames : list List that contains strings with the complete file names. aryLgcMsk : numpy array If the nii file is larger than this threshold (in MB), the file is loaded volume-by-volume in order to prevent memory overflow. Default threshold is 1000 MB. aryLgcVar : np.array 1D numpy array containing logical values. One value per voxel after mask has been applied. If `True`, the variance and mean of the voxel's time course are greater than the provided thresholds in all runs and the voxel is included in the output array (`aryFunc`). If `False`, the variance or mean of the voxel's time course is lower than threshold in at least one run and the voxel has been excluded from the output (`aryFunc`). This is to avoid problems in the subsequent model fitting. This array is necessary to put results into original dimensions after model fitting. tplNiiShp : tuple Tuple that describes the 3D shape of the output volume aryAff : np.array Array containing 'affine', i.e. information about spatial positioning of nii data. hdrMsk : nibabel-header-object Nii header of mask. outFormat : string, either '3D' or '4D' String specifying whether images will be saved as seperate 3D nii files or one 4D nii file Notes ----- [1] This function does not return any arrays but instead saves to disk. [2] Depending on whether outFormat is '3D' or '4D' images will be saved as seperate 3D nii files or one 4D nii file.

Response:
def export_nii(ary2dNii, lstNiiNames, aryLgcMsk, aryLgcVar, tplNiiShp, aryAff,
               hdrMsk, outFormat='3D'):
    """
    Export nii file(s).

    Parameters
    ----------
    ary2dNii : numpy array
        Numpy array with results to be exported to nii.
    lstNiiNames : list
        List that contains strings with the complete file names.
    aryLgcMsk : numpy array
        If the nii file is larger than this threshold (in MB), the file is
        loaded volume-by-volume in order to prevent memory overflow. Default
        threshold is 1000 MB.
    aryLgcVar : np.array
        1D numpy array containing logical values. One value per voxel after
        mask has been applied. If `True`, the variance and mean of the voxel's
        time course are greater than the provided thresholds in all runs and
        the voxel is included in the output array (`aryFunc`). If `False`, the
        variance or mean of the voxel's time course is lower than threshold in
        at least one run and the voxel has been excluded from the output
        (`aryFunc`). This is to avoid problems in the subsequent model fitting.
        This array is necessary to put results into original dimensions after
        model fitting.
    tplNiiShp : tuple
        Tuple that describes the 3D shape of the output volume
    aryAff : np.array
        Array containing 'affine', i.e. information about spatial positioning
        of nii data.
    hdrMsk : nibabel-header-object
        Nii header of mask.
    outFormat : string, either '3D' or '4D'
        String specifying whether images will be saved as seperate 3D nii
        files or one 4D nii file

    Notes
    -----
    [1] This function does not return any arrays but instead saves to disk.
    [2] Depending on whether outFormat is '3D' or '4D' images will be saved as
        seperate 3D nii files or one 4D nii file.
    """

    # Number of voxels that were included in the mask:
    varNumVoxMsk = np.sum(aryLgcMsk)

    # Number of maps in ary2dNii
    varNumMaps = ary2dNii.shape[-1]

    # Place voxels based on low-variance exlusion:
    aryPrfRes01 = np.zeros((varNumVoxMsk, varNumMaps), dtype=np.float32)
    for indMap in range(varNumMaps):
        aryPrfRes01[aryLgcVar, indMap] = ary2dNii[:, indMap]

    # Total number of voxels:
    varNumVoxTlt = (tplNiiShp[0] * tplNiiShp[1] * tplNiiShp[2])

    # Place voxels based on mask-exclusion:
    aryPrfRes02 = np.zeros((varNumVoxTlt, aryPrfRes01.shape[-1]),
                           dtype=np.float32)
    for indDim in range(aryPrfRes01.shape[-1]):
        aryPrfRes02[aryLgcMsk, indDim] = aryPrfRes01[:, indDim]

    # Reshape pRF finding results into original image dimensions:
    aryPrfRes = np.reshape(aryPrfRes02,
                           [tplNiiShp[0],
                            tplNiiShp[1],
                            tplNiiShp[2],
                            aryPrfRes01.shape[-1]])

    if outFormat == '3D':
        # Save nii results:
        for idxOut in range(0, aryPrfRes.shape[-1]):
            # Create nii object for results:
            niiOut = nb.Nifti1Image(aryPrfRes[..., idxOut],
                                    aryAff,
                                    header=hdrMsk
                                    )
            # Save nii:
            strTmp = lstNiiNames[idxOut]
            nb.save(niiOut, strTmp)

    elif outFormat == '4D':

        # adjust header
        hdrMsk.set_data_shape(aryPrfRes.shape)

        # Create nii object for results:
        niiOut = nb.Nifti1Image(aryPrfRes,
                                aryAff,
                                header=hdrMsk
                                )
        # Save nii:
        strTmp = lstNiiNames[0]
        nb.save(niiOut, strTmp)


Instruction:
How would you code a function in Python 3 to
join results from different processing units.

Response:
def joinRes(lstPrfRes, varPar, idxPos, inFormat='1D'):
    """Join results from different processing units (here cores).

    Parameters
    ----------
    lstPrfRes : list
        Output of results from parallelization.
    varPar : integer, positive
        Number of cores that were used during parallelization
    idxPos : integer, positive
        List position index that we expect the results to be collected to have.
    inFormat : string
        Specifies whether input will be 1d or 2d.

    Returns
    -------
    aryOut : numpy array
        Numpy array with results collected from different cores

    """

    if inFormat == '1D':
        # initialize output array
        aryOut = np.zeros((0,))
        # gather arrays from different processing units
        for idxRes in range(0, varPar):
            aryOut = np.append(aryOut, lstPrfRes[idxRes][idxPos])

    elif inFormat == '2D':
        # initialize output array
        aryOut = np.zeros((0, lstPrfRes[0][idxPos].shape[-1]))
        # gather arrays from different processing units
        for idxRes in range(0, varPar):
            aryOut = np.concatenate((aryOut, lstPrfRes[idxRes][idxPos]),
                                    axis=0)

    return aryOut


Instruction:
Explain what the following Python 3 code does
def cmp_res_R2(lstRat, lstNiiNames, strPathOut, strPathMdl, lgcSveMdlTc=True,
               lgcDel=False, strNmeExt=''):
    """"Compare results for different exponents and create winner nii.

    Parameters
    ----------
    lstRat : list
        List of floats containing the ratios that were tested for surround
        suppression.
    lstNiiNames : list
        List of names of the different pRF maps (e.g. xpos, ypos, SD)
    strPathOut : string
        Path to the parent directory where the results should be saved.
    strPathMdl : string
        Path to the parent directory where pRF models should be saved.
    lgcDel : boolean
        Should model time courses be saved as npy file?
    lgcDel : boolean
        Should inbetween results (in form of nii files) be deleted?
    strNmeExt : string
        Extra name appendix to denominate experiment name. If undesidered,
        provide empty string.

    Notes
    -----
    [1] This function does not return any arrays but instead saves to disk.

    """

    print('---Compare results for different ratios')

    # Extract the index position for R2 and Betas map in lstNiiNames
    indPosR2 = [ind for ind, item in enumerate(lstNiiNames) if 'R2' in item]
    indPosBetas = [ind for ind, item in enumerate(lstNiiNames) if 'Betas' in
                   item]
    # Check that only one index was found
    msgError = 'More than one nii file was provided that could serve as R2 map'
    assert len(indPosR2) == 1, msgError
    assert len(indPosBetas) == 1, msgError
    # turn list int index
    indPosR2 = indPosR2[0]
    indPosBetas = indPosBetas[0]

    # Get the names of the nii files with in-between results
    lstCmpRes = []
    for indRat in range(len(lstRat)):
        # Get strExpSve
        strExpSve = '_' + str(lstRat[indRat])
        # If ratio is marked with 1.0, set empty string to find results.
        # 1.0 is the key for fitting without a surround.
        if lstRat[indRat] == 1.0:
            strExpSve = ''
        # Create full path names from nii file names and output path
        lstPthNames = [strPathOut + strNii + strNmeExt + strExpSve + '.nii.gz'
                       for strNii in lstNiiNames]
        # Append list to list that contains nii names for all exponents
        lstCmpRes.append(lstPthNames)

    print('------Find ratio that yielded highest R2 per voxel')

    # Initialize winner R2 map with R2 values from fit without surround
    aryWnrR2 = load_nii(lstCmpRes[0][indPosR2])[0]
    # Initialize ratio map with 1 where no-surround model was fit, otherwise 0
    aryRatMap = np.zeros(aryWnrR2.shape)
    aryRatMap[np.nonzero(aryWnrR2)] = 1.0

    # Loop over R2 maps to establish which exponents wins
    # Skip the first ratio, since this is the reference ratio (no surround)
    # and is reflected already in the initialized arrays - aryWnrR2 & aryRatMap
    for indRat, lstMaps in zip(lstRat[1:], lstCmpRes[1:]):
        # Load R2 map for this particular exponent
        aryTmpR2 = load_nii(lstMaps[indPosR2])[0]
        # Load beta values for this particular exponent
        aryTmpBetas = load_nii(lstMaps[indPosBetas])[0]
        # Get logical that tells us where current R2 map is greater than
        # previous ones
        aryLgcWnr = np.greater(aryTmpR2, aryWnrR2)
        # Get logical that tells us where the beta parameter estimate for the
        # centre is positive and the estimate for the surround is negative
        aryLgcCtrSur1 = np.logical_and(np.greater(aryTmpBetas[..., 0], 0.0),
                                       np.less(aryTmpBetas[..., 1], 0.0))
        # Get logical that tells us where the absolute beta parameter estimate
        # for the surround is less than beta parameter estimate for the center
        aryLgcCtrSur2 = np.less(np.abs(aryTmpBetas[..., 1]),
                                np.abs(aryTmpBetas[..., 0]))
        # Combine the two logicals
        aryLgcCtrSur = np.logical_and(aryLgcCtrSur1, aryLgcCtrSur2)
        # Combine logical for winner R2 and center-surround conditions
        aryLgcWnr = np.logical_and(aryLgcWnr, aryLgcCtrSur)
        # Replace values of R2, where current R2 map was greater
        aryWnrR2[aryLgcWnr] = np.copy(aryTmpR2[aryLgcWnr])
        # Remember the index of the exponent that gave rise to this new R2
        aryRatMap[aryLgcWnr] = indRat

    # Initialize list with winner maps. The winner maps are initialized with
    # the same shape as the maps that the last tested ratio maps had.
    lstRatMap = []
    for strPthMaps in lstCmpRes[-1]:
        lstRatMap.append(np.zeros(nb.load(strPthMaps).shape))

    # Compose other maps by assigning map value from the map that resulted from
    # the exponent that won for particular voxel
    for indRat, lstMaps in zip(lstRat, lstCmpRes):
        # Find out where this exponent won in terms of R2
        lgcWinnerMap = [aryRatMap == indRat][0]
        # Loop over all the maps
        for indMap, _ in enumerate(lstMaps):
            # Load map for this particular ratio
            aryTmpMap = load_nii(lstMaps[indMap])[0]
            # Handle exception: beta map will be 1D, if from ratio 1.0
            # In this case we want to make it 2D. In particular, the second
            # set of beta weights should be all zeros, so that later when
            # forming the model time course, the 2nd predictors contributes 0
            if indRat == 1.0 and indMap == indPosBetas:
                aryTmpMap = np.concatenate((aryTmpMap,
                                            np.zeros(aryTmpMap.shape)),
                                           axis=-1)
            # Load current winner map from array
            aryCrrWnrMap = np.copy(lstRatMap[indMap])
            # Assign values in temporary map to current winner map for voxels
            # where this ratio won
            aryCrrWnrMap[lgcWinnerMap] = np.copy(aryTmpMap[lgcWinnerMap])
            lstRatMap[indMap] = aryCrrWnrMap

    print('------Export results as nii')

    # Save winner maps as nii files
    # Get header and affine array
    hdrMsk, aryAff = load_nii(lstMaps[indPosR2])[1:]
    # Loop over all the maps
    for indMap, aryMap in enumerate(lstRatMap):
        # Create nii object for results:
        niiOut = nb.Nifti1Image(aryMap,
                                aryAff,
                                header=hdrMsk
                                )
        # Save nii:
        strTmp = strPathOut + '_supsur' + lstNiiNames[indMap] + strNmeExt + \
            '.nii.gz'
        nb.save(niiOut, strTmp)

    # Save map with best ratios as nii
    niiOut = nb.Nifti1Image(aryRatMap,
                            aryAff,
                            header=hdrMsk
                            )
    # Save nii:
    strTmp = strPathOut + '_supsur' + '_Ratios' + strNmeExt + '.nii.gz'
    nb.save(niiOut, strTmp)

    if lgcSveMdlTc:
        print('------Save model time courses/parameters/responses for ' +
              'centre and surround, across all ratios')

        # Get the names of the npy files with inbetween model responses
        lstCmpMdlRsp = []
        for indRat in range(len(lstRat)):
            # Get strExpSve
            strExpSve = '_' + str(lstRat[indRat])
            # If ratio is marked with 0, set empty string to find results.
            # This is the code for fitting without a surround.
            if lstRat[indRat] == 1.0:
                strExpSve = ''
            # Create full path names from npy file names and output path
            lstPthNames = [strPathMdl + strNpy + strNmeExt + strExpSve + '.npy'
                           for strNpy in ['', '_params', '_mdlRsp']]
            # Append list to list that contains nii names for all exponents
            lstCmpMdlRsp.append(lstPthNames)

        # Load tc/parameters/responses for different ratios, for now skip "0.0"
        # ratio because its tc/parameters/responses differs in shape
        lstPrfTcSur = []
        lstMdlParamsSur = []
        lstMdlRspSur = []
        for indNpy, lstNpy in enumerate(lstCmpMdlRsp[1:]):
            lstPrfTcSur.append(np.load(lstNpy[0]))
            lstMdlParamsSur.append(np.load(lstNpy[1]))
            lstMdlRspSur.append(np.load(lstNpy[2]))
        # Turn into arrays
        aryPrfTcSur = np.stack(lstPrfTcSur, axis=2)
        aryMdlParamsSur = np.stack(lstMdlParamsSur, axis=2)
        aryMdlRspSur = np.stack(lstMdlRspSur, axis=2)

        # Now handle the "1.0" ratio
        # Load the tc/parameters/responses of the "1.0" ratio
        aryPrfTc = np.load(lstCmpMdlRsp[0][0])
        aryMdlParams = np.load(lstCmpMdlRsp[0][1])
        aryMdlRsp = np.load(lstCmpMdlRsp[0][2])
        # Make 2nd row of time courses all zeros so they get no weight in lstsq
        aryPrfTc = np.concatenate((aryPrfTc, np.zeros(aryPrfTc.shape)), axis=1)
        # Make 2nd row of parameters the same as first row
        aryMdlParams = np.stack((aryMdlParams, aryMdlParams), axis=1)
        # Make 2nd row of responses all zeros so they get no weight in lstsq
        aryMdlRsp = np.stack((aryMdlRsp, np.zeros(aryMdlRsp.shape)), axis=1)
        # Add the "1.0" ratio to tc/parameters/responses of other ratios
        aryPrfTcSur = np.concatenate((np.expand_dims(aryPrfTc, axis=2),
                                      aryPrfTcSur), axis=2)
        aryMdlParamsSur = np.concatenate((np.expand_dims(aryMdlParams, axis=2),
                                         aryMdlParamsSur), axis=2)
        aryMdlRspSur = np.concatenate((np.expand_dims(aryMdlRsp, axis=2),
                                      aryMdlRspSur), axis=2)

        # Save parameters/response for centre and surround, for all ratios
        np.save(strPathMdl + '_supsur' + '', aryPrfTcSur)
        np.save(strPathMdl + '_supsur' + '_params', aryMdlParamsSur)
        np.save(strPathMdl + '_supsur' + '_mdlRsp', aryMdlRspSur)

    # Delete all the inbetween results, if desired by user, skip "0.0" ratio
    if lgcDel:
        lstCmpRes = [item for sublist in lstCmpRes[1:] for item in sublist]
        print('------Delete in-between results')
        for strMap in lstCmpRes[:]:
            os.remove(strMap)
        if lgcSveMdlTc:
            lstCmpMdlRsp = [item for sublist in lstCmpMdlRsp[1:] for item in
                            sublist]
            for strMap in lstCmpMdlRsp[:]:
                os.remove(strMap)

Response: Compare results for different exponents and create winner nii.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def map_crt_to_pol(aryXCrds, aryYrds):

    aryRad = np.sqrt(aryXCrds**2+aryYrds**2)
    aryTht = np.arctan2(aryYrds, aryXCrds)

    return aryTht, aryRad

Response: Remap coordinates from cartesian to polar


Instruction:
Write a Python 3 script for
returning index of nearest expected polar angle.

Response:
def find_near_pol_ang(aryEmpPlrAng, aryExpPlrAng):
    """Return index of nearest expected polar angle.

    Parameters
    ----------
    aryEmpPlrAng : 1D numpy array
        Empirically found polar angle estimates
    aryExpPlrAng : 1D numpy array
        Theoretically expected polar angle estimates

    Returns
    -------
    aryXCrds : 1D numpy array
        Indices of nearest theoretically expected polar angle.
    aryYrds : 1D numpy array
        Distances to nearest theoretically expected polar angle.
    """

    dist = np.abs(np.subtract(aryEmpPlrAng[:, None],
                              aryExpPlrAng[None, :]))

    return np.argmin(dist, axis=-1), np.min(dist, axis=-1)


Instruction:
Here you have a function in Python 3, explain what it does
def rmp_rng(aryVls, varNewMin, varNewMax, varOldThrMin=None,
            varOldAbsMax=None):
    """Remap values in an array from one range to another.

    Parameters
    ----------
    aryVls : 1D numpy array
        Array with values that need to be remapped.
    varNewMin : float
        Desired minimum value of new, remapped array.
    varNewMax : float
        Desired maximum value of new, remapped array.
    varOldThrMin : float
        Theoretical minimum of old distribution. Can be specified if this
        theoretical minimum does not occur in empirical distribution but
        should be considered nontheless.
    varOldThrMin : float
        Theoretical maximum of old distribution. Can be specified if this
        theoretical maximum does not occur in empirical distribution but
        should be considered nontheless.

    Returns
    -------
    aryVls : 1D numpy array
        Array with remapped values.
    """
    if varOldThrMin is None:
        varOldMin = aryVls.min()
    else:
        varOldMin = varOldThrMin
    if varOldAbsMax is None:
        varOldMax = aryVls.max()
    else:
        varOldMax = varOldAbsMax

    aryNewVls = np.empty((aryVls.shape), dtype=aryVls.dtype)
    for ind, val in enumerate(aryVls):
        aryNewVls[ind] = (((val - varOldMin) * (varNewMax - varNewMin)) /
                          (varOldMax - varOldMin)) + varNewMin

    return aryNewVls

Response: Remap values in an array from one range to another.


Instruction:
Can you implement a function in Python 3 that
processes a new revision and detect a revert if it occurred.

Response:
def process(self, checksum, revision=None):
        """
        Process a new revision and detect a revert if it occurred.  Note that
        you can pass whatever you like as `revision` and it will be returned in
        the case that a revert occurs.

        :Parameters:
            checksum : str
                Any identity-machable string-based hash of revision content
            revision : `mixed`
                Revision metadata.  Note that any data will just be returned
                in the case of a revert.

        :Returns:
            a :class:`~mwreverts.Revert` if one occured or `None`
        """
        revert = None

        if checksum in self:  # potential revert

            reverteds = list(self.up_to(checksum))

            if len(reverteds) > 0:  # If no reverted revisions, this is a noop
                revert = Revert(revision, reverteds, self[checksum])

        self.insert(checksum, revision)
        return revert


Instruction:
Create a Python 3 function to
apply spatial smoothing to the input data.

Response:
def funcSmthSpt(aryFuncChnk, varSdSmthSpt):
    """Apply spatial smoothing to the input data.

    Parameters
    ----------
    aryFuncChnk : np.array
        TODO
    varSdSmthSpt : float (?)
        Extent of smoothing.
    Returns
    -------
    aryFuncChnk : np.array
        Smoothed data.
    """
    varNdim = aryFuncChnk.ndim

    # Number of time points in this chunk:
    varNumVol = aryFuncChnk.shape[-1]

    # Loop through volumes:
    if varNdim == 4:
        for idxVol in range(0, varNumVol):

            aryFuncChnk[:, :, :, idxVol] = gaussian_filter(
                aryFuncChnk[:, :, :, idxVol],
                varSdSmthSpt,
                order=0,
                mode='nearest',
                truncate=4.0)
    elif varNdim == 5:
        varNumMtnDrctns = aryFuncChnk.shape[3]
        for idxVol in range(0, varNumVol):
            for idxMtn in range(0, varNumMtnDrctns):
                aryFuncChnk[:, :, :, idxMtn, idxVol] = gaussian_filter(
                    aryFuncChnk[:, :, :, idxMtn, idxVol],
                    varSdSmthSpt,
                    order=0,
                    mode='nearest',
                    truncate=4.0)

    # Output list:
    return aryFuncChnk


Instruction:
Make a summary of the following Python 3 code
def funcSmthTmp(aryFuncChnk, varSdSmthTmp):
    # For the filtering to perform well at the ends of the time series, we
    # set the method to 'nearest' and place a volume with mean intensity
    # (over time) at the beginning and at the end.
    aryFuncChnkMean = np.mean(aryFuncChnk,
                              axis=1,
                              keepdims=True)

    aryFuncChnk = np.concatenate((aryFuncChnkMean,
                                  aryFuncChnk,
                                  aryFuncChnkMean), axis=1)

    # In the input data, time goes from left to right. Therefore, we apply
    # the filter along axis=1.
    aryFuncChnk = gaussian_filter1d(aryFuncChnk,
                                    varSdSmthTmp,
                                    axis=1,
                                    order=0,
                                    mode='nearest',
                                    truncate=4.0)

    # Remove mean-intensity volumes at the beginning and at the end:
    aryFuncChnk = aryFuncChnk[:, 1:-1]

    # Output list:
    return aryFuncChnk

Response: Apply temporal smoothing to fMRI data & pRF time course models.


Instruction:
Can you tell what is the following Python 3 function doing
def prep_models(aryPrfTc, varSdSmthTmp=2.0, lgcPrint=True):
    if lgcPrint:
        print('------Prepare pRF time course models')

    # Define temporal smoothing of pRF time course models
    def funcSmthTmp(aryPrfTc, varSdSmthTmp, lgcPrint=True):
        """Apply temporal smoothing to fMRI data & pRF time course models.

        Parameters
        ----------
        aryPrfTc : np.array
            4D numpy array with pRF time course models, with following
            dimensions: `aryPrfTc[x-position, y-position, SD, volume]`.
        varSdSmthTmp : float, positive
            Extent of temporal smoothing that is applied to functional data and
            pRF time course models, [SD of Gaussian kernel, in seconds]. If
            `zero`, no temporal smoothing is applied.
        lgcPrint : boolean
            Whether print statements should be executed.

        Returns
        -------
        aryPrfTc : np.array
            4D numpy array with prepared pRF time course models, same dimension
            as input (`aryPrfTc[x-position, y-position, SD, volume]`).
        """

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

        # For the filtering to perform well at the ends of the time series, we
        # set the method to 'nearest' and place a volume with mean intensity
        # (over time) at the beginning and at the end.
        aryPrfTcMean = np.mean(aryPrfTc, axis=-1, keepdims=True).reshape(-1, 1)

        aryPrfTc = np.concatenate((aryPrfTcMean, aryPrfTc, aryPrfTcMean),
                                  axis=-1)

        # In the input data, time goes from left to right. Therefore, we apply
        # the filter along axis=1.
        aryPrfTc = gaussian_filter1d(aryPrfTc.astype('float32'), varSdSmthTmp,
                                     axis=-1, order=0, mode='nearest',
                                     truncate=4.0)

        # Remove mean-intensity volumes at the beginning and at the end:
        aryPrfTc = aryPrfTc[..., 1:-1]

        # Output array:
        return aryPrfTc.reshape(tplInpShp).astype('float16')

    # Perform temporal smoothing of pRF time course models
    if 0.0 < varSdSmthTmp:
        if lgcPrint:
            print('---------Temporal smoothing on pRF time course models')
            print('------------SD tmp smooth is: ' + str(varSdSmthTmp))
        aryPrfTc = funcSmthTmp(aryPrfTc, varSdSmthTmp)

    # Z-score the prf time course models
    if lgcPrint:
        print('---------Zscore the pRF time course models')
    # De-mean the prf time course models:
    aryPrfTc = np.subtract(aryPrfTc, np.mean(aryPrfTc, axis=-1)[..., None])

    # Standardize the prf time course models:
    # In order to avoid devision by zero, only divide those voxels with a
    # standard deviation greater than zero:
    aryTmpStd = np.std(aryPrfTc, axis=-1)
    aryTmpLgc = np.greater(aryTmpStd, np.array([0.0]))
    aryPrfTc[aryTmpLgc, :] = np.divide(aryPrfTc[aryTmpLgc, :],
                                       aryTmpStd[aryTmpLgc, None])

    return aryPrfTc

Response: Prepare pRF time courses and pRF model time courses.


Instruction:
Implement a function in Python 3 to
load & prepare functional data for a specific nii file.

Response:
def prep_func(strPathNiiMask, lstPathNiiFunc, varAvgThr=100.,
              varVarThr=0.0001, strPrePro='demean'):
    """
    Load & prepare functional data.

    Parameters
    ----------
    strPathNiiMask: str
        Path to mask used to restrict pRF model finding. Only voxels with
        a value greater than zero in the mask are considered.
    lstPathNiiFunc : list
        List of paths of functional data (nii files).
    varAvgThr : float, positive, default = 100.
        Float. Voxels that have at least one run with a mean lower than this
        (before demeaning) will be excluded from model fitting.
    varVarThr : float, positive, default = 0.0001
        Float. Voxels that have at least one run with a variance lower than
        this (after demeaning) will be excluded from model fitting.
    strPrePro : string, default 'demean'
        Preprocessing that will be applied to the data.
        By default they are demeaned.

    Returns
    -------
    aryLgcMsk : np.array
        3D numpy array with logial values. Externally supplied mask (e.g grey
        matter mask). Voxels that are `False` in the mask are excluded.
    vecLgcIncl : np.array
        1D numpy array containing logical values. One value per voxel after
        mask has been applied. If `True`, the variance and mean of the voxel's
        time course are greater than the provided thresholds in all runs and
        the voxel is included in the output array (`aryFunc`). If `False`, the
        variance or mean of the voxel's time course is lower than threshold in
        at least one run and the voxel has been excluded from the output
        (`aryFunc`). This is to avoid problems in the subsequent model fitting.
        This array is necessary to put results into original dimensions after
        model fitting.
    hdrMsk : nibabel-header-object
        Nii header of mask.
    aryAff : np.array
        Array containing 'affine', i.e. information about spatial positioning
        of mask nii data.
    aryFunc : np.array
        2D numpy array containing prepared functional data, of the form
        aryFunc[voxelCount, time].
    tplNiiShp : tuple
        Spatial dimensions of input nii data (number of voxels in x, y, z
        direction). The data are reshaped during preparation, this
        information is needed to fit final output into original spatial
        dimensions.

    Notes
    -----
    Functional data is loaded from disk. The functional data is reshaped, into
    the form aryFunc[voxel, time]. A mask is applied (externally supplied, e.g.
    a grey matter mask). Subsequently, the functional data is de-meaned.
    """
    print('------Load & prepare nii data')

    # Load mask (to restrict model fitting):
    aryMask, hdrMsk, aryAff = load_nii(strPathNiiMask)

    # Mask is loaded as float32, but is better represented as integer:
    aryMask = np.array(aryMask).astype(np.int16)

    # Number of non-zero voxels in mask:
    # varNumVoxMsk = int(np.count_nonzero(aryMask))

    # Dimensions of nii data:
    tplNiiShp = aryMask.shape

    # Total number of voxels:
    varNumVoxTlt = (tplNiiShp[0] * tplNiiShp[1] * tplNiiShp[2])

    # Reshape mask:
    aryMask = np.reshape(aryMask, varNumVoxTlt)

    # List for arrays with functional data (possibly several runs):
    lstFunc = []

    # List for averages of the individual runs (before demeaning)
    lstFuncAvg = []

    # List for variances of the individual runs (after demeaning)
    lstFuncVar = []

    # Number of runs:
    varNumRun = len(lstPathNiiFunc)

    # Loop through runs and load data:
    for idxRun in range(varNumRun):

        print(('---------Prepare run ' + str(idxRun + 1)))

        # Load 4D nii data:
        aryTmpFunc, _, _ = load_nii(lstPathNiiFunc[idxRun])

        # Dimensions of nii data (including temporal dimension; spatial
        # dimensions need to be the same for mask & functional data):
        tplNiiShp = aryTmpFunc.shape

        # Reshape functional nii data, from now on of the form
        # aryTmpFunc[voxelCount, time]:
        aryTmpFunc = np.reshape(aryTmpFunc, [varNumVoxTlt, tplNiiShp[3]])

        # Apply mask:
        print('------------Mask')
        aryLgcMsk = np.greater(aryMask.astype(np.int16),
                               np.array([0], dtype=np.int16)[0])
        aryTmpFunc = aryTmpFunc[aryLgcMsk, :]

        # save the mean of the run
        lstFuncAvg.append(np.mean(aryTmpFunc, axis=1, dtype=np.float32))

        # also save the variance of the run
        lstFuncVar.append(np.var(aryTmpFunc, axis=1, dtype=np.float32))

        # De-mean functional data:
        if strPrePro == 'demean':
            print('------------Demean')
            aryTmpFunc = np.subtract(aryTmpFunc,
                                     np.mean(aryTmpFunc,
                                             axis=1,
                                             dtype=np.float32)[:, None])
        elif strPrePro == 'zscore':
            print('------------Zscore')
            aryTmpFunc = np.subtract(aryTmpFunc,
                                     np.mean(aryTmpFunc,
                                             axis=1,
                                             dtype=np.float32)[:, None])

            # Standardize the data time courses:
            # In order to avoid devision by zero, only divide
            # those voxels with a standard deviation greater
            # than zero:
            aryTmpStd = np.std(aryTmpFunc, axis=-1)
            aryTmpLgc = np.greater(aryTmpStd, np.array([0.0]))
            aryTmpFunc[aryTmpLgc, :] = np.divide(aryTmpFunc[aryTmpLgc, :],
                                                 aryTmpStd[aryTmpLgc, None])

        # Put prepared functional data of current run into list:
        lstFunc.append(aryTmpFunc)
        del(aryTmpFunc)

    # Put functional data from separate runs into one array. 2D array of the
    # form aryFunc[voxelCount, time]
    aryFunc = np.concatenate(lstFunc, axis=1).astype(np.float32, copy=False)
    del(lstFunc)

    # Put the averages (before demeaning) from the separate runs into one
    # array. 2D array of the form aryFuncVar[voxelCount, nr of runs]
    aryFuncAvg = np.stack(lstFuncAvg, axis=1).astype(np.float32, copy=False)
    del(lstFuncAvg)

    # Put the variance (after demeaning) from the separate runs into one array.
    # 2D array of the form aryFuncVar[voxelCount, nr of runs]
    aryFuncVar = np.stack(lstFuncVar, axis=1).astype(np.float32, copy=False)
    del(lstFuncVar)

    # Especially if data were recorded in different sessions, there can
    # sometimes be voxels that have close to zero signal in runs from one
    # session but regular signal in the runs from another session. These voxels
    # are very few, are located at the edge of the functional and can cause
    # problems during model fitting. They are therefore excluded.

    # Is the mean greater than threshold?
    aryLgcAvg = np.greater(aryFuncAvg,
                           np.array([varAvgThr]).astype(np.float32)[0])
    # Mean needs to be greater than threshold in every single run
    vecLgcAvg = np.all(aryLgcAvg, axis=1)

    # Voxels that are outside the brain and have no, or very little, signal
    # should not be included in the pRF model finding. We take the variance
    # over time and exclude voxels with a suspiciously low variance, if they
    # have low variance in at least one run. Because the data given into the
    # cython or GPU function has float32 precision, we calculate the variance
    # on data with float32 precision.

    # Is the variance greater than threshold?
    aryLgcVar = np.greater(aryFuncVar,
                           np.array([varVarThr]).astype(np.float32)[0])
    # Variance needs to be greater than threshold in every single run
    vecLgcVar = np.all(aryLgcVar, axis=1)

    # Are there any nan values in the functional time series?
    vecLgcNan = np.invert(np.any(np.isnan(aryFunc), axis=1))

    # combine the logical vectors for exclusion resulting from low variance and
    # low mean signal time course
    vecLgcIncl = np.logical_and(vecLgcAvg, vecLgcVar)

    # combine logical vectors for mean/variance with vector for nan exclsion
    vecLgcIncl = np.logical_and(vecLgcIncl, vecLgcNan)

    # Array with functional data for which conditions (mask inclusion and
    # cutoff value) are fullfilled:
    aryFunc = aryFunc[vecLgcIncl, :]

    # print info about the exclusion of voxels
    print('---------Minimum mean threshold for voxels applied at: ' +
          str(varAvgThr))
    print('---------Minimum variance threshold for voxels applied at:  ' +
          str(varVarThr))
    print('---------Number of voxels excluded due to low mean or variance: ' +
          str(np.sum(np.invert(vecLgcIncl))))

    return aryLgcMsk, vecLgcIncl, hdrMsk, aryAff, aryFunc, tplNiiShp


Instruction:
Make a summary of the following Python 3 code
def get(self,style):
        level = len(self.stack) -1
        while level >= 0:
            if style in self.stack[level]:
                return self.stack[level][style]
            else:
                level = level - 1
        return None

Response: what s the value of a style at the current stack level


Instruction:
Here you have a function in Python 3, explain what it does
def enforce_type(self, attr, val):
        if not attr in self.types:
            return utfstr(val)
        elif self.types[attr] == 'int':
            return int(float(val))
        elif self.types[attr] == 'float':
            return float(val)
        else:
            return utfstr(val)

Response: converts a value to the attribute s type


Instruction:
Write a Python 3 function that can
push a new level on the stack with a style dictionnary containing style : value pairs

Response:
def push(self, style={}):
        """push a new level on the stack with a style dictionnary containing style:value pairs"""
        _style = {}
        for attr in style:
            if attr in self.cmds and not style[attr] in self.cmds[attr]:
                print 'WARNING: ESC/POS PRINTING: ignoring invalid value: '+utfstr(style[attr])+' for style: '+utfstr(attr)
            else:
                _style[attr] = self.enforce_type(attr, style[attr])
        self.stack.append(_style)


Instruction:
How would you explain what the following Python 3 function does
def set(self, style={}):
        _style = {}
        for attr in style:
            if attr in self.cmds and not style[attr] in self.cmds[attr]:
                print 'WARNING: ESC/POS PRINTING: ignoring invalid value: '+utfstr(style[attr])+' for style: '+utfstr(attr)
            else:
                self.stack[-1][attr] = self.enforce_type(attr, style[attr])

Response: overrides style values at the current stack level


Instruction:
Write a Python 3 script to
convert the current style to an escpos command string

Response:
def to_escpos(self):
        """ converts the current style to an escpos command string """
        cmd = ''
        ordered_cmds = self.cmds.keys()
        ordered_cmds.sort(lambda x,y: cmp(self.cmds[x]['_order'], self.cmds[y]['_order']))
        for style in ordered_cmds:
            cmd += self.cmds[style][self.get(style)]
        return cmd


Instruction:
Can you generate the documentation for the following Python 3 function
def start_inline(self,stylestack=None):
        self.stack.append('inline')
        if self.dirty:
            self.escpos._raw(' ')
        if stylestack:
            self.style(stylestack)

Response: starts an inline entity with an optional style definition


Instruction:
Can you generate the documentation for the following Python 3 function
def start_block(self,stylestack=None):
        if self.dirty:
            self.escpos._raw('\n')
            self.dirty = False
        self.stack.append('block')
        if stylestack:
            self.style(stylestack)

Response: starts a block entity with an optional style definition


Instruction:
Can you generate the documentation for the following Python 3 function
def end_entity(self):
        if self.stack[-1] == 'block' and self.dirty:
            self.escpos._raw('\n')
            self.dirty = False
        if len(self.stack) > 1:
            self.stack = self.stack[:-1]

Response: Ends the entity definition.


Instruction:
Can you implement a function in Python 3 that
puts a string of text in the entity keeping the whitespace intact

Response:
def pre(self,text):
        """ puts a string of text in the entity keeping the whitespace intact """
        if text:
            self.escpos.text(text)
            self.dirty = True


Instruction:
Explain what the following Python 3 code does
def text(self,text):
        if text:
            text = utfstr(text)
            text = text.strip()
            text = re.sub('\s+',' ',text)
            if text:
                self.dirty = True
                self.escpos.text(text)

Response: puts text in the entity. Whitespace and newlines are stripped to single spaces.


Instruction:
Write a Python 3 function that can
check and fix the size of the image to 32 bits

Response:
def _check_image_size(self, size):
        """ Check and fix the size of the image to 32 bits """
        if size % 32 == 0:
            return (0, 0)
        else:
            image_border = 32 - (size % 32)
            if (image_border % 2) == 0:
                return (image_border / 2, image_border / 2)
            else:
                return (image_border / 2, (image_border / 2) + 1)


Instruction:
Implement a Python 3 function for
parsing image and prepare it to a printable format

Response:
def _convert_image(self, im):
        """ Parse image and prepare it to a printable format """
        pixels   = []
        pix_line = ""
        im_left  = ""
        im_right = ""
        switch   = 0
        img_size = [ 0, 0 ]

        if im.size[0] > 512:
            print  "WARNING: Image is wider than 512 and could be truncated at print time "
        if im.size[1] > 255:
            raise ImageSizeError()

        im_border = self._check_image_size(im.size[0])
        for i in range(im_border[0]):
            im_left += "0"
        for i in range(im_border[1]):
            im_right += "0"

        for y in range(im.size[1]):
            img_size[1] += 1
            pix_line += im_left
            img_size[0] += im_border[0]
            for x in range(im.size[0]):
                img_size[0] += 1
                RGB = im.getpixel((x, y))
                im_color = (RGB[0] + RGB[1] + RGB[2])
                im_pattern = "1X0"
                pattern_len = len(im_pattern)
                switch = (switch - 1 ) * (-1)
                for x in range(pattern_len):
                    if im_color <= (255 * 3 / pattern_len * (x+1)):
                        if im_pattern[x] == "X":
                            pix_line += "%d" % switch
                        else:
                            pix_line += im_pattern[x]
                        break
                    elif im_color > (255 * 3 / pattern_len * pattern_len) and im_color <= (255 * 3):
                        pix_line += im_pattern[-1]
                        break
            pix_line += im_right
            img_size[0] += im_border[1]

        return (pix_line, img_size)


Instruction:
How would you explain what the following Python 3 function does
def image(self,path_img):
        im_open = Image.open(path_img)
        im = im_open.convert("RGB")
        # Convert the RGB image in printable image
        pix_line, img_size = self._convert_image(im)
        self._print_image(pix_line, img_size)

Response: Open image file and print it in printable image


Instruction:
How would you implement a function in Python 3 that
prints QR Code for the provided string

Response:
def qr(self,text):
        """ Print QR Code for the provided string """
        qr_code = qrcode.QRCode(version=4, box_size=4, border=1)
        qr_code.add_data(text)
        qr_code.make(fit=True)
        qr_img = qr_code.make_image()
        im = qr_img._img.convert("RGB")
        # Convert the RGB image in printable image
        self._convert_image(im)


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

        def strclean(string):
            if not string:
                string = ''
            string = string.strip()
            string = re.sub('\s+',' ',string)
            return string

        def format_value(value, decimals=3, width=0, decimals_separator='.', thousands_separator=',', autoint=False, symbol='', position='after'):
            decimals = max(0,int(decimals))
            width    = max(0,int(width))
            value    = float(value)

            if autoint and math.floor(value) == value:
                decimals = 0
            if width == 0:
                width = ''

            if thousands_separator:
                formatstr = "{:"+str(width)+",."+str(decimals)+"f}"
            else:
                formatstr = "{:"+str(width)+"."+str(decimals)+"f}"

            ret = formatstr.format(value)
            ret = ret.replace(',','COMMA')
            ret = ret.replace('.','DOT')
            ret = ret.replace('COMMA',thousands_separator)
            ret = ret.replace('DOT',decimals_separator)

            if symbol:
                if position == 'after':
                    ret = ret + symbol
                else:
                    ret = symbol + ret
            return ret

        def print_elem(stylestack, serializer, elem, indent=0):

            elem_styles = {
                'h1': {'bold': 'on', 'size':'double'},
                'h2': {'size':'double'},
                'h3': {'bold': 'on', 'size':'double-height'},
                'h4': {'size': 'double-height'},
                'h5': {'bold': 'on'},
                'em': {'font': 'b'},
                'b':  {'bold': 'on'},
            }

            stylestack.push()
            if elem.tag in elem_styles:
                stylestack.set(elem_styles[elem.tag])
            stylestack.set(elem.attrib)

            if elem.tag in ('p','div','section','article','receipt','header','footer','li','h1','h2','h3','h4','h5'):
                serializer.start_block(stylestack)
                serializer.text(elem.text)
                for child in elem:
                    print_elem(stylestack,serializer,child)
                    serializer.start_inline(stylestack)
                    serializer.text(child.tail)
                    serializer.end_entity()
                serializer.end_entity()

            elif elem.tag in ('span','em','b','left','right'):
                serializer.start_inline(stylestack)
                serializer.text(elem.text)
                for child in elem:
                    print_elem(stylestack,serializer,child)
                    serializer.start_inline(stylestack)
                    serializer.text(child.tail)
                    serializer.end_entity()
                serializer.end_entity()

            elif elem.tag == 'value':
                serializer.start_inline(stylestack)
                serializer.pre(format_value(
                                              elem.text,
                                              decimals=stylestack.get('value-decimals'),
                                              width=stylestack.get('value-width'),
                                              decimals_separator=stylestack.get('value-decimals-separator'),
                                              thousands_separator=stylestack.get('value-thousands-separator'),
                                              autoint=(stylestack.get('value-autoint') == 'on'),
                                              symbol=stylestack.get('value-symbol'),
                                              position=stylestack.get('value-symbol-position')
                                            ))
                serializer.end_entity()

            elif elem.tag == 'line':
                width = stylestack.get('width')
                if stylestack.get('size') in ('double', 'double-width'):
                    width = width / 2

                lineserializer = XmlLineSerializer(stylestack.get('indent')+indent,stylestack.get('tabwidth'),width,stylestack.get('line-ratio'))
                serializer.start_block(stylestack)
                for child in elem:
                    if child.tag == 'left':
                        print_elem(stylestack,lineserializer,child,indent=indent)
                    elif child.tag == 'right':
                        lineserializer.start_right()
                        print_elem(stylestack,lineserializer,child,indent=indent)
                serializer.pre(lineserializer.get_line())
                serializer.end_entity()

            elif elem.tag == 'ul':
                serializer.start_block(stylestack)
                bullet = stylestack.get('bullet')
                for child in elem:
                    if child.tag == 'li':
                        serializer.style(stylestack)
                        serializer.raw(' ' * indent * stylestack.get('tabwidth') + bullet)
                    print_elem(stylestack,serializer,child,indent=indent+1)
                serializer.end_entity()

            elif elem.tag == 'ol':
                cwidth = len(str(len(elem))) + 2
                i = 1
                serializer.start_block(stylestack)
                for child in elem:
                    if child.tag == 'li':
                        serializer.style(stylestack)
                        serializer.raw(' ' * indent * stylestack.get('tabwidth') + ' ' + (str(i)+')').ljust(cwidth))
                        i = i + 1
                    print_elem(stylestack,serializer,child,indent=indent+1)
                serializer.end_entity()

            elif elem.tag == 'pre':
                serializer.start_block(stylestack)
                serializer.pre(elem.text)
                serializer.end_entity()

            elif elem.tag == 'hr':
                width = stylestack.get('width')
                if stylestack.get('size') in ('double', 'double-width'):
                    width = width / 2
                serializer.start_block(stylestack)
                serializer.text('-'*width)
                serializer.end_entity()

            elif elem.tag == 'br':
                serializer.linebreak()

            elif elem.tag == 'img':
                if 'src' in elem.attrib and 'data:' in elem.attrib['src']:
                    self.print_base64_image(elem.attrib['src'])

            elif elem.tag == 'barcode' and 'encoding' in elem.attrib:
                serializer.start_block(stylestack)
                self.barcode(strclean(elem.text),elem.attrib['encoding'])
                serializer.end_entity()

            elif elem.tag == 'cut':
                self.cut()
            elif elem.tag == 'partialcut':
                self.cut(mode='part')
            elif elem.tag == 'cashdraw':
                self.cashdraw(2)
                self.cashdraw(5)

            stylestack.pop()

        try:
            stylestack      = StyleStack()
            serializer      = XmlSerializer(self)
            root            = ET.fromstring(xml.encode('utf-8'))
            if 'sheet' in root.attrib and root.attrib['sheet'] == 'slip':
                self._raw(SHEET_SLIP_MODE)
                self.slip_sheet_mode = True
            else:
                self._raw(SHEET_ROLL_MODE)

            self._raw(stylestack.to_escpos())

            print_elem(stylestack,serializer,root)

            if 'open-cashdrawer' in root.attrib and root.attrib['open-cashdrawer'] == 'true':
                self.cashdraw(2)
                self.cashdraw(5)
            if not 'cut' in root.attrib or root.attrib['cut'] == 'true' :
                if self.slip_sheet_mode:
                    self._raw(CTL_FF)
                else:
                    self.cut()

        except Exception as e:
            errmsg = str(e)+'\n'+'-'*48+'\n'+traceback.format_exc() + '-'*48+'\n'
            self.text(errmsg)
            self.cut()

            raise e

Response: Prints an xml based receipt definition


Instruction:
Given the following Python 3 function, write the documentation
def text(self,txt):
        if not txt:
            return
        try:
            txt = txt.decode('utf-8')
        except:
            try:
                txt = txt.decode('utf-16')
            except:
                pass

        self.extra_chars = 0

        def encode_char(char):
            """
            Encodes a single utf-8 character into a sequence of
            esc-pos code page change instructions and character declarations
            """
            char_utf8 = char.encode('utf-8')
            encoded  = ''
            encoding = self.encoding # we reuse the last encoding to prevent code page switches at every character
            encodings = {
                    # TODO use ordering to prevent useless switches
                    # TODO Support other encodings not natively supported by python ( Thai, Khazakh, Kanjis )
                    'cp437': TXT_ENC_PC437,
                    'cp850': TXT_ENC_PC850,
                    'cp852': TXT_ENC_PC852,
                    'cp857': TXT_ENC_PC857,
                    'cp858': TXT_ENC_PC858,
                    'cp860': TXT_ENC_PC860,
                    'cp863': TXT_ENC_PC863,
                    'cp865': TXT_ENC_PC865,
                    'cp866': TXT_ENC_PC866,
                    'cp862': TXT_ENC_PC862,
                    'cp720': TXT_ENC_PC720,
                    'cp936': TXT_ENC_PC936,
                    'iso8859_2': TXT_ENC_8859_2,
                    'iso8859_7': TXT_ENC_8859_7,
                    'iso8859_9': TXT_ENC_8859_9,
                    'cp1254'   : TXT_ENC_WPC1254,
                    'cp1255'   : TXT_ENC_WPC1255,
                    'cp1256'   : TXT_ENC_WPC1256,
                    'cp1257'   : TXT_ENC_WPC1257,
                    'cp1258'   : TXT_ENC_WPC1258,
                    'katakana' : TXT_ENC_KATAKANA,
            }
            remaining = copy.copy(encodings)

            if not encoding :
                encoding = 'cp437'

            while True: # Trying all encoding until one succeeds
                try:
                    if encoding == 'katakana': # Japanese characters
                        if jcconv:
                            # try to convert japanese text to a half-katakanas
                            kata = jcconv.kata2half(jcconv.hira2kata(char_utf8))
                            if kata != char_utf8:
                                self.extra_chars += len(kata.decode('utf-8')) - 1
                                # the conversion may result in multiple characters
                                return encode_str(kata.decode('utf-8'))
                        else:
                             kata = char_utf8

                        if kata in TXT_ENC_KATAKANA_MAP:
                            encoded = TXT_ENC_KATAKANA_MAP[kata]
                            break
                        else:
                            raise ValueError()
                    else:
                        encoded = char.encode(encoding)
                        break

                except ValueError: #the encoding failed, select another one and retry
                    if encoding in remaining:
                        del remaining[encoding]
                    if len(remaining) >= 1:
                        encoding = remaining.items()[0][0]
                    else:
                        encoding = 'cp437'
                        encoded  = '\xb1'    # could not encode, output error character
                        break;

            if encoding != self.encoding:
                # if the encoding changed, remember it and prefix the character with
                # the esc-pos encoding change sequence
                self.encoding = encoding
                encoded = encodings[encoding] + encoded

            return encoded

        def encode_str(txt):
            buffer = ''
            for c in txt:
                buffer += encode_char(c)
            return buffer

        txt = encode_str(txt)

        # if the utf-8 -> codepage conversion inserted extra characters,
        # remove double spaces to try to restore the original string length
        # and prevent printing alignment issues
        while self.extra_chars > 0:
            dspace = txt.find('  ')
            if dspace > 0:
                txt = txt[:dspace] + txt[dspace+1:]
                self.extra_chars -= 1
            else:
                break

        self._raw(txt)

Response: Print Unicode encoded alpha - numeric text.


Instruction:
Write a Python 3 function for
cutting the log entry for a given entry.

Response:
def cut(self, mode=''):
        """ Cut paper """
        # Fix the size between last line and cut
        # TODO: handle this with a line feed
        self._raw("\n\n\n\n\n\n")
        if mode.upper() == "PART":
            self._raw(PAPER_PART_CUT)
        else: # DEFAULT MODE: FULL CUT
            self._raw(PAPER_FULL_CUT)


Instruction:
Given the following Python 3 function, write the documentation
def cashdraw(self, pin):
        if pin == 2:
            self._raw(CD_KICK_2)
        elif pin == 5:
            self._raw(CD_KICK_5)
        else:
            raise CashDrawerError()

Response: Send pulse to kick the cash drawer


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

        self.device = usb.core.find(idVendor=self.idVendor, idProduct=self.idProduct)
        if self.device is None:
            raise NoDeviceError()
        try:
            if self.device.is_kernel_driver_active(self.interface):
                self.device.detach_kernel_driver(self.interface)
            self.device.set_configuration()
            usb.util.claim_interface(self.device, self.interface)
        except usb.core.USBError as e:
            raise HandleDeviceError(e)

Response: Open USB tree and set is as escpos device


Instruction:
Can you generate the documentation for the following Python 3 function
def _raw(self, msg):
        if len(msg) != self.device.write(self.out_ep, msg, self.interface):
            self.device.write(self.out_ep, self.errorText, self.interface)
            raise TicketNotPrinted()

Response: Print any command sent in raw format


Instruction:
Explain what the following Python 3 code does
def open(self):
        self.device = serial.Serial(port=self.devfile, baudrate=self.baudrate, bytesize=self.bytesize, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=self.timeout, dsrdtr=True)

        if self.device is not None:
            print "Serial printer enabled"
        else:
            print "Unable to open serial printer on: %s" % self.devfile

Response: Open the device and set it as escpos device


Instruction:
Write a Python 3 script for
opening TCP socket and set it as escpos device

Response:
def open(self):
        """ Open TCP socket and set it as escpos device """
        self.device = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.device.connect((self.host, self.port))

        if self.device is None:
            print "Could not open socket for %s" % self.host


Instruction:
Write a Python 3 function that can
generate a list of Pinyin characters for a given set of characters.

Response:
def _pinyin_generator(chars, format):
    """Generate pinyin for chars, if char is not chinese character,
    itself will be returned.
    Chars must be unicode list.
    """
    for char in chars:
        key = "%X" % ord(char)
        pinyin = pinyin_dict.get(key, char)
        tone = pinyin_tone.get(key, 0)

        if tone == 0 or format == "strip":
            pass
        elif format == "numerical":
            pinyin += str(tone)
        elif format == "diacritical":
            # Find first vowel -- where we should put the diacritical mark
            vowels = itertools.chain((c for c in pinyin if c in "aeo"),
                                     (c for c in pinyin if c in "iuv"))
            vowel = pinyin.index(next(vowels)) + 1
            pinyin = pinyin[:vowel] + tonemarks[tone] + pinyin[vowel:]
        else:
            error = "Format must be one of: numerical/diacritical/strip"
            raise ValueError(error)

        yield unicodedata.normalize('NFC', pinyin)


Instruction:
Can you tell what is the following Python 3 function doing
def get(s, delimiter='', format="diacritical"):
    return delimiter.join(_pinyin_generator(u(s), format=format))

Response: Return pinyin of string


Instruction:
How would you implement a function in Python 3 that
returns the 1st char of pinyin of string

Response:
def get_initial(s, delimiter=' '):
    """Return the 1st char of pinyin of string, the string must be unicode
    """
    initials = (p[0] for p in _pinyin_generator(u(s), format="strip"))
    return delimiter.join(initials)


Instruction:
Write a Python 3 script to
add a word to the tree.

Response:
def _add_to_tree(tree, word, meaning):
    '''
    We build word search trees, where we walk down
    the letters of a word. For example:
      你 Good
      你好 Hello
    Would build the tree
         你
        /  \
      You   好
             \
           Hello
    '''
    if len(word) == 0:
        tree[''] = meaning
    else:
        _add_to_tree(tree[word[0]], word[1:], meaning)


Instruction:
Implement a Python 3 function for
loading in the Chinese - English dictionary. This takes 1 - 2 seconds. It is done when other functions are used.

Response:
def init():
    '''
    Load in the Chinese-English dictionary. This takes 1-2 seconds. It
    is done when the other functions are used, but this is public since
    preloading sometimes makes sense.
    '''
    global dictionaries, trees

    dictionaries = {
        'traditional': {},
        'simplified': {}
    }

    trees = {
        'traditional': Tree(),
        'simplified': Tree()
    }

    lines = gzip.open(
        os.path.join(os.path.dirname(__file__), "cedict.txt.gz"),
        mode='rt',
        encoding='utf-8'
    )
    exp = re.compile("^([^ ]+) ([^ ]+) \[(.*)\] /(.+)/")
    parsed_lines = (exp.match(line).groups()
                    for line in lines
                    if line[0] != '#')

    for traditional, simplified, pinyin, meaning in parsed_lines:
        meaning = meaning.split('/')
        dictionaries['traditional'][traditional] = meaning
        dictionaries['simplified'][simplified] = meaning
        _add_to_tree(trees['traditional'], traditional, meaning)
        _add_to_tree(trees['simplified'], simplified, meaning)


Instruction:
Can you implement a function in Python 3 that
translates a single character or word into a set of translations.

Response:
def translate_word(word, dictionary=['simplified']):
    '''
    Return the set of translations for a single character or word, if
    available.
    '''
    if not dictionaries:
        init()
    for d in dictionary:
        if word in dictionaries[d]:
            return dictionaries[d][word]
    return None


Instruction:
Explain what the following Python 3 code does
def _words_at_the_beginning(word, tree, prefix=""):
    '''
    We return all portions of the tree corresponding to the beginning
    of `word`. This is used recursively, so we pass the prefix so we
    can return meaningful words+translations.
    '''
    l = []
    if "" in tree:
        l.append([prefix, tree[""]])
    if len(word) > 0 and word[0] in tree:
        l.extend(_words_at_the_beginning(
            word[1:],
            tree[word[0]],
            prefix=prefix+word[0]
        ))
    return l

Response: Returns all words in the tree corresponding to the beginning of the word.


Instruction:
Given the following Python 3 function, write the documentation
def all_phrase_translations(phrase):
    '''
    Return the set of translations for all possible words in a full
    phrase. Chinese is sometimes ambiguous. We do not attempt to
    disambiguate, or handle unknown letters especially well. Full
    parsing is left to upstream logic.
    '''
    if not trees:
        init()
    phrase = phrase.split(string.whitespace)
    for word in phrase:
        for x in range(len(word)):
            for translation in _words_at_the_beginning(
                    word[x+1:],
                    trees['simplified'][word[x]],
                    prefix=word[x]):
                yield translation

Response:
Yields all possible translations for all possible words in a full
   .


Instruction:
Write a Python 3 script for
generating a key used to set a status on a field

Response:
def get_status_key(self, instance):
        """Generates a key used to set a status on a field"""
        key_id = "inst_%s" % id(instance) if instance.pk is None else instance.pk
        return "%s.%s-%s-%s" % (instance._meta.app_label,
                                get_model_name(instance),
                                key_id,
                                self.field.name)


Instruction:
Explain what the following Python 3 code does
def get_status(self, instance):
        status_key, status = self._get_status(instance)
        if status['state'] in ['complete', 'error']:
            cache.delete(status_key)
        return status

Response: Retrives a status of a field from cache.


Instruction:
Can you implement a function in Python 3 that
sets the status of the given instance in the cache.

Response:
def set_status(self, instance, status):
        """Sets the field status for up to 5 minutes."""
        status_key = self.get_status_key(instance)
        cache.set(status_key, status, timeout=300)