output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Return the dict element whose numeric key is closest to a target.
Make a summary of the following Python 3 code def get_nearest_by_numeric_key(data: dict, key: int) -> Any: return data.get(key, data[min(data.keys(), key=lambda k: abs(k - key))])
As a Python code composer, you craft elegant and concise scripts.
Create a blueprint resource route from a function.
Explain what the following Python 3 code does def resource(self, uri, methods=frozenset({'GET'}), host=None, strict_slashes=None, stream=False, version=None, name=None, **kwargs): """ Create a blueprint resource route from a decorated function. :param uri: endp...
As a Python code translator, you convert algorithms and pseudocode into Python.
def add_resource(self, handler, uri, methods=frozenset({'GET'}), host=None, strict_slashes=None, version=None, name=None, **kwargs): """ Create a blueprint resource route from a function. :param uri: endpoint at which the route will be accessible. ...
Implement a Python 3 function for adding a blueprint resource route to the app.
As a Python code composer, you craft elegant and concise scripts.
Returns the connection to the database using the settings. MONGODB
Can you generate a brief explanation for the following Python 3 code def _get_db(): from .settings import settings mongo = settings.MONGODB if 'URI' in mongo and mongo['URI']: uri = mongo['URI'] else: uri = 'mongodb://' if all(mongo.get(key) for key in ('USERNAME', 'PASSWORD'))...
As a python code expert, you are capable of creating scripts from specifications.
def getBetas(idxPrc, aryPrfTc, lstAllMdlInd, aryFuncChnk, aryBstIndChnk, betaSw, queOut): """Calculate voxel betas and R^2 for the best model. Parameters ---------- idxPrc : TODO (?) aryPrfTc : np.array, shape (?)...
Can you create a Python 3 function that calculates voxel betas and R^2 for the best model.
As a python code expert, you are capable of creating scripts from specifications.
This method returns the list of creator objects that are available for the article.
Here you have a function in Python 3, explain what it does def nav_creators(self, article): creator_list = [] for contrib_group in article.metadata.front.article_meta.contrib_group: for contrib in contrib_group.contrib: if not contrib.attrs['contrib-type'] == 'author': ...
As a Python code composer, you craft elegant and concise scripts.
This method returns the string representation of the article s title.
Here you have a function in Python 3, explain what it does def nav_title(self, article): article_title = article.metadata.front.article_meta.title_group.article_title.node return str(etree.tostring(article_title, method='text', encoding='utf-8'), encoding='utf-8')
You are a Python code architect, reviewing and designing scalable and efficient code
This method formats the given citation into a single - level citation list.
Can you tell what is the following Python 3 function doing def format_citation(citation, citation_type=None): cite_types = {'book': self.format_book_citation, 'commun': self.format_commun_citation, 'confproc': self.format_confproc_citation, 'discussion': self.fo...
As a Python code composer, you craft elegant and concise scripts.
Given a PLoS DOI into a URL path to the XML file.
Can you generate the documentation for the following Python 3 function def plos_doi_to_xmlurl(doi_string): #Create URL to request DOI resolution from http://dx.doi.org doi_url = 'http://dx.doi.org/{0}'.format(doi_string) log.debug('DOI URL: {0}'.format(doi_url)) #Open the page, follow the redirect t...
You are a Python code generator, capable of creating scripts from specifications.
This method expects a URL string and returns the root name of the xml file.
Can you tell what is the following Python 3 function doing def url_input(url_string, download=True): log.debug('URL Input - {0}'.format(url_string)) try: open_xml = urllib.request.urlopen(url_string) except urllib.error.URLError as err: print('utils.input.url_input received a bad URL, or cou...
You are a Python code generator, capable of creating scripts from specifications.
def _red_listing_validation(key, listing): """ Raises an RedValidationError, if the given listing does not comply with cwl_job_listing_schema. If listing is None or an empty list, no exception is thrown. :param key: The input key to build an error message if needed. :param listing: The listing to v...
Write a Python 3 function that can validate a given listing against the CWL job listing schema.
As a python code expert, you are capable of creating scripts from specifications.
def red_get_mount_connectors(red_data, ignore_outputs): """ Returns a list of mounting connectors :param red_data: The red data to be searched :param ignore_outputs: If outputs should be ignored :return: A list of connectors with active mount option. """ keys = [] batches = red_data.g...
Can you implement a function in Python 3 that returns a list of mounting connectors from the red data.
As a Python code translator, you convert algorithms and pseudocode into Python.
def cleanup(connector_manager, red_data, tmp_dir): """ Invokes the cleanup functions for all inputs. """ for key, arg in red_data['inputs'].items(): val = arg if isinstance(arg, list): for index, i in enumerate(arg): if not isinstance(i, dict): ...
Write a Python 3 function for invoking the cleanup functions for all inputs.
As a Python code translator, you convert algorithms and pseudocode into Python.
Executes a connector command and returns the return code and stderr of the connector command.
How would you explain what the following Python 3 function does def _execute_connector(connector_command, top_level_argument, *file_contents, listing=None): # create temp_files for every file_content temp_files = [] for file_content in file_contents: if file_content is None: ...
You are a Python code architect, reviewing and designing scalable and efficient code
Checks if a given listing is present under the given directory path.
Here you have a function in Python 3, explain what it does def directory_listing_content_check(directory_path, listing): if listing: for sub in listing: path = os.path.join(directory_path, sub['basename']) if sub['class'] == 'File': if not os.path....
As a python code expert, you are capable of creating scripts from specifications.
Imports pycuda at runtime and reads GPU information.
How would you explain what the following Python 3 function does def get_cuda_devices(): devices = [] try: import pycuda.autoinit import pycuda.driver as cuda for device_id in range(cuda.Device.count()): vram = cuda.Device(device_id).total_memory() devices.appe...
As a Python code composer, you craft elegant and concise scripts.
def match_gpus(available_devices, requirements): """ Determines sufficient GPUs for the given requirements and returns a list of GPUDevices. If there aren't sufficient GPUs a InsufficientGPUException is thrown. :param available_devices: A list of GPUDevices :param requirements: A list of GPURequire...
Implement a Python 3 function for determining sufficient GPUs for the given requirements and returns a list of GPUDevices.
As a Python code composer, you craft elegant and concise scripts.
Extracts the GPU from a dictionary requirements as list of GPURequirements.
Given the following Python 3 function, write the documentation def get_gpu_requirements(gpus_reqs): requirements = [] if gpus_reqs: if type(gpus_reqs) is dict: count = gpus_reqs.get('count') if count: for i in range(count): requirements.append...
You are a Python code architect, reviewing and designing scalable and efficient code
Sets the environment variables that are set in the Nvidia - GPUs environment variable.
Make a summary of the following Python 3 code def set_nvidia_environment_variables(environment, gpu_ids): if gpu_ids: nvidia_visible_devices = "" for gpu_id in gpu_ids: nvidia_visible_devices += "{},".format(gpu_id) environment["NVIDIA_VISIBLE_DEVICES"] = nvidia_visible_devices
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns whether the device is sufficient for this requirement.
Can you generate the documentation for the following Python 3 function def is_sufficient(self, device): sufficient = True if (self.min_vram is not None) and (device.vram < self.min_vram): sufficient = False return sufficient
As a Python code translator, you convert algorithms and pseudocode into Python.
Cross - platform placement of cached files
Can you tell what is the following Python 3 function doing def cache_location(): '''Cross-platform placement of cached files''' plat = platform.platform() log.debug('Platform read as: {0}'.format(plat)) if plat.startswith('Windows'): log.debug('Windows platform detected') return os.path....
As a Python code composer, you craft elegant and concise scripts.
Load the config. py file and return the module object.
Can you generate the documentation for the following Python 3 function def load_config_module(): import imp config_path = config_location() try: config = imp.load_source('config', config_path) except IOError: log.critical('Config file not found. oaepub exiting...') sys.exit('Conf...
As a Python code composer, you craft elegant and concise scripts.
This function returns an absolute path for the input path.
Given the following Python 3 function, write the documentation def get_absolute_path(some_path): if os.path.isabs(some_path): return some_path else: return evaluate_relative_path(os.getcwd(), some_path)
As a Python code composer, you craft elegant and concise scripts.
Returns the root name of a file from a full file path.
How would you explain what the following Python 3 function does def file_root_name(name): base = os.path.basename(name) root = os.path.splitext(base)[0] if not root: warning = 'file_root_name returned an empty root name from \"{0}\"' log.warning(warning.format(name)) return root
As a Python code analyst, you investigate and solve complex coding mysteries
Generator function that will iterate over all files in the specified directory and return a path to the files which possess a matching extension.
Explain what the following Python 3 code does def files_with_ext(extension, directory='.', recursive=False): if recursive: log.info('Recursively searching {0} for files with extension "{1}"'.format(directory, extension)) for dirname, subdirnames, filenames in os.walk(directory): for file...
You are a Python code architect, reviewing and designing scalable and efficient code
def dir_exists(directory): """ If a directory already exists that will be overwritten by some action, this will ask the user whether or not to continue with the deletion. If the user responds affirmatively, then the directory will be removed. If the user responds negatively, then the process will a...
Create a Python 3 function for checking if a directory already exists and if yes deletes it if it does not.
As a Python code analyst, you investigate and solve complex coding mysteries
def get_nearest_by_coordinates( data: list, latitude_key: str, longitude_key: str, target_latitude: float, target_longitude: float) -> Any: """Get the closest dict entry based on latitude/longitude.""" return min( data, key=lambda p: haversine( target_latitude, ...
Implement a Python 3 function for getting the nearest dict entry based on latitude and longitude.
As a python code expert, you are capable of creating scripts from specifications.
def haversine(lat1: float, lon1: float, lat2: float, lon2: float) -> float: """Determine the distance between two latitude/longitude pairs.""" lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) # haversine formula dlon = lon2 - lon1 dlat = lat2 - lat1 calc_a = sin(dlat / 2)**2 + co...
How would you code a function in Python 3 to determine the distance between two latitude and longitude pairs.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns an iterator over all of the insertion points in a given file.
Can you generate a brief explanation for the following Python 3 code def in_file(self, fn: str) -> Iterator[InsertionPoint]: logger.debug("finding insertion points in file: %s", fn) yield from self.__file_insertions.get(fn, [])
As a python code expert, you are capable of creating scripts from specifications.
def at_line(self, line: FileLine) -> Iterator[InsertionPoint]: """ Returns an iterator over all of the insertion points located at a given line. """ logger.debug("finding insertion points at line: %s", str(line)) filename = line.filename # type: str line_num = li...
Implement a function in Python 3 to return an iterator over all of the insertion points located at a specific line.
You are a Python code architect, reviewing and designing scalable and efficient code
Get UnitCost of a particular item.
Given the following Python 3 function, write the documentation def getUnitCost(self, CorpNum): result = self._httpget('/CloseDown/UnitCost', CorpNum) return float(result.unitCost)
As a Python code composer, you craft elegant and concise scripts.
휴폐업조회 대량 확인, 최대 1000건 args MemberCorpNum : 팝빌회원 사업자번호 CorpNumList : 조회할 사업자번호 배열 return 휴폐업정보 Object as List raise PopbillException
Make a summary of the following Python 3 code def checkCorpNums(self, MemberCorpNum, CorpNumList): if CorpNumList == None or len(CorpNumList) < 1: raise PopbillException(-99999999,"조죄할 사업자번호 목록이 입력되지 않았습니다.") postData = self._stringtify(CorpNumList) return self._httppost('/CloseDow...
You are a Python code architect, reviewing and designing scalable and efficient code
Load PNG files and return a 2d numpy array of the size of the image.
How would you explain what the following Python 3 function does def loadPng(varNumVol, tplPngSize, strPathPng): print('------Load PNGs') # Create list of png files to load: lstPngPaths = [None] * varNumVol for idx01 in range(0, varNumVol): lstPngPaths[idx01] = (strPathPng + str(idx01) + '.png') ...
You are a Python code analyst, evaluating scripts for potential improvements.
def loadPrsOrd(vecRunLngth, strPathPresOrd, vecVslStim): """Load presentation order of motion directions. Parameters ---------- vecRunLngth : list Number of volumes in every run strPathPresOrd : str Path to the npy vector containing order of presented motion directions. vecVslSt...
Write a Python 3 script for loading presentation order of motion directions.
You are a Python code architect, reviewing and designing scalable and efficient code
def crtPwBoxCarFn(varNumVol, aryPngData, aryPresOrd, vecMtDrctn): """Create pixel-wise boxcar functions. Parameters ---------- input1 : 2d numpy array, shape [n_samples, n_measurements] Description of input 1. input2 : float, positive Description of input 2. Returns ------- ...
Create a Python 3 function to create pixel - wise boxcar functions.
You are a Python code architect, reviewing and designing scalable and efficient code
Create 2D Gaussian kernel.
How would you explain what the following Python 3 function does def crtGauss2D(varSizeX, varSizeY, varPosX, varPosY, varSd): varSizeX = int(varSizeX) varSizeY = int(varSizeY) # aryX and aryY are in reversed order, this seems to be necessary: aryY, aryX = sp.mgrid[0:varSizeX, 0...
You are a Python code generator, capable of creating scripts from specifications.
Spatially convolve boxcar functions with 2D Gaussian.
Explain what the following Python 3 code does def cnvlGauss2D(idxPrc, aryBoxCar, aryMdlParamsChnk, tplPngSize, varNumVol, queOut): """Spatially convolve boxcar functions with 2D Gaussian. Parameters ---------- idxPrc : 2d numpy array, shape [n_samples, n_measurements] Descriptio...
You are a Python code analyst, evaluating scripts for potential improvements.
def crtPrfNrlTc(aryBoxCar, varNumMtDrctn, varNumVol, tplPngSize, varNumX, varExtXmin, varExtXmax, varNumY, varExtYmin, varExtYmax, varNumPrfSizes, varPrfStdMin, varPrfStdMax, varPar): """Create neural model time courses from pixel-wise boxcar functions. Parameters ---------...
How would you code a function in Python 3 to create neural time courses from pixel - wise boxcar functions.
You are a Python code analyst, evaluating scripts for potential improvements.
def cnvlPwBoxCarFn(aryNrlTc, varNumVol, varTr, tplPngSize, varNumMtDrctn, switchHrfSet, lgcOldSchoolHrf, varPar,): """Create 2D Gaussian kernel. Parameters ---------- aryNrlTc : 5d numpy array, shape [n_x_pos, n_y_pos, n_sd, n_mtn_dir, n_vol] Description of input 1. varNu...
Implement a function in Python 3 to create 2D Gaussian kernel. Parameters ---------- aryNrlTc : 5d numpy array, shape [n_x_pos, n_y_pos, n_sd, n_mtn_dir, n_vol] Description of input 1. varNumVol : float, positive Description of input 2. varTr : float, positive Description of input 1. tplPngSize : tuple Description of i...
You are a Python code analyst, evaluating scripts for potential improvements.
Resample pixel - time courses in high - res visual space.
Can you tell what is the following Python 3 function doing def rsmplInHighRes(aryBoxCarConv, tplPngSize, tplVslSpcHighSze, varNumMtDrctn, varNumVol): """Resample pixel-time courses in high-res visual space. Parameters ---------- ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_arg_parse(): """Parses the Command Line Arguments using argparse.""" # Create parser object: objParser = argparse.ArgumentParser() # Add argument to namespace -strCsvPrf results file path: objParser.add_argument('-strCsvPrf', required=True, metavar='/path/to/my_pr...
Create a Python 3 function to parse the Command Line Arguments using argparse.
You are a Python code analyst, evaluating scripts for potential improvements.
Decorator that ensures that the user is logged in and authorized to execute requests Except if the method is in authorized_methods of the auth_collection SARL
Make a summary of the following Python 3 code def login_required(wrapped): @wraps(wrapped) def wrapper(*args, **kwargs): request = args[1] auth_collection = settings.AUTH_COLLECTION[ settings.AUTH_COLLECTION.rfind('.') + 1: ].lower() auth_document = request.environ.g...
As a python code expert, you are capable of creating scripts from specifications.
Tries to atomically create the requested file.
Can you generate a brief explanation for the following Python 3 code def _doAtomicFileCreation(filePath): try: _os.close(_os.open(filePath, _os.O_CREAT | _os.O_EXCL)) return True except OSError as e: if e.errno == _errno.EEXIST: return False else: raise e
You are a Python code generator, capable of creating scripts from specifications.
def findNextFile(folder='.', prefix=None, suffix=None, fnameGen=None, base=0, maxattempts=10): """Finds the next available file-name in a sequence. This function will create a file of zero size and will return the path to ...
Write a Python 3 script to find the next available file-name in a sequence. This function will create a file of zero size and will return the path to it to the caller. No files which exist will be altered in this operation and concurrent executions of this function will return separate files. In case of conflict, the f...
As a Python code analyst, you investigate and solve complex coding mysteries
def _run(passedArgs=None, stderr=None, stdout=None, exitFn=None): """Executes the script, gets prefix/suffix from the command prompt and produces output on STDOUT. For help with command line options, invoke script with '--help'. """ description = """Finds the next available file-name in a sequence....
Can you write a function in Python 3 where it executes the command line script and returns the path of the next available file in the sequence.
As a python code expert, you are capable of creating scripts from specifications.
def _errstr(value): """Returns the value str, truncated to MAX_ERROR_STR_LEN characters. If it's truncated, the returned value will have '...' on the end. """ value = str(value) # We won't make the caller convert value to a string each time. if len(value) > MAX_ERROR_STR_LEN: return value[:...
Can you create a Python 3 function that returns the value str truncated to MAX_ERROR_STR_LEN characters. If the value is truncated it will be truncated to MAX_ERROR_STR_LEN characters. If the value is truncated it will be appended to the end.
As a Python code composer, you craft elegant and concise scripts.
Like the strip method except the strip argument describes different behavior.
Can you generate the documentation for the following Python 3 function def _getStrippedValue(value, strip): if strip is None: value = value.strip() # Call strip() with no arguments to strip whitespace. elif isinstance(strip, str): value = value.strip(strip) # Call strip(), passing the strip argu...
As a Python code translator, you convert algorithms and pseudocode into Python.
Raise ValidationException with standardExcMsg unless customExcMsg is specified.
Given the following Python 3 function, write the documentation def _raiseValidationException(standardExcMsg, customExcMsg=None): if customExcMsg is None: raise ValidationException(str(standardExcMsg)) else: raise ValidationException(str(customExcMsg))
You are a Python code architect, reviewing and designing scalable and efficient code
Internal function to perform the prevalidation check of the value passed for the parameter.
Here you have a function in Python 3, explain what it does def _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg=None): # TODO - add a allowlistFirst and blocklistFirst to determine which is checked first. (Right now it's allowlist) value = str(value) # Optionally strip ...
As a Python code composer, you craft elegant and concise scripts.
def _validateGenericParameters(blank, strip, allowlistRegexes, blocklistRegexes): """Returns None if the blank, strip, and blocklistRegexes parameters are valid of PySimpleValidate's validation functions have. Raises a PySimpleValidateException if any of the arguments are invalid.""" # Check blank para...
How would you implement a function in Python 3 that checks that the input parameters are valid for the current base class. Returns None if the input parameters are invalid. Raises a PySimpleValidateException if any of the arguments are invalid.
As a Python code analyst, you investigate and solve complex coding mysteries
def _validateParamsFor_validateNum(min=None, max=None, lessThan=None, greaterThan=None): """Raises an exception if the arguments are invalid. This is called by the validateNum(), validateInt(), and validateFloat() functions to check its arguments. This code was refactored out to a separate function so t...
Can you implement a function in Python 3 that raises an exception if the arguments are invalid.
You are a Python code analyst, evaluating scripts for potential improvements.
def validateStr(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None): """Raises ValidationException if value is not a string. This function is identical to the built-in input() function, but also offers the PySimpleValidate features of not allowing blank values by defau...
How would you implement a function in Python 3 that raises ValidationException if value is not a string.
You are a Python code architect, reviewing and designing scalable and efficient code
def validateNum(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, _numType='num', min=None, max=None, lessThan=None, greaterThan=None, excMsg=None): """Raises ValidationException if value is not a float or int. Returns value, so it can be used inline in an expression...
How would you code a function in Python 3 to raise ValidationException if value is not a number or int.
You are a Python code analyst, evaluating scripts for potential improvements.
def validateInt(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, min=None, max=None, lessThan=None, greaterThan=None, excMsg=None): """Raises ValidationException if value is not a int. Returns value, so it can be used inline in an expression: print(2 + vali...
Write a Python 3 script for raising ValidationException if value is not an int.
As a Python code analyst, you investigate and solve complex coding mysteries
def _validateParamsFor_validateChoice(choices, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, numbered=False, lettered=False, caseSensitive=False, excMsg=None): """Raises PySimpleValidateException if the arguments are invalid. This is called by the validateChoice() fun...
Can you write a function in Python 3 where it raises PySimpleValidateException if the arguments are invalid.
As a Python code analyst, you investigate and solve complex coding mysteries
def validateChoice(value, choices, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, numbered=False, lettered=False, caseSensitive=False, excMsg=None): """Raises ValidationException if value is not one of the values in choices. Returns the selected choice. Returns th...
Create a Python 3 function for raising ValidationException if value is not one of the values in choices. Returns the selected choice.
As a Python code analyst, you investigate and solve complex coding mysteries
Raises PySimpleValidateException if the arguments are invalid.
Can you generate the documentation for the following Python 3 function def _validateParamsFor__validateToDateTimeFormat(formats, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None): _validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegex...
As a python code expert, you are capable of creating scripts from specifications.
def validateTime(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, formats=('%H:%M:%S', '%H:%M', '%X'), excMsg=None): """Raises ValidationException if value is not a time formatted in one of the formats formats. Returns a datetime.time object of value. * value (...
Create a Python 3 function for raising ValidationException if value is not a time formatted in one of the formats formats. Returns a datetime. time object of value.
As a Python code composer, you craft elegant and concise scripts.
def validateDate(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, formats=('%Y/%m/%d', '%y/%m/%d', '%m/%d/%Y', '%m/%d/%y', '%x'), excMsg=None): """Raises ValidationException if value is not a time formatted in one of the formats formats. Returns a datetime.date obje...
Create a Python 3 function to raise ValidationException if value is not a time formatted in one of the formats formats. Returns a datetime. date object of value.
You are a Python code architect, reviewing and designing scalable and efficient code
Raises ValidationException if value is not a datetime formatted in one of the formats formats. Returns a datetime. datetime object of the datetime formatted in one .
How would you explain what the following Python 3 function does def validateDatetime(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, formats=('%Y/%m/%d %H:%M:%S', '%y/%m/%d %H:%M:%S', '%m/%d/%Y %H:%M:%S', '%m/%d/%y %H:%M:%S', '%x %H:%M:%S', ...
You are a Python code generator, capable of creating scripts from specifications.
Raises ValidationException if value is not a valid filename.
Can you generate the documentation for the following Python 3 function def validateFilename(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None): returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg) if returnNow: r...
You are a Python code generator, capable of creating scripts from specifications.
Raises ValidationException if value is not a valid file path. Returns the value argument.
Explain what the following Python 3 code does def validateFilepath(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None, mustExist=False): returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg) if returnNow: return val...
You are a Python code analyst, evaluating scripts for potential improvements.
Raises ValidationException if value is not an IPv4 or IPv6 address.
Can you generate the documentation for the following Python 3 function def validateIP(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None): # Validate parameters. _validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blockl...
You are a Python code generator, capable of creating scripts from specifications.
def validateRegex(value, regex, flags=0, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None): """Raises ValidationException if value does not match the regular expression in regex. Returns the value argument. This is similar to calling inputStr() and using the allowlistRegex...
Can you write a function in Python 3 where it raises ValidationException if value does not match the regular expression in regex.
You are a Python code analyst, evaluating scripts for potential improvements.
Raises ValidationException if value can t be used as a regular expression string. Returns the value argument as a regex object.
Here you have a function in Python 3, explain what it does def validateRegexStr(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None): # TODO - I'd be nice to check regexes in other languages, i.e. JS and Perl. _validateGenericParameters(blank=blank, strip=strip, allowlistR...
As a python code expert, you are capable of creating scripts from specifications.
Raises ValidationException if value is not a URL.
Can you generate a brief explanation for the following Python 3 code def validateURL(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None): # Reuse the logic in validateRegex() try: result = validateRegex(value=value, regex=URL_REGEX, blank=blank, strip=strip, allow...
As a python code expert, you are capable of creating scripts from specifications.
Raises ValidationException if value is not an email address. Returns the value argument.
Can you generate the documentation for the following Python 3 function def validateEmail(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None): # Reuse the logic in validateRegex() try: result = validateRegex(value=value, regex=EMAIL_REGEX, blank=blank, strip=strip,...
You are a Python code analyst, evaluating scripts for potential improvements.
def validateYesNo(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, yesVal='yes', noVal='no', caseSensitive=False, excMsg=None): """Raises ValidationException if value is not a yes or no response. Returns the yesVal or noVal argument, not value. Note that value can be any case (...
Write a Python 3 function for raising ValidationException if value is not a yes or no response.
As a python code expert, you are capable of creating scripts from specifications.
def validateBool(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, trueVal='True', falseVal='False', caseSensitive=False, excMsg=None): """Raises ValidationException if value is not an email address. Returns the yesVal or noVal argument, not value. * value (str): The value being...
Write a Python 3 script to raise ValidationException if value is not an email address. Returns the yesVal or noVal argument.
You are a Python code analyst, evaluating scripts for potential improvements.
Raises ValidationException if value is not a USA state. Returns the capitalized state abbreviation unless returnStateName is True Returns the titlecased state name.
Can you generate the documentation for the following Python 3 function def validateState(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None, returnStateName=False): # TODO - note that this is USA-centric. I should work on trying to make this more international. # Validat...
As a Python code composer, you craft elegant and concise scripts.
def validateMonth(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, monthNames=ENGLISH_MONTHS, excMsg=None): """Raises ValidationException if value is not a month, like 'Jan' or 'March'. Returns the titlecased month. * value (str): The value being validated as an email address. ...
Write a Python 3 function that can raise ValidationException if value is not a month. Returns the titlecased month name.
As a python code expert, you are capable of creating scripts from specifications.
def validateDayOfWeek(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, dayNames=ENGLISH_DAYS_OF_WEEK, excMsg=None): """Raises ValidationException if value is not a day of the week, such as 'Mon' or 'Friday'. Returns the titlecased day of the week. * value (str): The value being...
Write a Python 3 function that can raise ValidationException if value is not a day of the week such as Mon or Friday. Returns the titlecased day of the week.
You are a Python code architect, reviewing and designing scalable and efficient code
Raises ValidationException if value is not a day of the month from the given year month.
Can you generate a brief explanation for the following Python 3 code def validateDayOfMonth(value, year, month, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None): try: daysInMonth = calendar.monthrange(year, month)[1] except: raise PySimpleValidateException('inv...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns an appropriate logging level integer from a string name
Explain what the following Python 3 code does def get_level(level_string): levels = {'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL} try: level = levels[level_string.lower()] except KeyError: ...
You are a Python code analyst, evaluating scripts for potential improvements.
def config_logging(no_log_file, log_to, log_level, silent, verbosity): """ Configures and generates a Logger object, 'openaccess_epub' based on common parameters used for console interface script execution in OpenAccess_EPUB. These parameters are: no_log_file Boolean. Disables logging t...
Write a Python 3 function for configuring the logging system.
As a Python code translator, you convert algorithms and pseudocode into Python.
Remap x y sigma parameters from pixel to degree.
Can you tell what is the following Python 3 function doing def rmp_pixel_deg_xys(vecX, vecY, vecPrfSd, tplPngSize, varExtXmin, varExtXmax, varExtYmin, varExtYmax): """Remap x, y, sigma parameters from pixel to degree. Parameters ---------- vecX : 1D numpy array Array with ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def crt_mdl_prms(tplPngSize, varNum1, varExtXmin, varExtXmax, varNum2, varExtYmin, varExtYmax, varNumPrfSizes, varPrfStdMin, varPrfStdMax, kwUnt='pix', kwCrd='crt'): """Create an array with all possible model parameter combinations Parameters ---------- tplPngSize : t...
Write a Python 3 script to create an array with all possible model parameter combinations for a given set of pRF models.
You are a Python code architect, reviewing and designing scalable and efficient code
def crt_mdl_rsp(arySptExpInf, tplPngSize, aryMdlParams, varPar, strCrd='crt', lgcPrint=True): """Create responses of 2D Gauss models to spatial conditions. Parameters ---------- arySptExpInf : 3d numpy array, shape [n_x_pix, n_y_pix, n_conditions] All spatial conditions stacked ...
Write a Python 3 script for creating 2D Gauss models to spatial conditions.
You are a Python code analyst, evaluating scripts for potential improvements.
This function creates a neural time courses in a temporary space that is compatible with the neural time courses provided by the user.
Given the following Python 3 function, write the documentation def crt_nrl_tc(aryMdlRsp, aryCnd, aryOns, aryDrt, varTr, varNumVol, varTmpOvsmpl, lgcPrint=True): """Create temporally upsampled neural time courses. Parameters ---------- aryMdlRsp : 2d numpy array, shape [n_x_pos * n_y_pos ...
As a python code expert, you are capable of creating scripts from specifications.
def crt_prf_ftr_tc(aryMdlRsp, aryTmpExpInf, varNumVol, varTr, varTmpOvsmpl, switchHrfSet, tplPngSize, varPar, dctPrm=None, lgcPrint=True): """Create all spatial x feature prf time courses. Parameters ---------- aryMdlRsp : 2d numpy array, shape [n_x_pos * n_y_pos *...
Can you write a function in Python 3 where it creates all spatial x feature prf time courses for a given set of features.
You are a Python code analyst, evaluating scripts for potential improvements.
Find unique rows in 2D array.
Can you generate a brief explanation for the following Python 3 code def fnd_unq_rws(A, return_index=False, return_inverse=False): A = np.require(A, requirements='C') assert A.ndim == 2, "array must be 2-dim'l" B = np.unique(A.view([('', A.dtype)]*A.shape[1]), return_index=return_index, ...
As a Python code analyst, you investigate and solve complex coding mysteries
Make a request against air - matters. com.
Explain what the following Python 3 code does async def _request( self, method: str, endpoint: str, *, headers: dict = None) -> dict: """Make a request against air-matters.com.""" url = '{0}/{1}'.format(API_URL_SCAFFOLD, endpoint) if not headers: headers = {} hea...
As a Python code composer, you craft elegant and concise scripts.
This filter handles the response and transforms it to a Response instance.
Make a summary of the following Python 3 code def filter_transform_response(get_response, params): async def decorated_filter(request, *args, **kwargs): response = await get_response(request, *args, **kwargs) if isinstance(response, HTTPResponse) and \ not isinstance(response, Resp...
As a Python code translator, you convert algorithms and pseudocode into Python.
async def _raw_user_report_data(self) -> list: """Return user report data (if accompanied by latitude/longitude).""" data = await self._request('get', 'map/markers') return [ location for location in data if location['latitude'] and location['longitude'] ]
Implement a Python 3 function for returning user report data.
As a Python code analyst, you investigate and solve complex coding mysteries
async def _raw_state_data(self) -> list: """Return a list of states.""" data = await self._request('get', 'states') return [ location for location in data if location['name'] != 'United States' ]
Write a Python 3 function that can return a list of states.
As a Python code composer, you craft elegant and concise scripts.
async def nearest_by_coordinates( self, latitude: float, longitude: float) -> dict: """Get the nearest report (with local and state info) to a lat/lon.""" # Since user data is more granular than state or CDC data, find the # user report whose coordinates are closest to the provided ...
Write a Python 3 script for getting the nearest report to a lat / lon.
You are a Python code architect, reviewing and designing scalable and efficient code
initialize the internal state of the object
Can you generate the documentation for the following Python 3 function def initialize(self, maxsize, history=None): '''size specifies the maximum amount of history to keep''' super().__init__() self.maxsize = int(maxsize) self.history = deque(maxlen=self.maxsize) # Preserves order hist...
As a python code expert, you are capable of creating scripts from specifications.
Adds a new key - value pair. Returns any discarded values.
Given the following Python 3 function, write the documentation def insert(self, key, value): '''Adds a new key-value pair. Returns any discarded values.''' # Add to history and catch expectorate if len(self.history) == self.maxsize: expectorate = self.history[0] else: ...
You are a Python code analyst, evaluating scripts for potential improvements.
def up_to(self, key): '''Gets the recently inserted values up to a key''' for okey, ovalue in reversed(self.history): if okey == key: break else: yield ovalue
Write a Python 3 script for getting the recently inserted values up to a key
As a Python code translator, you convert algorithms and pseudocode into Python.
Decorator to add a resource route to the routing list.
How would you explain what the following Python 3 function does def resource(self, uri, methods=frozenset({'GET'}), **kwargs): def decorator(f): if kwargs.get('stream'): f.is_stream = kwargs['stream'] self.add_resource(f, uri=uri, methods=methods, **kwargs) retur...
As a Python code composer, you craft elegant and concise scripts.
def add_resource(self, handler, uri, methods=frozenset({'GET'}), **kwargs): """ Register a resource route. :param handler: function or class instance :param uri: path of the URL :param methods: list or tuple of methods allowed :param host: :p...
Can you implement a function in Python 3 that registers a resource route.
As a Python code translator, you convert algorithms and pseudocode into Python.
This method checks the revert status of a revision.
How would you explain what the following Python 3 function does def check(session, rev_id, page_id=None, radius=defaults.RADIUS, before=None, window=None, rvprop=None): """ Checks the revert status of a revision. With this method, you can determine whether an edit is a 'reverting' edit, was 'reve...
You are a Python code architect, reviewing and designing scalable and efficient code
def check_deleted(session, rev_id, title=None, timestamp=None, radius=defaults.RADIUS, before=None, window=None, rvprop=None): """ Checks the revert status of a deleted revision. With this method, you can determine whether an edit is a 'reverting' edit, was 'reverted' by...
Implement a Python 3 function for checking the revert status of a deleted revision.
You are a Python code architect, reviewing and designing scalable and efficient code
Find all commits between two commit SHAs.
Explain what the following Python 3 code does def get_commits(repo_dir, old_commit, new_commit, hide_merges=True): repo = Repo(repo_dir) commits = repo.iter_commits(rev="{0}..{1}".format(old_commit, new_commit)) if hide_merges: return [x for x in commits if not x.summary.startswith("Merge ")] el...
As a Python code composer, you craft elegant and concise scripts.
Determine URL to view commits for repo.
Can you tell what is the following Python 3 function doing def get_commit_url(repo_url): if "github.com" in repo_url: return repo_url[:-4] if repo_url.endswith(".git") else repo_url if "git.openstack.org" in repo_url: uri = '/'.join(repo_url.split('/')[-2:]) return "https://github.com/{0...
You are a Python code analyst, evaluating scripts for potential improvements.
Get all projects from multiple YAML files.
How would you explain what the following Python 3 function does def get_projects(osa_repo_dir, commit): # Check out the correct commit SHA from the repository repo = Repo(osa_repo_dir) checkout(repo, commit) yaml_files = glob.glob( '{0}/playbooks/defaults/repo_packages/*.yml'.format(osa_repo_di...
As a python code expert, you are capable of creating scripts from specifications.
def get_roles(osa_repo_dir, commit, role_requirements): """Read OSA role information at a particular commit.""" repo = Repo(osa_repo_dir) checkout(repo, commit) log.info("Looking for file {f} in repo {r}".format(r=osa_repo_dir, f=role_requirements...
Can you implement a function in Python 3 that reads OSA role information at a particular commit.
You are a Python code analyst, evaluating scripts for potential improvements.
def make_osa_report(repo_dir, old_commit, new_commit, args): """Create initial RST report header for OpenStack-Ansible.""" update_repo(repo_dir, args.osa_repo_url, args.update) # Are these commits valid? validate_commits(repo_dir, [old_commit, new_commit]) # Do we have a valid ...
Write a Python 3 function that can create an OAI - OSS report header for OpenStack - Ansible.
You are a Python code architect, reviewing and designing scalable and efficient code
Create a RST report from a list of projects and roles.
Can you generate the documentation for the following Python 3 function def make_report(storage_directory, old_pins, new_pins, do_update=False, version_mappings=None): """Create RST report from a list of projects/roles.""" report = "" version_mappings = version_mappings or {} for new_pin ...
You are a Python code generator, capable of creating scripts from specifications.
Normalize the YAML from project and role lookups.
Given the following Python 3 function, write the documentation def normalize_yaml(yaml): if isinstance(yaml, list): # Normalize the roles YAML data normalized_yaml = [(x['name'], x['src'], x.get('version', 'HEAD')) for x in yaml] else: # Extract the project nam...
As a Python code analyst, you investigate and solve complex coding mysteries