output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def apply_units_to_cache(self, data): """ Applies units to data when a proxy reader is used. For example if the data is cached as JSON and retrieved using the :class:`~simkit.core.data_readers.JSONReader`, then units can be applied from the original parameter schema. :pa...
Create a Python 3 function for applying units to data when a proxy reader is used.
As a python code expert, you are capable of creating scripts from specifications.
def load_data(self, model_instance, *args, **kwargs): """ Apply units to model. :return: data """ model_dict = copy_model_instance(model_instance) return super(DjangoModelReader, self).load_data(**model_dict)
Create a Python 3 function for applying units to model.
As a Python code analyst, you investigate and solve complex coding mysteries
Decorator for caching API calls request.
Can you generate the documentation for the following Python 3 function def cached(f): @functools.wraps(f) def wrapped(*args, **kwargs): with _cache_lock: identifier = (f.__name__, args, kwargs) key = pickle.dumps(identifier) value = cache.get(key) if valu...
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_api_client(): """Gets the reference to the API cient (singleton).""" with _api_lock: global _api_client if not _api_client: conf_file = os.path.join(os.environ.get("HOME"), ".python-grid5000.yaml") _api_client = Client.from_yam...
Can you implement a function in Python 3 that gets the reference to the API cient singleton.
You are a Python code analyst, evaluating scripts for potential improvements.
def grid_reload_from_name(job_name): """Reload all running or pending jobs of Grid'5000 with a given name. By default all the sites will be searched for jobs with the name ``job_name``. Using EnOSlib there can be only one job per site with name ``job_name``. Note that it honors the ``exluded_sites...
Can you create a Python 3 function that reloads all running or pending jobs with a given name.
As a Python code analyst, you investigate and solve complex coding mysteries
def grid_reload_from_ids(oargrid_jobids): """Reload all running or pending jobs of Grid'5000 from their ids Args: oargrid_jobids (list): list of ``(site, oar_jobid)`` identifying the jobs on each site Returns: The list of python-grid5000 jobs retrieved """ gk = get_api_...
How would you implement a function in Python 3 that reloads all running or pending jobs of Grid 5000 from their ids jobs
As a python code expert, you are capable of creating scripts from specifications.
def grid_destroy_from_name(job_name): """Destroy all the jobs with a given name. Args: job_name (str): the job name """ jobs = grid_reload_from_name(job_name) for job in jobs: job.delete() logger.info("Killing the job (%s, %s)" % (job.site, job.uid))
Can you implement a function in Python 3 that destroys all the jobs with a given name.
As a python code expert, you are capable of creating scripts from specifications.
def grid_destroy_from_ids(oargrid_jobids): """Destroy all the jobs with corresponding ids Args: oargrid_jobids (list): the ``(site, oar_job_id)`` list of tuple identifying the jobs for each site. """ jobs = grid_reload_from_ids(oargrid_jobids) for job in jobs: job.delete() ...
Can you create a Python 3 function that destroys all the jobs with corresponding ids
As a Python code analyst, you investigate and solve complex coding mysteries
Submit a list of jobs to the Grid5000 API.
How would you explain what the following Python 3 function does def submit_jobs(job_specs): gk = get_api_client() jobs = [] try: for site, job_spec in job_specs: logger.info("Submitting %s on %s" % (job_spec, site)) jobs.append(gk.sites[site].jobs.create(job_spec)) except...
As a Python code composer, you craft elegant and concise scripts.
def wait_for_jobs(jobs): """Waits for all the jobs to be runnning. Args: jobs(list): list of the python-grid5000 jobs to wait for Raises: Exception: if one of the job gets in error state. """ all_running = False while not all_running: all_running = True time.s...
Can you create a Python 3 function that waits for all the jobs to be runnning.
As a Python code composer, you craft elegant and concise scripts.
Deploy and wait for the deployment to complete.
Here you have a function in Python 3, explain what it does def grid_deploy(site, nodes, options): gk = get_api_client() environment = options.pop("env_name") options.update(environment=environment) options.update(nodes=nodes) key_path = DEFAULT_SSH_KEYFILE options.update(key=key_path.read_text()...
As a python code expert, you are capable of creating scripts from specifications.
def set_nodes_vlan(site, nodes, interface, vlan_id): """Set the interface of the nodes in a specific vlan. It is assumed that the same interface name is available on the node. Args: site(str): site to consider nodes(list): nodes to consider interface(str): the network interface to ...
Can you implement a function in Python 3 that sets the interface of the nodes in a specific vlan.
You are a Python code analyst, evaluating scripts for potential improvements.
def clusters_sites_obj(clusters): """Get all the corresponding sites of the passed clusters. Args: clusters(list): list of string uid of sites (e.g 'rennes') Return: dict corresponding to the mapping cluster uid to python-grid5000 site """ result = {} all_clusters = get_all_clu...
Can you write a function in Python 3 where it gets all the corresponding sites of the passed clusters.
As a Python code composer, you craft elegant and concise scripts.
def get_all_clusters_sites(): """Get all the cluster of all the sites. Returns: dict corresponding to the mapping cluster uid to python-grid5000 site """ result = {} gk = get_api_client() sites = gk.sites.list() for site in sites: clusters = site.clusters.list() resu...
How would you code a function in Python 3 to get all the cluster of all the sites
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_nodes(cluster): """Get all the nodes of a given cluster. Args: cluster(string): uid of the cluster (e.g 'rennes') """ gk = get_api_client() site = get_cluster_site(cluster) return gk.sites[site].clusters[cluster].nodes.list()
Write a Python 3 script to get all the nodes of a given cluster
As a Python code composer, you craft elegant and concise scripts.
def get_cluster_interfaces(cluster, extra_cond=lambda nic: True): """Get the network interfaces names corresponding to a criteria. Note that the cluster is passed (not the individual node names), thus it is assumed that all nodes in a cluster have the same interface names same configuration. In additio...
Implement a Python 3 function for getting the network interfaces that are part of a cluster.
You are a Python code generator, capable of creating scripts from specifications.
def get_clusters_interfaces(clusters, extra_cond=lambda nic: True): """ Returns for each cluster the available cluster interfaces Args: clusters (str): list of the clusters extra_cond (lambda): extra predicate to filter network card retrieved from the API. E.g lambda nic: not nic['mounted']...
Write a Python 3 function for returning for each cluster the available cluster interfaces
As a Python code composer, you craft elegant and concise scripts.
def can_start_on_cluster(nodes_status, nodes, start, walltime): """Check if #nodes can be started on a given cluster. This is intended to give a good enough approximation. This can be use to prefiltered possible reservation dates be...
How would you code a function in Python 3 to check if a given set of nodes can be started on a given cluster.
You are a Python code analyst, evaluating scripts for potential improvements.
Break an iterable into n lists of length n.
Make a summary of the following Python 3 code def chunked(iterable, n): return iter(functools.partial(take, n, iter(iterable)), [])
As a Python code analyst, you investigate and solve complex coding mysteries
Add data to given room s state
Here you have a function in Python 3, explain what it does def add_data(self, rawdata): for data in rawdata: try: item = data[0] if item[0] == 2: # Flush messages but we got nothing to flush continue if item[0] ...
As a python code expert, you are capable of creating scripts from specifications.
def register_callback(self): """Register callback that we will have to wait for""" cid = str(self.__cid) self.__cid += 1 event = queue.Queue() self.__callbacks[cid] = event return cid, event
Write a Python 3 function for registering a callback that we will have to wait for
As a python code expert, you are capable of creating scripts from specifications.
def _handle_401(self, data): """Handle Lain being helpful""" ex = ConnectionError( "Can't login to a protected room without a proper password", data ) self.conn.reraise(ex)
Create a Python 3 function to handle Lain being helpful
As a Python code analyst, you investigate and solve complex coding mysteries
def _handle_429(self, data): """Handle Lain being helpful""" ex = IOError("Too fast", data) self.conn.reraise(ex)
Implement a Python 3 function for handling Lain being helpful
As a Python code translator, you convert algorithms and pseudocode into Python.
Handle a callback. Only used with getFileinfo so far.
Here you have a function in Python 3, explain what it does def _handle_callback(self, data): cb_id = data.get("id") args = data.get("args") event = self.__callbacks.pop(cb_id, None) if not event: return if not args: event.put(args) return ...
As a python code expert, you are capable of creating scripts from specifications.
Handle user count changes
Can you generate a brief explanation for the following Python 3 code def _handle_userCount(self, data): self.room.user_count = data self.conn.enqueue_data("user_count", self.room.user_count)
You are a Python code generator, capable of creating scripts from specifications.
Handle user info from the server
Explain what the following Python 3 code does def _handle_userInfo(self, data): for k, v in data.items(): if k == "nick": if v == "None": v = "Volaphile" setattr(self.room.user, k, v) self.conn.enqueue_data(k, self.room.user.nick) ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def _handle_config(self, data): """Handle initial config push and config changes""" self.room.config.update(data) self.conn.enqueue_data("config", data)
Create a Python 3 function for handling initial config push and config changes
You are a Python code architect, reviewing and designing scalable and efficient code
def _handle_files(self, data): """Handle new files being uploaded""" initial = data.get("set", False) files = data["files"] for f in files: try: fobj = File( self.room, self.conn, f[0], ...
Write a Python 3 function for handling new files being uploaded
As a python code expert, you are capable of creating scripts from specifications.
def _handle_delete_file(self, data): """Handle files being removed""" file = self.room.filedict.get(data) if file: self.room.filedict = data, None self.conn.enqueue_data("delete_file", file)
Can you implement a function in Python 3 that handles files being removed
As a Python code translator, you convert algorithms and pseudocode into Python.
Handle user name changes
Here you have a function in Python 3, explain what it does def _handle_chat_name(self, data): self.room.user.nick = data self.conn.enqueue_data("user", self.room.user)
As a python code expert, you are capable of creating scripts from specifications.
def get_corrector_f(rinput, meta, ins, datamodel): """Corrector for intensity flat""" from emirdrp.processing.flatfield import FlatFieldCorrector flat_info = meta['master_flat'] with rinput.master_flat.open() as hdul: _logger.info('loading intensity flat') _logger.debug('flat info: %s', ...
Can you implement a function in Python 3 that gets the corrector for intensity flat
As a Python code analyst, you investigate and solve complex coding mysteries
def loginfo(method): """Log the contents of Recipe Input""" def loginfo_method(self, rinput): klass = rinput.__class__ for key in klass.stored(): val = getattr(rinput, key) if isinstance(val, DataFrame): self.logger.debug("DataFrame %s", info.gather_in...
Write a Python 3 function for logging the contents of Recipe Input
You are a Python code architect, reviewing and designing scalable and efficient code
def to_host(self): """Copy or coerce to a Host.""" return Host(self.address, alias=self.alias, user=self.user, keyfile=self.keyfile, port=self.port, extra=self.extra)
How would you code a function in Python 3 to copy or coerce to a Host.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns a dict with table_name keys mapped to the Interface that table exists in
Given the following Python 3 function, write the documentation def get_table_info(*table_names): ret = {} if table_names: for table_name in table_names: for name, inter in get_interfaces().items(): if inter.has_table(table_name): yield table_name, inter, i...
As a python code expert, you are capable of creating scripts from specifications.
def exvp(pos_x, pos_y): """Convert virtual pixel to real pixel""" pos_x = numpy.asarray(pos_x) pos_y = numpy.asarray(pos_y) # convert virtual pixel to real pixel # convert world coordinate to pixel center = [1024.5, 1024.5] cf = EMIR_PLATESCALE_RADS pos_base_x = pos_x - center[0] po...
Can you write a function in Python 3 where it converts virtual pixel to real pixel
You are a Python code generator, capable of creating scripts from specifications.
Verify that all the values in first appear in second.
Here you have a function in Python 3, explain what it does def match_sp_sep(first, second): if isinstance(first, list): one = [set(v.split(" ")) for v in first] else: one = [{v} for v in first.split(" ")] if isinstance(second, list): other = [set(v.split(" ")) for v in second] e...
You are a Python code architect, reviewing and designing scalable and efficient code
def _verify_sector_identifier(self, request): """ Verify `sector_identifier_uri` is reachable and that it contains `redirect_uri`s. :param request: Provider registration request :return: si_redirects, sector_id :raises: InvalidSectorIdentifier """ si_url...
Write a Python 3 function for verifying that the sector identifier_uri is reachable and that it contains redirect_uri s.
You are a Python code analyst, evaluating scripts for potential improvements.
def readline(self): """ Read and analyse the next line of the SExtractor catalog and return a dictionary {'param1': value, 'param2': value, ...}. """ if not(self._firstline): self._line = self._file.readline() self._firstline = False if not(self._lin...
Write a Python 3 script to read and analyse the next line of the SExtractor file and return a dictionary.
You are a Python code generator, capable of creating scripts from specifications.
Read the file until EOF and return a list of dictionaries.
Can you tell what is the following Python 3 function doing def read(self): __result = [] __ll = self.readline() while __ll: __result.append(__ll) __ll = self.readline() return list(__result)
As a Python code translator, you convert algorithms and pseudocode into Python.
Close the SExtractor file.
Given the following Python 3 function, write the documentation def close(self): if self._file: if not(self._file.closed): self._file.close() self.closed = True
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_driver(configuration): """Build an instance of the driver to interact with G5K """ resources = configuration["resources"] machines = resources["machines"] networks = resources["networks"] oargrid_jobids = configuration.get("oargrid_jobids") if oargrid_jobids: logger.debug("L...
Can you create a Python 3 function that builds an instance of the driver to interact with G5K
You are a Python code analyst, evaluating scripts for potential improvements.
Verifies the value of a cookie and returns the load and timestamp.
Explain what the following Python 3 code does def ver_dec_content(parts, sign_key=None, enc_key=None, sign_alg='SHA256'): if parts is None: return None elif len(parts) == 3: # verify the cookie signature timestamp, load, b64_mac = parts mac = base64.b64decode(b64_mac) ve...
You are a Python code architect, reviewing and designing scalable and efficient code
def make_cookie_content(name, load, sign_key, domain=None, path=None, timestamp="", enc_key=None, max_age=0, sign_alg='SHA256'): """ Create and return a cookies content If you only provide a `seed`, a HMAC gets added to the cookies value and this is check...
Implement a function in Python 3 to create and return a SimpleCookie instance for the cookie.
As a Python code analyst, you investigate and solve complex coding mysteries
def cookie_parts(name, kaka): """ Give me the parts of the cookie payload :param name: A name of a cookie object :param kaka: The cookie :return: A list of parts or None if there is no cookie object with the given name """ cookie_obj = SimpleCookie(as_unicode(kaka)) morsel = coo...
Can you create a Python 3 function that returns a list of parts of the cookie payload
You are a Python code architect, reviewing and designing scalable and efficient code
def parse_cookie(name, sign_key, kaka, enc_key=None, sign_alg='SHA256'): """Parses and verifies a cookie value Parses a cookie created by `make_cookie` and verifies it has not been tampered with. You need to provide the same `sign_key` and `enc_key` used when creating the cookie, otherwise the ver...
Can you write a function in Python 3 where it parses and verifies a cookie value.
You are a Python code analyst, evaluating scripts for potential improvements.
Create a cookie that will immediately expire when it hits the otherCOOKIE.
How would you explain what the following Python 3 function does def delete_cookie(self, cookie_name=None): if cookie_name is None: cookie_name = self.default_value['name'] return self.create_cookie("", "", cookie_name=cookie_name, kill=True)
You are a Python code architect, reviewing and designing scalable and efficient code
Get the value of a cookie.
Make a summary of the following Python 3 code def get_cookie_value(self, cookie=None, cookie_name=None): if cookie_name is None: cookie_name = self.default_value['name'] if cookie is None or cookie_name is None: return None else: try: info, ti...
As a Python code analyst, you investigate and solve complex coding mysteries
def append_cookie(self, cookie, name, payload, typ, domain=None, path=None, timestamp="", max_age=0): """ Adds a cookie to a SimpleCookie instance :param cookie: :param name: :param payload: :param typ: :param domain: :param path: ...
Can you write a function in Python 3 where it adds a cookie to a SimpleCookie instance.
As a Python code translator, you convert algorithms and pseudocode into Python.
def f_ac_power(inverter, v_mp, p_mp): """ Calculate AC power :param inverter: :param v_mp: :param p_mp: :return: AC power [W] """ return pvlib.pvsystem.snlinverter(v_mp, p_mp, inverter).flatten()
How would you implement a function in Python 3 that calculates AC power of a node.
As a Python code composer, you craft elegant and concise scripts.
def f_dc_power(effective_irradiance, cell_temp, module): """ Calculate DC power using Sandia Performance model :param effective_irradiance: effective irradiance [suns] :param cell_temp: PV cell temperature [degC] :param module: PV module dictionary or pandas data frame :returns: i_sc, i_mp, v_o...
Write a Python 3 script for calculating DC power using Sandia Performance model
You are a Python code analyst, evaluating scripts for potential improvements.
Calculates effective irradiance for Sandia Performance model
Given the following Python 3 function, write the documentation def f_effective_irradiance(poa_direct, poa_diffuse, am_abs, aoi, module): Ee = pvlib.pvsystem.sapm_effective_irradiance(poa_direct, poa_diffuse, am_abs, aoi, module) return Ee.reshape(1, -1)
As a Python code analyst, you investigate and solve complex coding mysteries
def f_cell_temp(poa_global, wind_speed, air_temp): """ Calculate cell temperature. :param poa_global: plane of array global irradiance [W/m**2] :param wind_speed: wind speed [m/s] :param air_temp: ambient dry bulb air temperature [degC] :return: cell temperature [degC] """ temps = pvlib...
Write a Python 3 script to calculate cell temperature. :param poa_global: plane of array global irradiance [W/m**2] :param wind_speed: wind speed [m/s] :param air_temp: ambient dry bulb air temperature [degC] :return: cell temperature [degC]
As a Python code translator, you convert algorithms and pseudocode into Python.
Calculate angle of incidence on a node in a node list.
Make a summary of the following Python 3 code def f_aoi(surface_tilt, surface_azimuth, solar_zenith, solar_azimuth): return pvlib.irradiance.aoi(surface_tilt, surface_azimuth, solar_zenith, solar_azimuth)
As a Python code translator, you convert algorithms and pseudocode into Python.
Find the version string in given file and return it.
Can you tell what is the following Python 3 function doing def find_version(filename): with open(filename, "r") as filep: version_file = filep.read() version_match = re.search( r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M ) if version_match: retur...
As a Python code translator, you convert algorithms and pseudocode into Python.
Save numpy array into a FITS file with the provided filename.
Can you generate the documentation for the following Python 3 function def save_ndarray_to_fits(array=None, file_name=None, main_header=None, cast_to_float=True, crpix1=None, crval1=None, cdelt1=None, overwrite=True): ...
You are a Python code generator, capable of creating scripts from specifications.
Find a EMIR CSU bar position in a 2d edge image.
Make a summary of the following Python 3 code def find_position(edges, prow, bstart, bend, total=5): nt = total // 2 # This bar is too near the border if prow-nt < 0 or prow + nt >= edges.shape[0]: return [] s2edges = edges[prow-nt:prow+nt+1, bstart:bend] structure = morph.generate_binar...
You are a Python code analyst, evaluating scripts for potential improvements.
def calc_fwhm(img, region, fexpand=3, axis=0): """Compute the FWHM in the direction given by axis""" # We compute know the FWHM of the slit # Given the computed position of the slit # Expand 'fexpand' pixels around # and cut an slice in the median filtered image xpregion = expand_region(region...
Can you implement a function in Python 3 that computes the FWHM of the maximum image in the given axis
As a python code expert, you are capable of creating scripts from specifications.
def simple_prot(x, start): """Find the first peak to the right of start""" # start must b >= 1 for i in range(start,len(x)-1): a,b,c = x[i-1], x[i], x[i+1] if b - a > 0 and b -c >= 0: return i else: return None
Create a Python 3 function to find the first peak to the right of start
As a Python code composer, you craft elegant and concise scripts.
def position_half_h(pslit, cpix, backw=4): """Find the position where the value is half of the peak""" # Find the first peak to the right of cpix next_peak = simple_prot(pslit, cpix) if next_peak is None: raise ValueError dis_peak = next_peak - cpix wpos2 = cpix - dis_peak wpos1 ...
Create a Python 3 function for finding the position where the value is half of the peak
You are a Python code architect, reviewing and designing scalable and efficient code
def locate_bar_l(icut, epos): """Fine position of the left CSU bar""" def swap_coor(x): return x def swap_line(tab): return tab return _locate_bar_gen(icut, epos, transform1=swap_coor, transform2=swap_line ...
Implement a function in Python 3 to fine position of the left CSU bar
You are a Python code generator, capable of creating scripts from specifications.
def locate_bar_r(icut, epos): """Fine position of the right CSU bar""" sm = len(icut) def swap_coor(x): return sm - 1 - x def swap_line(tab): return tab[::-1] return _locate_bar_gen(icut, epos, transform1=swap_coor, transform2=swap_line)
Implement a Python 3 function for fining position of the right CSU bar
You are a Python code generator, capable of creating scripts from specifications.
Overlaps of two intervals
Here you have a function in Python 3, explain what it does def overlap(intv1, intv2): return max(0, min(intv1[1], intv2[1]) - max(intv1[0], intv2[0]))
As a Python code composer, you craft elegant and concise scripts.
def exvp_scalar(x, y, x0, y0, c2, c4, theta0, ff): """Convert virtual pixel to real pixel. Parameters ---------- x : array-like of floats X coordinate (pixel). y : array-like of floats Y coordinate (pixel). x0 : float X coordinate of reference pixel, in units of 1E3. ...
How would you code a function in Python 3 to convert virtual pixel to real pixel.
As a python code expert, you are capable of creating scripts from specifications.
This function converts virtual pixel to real pixel.
Here you have a function in Python 3, explain what it does def exvp(x, y, x0, y0, c2, c4, theta0, ff): if all([np.isscalar(x), np.isscalar(y)]): xdist, ydist = exvp_scalar(x, y, x0=x0, y0=y0, c2=c2, c4=c4, theta0=theta0, ff=ff) return xdist, ydist elif any([np...
As a Python code composer, you craft elegant and concise scripts.
Return individual model parameters from object of type Parameters.
Can you generate the documentation for the following Python 3 function def return_params(islitlet, csu_bar_slit_center, params, parmodel): if parmodel == "longslit": # set each variable in EXPECTED_PARAMETER_LIST to the value # transferred through 'params' c2 = params['c2'].value c4...
As a Python code translator, you convert algorithms and pseudocode into Python.
def expected_distorted_boundaries(islitlet, csu_bar_slit_center, borderlist, params, parmodel, numpts, deg, debugplot=0): """Return expected SpectrumTrail instances associated to a given slitlet. Several SpectrumTrail objects can be computed f...
Can you implement a function in Python 3 that returns the expected distorted boundaries of a given set of parameters.
As a Python code translator, you convert algorithms and pseudocode into Python.
def fun_residuals(params, parmodel, bounddict, shrinking_factor, numresolution, islitmin, islitmax, debugplot): """Function to be minimised. Parameters ---------- params : :class:`~lmfit.parameter.Parameters` Parameters to be employed in the prediction of the...
Write a Python 3 script to function to be minimised.
As a Python code translator, you convert algorithms and pseudocode into Python.
Overplot boundaries on current plot.
Explain what the following Python 3 code does def overplot_boundaries_from_bounddict(ax, bounddict, micolors, linetype='-'): for islitlet in range(1, EMIR_NBARS + 1): tmpcolor = micolors[islitlet % 2] tmp_slitlet = 'slitlet' + str(islitlet).zfill(2) if tmp_slitlet in bounddict['contents'].k...
As a python code expert, you are capable of creating scripts from specifications.
Export to ds9 region file the boundaries in bounddict.
Explain what the following Python 3 code does def save_boundaries_from_bounddict_ds9(bounddict, ds9_filename, numpix=100): ds9_file = open(ds9_filename, 'w') ds9_file.write('# Region file format: DS9 version 4.1\n') ds9_file.write('global color=green dashlist=2 4 width=2 ' 'font="helvet...
You are a Python code analyst, evaluating scripts for potential improvements.
Export to ds9 region file the boundaries parametrised with params.
Given the following Python 3 function, write the documentation def save_boundaries_from_params_ds9(params, parmodel, list_islitlet, list_csu_bar_slit_center, uuid, grism, spfilter, ...
You are a Python code architect, reviewing and designing scalable and efficient code
def bound_params_from_dict(bound_param_dict): """Define `~lmfit.parameter.Parameters` object from dictionary. Parameters ---------- bound_param_dict : dictionary Dictionary containing the JSON contents of a boundary parameter file. Returns ------- params : :class:`~lmfit.pa...
Write a Python 3 script for defining ~lmfit. parameter. Parameters object from dictionary.
As a Python code composer, you craft elegant and concise scripts.
Set metadata in FITS headers.
Given the following Python 3 function, write the documentation def set_base_headers(self, hdr): hdr = super(StareImageRecipe2, self).set_base_headers(hdr) # Set EXP to 0 hdr['EXP'] = 0 return hdr
As a Python code composer, you craft elegant and concise scripts.
def set_base_headers(self, hdr): """Set metadata in FITS headers.""" hdr = super(StareImageBaseRecipe, self).set_base_headers(hdr) # Update EXP to 0 hdr['EXP'] = 0 return hdr
How would you code a function in Python 3 to set metadata in FITS headers.
You are a Python code analyst, evaluating scripts for potential improvements.
Compute rectification and wavelength calibration coefficients for a given image.
Can you generate a brief explanation for the following Python 3 code def apply_rectwv_coeff(reduced_image, rectwv_coeff, args_resampling=2, args_ignore_dtu_configuration=True, debugplot=0): """Compute rectification and wavel...
As a Python code composer, you craft elegant and concise scripts.
def transaction_start(self, name): """ start a transaction this will increment transaction semaphore and pass it to _transaction_start() """ if not name: raise ValueError("Transaction name cannot be empty") #uid = id(self) self.transaction_count ...
Implement a Python 3 function for starting a transaction this will increment transaction semaphore and pass it to _transaction_start()
As a Python code analyst, you investigate and solve complex coding mysteries
def transaction_stop(self): """stop/commit a transaction if ready""" if self.transaction_count > 0: logger.debug("{}. Stop transaction".format(self.transaction_count)) if self.transaction_count == 1: self._transaction_stop() self.transaction_count -= ...
Can you implement a function in Python 3 that stops a transaction if ready
As a python code expert, you are capable of creating scripts from specifications.
connect to the interface
Make a summary of the following Python 3 code def connect(self, connection_config=None, *args, **kwargs): if self.connected: return self.connected if connection_config: self.connection_config = connection_config self.connected = True try: self._connect(self.connection_confi...
As a python code expert, you are capable of creating scripts from specifications.
def close(self): """close an open connection""" if not self.connected: return True self._close() self.connected = False self.log("Closed Connection {}", self.connection_config.interface_name) return True
Write a Python 3 function that can close an open connection
As a Python code analyst, you investigate and solve complex coding mysteries
run a raw query on the database
Can you generate a brief explanation for the following Python 3 code def query(self, query_str, *query_args, **query_options): with self.connection(**query_options) as connection: query_options['connection'] = connection return self._query(query_str, query_args, **query_options)
You are a Python code architect, reviewing and designing scalable and efficient code
A context manager that creates a transaction for a bunch of db calls.
How would you explain what the following Python 3 function does def transaction(self, connection=None, **kwargs): with self.connection(connection) as connection: name = connection.transaction_name() connection.transaction_start(name) try: yield connection ...
You are a Python code analyst, evaluating scripts for potential improvements.
def set_table(self, schema, **kwargs): """ add the table to the db schema -- Schema() -- contains all the information about the table """ with self.connection(**kwargs) as connection: kwargs['connection'] = connection if self.has_table(str(schema), **kwar...
Can you write a function in Python 3 where it adds the table to the database
As a python code expert, you are capable of creating scripts from specifications.
def has_table(self, table_name, **kwargs): """ check to see if a table is in the db table_name -- string -- the table to check return -- boolean -- True if the table exists, false otherwise """ with self.connection(kwargs.get('connection', None)) as connection: ...
Write a Python 3 function for checking to see if a table exists in the db
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_tables(self, table_name="", **kwargs): """ get all the tables of the currently connected db table_name -- string -- if you would like to filter the tables list to only include matches with this name return -- list -- a list of table names """ with self.connection...
Implement a function in Python 3 to get all the tables of the currently connected db
You are a Python code analyst, evaluating scripts for potential improvements.
def delete_table(self, schema, **kwargs): """ remove a table matching schema from the db schema -- Schema() """ with self.connection(**kwargs) as connection: kwargs['connection'] = connection if not self.has_table(str(schema), **kwargs): return True ...
Can you write a function in Python 3 where it deletes a table from the database
As a python code expert, you are capable of creating scripts from specifications.
Delete all the tables in the database
Here you have a function in Python 3, explain what it does def delete_tables(self, **kwargs): if not kwargs.get('disable_protection', False): raise ValueError('In order to delete all the tables, pass in disable_protection=True') with self.connection(**kwargs) as connection: kwar...
As a python code expert, you are capable of creating scripts from specifications.
get all the indexes in a specific schema
Given the following Python 3 function, write the documentation def get_indexes(self, schema, **kwargs): with self.connection(**kwargs) as connection: kwargs['connection'] = connection return self._get_indexes(schema, **kwargs)
As a python code expert, you are capable of creating scripts from specifications.
def set_index(self, schema, name, fields, **index_options): """ add an index to the table schema -- Schema() name -- string -- the name of the index fields -- array -- the fields the index should be on **index_options -- dict -- any index options that might be useful to ...
Can you implement a function in Python 3 that adds an index to the table
As a Python code composer, you craft elegant and concise scripts.
def insert(self, schema, fields, **kwargs): """ Persist d into the db schema -- Schema() fields -- dict -- the values to persist return -- int -- the primary key of the row just inserted """ r = 0 with self.connection(**kwargs) as connection: ...
Write a Python 3 function that can persist d into the db
As a python code expert, you are capable of creating scripts from specifications.
def update(self, schema, fields, query, **kwargs): """ Persist the query.fields into the db that match query.fields_where schema -- Schema() fields -- dict -- the values to persist query -- Query() -- will be used to create the where clause return -- int -- how many row...
Write a Python 3 function for updating the fields of the record that match query. fields_where
As a Python code composer, you craft elegant and concise scripts.
wrapper around all the get queries
Given the following Python 3 function, write the documentation def _get_query(self, callback, schema, query=None, *args, **kwargs): if not query: query = Query() ret = None with self.connection(**kwargs) as connection: kwargs['connection'] = connection try: ...
As a Python code analyst, you investigate and solve complex coding mysteries
def get_one(self, schema, query=None, **kwargs): """ get one row from the db matching filters set in query schema -- Schema() query -- Query() return -- dict -- the matching row """ ret = self._get_query(self._get_one, schema, query, **kwargs) if not ret...
Create a Python 3 function to get one row from the db
As a python code expert, you are capable of creating scripts from specifications.
def get(self, schema, query=None, **kwargs): """ get matching rows from the db matching filters set in query schema -- Schema() query -- Query() return -- list -- a list of matching dicts """ ret = self._get_query(self._get, schema, query, **kwargs) if n...
How would you code a function in Python 3 to get matching rows from the db
As a Python code translator, you convert algorithms and pseudocode into Python.
def log(self, format_str, *format_args, **log_options): """ wrapper around the module's logger format_str -- string -- the message to log *format_args -- list -- if format_str is a string containing {}, then format_str.format(*format_args) is ran **log_options -- le...
Write a Python 3 function that can wrap around the module s logger. log
You are a Python code architect, reviewing and designing scalable and efficient code
this is just a wrapper to make the passed in exception an InterfaceError
Can you generate the documentation for the following Python 3 function def raise_error(self, e, exc_info=None): if not exc_info: exc_info = sys.exc_info() if not isinstance(e, InterfaceError): # allow python's built in errors to filter up through # https://docs.pytho...
As a python code expert, you are capable of creating scripts from specifications.
Query the database for the related object.
Make a summary of the following Python 3 code def _query(self, query_str, query_args=None, **query_options): ret = True # http://stackoverflow.com/questions/6739355/dictcursor-doesnt-seem-to-work-under-psycopg2 connection = query_options.get('connection', None) with self.connection(conne...
As a Python code composer, you craft elegant and concise scripts.
convert the generic Query instance into SQL
Given the following Python 3 function, write the documentation def get_SQL(self, schema, query, **sql_options): only_where_clause = sql_options.get('only_where_clause', False) symbol_map = { 'in': {'symbol': 'IN', 'list': True}, 'nin': {'symbol': 'NOT IN', 'list': True}, ...
As a python code expert, you are capable of creating scripts from specifications.
This method will go through all tables referenced by a and create all tables that are not referenced by any foreign key referenced by a .
Can you generate a brief explanation for the following Python 3 code def _set_all_tables(self, schema, **kwargs): with self.transaction(**kwargs) as connection: kwargs['connection'] = connection # go through and make sure all foreign key referenced tables exist for field_name...
You are a Python code generator, capable of creating scripts from specifications.
def random_path(instance, filename): """ Random path generator for uploads, specify this for upload_to= argument of FileFields """ # Split the uuid into two parts so that we won't run into subdirectory count limits. First part has 3 hex chars, # thus 4k possible values. uuid_hex = get_uuid() re...
Create a Python 3 function for generating a random path for uploads.
You are a Python code architect, reviewing and designing scalable and efficient code
def initialize(signal_number=DEFAULT_TIMER_SIGNAL_NUMBER, update_period_s=DEFAULT_UPDATE_PERIOD_S): """Initialize metrics, must be invoked at least once prior to invoking any other method.""" global initialized if initialized: return initialized = True uwsgi.add_timer(sign...
Can you write a function in Python 3 where it initializes metrics, must be invoked at least once prior to invoking any other method.
You are a Python code generator, capable of creating scripts from specifications.
Serialize metrics to the memory mapped buffer.
Here you have a function in Python 3, explain what it does def emit(_): if not initialized: raise NotInitialized view = { 'version': __version__, 'counters': {}, 'gauges': {}, 'histograms': {}, 'meters': {}, 'timers': {}, } for (ty, module, name)...
As a Python code analyst, you investigate and solve complex coding mysteries