output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def validate_bool_maybe_none(b): 'Convert b to a boolean or raise' if isinstance(b, six.string_types): b = b.lower() if b is None or b == 'none': return None return validate_bool(b)
Write a Python 3 script for converting b to a boolean or raise
As a Python code composer, you craft elegant and concise scripts.
def validate_bool(b): """Convert b to a boolean or raise""" if isinstance(b, six.string_types): b = b.lower() if b in ('t', 'y', 'yes', 'on', 'true', '1', 1, True): return True elif b in ('f', 'n', 'no', 'off', 'false', '0', 0, False): return False else: raise ValueEr...
Implement a Python 3 function for converting a string to a boolean or raise a ValueError
As a Python code translator, you convert algorithms and pseudocode into Python.
Validate a string s is a valid .
Can you generate the documentation for the following Python 3 function def validate_str(s): if not isinstance(s, six.string_types): raise ValueError("Did not found string!") return six.text_type(s)
As a Python code translator, you convert algorithms and pseudocode into Python.
Validate a list of strings containing a single element.
Here you have a function in Python 3, explain what it does def validate_stringlist(s): if isinstance(s, six.string_types): return [six.text_type(v.strip()) for v in s.split(',') if v.strip()] else: try: return list(map(validate_str, s)) except TypeError as e: rais...
As a Python code analyst, you investigate and solve complex coding mysteries
def add_base_str(self, base_str, pattern='.+', pattern_base=None, append=True): """ Add further base string to this instance Parameters ---------- base_str: str or list of str Strings that are used as to look for keys to get and set keys in ...
Write a Python 3 script for adding further base string to the instance of the n - tuple.
You are a Python code generator, capable of creating scripts from specifications.
Connect a function to the given formatoption
Here you have a function in Python 3, explain what it does def connect(self, key, func): key = self._get_depreceated(key)[0] if key is not None: self._connections[key].append(func)
You are a Python code architect, reviewing and designing scalable and efficient code
def disconnect(self, key=None, func=None): """Disconnect the connections to the an rcParams key Parameters ---------- key: str The rcParams key. If None, all keys are used func: function The function that is connected. If None, all functions are ...
Implement a function in Python 3 to disconnect the connections to the rcParams key.
You are a Python code analyst, evaluating scripts for potential improvements.
Update the internal state of the object with the default parameters.
Can you generate a brief explanation for the following Python 3 code def update_from_defaultParams(self, defaultParams=None, plotters=True): """Update from the a dictionary like the :attr:`defaultParams` Parameters ---------- defaultParams: dict ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Return sorted list of keys.
How would you explain what the following Python 3 function does def keys(self): k = list(dict.keys(self)) k.sort() return k
As a Python code composer, you craft elegant and concise scripts.
def find_all(self, pattern): """ Return the subset of this RcParams dictionary whose keys match, using :func:`re.search`, the given ``pattern``. Parameters ---------- pattern: str pattern as suitable for re.compile Returns ------- RcP...
Implement a function in Python 3 to return a subset of this RcParams dictionary whose keys match pattern Return the subset of this RcParams instance with entries that match pattern
You are a Python code generator, capable of creating scripts from specifications.
Update rcParams from user - defined settings
Can you tell what is the following Python 3 function doing def load_from_file(self, fname=None): fname = fname or psyplot_fname() if fname and os.path.exists(fname): with open(fname) as f: d = yaml.load(f) self.update(d) if (d.get('project.plot...
You are a Python code generator, capable of creating scripts from specifications.
Dump this instance to a yaml file.
How would you explain what the following Python 3 function does def dump(self, fname=None, overwrite=True, include_keys=None, exclude_keys=['project.plotters'], include_descriptions=True, **kwargs): """Dump this instance to a yaml file Parameters ---------- fna...
You are a Python code architect, reviewing and designing scalable and efficient code
Load the psyplot plugins and return the entry points for the psyplot plugin module
Here you have a function in Python 3, explain what it does def _load_plugin_entrypoints(self): from pkg_resources import iter_entry_points def load_plugin(ep): if plugins_env == ['no']: return False elif ep.module_name in exclude_plugins: return F...
As a python code expert, you are capable of creating scripts from specifications.
def load_plugins(self, raise_error=False): """ Load the plotters and defaultParams from the plugins This method loads the `plotters` attribute and `defaultParams` attribute from the plugins that use the entry point specified by `group`. Entry points must be objects (or modules) ...
Write a Python 3 script for loading the plotters and defaultParams from the plugins that use the entry point specified by the group.
You are a Python code generator, capable of creating scripts from specifications.
Assemble the middleware pipeline
Given the following Python 3 function, write the documentation def deploy(project_name): request_log = requestlog.RequestLog header_addon = HeaderControl fault_wrapper = FaultWrapper application = handler.SdkHandler() # currently we have 3 middleware for middleware in (header_addon, ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Power on z / VM instance.
Can you tell what is the following Python 3 function doing def guest_start(self, userid): LOG.info("Begin to power on vm %s", userid) self._smtclient.guest_start(userid) LOG.info("Complete power on vm %s", userid)
You are a Python code generator, capable of creating scripts from specifications.
Reboot a guest vm.
How would you explain what the following Python 3 function does def guest_reboot(self, userid): LOG.info("Begin to reboot vm %s", userid) self._smtclient.guest_reboot(userid) LOG.info("Complete reboot vm %s", userid)
You are a Python code analyst, evaluating scripts for potential improvements.
Reset z / VM instance.
Can you tell what is the following Python 3 function doing def guest_reset(self, userid): LOG.info("Begin to reset vm %s", userid) self._smtclient.guest_reset(userid) LOG.info("Complete reset vm %s", userid)
As a Python code analyst, you investigate and solve complex coding mysteries
Move an eligible running z/VM system to another z/VM system within an SSI cluster.
Can you tell what is the following Python 3 function doing def live_migrate_vm(self, userid, destination, parms, action): # Check guest state is 'on' state = self.get_power_state(userid) if state != 'on': LOG.error("Failed to live migrate guest %s, error: " "guest...
As a Python code analyst, you investigate and solve complex coding mysteries
def create_vm(self, userid, cpu, memory, disk_list, user_profile, max_cpu, max_mem, ipl_from, ipl_param, ipl_loadparam): """Create z/VM userid into user directory for a z/VM instance.""" LOG.info("Creating the user directory for vm %s", userid) info = self._s...
How would you implement a function in Python 3 that creates z / VM userid into user directory.
You are a Python code analyst, evaluating scripts for potential improvements.
def delete_vm(self, userid): """Delete z/VM userid for the instance.""" LOG.info("Begin to delete vm %s", userid) self._smtclient.delete_vm(userid) # remove userid from smapi namelist self._smtclient.namelist_remove(self._namelist, userid) LOG.info("Complete delete vm %s...
Create a Python 3 function to delete z / VM userid for the instance.
You are a Python code analyst, evaluating scripts for potential improvements.
def execute_cmd(self, userid, cmdStr): """Execute commands on the guest vm.""" LOG.debug("executing cmd: %s", cmdStr) return self._smtclient.execute_cmd(userid, cmdStr)
Write a Python 3 function for executing a command on the guest vm.
As a Python code composer, you craft elegant and concise scripts.
Punch a script that used to set the hostname of the guest.
Here you have a function in Python 3, explain what it does def set_hostname(self, userid, hostname, os_version): tmp_path = self._pathutils.get_guest_temp_path(userid) if not os.path.exists(tmp_path): os.makedirs(tmp_path) tmp_file = tmp_path + '/hostname.sh' lnxdist = self....
As a python code expert, you are capable of creating scripts from specifications.
Convert a disk storage value to a number of blocks.
Can you tell what is the following Python 3 function doing def cvtToBlocks(rh, diskSize): rh.printSysLog("Enter generalUtils.cvtToBlocks") blocks = 0 results = {'overallRC': 0, 'rc': 0, 'rs': 0, 'errno': 0} blocks = diskSize.strip().upper() lastChar = blocks[-1] if lastChar == 'G' or lastChar ...
As a python code expert, you are capable of creating scripts from specifications.
def cvtToMag(rh, size): """ Convert a size value to a number with a magnitude appended. Input: Request Handle Size bytes Output: Converted value with a magnitude """ rh.printSysLog("Enter generalUtils.cvtToMag") mSize = '' size = size / (1024 * 1024) if size...
Implement a Python 3 function for converting a size value to a number with a magnitude appended.
You are a Python code analyst, evaluating scripts for potential improvements.
This function converts a size value from page to a number with a magnitude appended.
Here you have a function in Python 3, explain what it does def getSizeFromPage(rh, page): rh.printSysLog("Enter generalUtils.getSizeFromPage") bSize = float(page) * 4096 mSize = cvtToMag(rh, bSize) rh.printSysLog("Exit generalUtils.getSizeFromPage, magSize: " + mSize) return mSize
As a python code expert, you are capable of creating scripts from specifications.
Parse the command line and return the appropriate response code.
How would you explain what the following Python 3 function does def parseCmdline(rh, posOpsList, keyOpsList): rh.printSysLog("Enter generalUtils.parseCmdline") # Handle any positional operands on the line. if rh.results['overallRC'] == 0 and rh.subfunction in posOpsList: ops = posOpsList[rh.subfun...
You are a Python code architect, reviewing and designing scalable and efficient code
def default_52xhandler(response, resource, url, params): """ Default 52x handler that loops every second until a non 52x response is received. :param response: The response of the last executed api request. :param resource: The resource of the last executed api request. :param url: The url of the la...
Can you create a Python 3 function that defaults 52x handler that loops every second until a response is received.
As a Python code analyst, you investigate and solve complex coding mysteries
def validate(self): """ Perform validation check on properties. """ if not self.api_token or not self.api_token_secret: raise ImproperlyConfigured("'api_token' and 'api_token_secret' are required for authentication.") if self.response_type not in ["json", "pson", "xm...
Implement a Python 3 function for performing validation on properties.
You are a Python code generator, capable of creating scripts from specifications.
Executes a call to the API.
Can you tell what is the following Python 3 function doing def execute(self, url, params): response = requests.get(url, params=params, **self.config.requests_kwargs) if 520 <= response.status_code < 530: if self.config.handler52x: return self.config.handler52x(response, self...
You are a Python code generator, capable of creating scripts from specifications.
def _create_invokeScript(self, network_file_path, commands, files_map): """invokeScript: Configure zLinux os network invokeScript is included in the network.doscript, it is used to put the network configuration file to the directory where it belongs and call...
How would you implement a function in Python 3 that creates the invokeScript shell for the current network.
As a python code expert, you are capable of creating scripts from specifications.
Create the network. doscript file in the folder specified by network_file_path.
Here you have a function in Python 3, explain what it does def _create_network_doscript(self, network_file_path): # Generate the tar package for punch LOG.debug('Creating network doscript in the folder %s' % network_file_path) network_doscript = os.path.join(network_file_path, ...
You are a Python code generator, capable of creating scripts from specifications.
Salsa 20 / 8 algorithm.
Given the following Python 3 function, write the documentation def salsa20_8(B, x, src, s_start, dest, d_start): # Merged blockxor for speed for i in xrange(16): x[i] = B[i] = B[i] ^ src[s_start + i] # This is the actual Salsa 20/8: four identical double rounds for i in xrange(4): R(x,...
As a Python code composer, you craft elegant and concise scripts.
Returns an iterator to a file - like object that yields fixed size chunks of the file - like object that yields fixed size chunks of the file - like object.
Explain what the following Python 3 code does def fileChunkIter(file_object, file_chunk_size=65536): while True: chunk = file_object.read(file_chunk_size) if chunk: yield chunk else: break
You are a Python code architect, reviewing and designing scalable and efficient code
def scrypt(password, salt, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p, olen=64): """Returns a key derived using the scrypt key-derivarion function N must be a power of two larger than 1 but no larger than 2 ** 63 (insane) r and p must be positive numbers such that r * p < 2 ** 30 The default values are: N...
Can you create a Python 3 function that returns a key derived using the scrypt key - derivarion function.
You are a Python code architect, reviewing and designing scalable and efficient code
def scrypt_mcf(password, salt=None, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p, prefix=SCRYPT_MCF_PREFIX_DEFAULT): """Derives a Modular Crypt Format hash using the scrypt KDF Parameter space is smaller than for scrypt(): N must be a power of two larger than 1 but no larger than 2 ** 31 r and p m...
Write a Python 3 function for deriving a Modular Crypt Format hash using the scrypt function.
As a Python code translator, you convert algorithms and pseudocode into Python.
def scrypt_mcf_check(mcf, password): """Returns True if the password matches the given MCF hash""" if not isinstance(mcf, bytes): raise TypeError('MCF must be a byte string') if isinstance(password, unicode): password = password.encode('utf8') elif not isinstance(password, bytes): ...
Implement a Python 3 function for returning True if the password matches the given MCF hash
As a Python code analyst, you investigate and solve complex coding mysteries
Turns. obj face index string line into [ verts texcoords normals ] numeric tuples.
How would you explain what the following Python 3 function does def parse_mixed_delim_str(line): arrs = [[], [], []] for group in line.split(' '): for col, coord in enumerate(group.split('/')): if coord: arrs[col].append(int(coord)) return [tuple(arr) for arr in arrs]
As a Python code composer, you craft elegant and concise scripts.
Takes. obj filename and returns dict of object properties for each object in file.
Can you generate the documentation for the following Python 3 function def read_objfile(fname): verts = defaultdict(list) obj_props = [] with open(fname) as f: lines = f.read().splitlines() for line in lines: if line: split_line = line.strip().split(' ', 1) if le...
As a Python code analyst, you investigate and solve complex coding mysteries
Reads a wavefront file and returns a dictionary along with their material dictionary.
Can you tell what is the following Python 3 function doing def read_wavefront(fname_obj): fname_mtl = '' geoms = read_objfile(fname_obj) for line in open(fname_obj): if line: split_line = line.strip().split(' ', 1) if len(split_line) < 2: continue ...
You are a Python code architect, reviewing and designing scalable and efficient code
def disableEnableDisk(rh, userid, vaddr, option): """ Disable or enable a disk. Input: Request Handle: owning userid virtual address option ('-e': enable, '-d': disable) Output: Dictionary containing the following: overallRC - overall return code, ...
Can you write a function in Python 3 where it disables or enable a disk.
As a Python code analyst, you investigate and solve complex coding mysteries
This routine sends a command to a virtual machine using IUCV.
Make a summary of the following Python 3 code def execCmdThruIUCV(rh, userid, strCmd, hideInLog=[]): if len(hideInLog) == 0: rh.printSysLog("Enter vmUtils.execCmdThruIUCV, userid: " + userid + " cmd: " + strCmd) else: logCmd = strCmd.split(' ') for i in hideInLog: ...
As a Python code analyst, you investigate and solve complex coding mysteries
def getPerfInfo(rh, useridlist): """ Get the performance information for a userid Input: Request Handle Userid to query <- may change this to a list later. Output: Dictionary containing the following: overallRC - overall return code, 0: success, non-zero: failure ...
Create a Python 3 function to get the performance information for a userid Input: Request Handle Userid to query <- may change this to a list later. Output: Dictionary containing the following: overallRC - overall return code, 0: success, non-zero: failure rc - RC returned from SMCLI if overallRC = 0. rs - RS returned ...
You are a Python code analyst, evaluating scripts for potential improvements.
This function installs a filesystem on a virtual machine.
Here you have a function in Python 3, explain what it does def installFS(rh, vaddr, mode, fileSystem, diskType): rh.printSysLog("Enter vmUtils.installFS, userid: " + rh.userid + ", vaddr: " + str(vaddr) + ", mode: " + mode + ", file system: " + fileSystem + ", disk type: " + diskType) results ...
As a Python code composer, you craft elegant and concise scripts.
Invoke the SMCLI command and return the results.
Here you have a function in Python 3, explain what it does def invokeSMCLI(rh, api, parms, hideInLog=[]): if len(hideInLog) == 0: rh.printSysLog("Enter vmUtils.invokeSMCLI, userid: " + rh.userid + ", function: " + api + ", parms: " + str(parms)) else: ...
As a Python code composer, you craft elegant and concise scripts.
def isLoggedOn(rh, userid): """ Determine whether a virtual machine is logged on. Input: Request Handle: userid being queried Output: Dictionary containing the following: overallRC - overall return code, 0: success, non-zero: failure rc - 0: if we got...
How would you implement a function in Python 3 that returns a dictionary containing the contents of the virtual machine with the specified userid.
As a python code expert, you are capable of creating scripts from specifications.
Punch a file to a virtual reader of the specified virtual machine.
How would you explain what the following Python 3 function does def punch2reader(rh, userid, fileLoc, spoolClass): rh.printSysLog("Enter punch2reader.punchFile") results = {} # Setting rc to time out rc code as default and its changed during runtime results['rc'] = 9 # Punch to the current user i...
As a Python code translator, you convert algorithms and pseudocode into Python.
This function waits for the virtual OS to go into the desired state.
Can you generate the documentation for the following Python 3 function def waitForOSState(rh, userid, desiredState, maxQueries=90, sleepSecs=5): rh.printSysLog("Enter vmUtils.waitForOSState, userid: " + userid + " state: " + desiredState + " maxWait: " + str(ma...
You are a Python code architect, reviewing and designing scalable and efficient code
This function waits for the virtual machine to go into the desired state.
Given the following Python 3 function, write the documentation def waitForVMState(rh, userid, desiredState, maxQueries=90, sleepSecs=5): rh.printSysLog("Enter vmUtils.waitForVMState, userid: " + userid + " state: " + desiredState + " maxWait: " + str(maxQueries...
As a Python code translator, you convert algorithms and pseudocode into Python.
def match(self, context, line): """Match lines prefixed with a hash ("#") mark that don't look like text.""" stripped = line.stripped return stripped.startswith('#') and not stripped.startswith('#{')
Implement a function in Python 3 to match lines prefixed with a hash mark that don t look like text.
As a Python code translator, you convert algorithms and pseudocode into Python.
def flatten(input, file=None, encoding=None, errors='strict'): """Return a flattened representation of a cinje chunk stream. This has several modes of operation. If no `file` argument is given, output will be returned as a string. The type of string will be determined by the presence of an `encoding`; if one is g...
How would you code a function in Python 3 to return a flattened version of a cinje chunk stream.
As a python code expert, you are capable of creating scripts from specifications.
def fragment(string, name="anonymous", **context): """Translate a template fragment into a callable function. **Note:** Use of this function is discouraged everywhere except tests, as no caching is implemented at this time. Only one function may be declared, either manually, or automatically. If automatic defint...
How would you code a function in Python 3 to translate a template fragment into a callable function.
As a Python code composer, you craft elegant and concise scripts.
def iterate(obj): """Loop over an iterable and track progress, including first and last state. On each iteration yield an Iteration named tuple with the first and last flags, current element index, total iterable length (if possible to acquire), and value, in that order. for iteration in iterate(something): ...
Write a Python 3 function for iterating over an iterable and track progress.
You are a Python code generator, capable of creating scripts from specifications.
Yields a block of text into plain text and code sections.
Can you tell what is the following Python 3 function doing def chunk(line, mapping={None: 'text', '${': 'escape', '#{': 'bless', '&{': 'args', '%{': 'format', '@{': 'json'}): skipping = 0 # How many closing parenthesis will we need to skip? start = None # Starting position of current match. last = 0 i = 0 ...
You are a Python code generator, capable of creating scripts from specifications.
Prepare the ordered list of transformers and reset context state to initial.
Given the following Python 3 function, write the documentation def prepare(self): self.scope = 0 self.mapping = deque([0]) self._handler = [i() for i in sorted(self.handlers, key=lambda handler: handler.priority)]
As a Python code analyst, you investigate and solve complex coding mysteries
This method is used to generate a list of source code lines from the input lines.
Given the following Python 3 function, write the documentation def stream(self): if 'init' not in self.flag: root = True self.prepare() else: root = False # Track which lines were generated in response to which lines of source code. # The end result is that there is one entry here for every line ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def classify(self, line): """Identify the correct handler for a given line of input.""" for handler in self._handler: if handler.match(self, line): return handler
How would you code a function in Python 3 to identify the correct handler for a given line of input.
As a Python code composer, you craft elegant and concise scripts.
Encode the deltas to reduce entropy.
Can you generate a brief explanation for the following Python 3 code def red(numbers): line = 0 deltas = [] for value in numbers: deltas.append(value - line) line = value return b64encode(compress(b''.join(chr(i).encode('latin1') for i in deltas))).decode('latin1')
As a Python code analyst, you investigate and solve complex coding mysteries
def match(self, context, line): """Match code lines prefixed with a variety of keywords.""" return line.kind == 'code' and line.partitioned[0] in self._both
Write a Python 3 function that can match code lines prefixed with a variety of keywords.
As a python code expert, you are capable of creating scripts from specifications.
Returns the field object for the given field name.
Explain what the following Python 3 code does def _get_field_by_name(model_class, field_name): field = model_class._meta.get_field(field_name) return ( field, # field field.model, # model not field.auto_created or fiel...
You are a Python code architect, reviewing and designing scalable and efficient code
def _get_remote_field(field): """ Compatible with Django 1.8~1.10 ('related' was renamed to 'remote_field') """ if hasattr(field, 'remote_field'): return field.remote_field elif hasattr(field, 'related'): return field.related else: return None
How would you code a function in Python 3 to return the remote_field or related_field if it exists.
As a Python code composer, you craft elegant and concise scripts.
Returns a list of all the field names for the given model.
How would you explain what the following Python 3 function does def _get_all_field_names(model): return list(set(chain.from_iterable( (field.name, field.attname) if hasattr(field, 'attname') else (field.name,) for field in model._meta.get_fields() # For complete backwards compatibility, you ...
As a python code expert, you are capable of creating scripts from specifications.
def get_relation_fields_from_model(model_class): """ Get related fields (m2m, FK, and reverse FK) """ relation_fields = [] all_fields_names = _get_all_field_names(model_class) for field_name in all_fields_names: field, model, direct, m2m = _get_field_by_name(model_class, field_name) # ge...
Write a Python 3 function for getting related fields from a model class.
As a Python code composer, you craft elegant and concise scripts.
def get_direct_fields_from_model(model_class): """ Direct, not m2m, not FK """ direct_fields = [] all_fields_names = _get_all_field_names(model_class) for field_name in all_fields_names: field, model, direct, m2m = _get_field_by_name(model_class, field_name) if direct and not m2m and not...
Write a Python 3 function that can get the direct fields from a model class.
As a Python code analyst, you investigate and solve complex coding mysteries
def get_model_from_path_string(root_model, path): """ Return a model class for a related model root_model is the class of the initial model path is like foo__bar where bar is related to foo """ for path_section in path.split('__'): if path_section: try: field, mod...
Create a Python 3 function to return a model class for a related model based on a path string.
As a Python code composer, you craft elegant and concise scripts.
def get_fields(model_class, field_name='', path=''): """ Get fields and meta data from a model :param model_class: A django model class :param field_name: The field name to get sub fields from :param path: path of our field in format field_name__second_field_name__ect__ :returns: Returns fi...
How would you code a function in Python 3 to get fields and meta data from a django model class.
As a Python code translator, you convert algorithms and pseudocode into Python.
Get fields related to a given model.
Make a summary of the following Python 3 code def get_related_fields(model_class, field_name, path=""): if field_name: field, model, direct, m2m = _get_field_by_name(model_class, field_name) if direct: # Direct field try: new_model = _get_remote_field(field).p...
You are a Python code architect, reviewing and designing scalable and efficient code
Emit the code needed to flush the buffer.
Can you tell what is the following Python 3 function doing def flush_template(context, declaration=None, reconstruct=True): if declaration is None: declaration = Line(0, '') if {'text', 'dirty'}.issubset(context.flag): yield declaration.clone(line='yield "".join(_buffer)') context.flag.remove('text') # ...
You are a Python code generator, capable of creating scripts from specifications.
Inject speedup shortcut bindings into the argument specification for a function.
Can you tell what is the following Python 3 function doing def _optimize(self, context, argspec): argspec = argspec.strip() optimization = ", ".join(i + "=" + i for i in self.OPTIMIZE) split = None prefix = '' suffix = '' if argspec: matches = list(self.STARARGS.finditer(argspec)) if matches...
You are a Python code architect, reviewing and designing scalable and efficient code
Return True iff user has either change or view permission for model.
Can you generate a brief explanation for the following Python 3 code def _can_change_or_view(model, user): model_name = model._meta.model_name app_label = model._meta.app_label can_change = user.has_perm(app_label + '.change_' + model_name) can_view = user.has_perm(app_label + '.view_' + model_name) ...
As a Python code composer, you craft elegant and concise scripts.
Convert a report to a list of objects.
How would you explain what the following Python 3 function does def report_to_list(queryset, display_fields, user): model_class = queryset.model objects = queryset message = "" if not _can_change_or_view(model_class, user): return [], 'Permission Denied' # Convert list of strings to Displa...
As a python code expert, you are capable of creating scripts from specifications.
Create just a openpxl workbook from a list of data
Explain what the following Python 3 code does def list_to_workbook(data, title='report', header=None, widths=None): wb = Workbook() title = re.sub(r'\W+', '', title)[:30] if isinstance(data, dict): i = 0 for sheet_name, sheet_data in data.items(): if i > 0: wb.cr...
As a Python code composer, you craft elegant and concise scripts.
Take a workbook and return a xlsx file response
Can you tell what is the following Python 3 function doing def build_xlsx_response(wb, title="report"): title = generate_filename(title, '.xlsx') myfile = BytesIO() myfile.write(save_virtual_workbook(wb)) response = HttpResponse( myfile.getvalue(), content_type='application/vnd.openxmlfo...
You are a Python code architect, reviewing and designing scalable and efficient code
Convert a list into a xlsx response
Can you tell what is the following Python 3 function doing def list_to_xlsx_response(data, title='report', header=None, widths=None): """ Make 2D list into a xlsx response for download data can be a 2d array or a dict of 2d arrays like {'sheet_1': [['A1', 'B1']]} """ wb = l...
As a Python code composer, you craft elegant and concise scripts.
def list_to_csv_response(data, title='report', header=None, widths=None): """ Make 2D list into a csv response for download data. """ response = HttpResponse(content_type="text/csv; charset=UTF-8") cw = csv.writer(response) for row in chain([header] if header else [], data): cw.writerow([for...
Implement a Python 3 function for making a 2D list into a csv response for download data.
As a Python code analyst, you investigate and solve complex coding mysteries
def wrap(scope, lines, format=BARE_FORMAT): """Wrap a stream of lines in armour. Takes a stream of lines, for example, the following single line: Line(1, "Lorem ipsum dolor.") Or the following multiple lines: Line(1, "Lorem ipsum") Line(2, "dolor") Line(3, "sit amet.") Provides a gene...
Create a Python 3 function for wrapping a stream of lines in armour.
You are a Python code architect, reviewing and designing scalable and efficient code
Yields all contiguous lines of text preserving line numbers.
Here you have a function in Python 3, explain what it does def gather(input): try: line = input.next() except StopIteration: return lead = True buffer = [] # Gather contiguous (uninterrupted) lines of template text. while line.kind == 'text': value = line.line.rstrip().rstrip('\\') + ('' i...
As a Python code composer, you craft elegant and concise scripts.
def process(self, context, lines): """Chop up individual lines into static and dynamic parts. Applies light optimizations, such as empty chunk removal, and calls out to other methods to process different chunk types. The processor protocol here requires the method to accept values by yielding resulting li...
Can you write a function in Python 3 where it processes the lines into static and dynamic parts.
You are a Python code generator, capable of creating scripts from specifications.
Combine multiple lines of bare text and emit as a Python string literal.
Make a summary of the following Python 3 code def process_text(self, kind, context): result = None while True: chunk = yield None if chunk is None: if result: yield result.clone(line=repr(result.line)) return if not result: result = chunk continue result.line ...
You are a Python code analyst, evaluating scripts for potential improvements.
Transform otherwise unhandled kinds of chunks by calling an underscore prefixed function by that name.
Given the following Python 3 function, write the documentation def process_generic(self, kind, context): result = None while True: chunk = yield result if chunk is None: return result = chunk.clone(line='_' + kind + '(' + chunk.line + ')')
As a Python code translator, you convert algorithms and pseudocode into Python.
Handle transforming format string + arguments into Python code.
Can you generate the documentation for the following Python 3 function def process_format(self, kind, context): result = None while True: chunk = yield result if chunk is None: return # We need to split the expression defining the format string from the values to pass when formatting. ...
As a Python code analyst, you investigate and solve complex coding mysteries
Find the Player with the given properties
Can you generate a brief explanation for the following Python 3 code def find_player(self, username: str = None): if username != None: return next((player for player in self.players if player.name == username), None) else: return None
As a Python code translator, you convert algorithms and pseudocode into Python.
def find_team(self, color: str = None): """Find the :class:`~.Team` with the given properties Returns the team whose attributes match the given properties, or ``None`` if no match is found. :param color: The :class:`~.Team.Color` of the Team """ if color != None: ...
How would you code a function in Python 3 to find the team with the given properties Returns the team whose attributes match the given properties or None if no match is found.
As a Python code translator, you convert algorithms and pseudocode into Python.
This method is used to geocode the given PlaceQuery object and return a list of location Candidates.
Can you tell what is the following Python 3 function doing def _geocode(self, pq): #: List of desired output fields #: See `ESRI docs <https://developers.arcgis.com/rest/geocode/api-reference/geocoding-geocode-addresses.htm>_` for details outFields = ('Loc_name', # 'Shape', ...
As a Python code analyst, you investigate and solve complex coding mysteries
Construct a street address from a geocoder response.
Can you generate the documentation for the following Python 3 function def _street_addr_from_response(self, attributes): # The exact ordering of the address component fields that should be # used to reconstruct the full street address is not specified in the # Esri documentation, but the example...
You are a Python code analyst, evaluating scripts for potential improvements.
Returns a token suitable for use with the Esri geocoding API.
Given the following Python 3 function, write the documentation def get_token(self, expires=None): endpoint = 'https://www.arcgis.com/sharing/rest/oauth2/token/' query = {'client_id': self._client_id, 'client_secret': self._client_secret, 'grant_type': 'client_credential...
As a Python code analyst, you investigate and solve complex coding mysteries
def process(self, pq): """ :arg PlaceQuery pq: PlaceQuery instance :returns: PlaceQuery instance with truncated address range / number """ pq.query = self.replace_range(pq.query) pq.address = self.replace_range(pq.address) return pq
Can you implement a function in Python 3 that replaces truncated address range with number of entries in the PlaceQuery instance pq.
As a python code expert, you are capable of creating scripts from specifications.
def process(self, pq): """ :arg PlaceQuery pq: PlaceQuery instance :returns: PlaceQuery instance with :py:attr:`query` converted to individual elements """ if pq.query != '': postcode = address = city = '' # define the vars we'll use # ...
Write a Python 3 function for processing the PlaceQuery instance with the given query and return the corresponding elements.
You are a Python code architect, reviewing and designing scalable and efficient code
Process a PlaceQuery instance and return a new PlaceQuery instance with the new ones.
Explain what the following Python 3 code does def process(self, pq): # Map country, but don't let map overwrite if pq.country not in self.acceptable_countries and pq.country in self.country_map: pq.country = self.country_map[pq.country] if pq.country != '' and \ self.accep...
You are a Python code architect, reviewing and designing scalable and efficient code
Process the ISO 3166 - 1 ISO 3166 - 1 ISO 3166 - 1 ISO 3166 - 1 ISO 3166 - 1 ISO 3166 - 1 ISO 3166 - 1 ISO 3166 - 1 ISO 3166 - 1 ISO 3166 - 1 ISO 3166 - 1 ISO 3166 - 1 ISO 3166 - 1 ISO 3166 - 1 ISO 3166 - 1 ISO 3166 - 1 ISO 3166 - 1 ISO 3166 - 1 ISO 3166 - 1 ISO 3
How would you explain what the following Python 3 function does def process(self, pq): if pq.country.strip() == '': if self.default_country == '': return False else: pq.country = self.default_country return pq
You are a Python code generator, capable of creating scripts from specifications.
def _street_addr_from_response(self, match): """Construct a street address (no city, region, etc.) from a geocoder response. :param match: The match object returned by the geocoder. """ # Same caveat as above regarding the ordering of these fields; the # documentation is not exp...
Write a Python 3 script to construct a street address from a geocoder response.
You are a Python code architect, reviewing and designing scalable and efficient code
def copy(self, *args, **kwargs): """ Copy the request and environment object. This only does a shallow copy, except of wsgi.input """ self.make_body_seekable() env = self.environ.copy() new_req = self.__class__(env, *args, **kwargs) new_req.copy_body() ...
Write a Python 3 function for returning a shallow copy of the request and environment object.
You are a Python code architect, reviewing and designing scalable and efficient code
Add a geocoding service to this instance.
Explain what the following Python 3 code does def add_source(self, source): geocode_service = self._get_service_by_name(source[0]) self._sources.append(geocode_service(**source[1]))
You are a Python code architect, reviewing and designing scalable and efficient code
Remove a geocoding service from this instance.
Here you have a function in Python 3, explain what it does def remove_source(self, source): geocode_service = self._get_service_by_name(source[0]) self._sources.remove(geocode_service(**source[1]))
As a python code expert, you are capable of creating scripts from specifications.
def set_sources(self, sources): """ Creates GeocodeServiceConfigs from each str source """ if len(sources) == 0: raise Exception('Must declare at least one source for a geocoder') self._sources = [] for source in sources: # iterate through a list of sources ...
Write a Python 3 function for setting the sources for this geocoder
As a Python code analyst, you investigate and solve complex coding mysteries
This method will geocode the universal address of the given PlaceQuery object and return a dictionary containing the results of the geocoding.
Given the following Python 3 function, write the documentation def geocode(self, pq, waterfall=None, force_stats_logging=False): waterfall = self.waterfall if waterfall is None else waterfall if type(pq) in (str, str): pq = PlaceQuery(pq) processed_pq = copy.copy(pq) for p ...
As a Python code composer, you craft elegant and concise scripts.
def _apply_param_actions(self, params, schema_params): """Traverse a schema and perform the updates it describes to params.""" for key, val in schema_params.items(): if key not in params: continue if isinstance(val, dict): self._apply_param_actio...
How would you code a function in Python 3 to traverse a schema and perform the updates it describes to params.
You are a Python code generator, capable of creating scripts from specifications.
Validate the VCF file and set self. is_validated to True.
Can you generate the documentation for the following Python 3 function def validator(self): tstart = datetime.now() v = validator.Validator(self.vcf_file) std = v.run() if std == 0: self.is_validated = True tend = datetime.now() execution_time = tend - tstart
As a python code expert, you are capable of creating scripts from specifications.
def sanitycheck(self): """ Search and Remove variants with [0/0, ./.] Search and Replace chr from the beggining of the chromossomes to get positionning. Sort VCF by 1...22, X, Y, MT and nothing else #Discard other variants """ # logging.info('Starting Sanity C...
Can you create a Python 3 function that runs a sanity check on the current VCF file.
You are a Python code analyst, evaluating scripts for potential improvements.
run SNPEFF and return the output
Can you generate the documentation for the following Python 3 function def snpeff(self): # calculate time thread took to finish # logging.info('Starting snpEff') tstart = datetime.now() se = snpeff.Snpeff(self.vcf_file) std = se.run() tend = datetime.now() execu...
As a Python code composer, you craft elegant and concise scripts.