output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Returns a copy of seq sorted by natural string sort.
Given the following Python 3 function, write the documentation def natsorted(seq, cmp=natcmp): "Returns a copy of seq, sorted by natural string sort." import copy temp = copy.copy(seq) natsort(temp, cmp) return temp
As a Python code translator, you convert algorithms and pseudocode into Python.
returns time as ISO string mapping to and from datetime in ugly way
Can you generate the documentation for the following Python 3 function def get_iso_time(): '''returns time as ISO string, mapping to and from datetime in ugly way convert to string with str() ''' t1 = time.time() t2 = datetime.datetime.fromtimestamp(t1) t4 = t2.__str__() try: ...
As a Python code composer, you craft elegant and concise scripts.
returns time as double precision floats - Time64 in pytables - mapping to and from python datetime s
Can you generate the documentation for the following Python 3 function def get_float_time(): '''returns time as double precision floats - Time64 in pytables - mapping to and from python datetime's ''' t1 = time.time() t2 = datetime.datetime.fromtimestamp(t1) return time.mktime(t2.timetuple())...
You are a Python code analyst, evaluating scripts for potential improvements.
Group dict of dicts by key.
Explain what the following Python 3 code does def groupby_dict(dictionary, key): ''' Group dict of dicts by key. ''' return dict((k, list(g)) for k, g in itertools.groupby(sorted(dictionary.keys(), key=lambda name: dictionary[name][key]), key=lambda name: dictionary[name][key]))
As a python code expert, you are capable of creating scripts from specifications.
def zip_nofill(*iterables): '''Zipping iterables without fillvalue. Note: https://stackoverflow.com/questions/38054593/zip-longest-without-fillvalue ''' return (tuple([entry for entry in iterable if entry is not None]) for iterable in itertools.izip_longest(*iterables, fillvalue=None))
Write a Python 3 script for returning a new iterable with fillvalue removed from the first iterable.
You are a Python code analyst, evaluating scripts for potential improvements.
def find_file_dir_up(filename, path=None, n=None): '''Finding file in directory upwards. ''' if path is None: path = os.getcwd() i = 0 while True: current_path = path for _ in range(i): current_path = os.path.split(current_path)[0] if os.path.isf...
Write a Python 3 function for finding a file in a directory upwards.
As a Python code composer, you craft elegant and concise scripts.
def load_configuration_from_text_file(register, configuration_file): '''Loading configuration from text files to register object Parameters ---------- register : pybar.fei4.register object configuration_file : string Full path (directory and filename) of the configuration file. If na...
Write a Python 3 function that can load configuration from a text file into a single object.
You are a Python code generator, capable of creating scripts from specifications.
def load_configuration_from_hdf5(register, configuration_file, node=''): '''Loading configuration from HDF5 file to register object Parameters ---------- register : pybar.fei4.register object configuration_file : string, file Filename of the HDF5 configuration file or file object. ...
Can you implement a function in Python 3 that loads a configuration from a HDF5 file to a register object.
As a Python code composer, you craft elegant and concise scripts.
def save_configuration_to_text_file(register, configuration_file): '''Saving configuration to text files from register object Parameters ---------- register : pybar.fei4.register object configuration_file : string Filename of the configuration file. ''' configuration_path, ...
Write a Python 3 script to save the configuration to text files from the given register object.
You are a Python code generator, capable of creating scripts from specifications.
def save_configuration_to_hdf5(register, configuration_file, name=''): '''Saving configuration to HDF5 file from register object Parameters ---------- register : pybar.fei4.register object configuration_file : string, file Filename of the HDF5 configuration file or file object. ...
Write a Python 3 script for saving a configuration to HDF5 file from register object.
As a Python code translator, you convert algorithms and pseudocode into Python.
Load the configuration file.
Given the following Python 3 function, write the documentation def load_configuration(self, configuration_file): '''Loading configuration Parameters ---------- configuration_file : string Path to the configuration file (text or HDF5 file). ''' if os.p...
As a Python code translator, you convert algorithms and pseudocode into Python.
Save the configuration file.
Make a summary of the following Python 3 code def save_configuration(self, configuration_file): '''Saving configuration Parameters ---------- configuration_file : string Filename of the configuration file. ''' if not isinstance(configuration_file, tb....
You are a Python code analyst, evaluating scripts for potential improvements.
def get_commands(self, command_name, **kwargs): """get fe_command from command name and keyword arguments wrapper for build_commands() implements FEI4 specific behavior """ chip_id = kwargs.pop("ChipID", self.chip_id_bitarray) commands = [] if command_n...
Write a Python 3 script to get fe_command from command name and keyword arguments return list of fe_command
You are a Python code generator, capable of creating scripts from specifications.
def build_command(self, command_name, **kwargs): """build command from command_name and keyword values Returns ------- command_bitvector : list List of bitarrays. Usage ----- Receives: command name as defined inside xml file, key-value-pair...
Create a Python 3 function for building command from command_name and keyword values Returns list of bitarrays.
You are a Python code architect, reviewing and designing scalable and efficient code
def get_global_register_attributes(self, register_attribute, do_sort=True, **kwargs): """Calculating register numbers from register names. Usage: get_global_register_attributes("attribute_name", name = [regname_1, regname_2, ...], addresses = 2) Receives: attribute name to be returned, dict...
How would you code a function in Python 3 to return a list of attributes that are not in the global register.
You are a Python code analyst, evaluating scripts for potential improvements.
def get_global_register_objects(self, do_sort=None, reverse=False, **kwargs): """Generate register objects (list) from register name list Usage: get_global_register_objects(name = ["Amp2Vbn", "GateHitOr", "DisableColumnCnfg"], address = [2, 3]) Receives: keyword lists of register names, add...
Write a Python 3 function for generating register objects from register names list
As a Python code composer, you craft elegant and concise scripts.
This function returns a list of register bitsets that are in the global register table.
Can you tell what is the following Python 3 function doing def get_global_register_bitsets(self, register_addresses): # TOTO: add sorting register_bitsets = [] for register_address in register_addresses: register_objects = self.get_global_register_objects(addresses=register_address) ...
As a Python code composer, you craft elegant and concise scripts.
Generate register objects from register name list
Given the following Python 3 function, write the documentation def get_pixel_register_objects(self, do_sort=None, reverse=False, **kwargs): # speed up of the most often used keyword name try: names = iterable(kwargs.pop('name')) except KeyError: register_objects = []...
As a Python code translator, you convert algorithms and pseudocode into Python.
This function calculates the bitset of the specified register bit number from the given double column number.
Can you tell what is the following Python 3 function doing def get_pixel_register_bitset(self, register_object, bit_no, dc_no): if not 0 <= dc_no < 40: raise ValueError("Pixel register %s: DC out of range" % register_object['name']) if not 0 <= bit_no < register_object['bitlength']: ...
As a python code expert, you are capable of creating scripts from specifications.
Creates a new configuration restore point.
Make a summary of the following Python 3 code def create_restore_point(self, name=None): '''Creating a configuration restore point. Parameters ---------- name : str Name of the restore point. If not given, a md5 hash will be generated. ''' if name is ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Restores a configuration restore point.
Make a summary of the following Python 3 code def restore(self, name=None, keep=False, last=True, global_register=True, pixel_register=True): '''Restoring a configuration restore point. Parameters ---------- name : str Name of the restore point. If not given, a md5 has...
As a Python code composer, you craft elegant and concise scripts.
def clear_restore_points(self, name=None): '''Deleting all/a configuration restore points/point. Parameters ---------- name : str Name of the restore point to be deleted. If not given, all restore points will be deleted. ''' if name is None: ...
Write a Python 3 function for clearing all configuration restore points and point.
You are a Python code generator, capable of creating scripts from specifications.
Stores any configuration dictionary to HDF5 file.
Here you have a function in Python 3, explain what it does def save_configuration_dict(h5_file, configuation_name, configuration, **kwargs): '''Stores any configuration dictionary to HDF5 file. Parameters ---------- h5_file : string, file Filename of the HDF5 configuration file or file ob...
As a Python code analyst, you investigate and solve complex coding mysteries
def convert_data_array(array, filter_func=None, converter_func=None): # TODO: add copy parameter, otherwise in-place '''Filter and convert raw data numpy array (numpy.ndarray). Parameters ---------- array : numpy.array Raw data array. filter_func : function Function that ta...
Write a Python 3 function that can filter and convert raw data numpy array.
You are a Python code generator, capable of creating scripts from specifications.
def convert_data_iterable(data_iterable, filter_func=None, converter_func=None): # TODO: add concatenate parameter '''Convert raw data in data iterable. Parameters ---------- data_iterable : iterable Iterable where each element is a tuple with following content: (raw data, timestamp_star...
Create a Python 3 function to convert raw data in data iterable.
As a Python code composer, you craft elegant and concise scripts.
Convert data iterable to raw data numpy array.
Explain what the following Python 3 code does def data_array_from_data_iterable(data_iterable): '''Convert data iterable to raw data numpy array. Parameters ---------- data_iterable : iterable Iterable where each element is a tuple with following content: (raw data, timestamp_start, times...
As a Python code composer, you craft elegant and concise scripts.
def convert_tdc_to_channel(channel): ''' Converts TDC words at a given channel to common TDC header (0x4). ''' def f(value): filter_func = logical_and(is_tdc_word, is_tdc_from_channel(channel)) select = filter_func(value) value[select] = np.bitwise_and(value[select], 0x0FFFFFFF...
Write a Python 3 script for converting TDC words at a given channel to common TDC header ( 0x4.
You are a Python code analyst, evaluating scripts for potential improvements.
def is_data_from_channel(channel=4): # function factory '''Selecting FE data from given channel. Parameters ---------- channel : int Channel number (4 is default channel on Single Chip Card). Returns ------- Function. Usage: 1 Selecting FE data from channel 4...
Write a Python 3 function for returning a function that returns True if the FE data is from the given channel.
You are a Python code analyst, evaluating scripts for potential improvements.
Logical and from functions.
How would you explain what the following Python 3 function does def logical_and(f1, f2): # function factory '''Logical and from functions. Parameters ---------- f1, f2 : function Function that takes array and returns true or false for each item in array. Returns ------- ...
You are a Python code generator, capable of creating scripts from specifications.
def logical_or(f1, f2): # function factory '''Logical or from functions. Parameters ---------- f1, f2 : function Function that takes array and returns true or false for each item in array. Returns ------- Function. ''' def f(value): return np.logical_o...
Implement a Python 3 function for returning a function that returns true or false for each item in array f1 and f2.
As a Python code composer, you craft elegant and concise scripts.
Returns a function that returns true or false for each item in array f1 and f2.
Here you have a function in Python 3, explain what it does def logical_not(f): # function factory '''Logical not from functions. Parameters ---------- f1, f2 : function Function that takes array and returns true or false for each item in array. Returns ------- Function. ...
As a python code expert, you are capable of creating scripts from specifications.
Logical xor from functions. Parameters ---------- f1, f2 : function Function that takes array and returns true or false for each item in array. Returns ------- Function.
Here you have a function in Python 3, explain what it does def logical_xor(f1, f2): # function factory '''Logical xor from functions. Parameters ---------- f1, f2 : function Function that takes array and returns true or false for each item in array. Returns ------- Funct...
As a python code expert, you are capable of creating scripts from specifications.
def get_trigger_data(value, mode=0): '''Returns 31bit trigger counter (mode=0), 31bit timestamp (mode=1), 15bit timestamp and 16bit trigger counter (mode=2) ''' if mode == 2: return np.right_shift(np.bitwise_and(value, 0x7FFF0000), 16), np.bitwise_and(value, 0x0000FFFF) else: retur...
Can you write a function in Python 3 where it returns 31bit timestamp and 16bit trigger counter
As a python code expert, you are capable of creating scripts from specifications.
Convert raw data array to column row and ToT array.
Can you tell what is the following Python 3 function doing def get_col_row_tot_array_from_data_record_array(array): # TODO: max ToT '''Convert raw data array to column, row, and ToT array. Parameters ---------- array : numpy.array Raw data array. Returns ------- Tuple of...
You are a Python code architect, reviewing and designing scalable and efficient code
def interpret_pixel_data(data, dc, pixel_array, invert=True): '''Takes the pixel raw data and interprets them. This includes consistency checks and pixel/data matching. The data has to come from one double column only but can have more than one pixel bit (e.g. TDAC = 5 bit). Parameters ---------- ...
Can you create a Python 3 function that takes the raw data and interprets them. This includes consistency checks and pixel data matching.
As a python code expert, you are capable of creating scripts from specifications.
Set all settings to their standard values.
How would you explain what the following Python 3 function does def set_standard_settings(self): '''Set all settings to their standard values. ''' if self.is_open(self.out_file_h5): self.out_file_h5.close() self.out_file_h5 = None self._setup_clusterizer() sel...
As a Python code analyst, you investigate and solve complex coding mysteries
Set the number of BCIDs of one event.
Make a summary of the following Python 3 code def trig_count(self, value): self._trig_count = 16 if value == 0 else value self.interpreter.set_trig_count(self._trig_count)
You are a Python code generator, capable of creating scripts from specifications.
def max_tot_value(self, value): """Set maximum ToT value that is considered to be a hit""" self._max_tot_value = value self.interpreter.set_max_tot(self._max_tot_value) self.histogram.set_max_tot(self._max_tot_value) self.clusterizer.set_max_hit_charge(self._max_tot_value)
Create a Python 3 function to set the maximum ToT value that is considered to be a hit
As a Python code composer, you craft elegant and concise scripts.
Interprets the raw data word table of all given raw data files with the c ++ library.
Here you have a function in Python 3, explain what it does def interpret_word_table(self, analyzed_data_file=None, use_settings_from_file=True, fei4b=None): '''Interprets the raw data word table of all given raw data files with the c++ library. Creates the h5 output file and PDF plots. Paramete...
You are a Python code generator, capable of creating scripts from specifications.
def analyze_hit_table(self, analyzed_data_file=None, analyzed_data_out_file=None): '''Analyzes a hit table with the c++ histogrammming/clusterizer. Parameters ---------- analyzed_data_file : string The filename of the analyzed data file. If None, the analyzed data file ...
Write a Python 3 function that can analyze a hit table with the c ++ histogrammming and clusterizer.
You are a Python code architect, reviewing and designing scalable and efficient code
Parses the raw data file and sets the settings to True.
How would you explain what the following Python 3 function does def _deduce_settings_from_file(self, opened_raw_data_file): # TODO: parse better '''Tries to get the scan parameters needed for analysis from the raw data file ''' try: # take infos raw data files (not avalable in old files) ...
As a Python code composer, you craft elegant and concise scripts.
Calculates the charge from the stored PlsrDAC array and the stored C - high mask.
How would you explain what the following Python 3 function does def _get_plsr_dac_charge(self, plsr_dac_array, no_offset=False): '''Takes the PlsrDAC calibration and the stored C-high/C-low mask to calculate the charge from the PlsrDAC array on a pixel basis ''' charge = np.zeros_like(self.c_low...
As a Python code translator, you convert algorithms and pseudocode into Python.
def _parse_fields(self, result, field_name): """ If Schema access, parse fields and build respective lists """ field_list = [] for key, value in result.get('schema', {}).get(field_name, {}).items(): if key not in field_list: field_list.append(key) retu...
Can you create a Python 3 function that parses the fields of the resource.
As a Python code analyst, you investigate and solve complex coding mysteries
Builds a list of valid fields from the solr server.
Here you have a function in Python 3, explain what it does def _build_fields(self): declared_fields = self.solr._send_request('get', ADMIN_URL) result = decoder.decode(declared_fields) self.field_list = self._parse_fields(result, 'fields') # Build regular expressions to match dynamic fi...
As a Python code composer, you craft elegant and concise scripts.
Reformats the given document before insertion into Solr.
Can you generate the documentation for the following Python 3 function def _clean_doc(self, doc, namespace, timestamp): # Translate the _id field to whatever unique key we're using. # _id may not exist in the doc, if we retrieved it from Solr # as part of update. if '_id' in doc: ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def apply_update(self, doc, update_spec): """Override DocManagerBase.apply_update to have flat documents.""" # Replace a whole document if not '$set' in update_spec and not '$unset' in update_spec: # update_spec contains the new document. # Update the key in Solr based on...
Create a Python 3 function to override DocManagerBase. apply_update to have flat documents.
You are a Python code analyst, evaluating scripts for potential improvements.
def update(self, document_id, update_spec, namespace, timestamp): """Apply updates given in update_spec to the document whose id matches that of doc. """ # Commit outstanding changes so that the document to be updated is the # same version to which the changes apply. sel...
How would you code a function in Python 3 to update the document with the given id with the given update spec.
You are a Python code analyst, evaluating scripts for potential improvements.
Update or insert a document into Solr
Given the following Python 3 function, write the documentation def upsert(self, doc, namespace, timestamp): if self.auto_commit_interval is not None: self.solr.add([self._clean_doc(doc, namespace, timestamp)], commit=(self.auto_commit_interval == 0), ...
As a Python code composer, you craft elegant and concise scripts.
def bulk_upsert(self, docs, namespace, timestamp): """Update or insert multiple documents into Solr docs may be any iterable """ if self.auto_commit_interval is not None: add_kwargs = { "commit": (self.auto_commit_interval == 0), "commitWithin...
Write a Python 3 script for updating or insert multiple documents into Solr
You are a Python code analyst, evaluating scripts for potential improvements.
def remove(self, document_id, namespace, timestamp): """Removes documents from Solr The input is a python dictionary that represents a mongo document. """ self.solr.delete(id=u(document_id), commit=(self.auto_commit_interval == 0))
Can you create a Python 3 function that removes documents from Solr
You are a Python code generator, capable of creating scripts from specifications.
def search(self, start_ts, end_ts): """Called to query Solr for documents in a time range.""" query = '_ts: [%s TO %s]' % (start_ts, end_ts) return self._stream_search(query)
Create a Python 3 function for calling to query Solr for documents in a time range.
You are a Python code generator, capable of creating scripts from specifications.
Returns the last document stored in the Solr engine.
Explain what the following Python 3 code does def get_last_doc(self): #search everything, sort by descending timestamp, return 1 row try: result = self.solr.search('*:*', sort='_ts desc', rows=1) except ValueError: return None for r in result: r['_id'...
As a Python code composer, you craft elegant and concise scripts.
def pbkdf2_single(password, salt, key_length, prf): '''Returns the result of the Password-Based Key Derivation Function 2 with a single iteration (i.e. count = 1). prf - a psuedorandom function See http://en.wikipedia.org/wiki/PBKDF2 ''' block_number = 0 result = b'' # The i...
Can you implement a function in Python 3 that returns the result of the Password - based Key Derivation Function 2 with a single iteration.
As a Python code composer, you craft elegant and concise scripts.
def hash(password, salt, N, r, p, dkLen): """Returns the result of the scrypt password-based key derivation function. Constraints: r * p < (2 ** 30) dkLen <= (((2 ** 32) - 1) * 32 N must be a power of 2 greater than 1 (eg. 2, 4, 8, 16, 32...) N, r, p must be positive ...
Can you create a Python 3 function that returns the result of the scrypt password-based key derivation function. Constraints: r * p < (2 ** 30) dkLen <= (((2 ** 32) - 1) * 32 N must be a power of 2 greater than 1 (eg. 2, 4, 8, 16, 32...) N, r, p must be positive
As a Python code translator, you convert algorithms and pseudocode into Python.
def _load_get_attr(self, name): 'Return an internal attribute after ensuring the headers is loaded if necessary.' if self._mode in _allowed_read and self._N is None: self._read_header() return getattr(self, name)
Implement a Python 3 function for returning an internal attribute after ensuring the headers is loaded if necessary.
As a Python code composer, you craft elegant and concise scripts.
def close(self): '''Close the underlying file. Sets data attribute .closed to True. A closed file cannot be used for further I/O operations. close() may be called more than once without error. Some kinds of file objects (for example, opened by popen()) may return an exit status ...
Can you write a function in Python 3 where it closes the underlying file.
As a python code expert, you are capable of creating scripts from specifications.
Returns whether a scrypt encrypted file is valid.
How would you explain what the following Python 3 function does def verify_file(fp, password): 'Returns whether a scrypt encrypted file is valid.' sf = ScryptFile(fp = fp, password = password) for line in sf: pass sf.close() return sf.valid
As a Python code analyst, you investigate and solve complex coding mysteries
Read a line from the decrypted file as a string.
Can you generate the documentation for the following Python 3 function def readline(self, size = None): '''Next line from the decrypted file, as a string. Retain newline. A non-negative size argument limits the maximum number of bytes to return (an incomplete line may be returned then). ...
You are a Python code generator, capable of creating scripts from specifications.
def _read_header(self): '''Read and parse the header and calculate derived keys.''' try: # Read the entire header header = self._fp.read(96) if len(header) != 96: raise InvalidScryptFileFormat("Incomplete header") # Magic number ...
Write a Python 3 script for reading and parse the header and calculate derived keys.
As a Python code composer, you craft elegant and concise scripts.
Reads at most size bytes and returns them as a string.
Can you generate a brief explanation for the following Python 3 code def read(self, size = None): '''Read at most size bytes, returned as a string. If the size argument is negative or omitted, read until EOF is reached. Notice that when in non-blocking mode, less data than what was requested ...
You are a Python code analyst, evaluating scripts for potential improvements.
def _write_header(self): 'Writes the header to the underlying file object.' header = b'scrypt' + CHR0 + struct.pack('>BII', int(math.log(self.N, 2)), self.r, self.p) + self.salt # Add the header checksum to the header checksum = hashlib.sha256(header).digest()[:16] header += ch...
Write a Python 3 script to write the header to the underlying file object.
You are a Python code analyst, evaluating scripts for potential improvements.
Finishes any unencrypted bytes and writes the final checksum.
Here you have a function in Python 3, explain what it does def _finalize_write(self): 'Finishes any unencrypted bytes and writes the final checksum.' # Make sure we have written the header if not self._done_header: self._write_header() # Write the remaining decrypted part t...
As a Python code composer, you craft elegant and concise scripts.
Write string str to the underlying file.
Can you generate a brief explanation for the following Python 3 code def write(self, str): '''Write string str to the underlying file. Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written.''' if self.closed: raise ValueError('Fi...
You are a Python code generator, capable of creating scripts from specifications.
def get_logger(logger_name): """ Return a logger with the specified name, creating it if necessary. """ # Use default global logger if logger_name is None: return __instance assert isinstance(logger_name, str), 'Logger name must be a string!' with __lock: if logger_name in...
Write a Python 3 script to return a logger with the specified name creating it if necessary.
As a Python code translator, you convert algorithms and pseudocode into Python.
copy file or directory at a given location ; can be pasted later
Explain what the following Python 3 code does def copy(location): copyData = settings.getDataFile() copyFileLocation = os.path.abspath(location) copy = {"copyLocation": copyFileLocation} dataFile = open(copyData, "wb") pickle.dump(copy, dataFile) speech.speak(location + " copied successfully!") speech.speak("Tip...
As a Python code analyst, you investigate and solve complex coding mysteries
paste a file or directory that has been previously copied to the current directory
Can you generate a brief explanation for the following Python 3 code def paste(location): copyData = settings.getDataFile() if not location: location = "." try: data = pickle.load(open(copyData, "rb")) speech.speak("Pasting " + data["copyLocation"] + " to current directory.") except: speech.fail("It doesn't...
You are a Python code analyst, evaluating scripts for potential improvements.
Adds the ZFS repository to the apt - get root directory
Make a summary of the following Python 3 code def add_zfs_apt_repository(): with settings(hide('warnings', 'running', 'stdout'), warn_only=False, capture=True): sudo('DEBIAN_FRONTEND=noninteractive /usr/bin/apt-get update') install_ubuntu_development_tools() apt_install(pac...
As a Python code composer, you craft elegant and concise scripts.
installs a apt package
Can you generate a brief explanation for the following Python 3 code def apt_install(**kwargs): for pkg in list(kwargs['packages']): if is_package_installed(distribution='ubuntu', pkg=pkg) is False: sudo("DEBIAN_FRONTEND=noninteractive /usr/bin/apt-get install -y %s" % pkg) # if we didn'...
You are a Python code analyst, evaluating scripts for potential improvements.
installs a pkg from a url
Explain what the following Python 3 code does def apt_install_from_url(pkg_name, url, log=False): if is_package_installed(distribution='ubuntu', pkg=pkg_name) is False: if log: log_green( "installing %s from %s" % (pkg_name, url)) with settings(hide('warnings', 'running...
You are a Python code architect, reviewing and designing scalable and efficient code
def apt_add_key(keyid, keyserver='keyserver.ubuntu.com', log=False): """ trust a new PGP key related to a apt-repository """ if log: log_green( 'trusting keyid %s from %s' % (keyid, keyserver) ) with settings(hide('warnings', 'running', 'stdout')): sudo('apt-key adv --key...
How would you code a function in Python 3 to trust a new PGP key related to apt - repository
As a python code expert, you are capable of creating scripts from specifications.
def enable_apt_repositories(prefix, url, version, repositories): """ adds an apt repository """ with settings(hide('warnings', 'running', 'stdout'), warn_only=False, capture=True): sudo('apt-add-repository "%s %s %s %s"' % (prefix, url...
Can you write a function in Python 3 where it adds an apt repository
You are a Python code generator, capable of creating scripts from specifications.
install a particular gem
Here you have a function in Python 3, explain what it does def install_gem(gem): with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=False, capture=True): # convert 0 into True, any errors will always raise an exception return not bool( run("gem ins...
As a python code expert, you are capable of creating scripts from specifications.
def install_python_module_locally(name): """ instals a python module using pip """ with settings(hide('everything'), warn_only=False, capture=True): # convert 0 into True, any errors will always raise an exception print(not bool(local('pip --quiet install %s' % name).return_cod...
How would you code a function in Python 3 to install a python module locally
As a Python code composer, you craft elegant and concise scripts.
checks if a particular package is installed
Here you have a function in Python 3, explain what it does def is_package_installed(distribution, pkg): if ('centos' in distribution or 'el' in distribution or 'redhat' in distribution): return(is_rpm_package_installed(pkg)) if ('ubuntu' in distribution or 'debian' i...
As a Python code composer, you craft elegant and concise scripts.
def is_rpm_package_installed(pkg): """ checks if a particular rpm package is installed """ with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=True, capture=True): result = sudo("rpm -q %s" % pkg) if result.return_code == 0: return True ...
Can you create a Python 3 function that checks if a particular rpm package is installed
As a Python code composer, you craft elegant and concise scripts.
installs a yum package from a list of packages
Given the following Python 3 function, write the documentation def yum_install(**kwargs): if 'repo' in kwargs: repo = kwargs['repo'] for pkg in list(kwargs['packages']): if is_package_installed(distribution='el', pkg=pkg) is False: if 'repo' in locals(): log_green( ...
As a Python code analyst, you investigate and solve complex coding mysteries
installs a yum group
Can you generate the documentation for the following Python 3 function def yum_group_install(**kwargs): for grp in list(kwargs['groups']): log_green("installing %s ..." % grp) if 'repo' in kwargs: repo = kwargs['repo'] sudo("yum groupinstall -y --quiet " "--e...
You are a Python code generator, capable of creating scripts from specifications.
def yum_install_from_url(pkg_name, url): """ installs a pkg from a url p pkg_name: the name of the package to install p url: the full URL for the rpm package """ if is_package_installed(distribution='el', pkg=pkg_name) is False: log_green( "installing %s from %s" % (pkg_n...
Create a Python 3 function to install a pkg from a url
As a Python code analyst, you investigate and solve complex coding mysteries
Launch the callable job in background thread.
Can you tell what is the following Python 3 function doing def launch_background_job(self, job, on_error=None, on_success=None): if not self.main.mode_online: self.sortie_erreur_GUI( "Local mode activated. Can't run background task !") self.reset() return ...
As a Python code analyst, you investigate and solve complex coding mysteries
def filtre(liste_base, criteres) -> groups.Collection: """ Return a filter list, bases on criteres :param liste_base: Acces list :param criteres: Criteria { `attribut`:[valeurs,...] } """ def choisi(ac): for cat, li in criteres.items(): v = a...
Create a Python 3 function to return a list of items that are in the list list_base and have the same items as the liste_base.
As a Python code translator, you convert algorithms and pseudocode into Python.
def load_remote_data(self, callback_etat=print): """ Load remote data. On succes, build base. On failure, raise :class:`~.Core.exceptions.StructureError`, :class:`~.Core.exceptions.ConnexionError` :param callback_etat: State renderer str , int , int -> None """ callback_...
Can you implement a function in Python 3 that loads remote data from database.
As a python code expert, you are capable of creating scripts from specifications.
def _load_users(self): """Default implentation requires users from DB. Should setup `users` attribute""" r = sql.abstractRequetesSQL.get_users()() self.users = {d["id"]: dict(d) for d in r}
Can you create a Python 3 function that defaults implementation requires users from DB. Should setup users attribute
You are a Python code analyst, evaluating scripts for potential improvements.
Read auto - connection parameters and returns local password or None
Given the following Python 3 function, write the documentation def has_autolog(self, user_id): try: with open("local/init", "rb") as f: s = f.read() s = security.protege_data(s, False) self.autolog = json.loads(s).get("autolog", {}) except File...
You are a Python code analyst, evaluating scripts for potential improvements.
def loggin(self, user_id, mdp, autolog): """Check mdp and return True it's ok""" r = sql.abstractRequetesSQL.check_mdp_user(user_id, mdp) if r(): # update auto-log params self.autolog[user_id] = autolog and mdp or False self.modules = self.users[user_id]["modu...
Write a Python 3 script for checking mdp and return True it's ok
You are a Python code architect, reviewing and designing scalable and efficient code
Convenience function to add a widget to the current instance of the class.
Explain what the following Python 3 code does def add_widget(self, w): if self.layout(): self.layout().addWidget(w) else: layout = QVBoxLayout(self) layout.addWidget(w)
As a Python code composer, you craft elegant and concise scripts.
Find the length of the longest element of a list. Return that value + two.
Given the following Python 3 function, write the documentation def mkpad(items): ''' Find the length of the longest element of a list. Return that value + two. ''' pad = 0 stritems = [str(e) for e in items] # cast list to strings for e in stritems: index = stritems.index(e) if l...
As a Python code translator, you convert algorithms and pseudocode into Python.
def mkcols(l, rows): ''' Compute the size of our columns by first making them a divisible of our row height and then splitting our list into smaller lists the size of the row height. ''' cols = [] base = 0 while len(l) > rows and len(l) % rows != 0: l.append("") for i in rang...
How would you code a function in Python 3 to compute the size of our columns by first making them divisible of our row height and then splitting them into smaller lists.
You are a Python code generator, capable of creating scripts from specifications.
def mkrows(l, pad, width, height): ''' Compute the optimal number of rows based on our lists' largest element and our terminal size in columns and rows. Work out our maximum column number by dividing the width of the terminal by our largest element. While the length of our list is greater than...
Can you implement a function in Python 3 that computes the optimal number of rows based on our lists largest element and our terminal size in columns and rows.
As a Python code composer, you craft elegant and concise scripts.
Print the columns of a list of items.
Can you tell what is the following Python 3 function doing def prtcols(items, vpad=6): ''' After computing the size of our rows and columns based on the terminal size and length of the largest element, use zip to aggregate our column lists into row lists and then iterate over the row lists and print the...
You are a Python code analyst, evaluating scripts for potential improvements.
Executes a command through the operating system and returns the output as a list.
Given the following Python 3 function, write the documentation def cmd2list(cmd): ''' Executes a command through the operating system and returns the output as a list, or on error a string with the standard error. EXAMPLE: >>> from subprocess import Popen, PIPE >>> CMDout2array('ls -l') ''' p...
You are a Python code generator, capable of creating scripts from specifications.
def return_timer(self, name, status, timer): ''' Return a text formatted timer ''' timer_template = '%s %s %s : %s : %9s' t = str(timedelta(0, timer)).split(',')[-1].strip().split(':') #t = str(timedelta(0, timer)).split(':') if len(t) == 4: h, m, s = int(t[0])*24 + int(t[1]), i...
Implement a Python 3 function for returning a text formatted timer
As a Python code composer, you craft elegant and concise scripts.
def print_timers(self): ''' PRINT EXECUTION TIMES FOR THE LIST OF PROGRAMS ''' self.timer += time() total_time = self.timer tmp = '* %s *' debug.log( '', '* '*29, tmp%(' '*51), tmp%('%s %s %s'%('Program Name'.ljust(20), 'Status'.ljust(7), 'Execute Ti...
Can you implement a function in Python 3 that prints the execution times for all the processes in the list.
As a python code expert, you are capable of creating scripts from specifications.
This function returns the commanline call of the program.
Can you generate the documentation for the following Python 3 function def get_cmd(self): cmd = [] if self.path is not None: if '/' in self.path and not os.path.exists(self.path): debug.log('Error: path contains / but does not exist: %s'%self.path) else: if self.pty...
As a Python code composer, you craft elegant and concise scripts.
This function appends the provided arguments to the program object.
Can you generate a brief explanation for the following Python 3 code def append_args(self, arg): debug.log("Adding Arguments: %s"%(arg)) if isinstance(arg, (int,float)): self.args.append(str(arg)) if isinstance(arg, str): self.args.append(arg) if isinstance(arg, list): if sys.version_in...
You are a Python code architect, reviewing and designing scalable and efficient code
This function will wait for a given pattern to finish.
Explain what the following Python 3 code does def wait(self, pattern='Done', interval=None, epatterns=['error','Error','STACK','Traceback']): """ This function will wait on a given pattern being shown on the last line of a given outputfile. OPTIONS pattern - The stri...
You are a Python code generator, capable of creating scripts from specifications.
This function will read the standard out of the program catch variables and return the values ArcGIS variable name.
Given the following Python 3 function, write the documentation def find_out_var(self, varnames=[]): if self.wdir != '': stdout = "%s/%s"%(self.wdir, self.stdout) else: stdout = self.stdout response = [None]*len(varnames) # First we check if the file we want to print does exists...
You are a Python code analyst, evaluating scripts for potential improvements.
This function will read the standard error of the program and return a list of lines that match the pattern.
Can you tell what is the following Python 3 function doing def find_err_pattern(self, pattern): if self.wdir != '': stderr = "%s/%s"%(self.wdir, self.stderr) else: stderr = self.stderr response = [] # First we check if the file we want to print does exists if os.path.exis...
You are a Python code architect, reviewing and designing scalable and efficient code
Decodes a byte string in NFO format from DOS Code Page 437 to Unicode.
Can you tell what is the following Python 3 function doing def decode_nfo( buffer ): assert utils.is_bytes( buffer ) return '\n'.join( [''.join( [CP437[y] for y in x] ) for x in buffer.split( b'\r\n' )] )
As a Python code translator, you convert algorithms and pseudocode into Python.
Run the necessary methods in the correct order
Can you tell what is the following Python 3 function doing def runner(self): if os.path.isfile(self.report): self.report_parse() else: logging.info('Starting {} analysis pipeline'.format(self.analysistype)) # Create the objects to be used in the analyses (if required)...
As a Python code analyst, you investigate and solve complex coding mysteries
Runs the necessary methods to parse raw read outputs and produce a dictionary of results.
Explain what the following Python 3 code does def reporter(self): logging.info('Preparing reports') # Populate self.plusdict in order to reuse parsing code from an assembly-based method for sample in self.runmetadata.samples: self.plusdict[sample.name] = dict() self.match...
As a python code expert, you are capable of creating scripts from specifications.