output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Checks whether a formatoption is data dependent
Can you tell what is the following Python 3 function doing def is_data_dependent(fmto, data): if callable(fmto.data_dependent): return fmto.data_dependent(data) return fmto.data_dependent
As a Python code composer, you craft elegant and concise scripts.
Set the value of the key in the plotter with the given value.
How would you explain what the following Python 3 function does def set_value(self, value, validate=True, todefault=False): value = value if not validate else self.validate(value) # if the key in the plotter is not already set (i.e. it is initialized # with None, we set it) if self.plott...
You are a Python code generator, capable of creating scripts from specifications.
Axes instance of the plot
How would you explain what the following Python 3 function does def ax(self): if self._ax is None: import matplotlib.pyplot as plt plt.figure() self._ax = plt.axes(projection=self._get_sample_projection()) return self._ax
You are a Python code generator, capable of creating scripts from specifications.
A mapping from the base_variable names to the variables
How would you explain what the following Python 3 function does def iter_base_variables(self): if isinstance(self.data, InteractiveList): return chain(*(arr.psy.iter_base_variables for arr in self.data)) else: return self.data.psy.iter_base_variables
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the dictionary containing the key value pairs that are not the default
How would you explain what the following Python 3 function does def changed(self): return {key: value for key, value in six.iteritems(self) if getattr(self, key).changed}
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a dictionary mapping from group to a set of formatoptions
Here you have a function in Python 3, explain what it does def _fmto_groups(self): ret = defaultdict(set) for key in self: ret[getattr(self, key).group].add(getattr(self, key)) return dict(ret)
As a Python code analyst, you investigate and solve complex coding mysteries
def logger(self): """:class:`logging.Logger` of this plotter""" try: return self.data.psy.logger.getChild(self.__class__.__name__) except AttributeError: name = '%s.%s' % (self.__module__, self.__class__.__name__) return logging.getLogger(name)
Write a Python 3 script to return the logging. Logger of this plotter.
As a Python code analyst, you investigate and solve complex coding mysteries
Try to set the value in fmto and gives additional informations when fail is set
Make a summary of the following Python 3 code def _try2set(self, fmto, *args, **kwargs): try: fmto.set_value(*args, **kwargs) except Exception as e: critical("Error while setting %s!" % fmto.key, logger=getattr(self, 'logger', None)) raise e
As a Python code translator, you convert algorithms and pseudocode into Python.
Checks whether the key is a valid formatoption .
How would you explain what the following Python 3 function does def check_key(self, key, raise_error=True, *args, **kwargs): return check_key( key, possible_keys=list(self), raise_error=raise_error, name='formatoption keyword', *args, **kwargs)
You are a Python code analyst, evaluating scripts for potential improvements.
Initialize the plot for a given data array.
Here you have a function in Python 3, explain what it does def initialize_plot(self, data=None, ax=None, make_plot=True, clear=False, draw=False, remove=False, priority=None): """ Initialize the plot for a data array Parameters ---------- data: Interactiv...
You are a Python code architect, reviewing and designing scalable and efficient code
def _register_update(self, fmt={}, replot=False, force=False, todefault=False): """ Register formatoptions for the update Parameters ---------- fmt: dict Keys can be any valid formatoptions with the corresponding values (see the :...
Can you implement a function in Python 3 that registers formatoptions for the update
You are a Python code generator, capable of creating scripts from specifications.
def start_update(self, draw=None, queues=None, update_shared=True): """ Conduct the registered plot updates This method starts the updates from what has been registered by the :meth:`update` method. You can call this method if you did not set the `auto_update` parameter to True ...
Can you create a Python 3 function that starts the update of the formatoptions.
As a Python code translator, you convert algorithms and pseudocode into Python.
Draw the figures and those that are shared and have been changed
Make a summary of the following Python 3 code def draw(self): for fig in self.figs2draw: fig.canvas.draw() self._figs2draw.clear()
As a Python code translator, you convert algorithms and pseudocode into Python.
def _insert_additionals(self, fmtos, seen=None): """ Insert additional formatoptions into `fmtos`. This method inserts those formatoptions into `fmtos` that are required because one of the following criteria is fullfilled: 1. The :attr:`replot` attribute is True 2. Any ...
How would you code a function in Python 3 to insert additional formatoptions into fmtos.
As a python code expert, you are capable of creating scripts from specifications.
Yields all formatoption objects in the order of their priority and dependency.
Here you have a function in Python 3, explain what it does def _sorted_by_priority(self, fmtos, changed=None): def pop_fmto(key): idx = fmtos_keys.index(key) del fmtos_keys[idx] return fmtos.pop(idx) def get_children(fmto, parents_keys): all_fmtos = fmtos...
As a Python code translator, you convert algorithms and pseudocode into Python.
This method returns an iterator over formatoptions in this class.
Make a summary of the following Python 3 code def _get_formatoptions(cls, include_bases=True): def base_fmtos(base): return filter( lambda key: isinstance(getattr(cls, key), Formatoption), getattr(base, '_get_formatoptions', empty)(False)) def empty(*args, **...
As a Python code composer, you craft elegant and concise scripts.
Enhance the given keys by groups and return the enhanced list of formatoptions.
Can you tell what is the following Python 3 function doing def _enhance_keys(cls, keys=None, *args, **kwargs): all_keys = list(cls._get_formatoptions()) if isinstance(keys, six.string_types): keys = [keys] else: keys = list(keys or sorted(all_keys)) fmto_groups = ...
As a Python code translator, you convert algorithms and pseudocode into Python.
A method to print the summary of the keys and other parameters.
Given the following Python 3 function, write the documentation def show_summaries(cls, keys=None, indent=0, *args, **kwargs): def find_summary(key, key_txt, doc): return '\n'.join(wrapper.wrap(doc[:doc.find('\n\n')])) str_indent = " " * indent wrapper = TextWrapper(width=80, initial_...
As a python code expert, you are capable of creating scripts from specifications.
A method to print the full documentations of the formatoptions .
Explain what the following Python 3 code does def show_docs(cls, keys=None, indent=0, *args, **kwargs): def full_doc(key, key_txt, doc): return ('=' * len(key_txt)) + '\n' + doc + '\n' return cls._show_doc(full_doc, keys=keys, indent=indent, *args, **kwargs)
As a python code expert, you are capable of creating scripts from specifications.
Method to set the rcparams and defaultParams for this plotter
How would you explain what the following Python 3 function does def _set_rc(self): base_str = self._get_rc_strings() # to make sure that the '.' is not interpreted as a regex pattern, # we specify the pattern_base by ourselves pattern_base = map(lambda s: s.replace('.', '\.'), base_str) ...
As a python code expert, you are capable of creating scripts from specifications.
def update(self, fmt={}, replot=False, auto_update=False, draw=None, force=False, todefault=False, **kwargs): """ Update the formatoptions and the plot If the :attr:`data` attribute of this plotter is None, the plotter is updated like a usual dictionary (see :meth:`dict.u...
Create a Python 3 function to update the formatoptions and the plotter.
As a Python code analyst, you investigate and solve complex coding mysteries
def _set_sharing_keys(self, keys): """ Set the keys to share or unshare Parameters ---------- keys: string or iterable of strings The iterable may contain formatoptions that shall be shared (or unshared), or group names of formatoptions to share all ...
Create a Python 3 function to set the keys to share or unshare the given set of formatoptions.
As a Python code translator, you convert algorithms and pseudocode into Python.
This method shares the formatoptions of this plotter with the others.
Given the following Python 3 function, write the documentation def share(self, plotters, keys=None, draw=None, auto_update=False): auto_update = auto_update or not self.no_auto_update if isinstance(plotters, Plotter): plotters = [plotters] keys = self._set_sharing_keys(keys) ...
As a Python code composer, you craft elegant and concise scripts.
Unshare the given plotters with the given keys.
Here you have a function in Python 3, explain what it does def unshare(self, plotters, keys=None, auto_update=False, draw=None): auto_update = auto_update or not self.no_auto_update if isinstance(plotters, Plotter): plotters = [plotters] keys = self._set_sharing_keys(keys) fo...
As a python code expert, you are capable of creating scripts from specifications.
def unshare_me(self, keys=None, auto_update=False, draw=None, update_other=True): """ Close the sharing connection of this plotter with others This method undoes the sharing connections made by the :meth:`share` method and release this plotter again. Paramete...
Can you write a function in Python 3 where it closes the sharing connection of this plotter with others This method undoes the sharing connections made by the :meth:`share` method and release this plotter again. Parameters ---------- keys: string or iterable of strings The formatoptions to unshare, or group names of fo...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a list of the old value and the new value of the formatoption with the given key.
Here you have a function in Python 3, explain what it does def has_changed(self, key, include_last=True): if self._initializing or key not in self: return fmto = getattr(self, key) if self._old_fmt and key in self._old_fmt[-1]: old_val = self._old_fmt[-1][key] els...
As a python code expert, you are capable of creating scripts from specifications.
execute command return rc and output string.
Here you have a function in Python 3, explain what it does def execute(cmd): # Parse cmd string to a list if not isinstance(cmd, list): cmd = shlex.split(cmd) # Execute command rc = 0 output = "" try: output = subprocess.check_output(cmd, close_fds=True, ...
As a Python code composer, you craft elegant and concise scripts.
def convert_to_mb(s): """Convert memory size from GB to MB.""" s = s.upper() try: if s.endswith('G'): return float(s[:-1].strip()) * 1024 elif s.endswith('T'): return float(s[:-1].strip()) * 1024 * 1024 else: return float(s[:-1].strip()) except...
How would you implement a function in Python 3 that converts memory size from GB to MB.
As a Python code translator, you convert algorithms and pseudocode into Python.
def valid_mac_addr(addr): ''' Validates a mac address''' if not isinstance(addr, six.string_types): return False valid = re.compile(r''' (^([0-9A-F]{2}[:]){5}([0-9A-F]{2})$) ''', re.VERBOSE | re.IGNORECASE) return valid.match(addr...
Implement a Python 3 function for validating a mac address
As a python code expert, you are capable of creating scripts from specifications.
Catch exceptions when using zvm client response data.
Make a summary of the following Python 3 code def expect_invalid_resp_data(data=''): try: yield except (ValueError, TypeError, IndexError, AttributeError, KeyError) as err: msg = ('Invalid smt response data: %s. Error: %s' % (data, six.text_type(err))) LOG.erro...
As a Python code translator, you convert algorithms and pseudocode into Python.
def wrap_invalid_resp_data_error(function): """Catch exceptions when using zvm client response data.""" @functools.wraps(function) def decorated_function(*arg, **kwargs): try: return function(*arg, **kwargs) except (ValueError, TypeError, IndexError, AttributeError, ...
Write a Python 3 function for catching exceptions when using zvm client response data.
You are a Python code architect, reviewing and designing scalable and efficient code
def expect_and_reraise_internal_error(modID='SDK'): """Catch all kinds of zvm client request failure and reraise. modID: the moduleID that the internal error happens in. """ try: yield except exception.SDKInternalError as err: msg = err.format_message() raise exception.SDKIn...
Implement a Python 3 function for catching all kinds of zvm client request failure and reraise the exception. SDKInternalError
You are a Python code analyst, evaluating scripts for potential improvements.
def log_and_reraise_smt_request_failed(action=None): """Catch SDK base exception and print error log before reraise exception. msg: the error message to be logged. """ try: yield except exception.SDKSMTRequestFailed as err: msg = '' if action is not None: msg = "...
How would you code a function in Python 3 to catch SDK base exception and print error log before reraise exception.
You are a Python code analyst, evaluating scripts for potential improvements.
Get the userid of the smt server
Can you generate the documentation for the following Python 3 function def get_smt_userid(): cmd = ["sudo", "/sbin/vmcp", "query userid"] try: userid = subprocess.check_output(cmd, close_fds=True, stderr=subprocess.STDOUT)...
You are a Python code generator, capable of creating scripts from specifications.
def get_namelist(): """Generate namelist. Either through set CONF.zvm.namelist, or by generate based on smt userid. """ if CONF.zvm.namelist is not None: # namelist length limit should be 64, but there's bug limit to 8 # will change the limit to 8 once the bug fixed if len(CONF....
Can you create a Python 3 function that generates namelist. Either through set CONF.zvm.namelist, or by generate based on smt userid.
You are a Python code analyst, evaluating scripts for potential improvements.
def generate_iucv_authfile(fn, client): """Generate the iucv_authorized_userid file""" lines = ['#!/bin/bash\n', 'echo -n %s > /etc/iucv_authorized_userid\n' % client] with open(fn, 'w') as f: f.writelines(lines)
Can you implement a function in Python 3 that generates the iucv_authorized_userid file
You are a Python code analyst, evaluating scripts for potential improvements.
Translate SMT response to a python dictionary.
Here you have a function in Python 3, explain what it does def translate_response_to_dict(rawdata, dirt): data_list = rawdata.split("\n") data = {} for ls in data_list: for k in list(dirt.keys()): if ls.__contains__(dirt[k]): data[k] = ls[(ls.find(dirt[k]) + len(dirt[k])...
As a Python code translator, you convert algorithms and pseudocode into Python.
Delete a virtual machine.
Given the following Python 3 function, write the documentation def delete_guest(userid): # Check if the guest exists. guest_list_info = client.send_request('guest_list') # the string 'userid' need to be coded as 'u'userid' in case of py2 interpreter. userid_1 = (unicode(userid, "utf-8") if sys.version[0...
As a Python code analyst, you investigate and solve complex coding mysteries
def describe_guest(userid): """ Get the basic information of virtual machine. Input parameters: :userid: USERID of the guest, last 8 if length > 8 """ # Check if the guest exists. guest_list_info = client.send_request('guest_list') userid_1 = (unicode(userid, "utf-8") if sys.version[0] =...
Create a Python 3 function for getting the basic information of a virtual machine.
As a Python code analyst, you investigate and solve complex coding mysteries
def import_image(image_path, os_version): """ Import the specific image. Input parameters: :image_path: Image file name :os_version: Operation System version. e.g. rhel7.4 """ image_name = os.path.basename(image_path) print("\nChecking if image %s exists ..." % image_name) image_...
Write a Python 3 function that can import the specific image.
You are a Python code generator, capable of creating scripts from specifications.
Create the userid. Input parameters: :userid: USERID of the guest, last 8 if length > 8 :cpu: the number of vcpus :memory: memory :disks_list: list of disks to add :profile: profile of the userid
Make a summary of the following Python 3 code def create_guest(userid, cpu, memory, disks_list, profile): # Check if the userid already exists. guest_list_info = client.send_request('guest_list') userid_1 = (unicode(userid, "utf-8") if sys.version[0] == '2' else userid) if userid_1 in guest_list_info['...
You are a Python code generator, capable of creating scripts from specifications.
def deploy_guest(userid, image_name): """ Deploy image to root disk. Input parameters: :userid: USERID of the guest, last 8 if length > 8 :image_path: Image file name """ print("\nDeploying %s to %s ..." % (image_name, userid)) guest_deploy_info = client.send_request('gues...
Write a Python 3 script for deploying image to root disk.
You are a Python code architect, reviewing and designing scalable and efficient code
Create network device and configure network interface.
Explain what the following Python 3 code does def create_network(userid, os_version, network_info): print("\nConfiguring network interface for %s ..." % userid) network_create_info = client.send_request('guest_create_network_interface', userid, os_version, network_...
As a Python code analyst, you investigate and solve complex coding mysteries
Couple to vswitch. Input parameters: :userid: USERID of the guest, last 8 if length > 8 :network_info: dict of network info
How would you explain what the following Python 3 function does def coupleTo_vswitch(userid, vswitch_name): print("\nCoupleing to vswitch for %s ..." % userid) vswitch_info = client.send_request('guest_nic_couple_to_vswitch', userid, '1000', vswitch_name) if vswitch_...
You are a Python code generator, capable of creating scripts from specifications.
def grant_user(userid, vswitch_name): """ Grant user. Input parameters: :userid: USERID of the guest, last 8 if length > 8 :network_info: dict of network info """ print("\nGranting user %s ..." % userid) user_grant_info = client.send_request('vswitch_grant_user', vswitch_nam...
Can you create a Python 3 function that grants user to guest
You are a Python code generator, capable of creating scripts from specifications.
Power on the guest.
Explain what the following Python 3 code does def start_guest(userid): # Check the power state before starting guest. power_state_info = client.send_request('guest_get_power_state', userid) print("\nPower state is: %s." % power_state_info['output']) # start guest. guest_start_info = client.send_req...
You are a Python code analyst, evaluating scripts for potential improvements.
def _run_guest(userid, image_path, os_version, profile, cpu, memory, network_info, vswitch_name, disks_list): """ Deploy and provide a virtual machine. Input parameters: :userid: USERID of the guest, no more than 8 :image_path: image file path :os_version: ...
Create a Python 3 function for creating a new virtual machine and create the network and grant user and configure network interface.
You are a Python code analyst, evaluating scripts for potential improvements.
A sample for quickly deploy and start a virtual guest.
Can you tell what is the following Python 3 function doing def run_guest(): # user input the properties of guest, image and network. _user_input_properties() # run a guest. _run_guest(GUEST_USERID, IMAGE_PATH, IMAGE_OS_VERSION, GUEST_PROFILE, GUEST_VCPUS, GUEST_MEMORY, NETWORK_INFO, VS...
You are a Python code generator, capable of creating scripts from specifications.
Return package version string by reading filename and retrieving its module - global variable varname.
Explain what the following Python 3 code does def package_version(filename, varname): _locals = {} with open(filename) as fp: exec(fp.read(), None, _locals) return _locals[varname]
You are a Python code architect, reviewing and designing scalable and efficient code
Process a request. Input: Request as either a string or a list. captureLogs=<True|False> Enables or disables log capture per request. This overrides the value from SMT. requestId=<id> to pass a value for the request Id instead of using ...
Given the following Python 3 function, write the documentation def request(self, requestData, **kwArgs): self.reqCnt = self.reqCnt + 1 # Determine whether the request will be capturing logs if 'captureLogs' in kwArgs.keys(): logFlag = kwArgs['captureLogs'] else: ...
You are a Python code generator, capable of creating scripts from specifications.
def invokeSmapiApi(rh): """ Invoke a SMAPI API. Input: Request Handle with the following properties: function - 'SMAPI' subfunction - 'API' userid - 'HYPERVISOR' parms['apiName'] - Name of API as defined by SMCLI parms['operands'] - List (...
Can you implement a function in Python 3 that invokes a SMAPI API and return the result.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _parse(self, init_info): """Initialize a FCP device object from several lines of string describing properties of the FCP device. Here is a sample: opnstk1: FCP device number: B83D opnstk1: Status: Free opnstk1: NPIV world wide port numbe...
Create a Python 3 function to parse the FCP device object from several lines of string containing properties of the FCP device object.
As a Python code analyst, you investigate and solve complex coding mysteries
def _init_fcp_pool(self, fcp_list, assigner_id): """The FCP infomation got from smt(zthin) looks like : host: FCP device number: xxxx host: Status: Active host: NPIV world wide port number: xxxxxxxx host: Channel path ID: xx host: Physical world wid...
Implement a Python 3 function for initializing the FCP pool.
As a Python code analyst, you investigate and solve complex coding mysteries
Expand fcp list into a python list object which contains each fcp device address and range indicator -.
How would you explain what the following Python 3 function does def _expand_fcp_list(fcp_list): LOG.debug("Expand FCP list %s" % fcp_list) if not fcp_list: return set() range_pattern = '[0-9a-fA-F]{1,4}(-[0-9a-fA-F]{1,4})?' match_pattern = "^(%(range)s)(;%(range)s)*$" % {'...
You are a Python code generator, capable of creating scripts from specifications.
def _add_fcp(self, fcp): """add fcp to db if it's not in db but in fcp list and init it""" try: LOG.info("fcp %s found in CONF.volume.fcp_list, add it to db" % fcp) self.db.new(fcp) except Exception: LOG.info("failed to add fcp %s into db"...
Write a Python 3 script to add fcp to db if it s not in db and init it
As a python code expert, you are capable of creating scripts from specifications.
sync db records from given fcp list for example you need to add new FCP to the database
How would you explain what the following Python 3 function does def _sync_db_fcp_list(self): fcp_db_list = self.db.get_all() for fcp_rec in fcp_db_list: if not fcp_rec[0].lower() in self._fcp_pool: self._report_orphan_fcp(fcp_rec[0]) for fcp_conf_rec, v in self._fcp...
As a Python code composer, you craft elegant and concise scripts.
find a fcp and reserve it
Explain what the following Python 3 code does def find_and_reserve_fcp(self, assigner_id): fcp_list = self.db.get_from_assigner(assigner_id) if not fcp_list: new_fcp = self.db.find_and_reserve() if new_fcp is None: LOG.info("no more fcp to be allocated") ...
As a Python code composer, you craft elegant and concise scripts.
Increase the fcp usage of given fcp Returns True if it s a new fcp otherwise return False
Here you have a function in Python 3, explain what it does def increase_fcp_usage(self, fcp, assigner_id=None): # TODO: check assigner_id to make sure on the correct fcp record connections = self.db.get_connections_from_assigner(assigner_id) new = False if connections == 0: ...
You are a Python code generator, capable of creating scripts from specifications.
get all the fcps not reserved
Explain what the following Python 3 code does def get_available_fcp(self): # get the unreserved FCP devices belongs to assigner_id available_list = [] free_unreserved = self.db.get_all_free_unreserved() for item in free_unreserved: available_list.append(item[0]) retur...
You are a Python code analyst, evaluating scripts for potential improvements.
def _attach(self, fcp, assigner_id, target_wwpn, target_lun, multipath, os_version, mount_point): """Attach a volume First, we need translate fcp into local wwpn, then dedicate fcp to the user if it's needed, after that call smt layer to call linux command """ ...
Can you create a Python 3 function that attaches a volume to a specific FCP.
You are a Python code generator, capable of creating scripts from specifications.
Detach a volume from a guest
Given the following Python 3 function, write the documentation def _detach(self, fcp, assigner_id, target_wwpn, target_lun, multipath, os_version, mount_point): """Detach a volume from a guest""" LOG.info('Start to detach device from %s' % assigner_id) connections = self.fcp_mgr....
As a Python code composer, you craft elegant and concise scripts.
def detach(self, connection_info): """Detach a volume from a guest """ fcp = connection_info['zvm_fcp'] fcp = fcp.lower() target_wwpn = connection_info['target_wwpn'] target_lun = connection_info['target_lun'] assigner_id = connection_info['assigner_id'] a...
Write a Python 3 function that can detach a volume from a guest
You are a Python code generator, capable of creating scripts from specifications.
Get connector information of the instance for attaching to volumes.
Explain what the following Python 3 code does def get_volume_connector(self, assigner_id): empty_connector = {'zvm_fcp': [], 'wwpns': [], 'host': ''} # init fcp pool self.fcp_mgr.init_fcp(assigner_id) fcp_list = self.fcp_mgr.get_available_fcp() if not fcp_list: errm...
As a Python code composer, you craft elegant and concise scripts.
Salsa 20 / 8 algorithm.
How would you explain what the following Python 3 function does 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): a =...
As a Python code analyst, you investigate and solve complex coding mysteries
Blockmix ; Used by SMix
How would you explain what the following Python 3 function does def blockmix_salsa8(BY, Yi, r): start = (2 * r - 1) * 16 X = BY[start:start+16] # BlockMix - 1 tmp = [0]*16 for i in xrange(2 * r): # BlockMix - 2 #blockxor(BY, i * 16, X, 0, ...
As a Python code translator, you convert algorithms and pseudocode into Python.
SMix based on Salsa20 and 8
Explain what the following Python 3 code does def smix(B, Bi, r, N, V, X): X[0:(0)+(32 * r)] = B[Bi:(Bi)+(32 * r)] for i in xrange(N): # ROMix - 2 V[i * (32 * r):(i * (32 * r))+(32 * r)] = X[0:(0)+(32 * r)] blockmix_salsa8(X, 32 * r, r) # ROMix -...
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...
Implement a function in Python 3 to return 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 -- 2**14 (~16k) r -- 8 p -- 1 Memory usage is proportional to ...
As a Python code analyst, you investigate and solve complex coding mysteries
Derives a Modular Crypt Format hash using the scrypt KDF
Make a summary of the following Python 3 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 t...
As a Python code translator, you convert algorithms and pseudocode into Python.
def _update_versions(): """Update :attr:`_versions` with the registered plotter methods""" for pm_name in plot._plot_methods: pm = getattr(plot, pm_name) plugin = pm._plugin if (plugin is not None and plugin not in _versions and pm.module in sys.modules): _ver...
Can you create a Python 3 function that updates the _versions attribute with the registered plotter methods
As a Python code translator, you convert algorithms and pseudocode into Python.
Function to create subplots on the same figure.
Can you tell what is the following Python 3 function doing def multiple_subplots(rows=1, cols=1, maxplots=None, n=1, delete=True, for_maps=False, *args, **kwargs): """ Function to create subplots. This function creates so many subplots on so many figures until the specified number...
As a Python code analyst, you investigate and solve complex coding mysteries
def _only_main(func): """Call the given `func` only from the main project""" @wraps(func) def wrapper(self, *args, **kwargs): if not self.is_main: return getattr(self.main, func.__name__)(*args, **kwargs) return func(self, *args, **kwargs) return wrapper
Can you write a function in Python 3 where it calls the given func only from the main project
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the current project or project depending on main flag.
Explain what the following Python 3 code does def gcp(main=False): if main: return project() if _current_project is None else _current_project else: return gcp(True) if _current_subproject is None else \ _current_subproject
As a Python code analyst, you investigate and solve complex coding mysteries
scp version that allows a bit more control over whether the project is a main project or not
Given the following Python 3 function, write the documentation def _scp(p, main=False): global _current_subproject global _current_project if p is None: mp = project() if main or _current_project is None else \ _current_project _current_subproject = Project(main=mp) elif not ...
As a Python code composer, you craft elegant and concise scripts.
def project(num=None, *args, **kwargs): """ Create a new main project Parameters ---------- num: int The number of the project %(Project.parameters.no_num)s Returns ------- Project The with the given `num` (if it does not already exist, it is created) See Also ...
Can you implement a function in Python 3 that creates a new project with the given number
You are a Python code architect, reviewing and designing scalable and efficient code
def close(num=None, figs=True, data=True, ds=True, remove_only=False): """ Close the project This method closes the current project (figures, data and datasets) or the project specified by `num` Parameters ---------- num: int, None or 'all' if :class:`int`, it specifies the number ...
Create a Python 3 function for closing the current project or the current project.
As a Python code analyst, you investigate and solve complex coding mysteries
def register_plotter(identifier, module, plotter_name, plotter_cls=None, sorter=True, plot_func=True, import_plotter=None, **kwargs): """ Register a :class:`psyplot.plotter.Plotter` for the projects This function registers plotters for the :class:`Project` class to...
Create a Python 3 function to register a plotter class for the specified project and returns the resulting tree structure.
You are a Python code analyst, evaluating scripts for potential improvements.
Unregisters a plotter for the projects
How would you explain what the following Python 3 function does def unregister_plotter(identifier, sorter=True, plot_func=True): d = registered_plotters.get(identifier, {}) if sorter and hasattr(Project, identifier): delattr(Project, identifier) d['sorter'] = False if plot_func and hasattr(P...
As a Python code analyst, you investigate and solve complex coding mysteries
An iterator over formatoption objects containing only the formatoption whose keys are in all plotters in this list Contains only the formatoption whose keys are in all plotters in this list
Can you generate a brief explanation for the following Python 3 code def _fmtos(self): plotters = self.plotters if len(plotters) == 0: return {} p0 = plotters[0] if len(plotters) == 1: return p0._fmtos return (getattr(p0, key) for key in set(p0).intersecti...
As a python code expert, you are capable of creating scripts from specifications.
A mapping from figures to data objects with the plotter in this figure
Can you generate a brief explanation for the following Python 3 code def figs(self): ret = utils.DefaultOrderedDict(lambda: self[1:0]) for arr in self: if arr.psy.plotter is not None: ret[arr.psy.plotter.ax.get_figure()].append(arr) return OrderedDict(ret)
You are a Python code generator, capable of creating scripts from specifications.
A mapping from axes to data objects with the plotter in this axes
Can you generate a brief explanation for the following Python 3 code def axes(self): ret = utils.DefaultOrderedDict(lambda: self[1:0]) for arr in self: if arr.psy.plotter is not None: ret[arr.psy.plotter.ax].append(arr) return OrderedDict(ret)
You are a Python code analyst, evaluating scripts for potential improvements.
Returns the logger of this instance.
Can you tell what is the following Python 3 function doing def logger(self): if not self.is_main: return self.main.logger try: return self._logger except AttributeError: name = '%s.%s.%s' % (self.__module__, self.__class__.__name__, ...
As a Python code translator, you convert algorithms and pseudocode into Python.
A mapping from dataset numbers to datasets in this list
Given the following Python 3 function, write the documentation def datasets(self): return {key: val['ds'] for key, val in six.iteritems( self._get_ds_descriptions(self.array_info(ds_description=['ds'])))}
You are a Python code generator, capable of creating scripts from specifications.
def _register_plotter(cls, identifier, module, plotter_name, plotter_cls=None): """ Register a plotter in the :class:`Project` class to easy access it Parameters ---------- identifier: str Name of the attribute that is used to filter for the...
Implement a Python 3 function for registering a plotter in the project class.
You are a Python code generator, capable of creating scripts from specifications.
Disables the plotters in this list
Here you have a function in Python 3, explain what it does def disable(self): for arr in self: if arr.psy.plotter: arr.psy.plotter.disabled = True
As a Python code analyst, you investigate and solve complex coding mysteries
def close(self, figs=True, data=False, ds=False, remove_only=False): """ Close this project instance Parameters ---------- figs: bool Close the figures data: bool delete the arrays from the (main) project ds: bool If True, clos...
Can you implement a function in Python 3 that closes the current instance of the object and all its children.
You are a Python code architect, reviewing and designing scalable and efficient code
def _add_data(self, plotter_cls, filename_or_obj, fmt={}, make_plot=True, draw=False, mf_mode=False, ax=None, engine=None, delete=True, share=False, clear=False, enable_post=None, concat_dim=_concat_dim_default, load=False, *args, **kwargs): ...
Create a Python 3 function to add data to the current object.
As a python code expert, you are capable of creating scripts from specifications.
Returns a string with the joined attributes of the array in this project.
Can you generate a brief explanation for the following Python 3 code def joined_attrs(self, delimiter=', ', enhanced=True, plot_data=False, keep_all=True): """Join the attributes of the arrays in this project Parameters ---------- %(join_dicts.parameters.delimiter)s...
You are a Python code generator, capable of creating scripts from specifications.
Exports the figures of the project to one or more image files.
Can you generate a brief explanation for the following Python 3 code def export(self, output, tight=False, concat=True, close_pdf=None, use_time=False, **kwargs): """Exports the figures of the project to one or more image files Parameters ---------- output: str, iterable ...
You are a Python code generator, capable of creating scripts from specifications.
This method shares the formatoptions of one plotter with all the others.
Can you generate a brief explanation for the following Python 3 code def share(self, base=None, keys=None, by=None, **kwargs): if by is not None: if base is not None: if hasattr(base, 'psy') or isinstance(base, Plotter): base = [base] if by.lower()...
As a Python code analyst, you investigate and solve complex coding mysteries
Save this project to a file.
Explain what the following Python 3 code does def save_project(self, fname=None, pwd=None, pack=False, **kwargs): # store the figure informatoptions and array informations if fname is not None and pwd is None and not pack: pwd = os.path.dirname(fname) if pack and fname is not None: ...
As a Python code analyst, you investigate and solve complex coding mysteries
Show the available formatoptions in this project.
Can you generate a brief explanation for the following Python 3 code def keys(self, *args, **kwargs): class TmpClass(Plotter): pass for fmto in self._fmtos: setattr(TmpClass, fmto.key, type(fmto)(fmto.key)) return TmpClass.show_keys(*args, **kwargs)
You are a Python code analyst, evaluating scripts for potential improvements.
def summaries(self, *args, **kwargs): """ Show the available formatoptions and their summaries in this project Parameters ---------- %(Plotter.show_keys.parameters)s Other Parameters ---------------- %(Plotter.show_keys.other_parameters)s Return...
Can you implement a function in Python 3 that shows the available formatoptions and their summaries in this project.
As a Python code composer, you craft elegant and concise scripts.
Show the available formatoptions in this project and their full docu
Given the following Python 3 function, write the documentation def docs(self, *args, **kwargs): class TmpClass(Plotter): pass for fmto in self._fmtos: setattr(TmpClass, fmto.key, type(fmto)(fmto.key)) return TmpClass.show_docs(*args, **kwargs)
You are a Python code generator, capable of creating scripts from specifications.
Construct an ArrayList instance from an existing base dataset.
How would you explain what the following Python 3 function does def from_dataset(cls, *args, **kwargs): main = kwargs.pop('main', None) ret = super(Project, cls).from_dataset(*args, **kwargs) if main is not None: ret.main = main main.extend(ret, new_name=False) re...
You are a Python code analyst, evaluating scripts for potential improvements.
def load_project(cls, fname, auto_update=None, make_plot=True, draw=False, alternative_axes=None, main=False, encoding=None, enable_post=False, new_fig=True, clear=None, **kwargs): """ Load a project from a file or dict This classme...
Implement a Python 3 function for loading a project from a file or dict This classmethod allows to load a project that has been stored using the :meth:`save_project` method and reads all the data and creates the figures. Since the data is stored in external files when saving a project, make sure that the data is access...
As a Python code composer, you craft elegant and concise scripts.
def scp(cls, project): """ Set the current project Parameters ---------- project: Project or None The project to set. If it is None, the current subproject is set to empty. If it is a sub project (see:attr:`Project.is_main`), the current subpr...
Write a Python 3 script for setting the current project to the given project.
As a Python code composer, you craft elegant and concise scripts.
def new(cls, num=None, *args, **kwargs): """ Create a new main project Parameters ---------- num: int The number of the project %(Project.parameters.no_num)s Returns ------- Project The with the given `num` (if it does not...
Write a Python 3 function for creating a new main project with the given parameters
You are a Python code generator, capable of creating scripts from specifications.
Get the parameters ( heigth width etc. to create a figure
Make a summary of the following Python 3 code def inspect_figure(fig): return fig.number, { 'num': fig.number, 'figsize': (fig.get_figwidth(), fig.get_figheight()), 'dpi': fig.get_dpi() / getattr(fig.canvas, '_dpi_ratio', 1), 'facecolor': fig.get_facecolor(), ...
You are a Python code analyst, evaluating scripts for potential improvements.
Create a figure from what is returned by inspect_figure
Can you tell what is the following Python 3 function doing def load_figure(d, new_fig=True): import matplotlib.pyplot as plt subplotpars = d.pop('subplotpars', None) if subplotpars is not None: subplotpars.pop('validate', None) subplotpars = mfig.SubplotParams(**subplotpa...
You are a Python code analyst, evaluating scripts for potential improvements.
def inspect_axes(ax): """Inspect an axes or subplot to get the initialization parameters""" ret = {'fig': ax.get_figure().number} if mpl.__version__ < '2.0': ret['axisbg'] = ax.get_axis_bgcolor() else: # axisbg is depreceated ret['facecolor'] = ax.get_facecolor()...
Write a Python 3 script for inspecting an axes or subplot to get the initialization parameters
You are a Python code analyst, evaluating scripts for potential improvements.